answer stringlengths 17 10.2M |
|---|
package com.sun.jna.platform.unix;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.Callback;
import com.sun.jna.FromNativeContext;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.PointerType;
import com.sun.jna.Structure;
import com.sun.jna.Union;
import com.sun.jna.ptr.ByReference;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.NativeLongByReference;
import com.sun.jna.ptr.PointerByReference;
/** Definition (incomplete) of the X library. */
public interface X11 extends Library {
class VisualID extends NativeLong {
private static final long serialVersionUID = 1L;
public VisualID() { }
public VisualID(long value) { super(value); }
}
class XID extends NativeLong {
private static final long serialVersionUID = 1L;
public static final XID None = null;
public XID() { this(0); }
public XID(long id) { super(id); }
protected boolean isNone(Object o) {
return o == null
|| (o instanceof Number
&& ((Number)o).longValue() == X11.None);
}
public Object fromNative(Object nativeValue, FromNativeContext context) {
if (isNone(nativeValue))
return None;
return new XID(((Number)nativeValue).longValue());
}
public String toString() {
return "0x" + Long.toHexString(longValue());
}
}
class Atom extends XID {
private static final long serialVersionUID = 1L;
public static final Atom None = null;
public Atom() { }
public Atom(long id) { super(id); }
/** Return constants for predefined <code>Atom</code> values. */
public Object fromNative(Object nativeValue, FromNativeContext context) {
long value = ((Number)nativeValue).longValue();
if (value <= Integer.MAX_VALUE) {
switch((int)value) {
case 0: return None;
case 1: return XA_PRIMARY;
case 2: return XA_SECONDARY;
case 3: return XA_ARC;
case 4: return XA_ATOM;
case 5: return XA_BITMAP;
case 6: return XA_CARDINAL;
case 7: return XA_COLORMAP;
case 8: return XA_CURSOR;
case 9: return XA_CUT_BUFFER0;
case 10: return XA_CUT_BUFFER1;
case 11: return XA_CUT_BUFFER2;
case 12: return XA_CUT_BUFFER3;
case 13: return XA_CUT_BUFFER4;
case 14: return XA_CUT_BUFFER5;
case 15: return XA_CUT_BUFFER6;
case 16: return XA_CUT_BUFFER7;
case 17: return XA_DRAWABLE;
case 18: return XA_FONT;
case 19: return XA_INTEGER;
case 20: return XA_PIXMAP;
case 21: return XA_POINT;
case 22: return XA_RECTANGLE;
case 23: return XA_RESOURCE_MANAGER;
case 24: return XA_RGB_COLOR_MAP;
case 25: return XA_RGB_BEST_MAP;
case 26: return XA_RGB_BLUE_MAP;
case 27: return XA_RGB_DEFAULT_MAP;
case 28: return XA_RGB_GRAY_MAP;
case 29: return XA_RGB_GREEN_MAP;
case 30: return XA_RGB_RED_MAP;
case 31: return XA_STRING;
case 32: return XA_VISUALID;
case 33: return XA_WINDOW;
case 34: return XA_WM_COMMAND;
case 35: return XA_WM_HINTS;
case 36: return XA_WM_CLIENT_MACHINE;
case 37: return XA_WM_ICON_NAME;
case 38: return XA_WM_ICON_SIZE;
case 39: return XA_WM_NAME;
case 40: return XA_WM_NORMAL_HINTS;
case 41: return XA_WM_SIZE_HINTS;
case 42: return XA_WM_ZOOM_HINTS;
case 43: return XA_MIN_SPACE;
case 44: return XA_NORM_SPACE;
case 45: return XA_MAX_SPACE;
case 46: return XA_END_SPACE;
case 47: return XA_SUPERSCRIPT_X;
case 48: return XA_SUPERSCRIPT_Y;
case 49: return XA_SUBSCRIPT_X;
case 50: return XA_SUBSCRIPT_Y;
case 51: return XA_UNDERLINE_POSITION;
case 52: return XA_UNDERLINE_THICKNESS;
case 53: return XA_STRIKEOUT_ASCENT;
case 54: return XA_STRIKEOUT_DESCENT;
case 55: return XA_ITALIC_ANGLE;
case 56: return XA_X_HEIGHT;
case 57: return XA_QUAD_WIDTH;
case 58: return XA_WEIGHT;
case 59: return XA_POINT_SIZE;
case 60: return XA_RESOLUTION;
case 61: return XA_COPYRIGHT;
case 62: return XA_NOTICE;
case 63: return XA_FONT_NAME;
case 64: return XA_FAMILY_NAME;
case 65: return XA_FULL_NAME;
case 66: return XA_CAP_HEIGHT;
case 67: return XA_WM_CLASS;
case 68: return XA_WM_TRANSIENT_FOR;
default:
}
}
return new Atom(value);
}
}
class AtomByReference extends ByReference {
public AtomByReference() { super(XID.SIZE); }
public Atom getValue() {
NativeLong value = getPointer().getNativeLong(0);
return (Atom)new Atom().fromNative(value, null);
}
}
class Colormap extends XID {
private static final long serialVersionUID = 1L;
public static final Colormap None = null;
public Colormap() { }
public Colormap(long id) { super(id); }
public Object fromNative(Object nativeValue, FromNativeContext context) {
if (isNone(nativeValue))
return None;
return new Colormap(((Number)nativeValue).longValue());
}
}
class Font extends XID {
private static final long serialVersionUID = 1L;
public static final Font None = null;
public Font() { }
public Font(long id) { super(id); }
public Object fromNative(Object nativeValue, FromNativeContext context) {
if (isNone(nativeValue))
return None;
return new Font(((Number)nativeValue).longValue());
}
}
class Cursor extends XID {
private static final long serialVersionUID = 1L;
public static final Cursor None = null;
public Cursor() { }
public Cursor(long id) { super(id); }
public Object fromNative(Object nativeValue, FromNativeContext context) {
if (isNone(nativeValue))
return None;
return new Cursor(((Number)nativeValue).longValue());
}
}
class KeySym extends XID {
private static final long serialVersionUID = 1L;
public static final KeySym None = null;
public KeySym() { }
public KeySym(long id) { super(id); }
public Object fromNative(Object nativeValue, FromNativeContext context) {
if (isNone(nativeValue))
return None;
return new KeySym(((Number)nativeValue).longValue());
}
}
class Drawable extends XID {
private static final long serialVersionUID = 1L;
public static final Drawable None = null;
public Drawable() { }
public Drawable(long id) { super(id); }
public Object fromNative(Object nativeValue, FromNativeContext context) {
if (isNone(nativeValue))
return None;
return new Drawable(((Number)nativeValue).longValue());
}
}
class Window extends Drawable {
private static final long serialVersionUID = 1L;
public static final Window None = null;
public Window() { }
public Window(long id) { super(id); }
public Object fromNative(Object nativeValue, FromNativeContext context) {
if (isNone(nativeValue))
return None;
return new Window(((Number)nativeValue).longValue());
}
}
class WindowByReference extends ByReference {
public WindowByReference() { super(XID.SIZE); }
public Window getValue() {
NativeLong value = getPointer().getNativeLong(0);
return value.longValue() == X11.None
? Window.None : new Window(value.longValue());
}
}
class Pixmap extends Drawable {
private static final long serialVersionUID = 1L;
public static final Pixmap None = null;
public Pixmap() { }
public Pixmap(long id) { super(id); }
public Object fromNative(Object nativeValue, FromNativeContext context) {
if (isNone(nativeValue))
return None;
return new Pixmap(((Number)nativeValue).longValue());
}
}
// TODO: define structure
class Display extends PointerType { }
// TODO: define structure
class Visual extends PointerType {
public NativeLong getVisualID() {
if (getPointer() != null)
return getPointer().getNativeLong(Native.POINTER_SIZE);
return new NativeLong(0);
}
public String toString() {
return "Visual: VisualID=0x" + Long.toHexString(getVisualID().longValue());
}
}
// TODO: define structure
class Screen extends PointerType { }
// TODO: define structure
class GC extends PointerType { }
// TODO: define structure
class XImage extends PointerType { }
/** Definition (incomplete) of the Xext library. */
interface Xext extends Library {
Xext INSTANCE = (Xext)Native.loadLibrary("Xext", Xext.class);
// Shape Kinds
int ShapeBounding = 0;
int ShapeClip = 1;
int ShapeInput = 2;
// Operations
int ShapeSet = 0;
int ShapeUnion = 1;
int ShapeIntersect = 2;
int ShapeSubtract = 3;
int ShapeInvert = 4;
void XShapeCombineMask(Display display, Window window, int dest_kind,
int x_off, int y_off, Pixmap src, int op);
}
/** Definition (incomplete) of the Xrender library. */
interface Xrender extends Library {
Xrender INSTANCE = (Xrender)Native.loadLibrary("Xrender", Xrender.class);
class XRenderDirectFormat extends Structure {
public short red, redMask;
public short green, greenMask;
public short blue, blueMask;
public short alpha, alphaMask;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "red", "redMask", "green", "greenMask", "blue", "blueMask", "alpha", "alphaMask" });
}
}
class PictFormat extends NativeLong {
private static final long serialVersionUID = 1L;
public PictFormat(long value) { super(value); }
public PictFormat() { }
}
class XRenderPictFormat extends Structure {
public PictFormat id;
public int type;
public int depth;
public XRenderDirectFormat direct;
public Colormap colormap;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "id", "type", "depth", "direct", "colormap" });
}
}
int PictTypeIndexed = 0x0;
int PictTypeDirect = 0x1;
XRenderPictFormat XRenderFindVisualFormat(Display display, Visual visual);
}
/** Definition of the Xevie library. */
interface Xevie extends Library {
/** Instance of Xevie. Note: This extension has been removed from xorg/xserver on Oct 22, 2008 because it is broken and maintainerless. */
Xevie INSTANCE = (Xevie)Native.loadLibrary("Xevie", Xevie.class);
int XEVIE_UNMODIFIED = 0;
int XEVIE_MODIFIED = 1;
// Bool XevieQueryVersion (Display* display, int* major_version, int* minor_version);
boolean XevieQueryVersion (Display display, IntByReference major_version, IntByReference minor_version);
// Status XevieStart (Display* display);
int XevieStart (Display display);
// Status XevieEnd (Display* display);
int XevieEnd (Display display);
// Status XevieSendEvent (Display* display, XEvent* event, int data_type);
int XevieSendEvent (Display display, XEvent event, int data_type);
// Status XevieSelectInput (Display* display, NativeLong event_mask);
int XevieSelectInput (Display display, NativeLong event_mask);
}
/** Definition of the XTest library. */
interface XTest extends Library {
XTest INSTANCE = (XTest)Native.loadLibrary("Xtst", XTest.class);///usr/lib/libxcb-xtest.so.0
boolean XTestQueryExtension(Display display, IntByReference event_basep, IntByReference error_basep, IntByReference majorp, IntByReference minorp);
boolean XTestCompareCursorWithWindow(Display display, Window window, Cursor cursor);
boolean XTestCompareCurrentCursorWithWindow(Display display, Window window);
// extern int XTestFakeKeyEvent(Display* display, unsigned int keycode, Bool is_press, unsigned long delay);
int XTestFakeKeyEvent(Display display, int keycode, boolean is_press, NativeLong delay);
int XTestFakeButtonEvent(Display display, int button, boolean is_press, NativeLong delay);
int XTestFakeMotionEvent(Display display, int screen, int x, int y, NativeLong delay);
int XTestFakeRelativeMotionEvent(Display display, int x, int y, NativeLong delay);
int XTestFakeDeviceKeyEvent(Display display, XDeviceByReference dev, int keycode, boolean is_press, IntByReference axes, int n_axes, NativeLong delay);
int XTestFakeDeviceButtonEvent(Display display, XDeviceByReference dev, int button, boolean is_press, IntByReference axes, int n_axes, NativeLong delay);
int XTestFakeProximityEvent(Display display, XDeviceByReference dev, boolean in_prox, IntByReference axes, int n_axes, NativeLong delay);
int XTestFakeDeviceMotionEvent(Display display, XDeviceByReference dev, boolean is_relative, int first_axis, IntByReference axes, int n_axes, NativeLong delay);
int XTestGrabControl(Display display, boolean impervious);
//void XTestSetGContextOfGC(GC gc, GContext gid);
void XTestSetVisualIDOfVisual(Visual visual, VisualID visualid);
int XTestDiscard(Display display);
}
class XInputClassInfoByReference extends Structure implements Structure.ByReference {
public byte input_class;
public byte event_type_base;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "input_class", "event_type_base" });
}
}
class XDeviceByReference extends Structure implements Structure.ByReference {
public XID device_id;
public int num_classes;
public XInputClassInfoByReference classes;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "device_id", "num_classes", "classes" });
}
}
X11 INSTANCE = (X11)Native.loadLibrary("X11", X11.class);
/*
typedef struct {
long flags; // marks which fields in this structure are defined
Bool input; // does this application rely on the window manager to
// get keyboard input?
int initial_state; // see below
Pixmap icon_pixmap; // pixmap to be used as icon
Window icon_window; // window to be used as icon
int icon_x, icon_y; // initial position of icon
Pixmap icon_mask; // icon mask bitmap
XID window_group; // id of related window group
// this structure may be extended in the future
} XWMHints;
*/
class XWMHints extends Structure {
public NativeLong flags;
public boolean input;
public int initial_state;
public Pixmap icon_pixmap;
public Window icon_window;
public int icon_x, icon_y;
public Pixmap icon_mask;
public XID window_group;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "flags", "input", "initial_state", "icon_pixmap", "icon_window", "icon_x", "icon_y", "icon_mask", "window_group" });
}
}
/*
typedef struct {
unsigned char *value; // same as Property routines
Atom encoding; // prop type
int format; // prop data format: 8, 16, or 32
unsigned long nitems; // number of data items in value
} XTextProperty;
*/
class XTextProperty extends Structure {
public String value;
public Atom encoding;
public int format;
public NativeLong nitems;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "value", "encoding", "format", "nitems" });
}
}
/*
typedef struct {
long flags; // marks which fields in this structure are defined
int x, y; // obsolete for new window mgrs, but clients
int width, height; /// should set so old wm's don't mess up
int min_width, min_height;
int max_width, max_height;
int width_inc, height_inc;
struct {
int x; // numerator
int y; // denominator
} min_aspect, max_aspect;
int base_width, base_height; // added by ICCCM version 1
int win_gravity; // added by ICCCM version 1
} XSizeHints;
*/
class XSizeHints extends Structure {
public NativeLong flags;
public int x, y;
public int width, height;
public int min_width, min_height;
public int max_width, max_height;
public int width_inc, height_inc;
public static class Aspect extends Structure {
public int x; // numerator
public int y; // denominator
protected List getFieldOrder() {
return Arrays.asList(new String[] { "x", "y" }); }
}
public Aspect min_aspect, max_aspect;
public int base_width, base_height;
public int win_gravity;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "flags", "x", "y", "width", "height", "min_width", "min_height", "max_width", "max_height", "width_inc", "height_inc", "min_aspect", "max_aspect", "base_width", "base_height", "win_gravity" }); }
}
/*
typedef struct {
int x, y; // location of window
int width, height; // width and height of window
int border_width; // border width of window
int depth; // depth of window
Visual *visual; // the associated visual structure
Window root; // root of screen containing window
#if defined(__cplusplus) || defined(c_plusplus)
int c_class; // C++ InputOutput, InputOnly
#else
int class; // InputOutput, InputOnly
#endif
int bit_gravity; // one of bit gravity values
int win_gravity; // one of the window gravity values
int backing_store; // NotUseful, WhenMapped, Always
unsigned long backing_planes;// planes to be preserved if possible
unsigned long backing_pixel;// value to be used when restoring planes
Bool save_under; // boolean, should bits under be saved?
Colormap colormap; // color map to be associated with window
Bool map_installed; // boolean, is color map currently installed
int map_state; // IsUnmapped, IsUnviewable, IsViewable
long all_event_masks; // set of events all people have interest in
long your_event_mask; // my event mask
long do_not_propagate_mask; // set of events that should not propagate
Bool override_redirect; // boolean value for override-redirect
Screen *screen; // back pointer to correct screen
} XWindowAttributes;
*/
class XWindowAttributes extends Structure {
public int x, y;
public int width, height;
public int border_width;
public int depth;
public Visual visual;
public Window root;
public int c_class;
public int bit_gravity;
public int win_gravity;
public int backing_store;
public NativeLong backing_planes;
public NativeLong backing_pixel;
public boolean save_under;
public Colormap colormap;
public boolean map_installed;
public int map_state;
public NativeLong all_event_masks;
public NativeLong your_event_mask;
public NativeLong do_not_propagate_mask;
public boolean override_redirect;
public Screen screen;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "x", "y", "width", "height", "border_width", "depth", "visual", "root", "c_class", "bit_gravity", "win_gravity", "backing_store", "backing_planes", "backing_pixel", "save_under", "colormap", "map_installed", "map_state", "all_event_masks", "your_event_mask", "do_not_propagate_mask", "override_redirect", "screen" });
}
}
/*
typedef struct {
Pixmap background_pixmap; // background or None or ParentRelative
unsigned long background_pixel; // background pixel
Pixmap border_pixmap; // border of the window
unsigned long border_pixel; // border pixel value
int bit_gravity; // one of bit gravity values
int win_gravity; // one of the window gravity values
int backing_store; // NotUseful, WhenMapped, Always
unsigned long backing_planes;// planes to be preseved if possible
unsigned long backing_pixel;// value to use in restoring planes
Bool save_under; // should bits under be saved? (popups)
long event_mask; // set of events that should be saved
long do_not_propagate_mask; // set of events that should not propagate
Bool override_redirect; // boolean value for override-redirect
Colormap colormap; // color map to be associated with window
Cursor cursor; // cursor to be displayed (or None)
} XSetWindowAttributes;
*/
class XSetWindowAttributes extends Structure {
public Pixmap background_pixmap;
public NativeLong background_pixel;
public Pixmap border_pixmap;
public NativeLong border_pixel;
public int bit_gravity;
public int win_gravity;
public int backing_store;
public NativeLong backing_planes;
public NativeLong backing_pixel;
public boolean save_under;
public NativeLong event_mask;
public NativeLong do_not_propagate_mask;
public boolean override_redirect;
public Colormap colormap;
public Cursor cursor;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "background_pixmap", "background_pixel", "border_pixmap", "border_pixel", "bit_gravity", "win_gravity", "backing_store", "backing_planes", "backing_pixel", "save_under", "event_mask", "do_not_propagate_mask", "override_redirect", "colormap", "cursor" });
}
}
int XK_0 = 0x30;
int XK_9 = 0x39;
int XK_A = 0x41;
int XK_Z = 0x5a;
int XK_a = 0x61;
int XK_z = 0x7a;
int XK_Shift_L = 0xffe1;
int XK_Shift_R = 0xffe1;
int XK_Control_L = 0xffe3;
int XK_Control_R = 0xffe4;
int XK_CapsLock = 0xffe5;
int XK_ShiftLock = 0xffe6;
int XK_Meta_L = 0xffe7;
int XK_Meta_R = 0xffe8;
int XK_Alt_L = 0xffe9;
int XK_Alt_R = 0xffea;
int VisualNoMask = 0x0;
int VisualIDMask = 0x1;
int VisualScreenMask = 0x2;
int VisualDepthMask = 0x4;
int VisualClassMask = 0x8;
int VisualRedMaskMask = 0x10;
int VisualGreenMaskMask = 0x20;
int VisualBlueMaskMask = 0x40;
int VisualColormapSizeMask = 0x80;
int VisualBitsPerRGBMask = 0x100;
int VisualAllMask = 0x1FF;
class XVisualInfo extends Structure {
public Visual visual;
public VisualID visualid;
public int screen;
public int depth;
public int c_class;
public NativeLong red_mask;
public NativeLong green_mask;
public NativeLong blue_mask;
public int colormap_size;
public int bits_per_rgb;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "visual", "visualid", "screen", "depth", "c_class", "red_mask", "green_mask", "blue_mask", "colormap_size", "bits_per_rgb" });
}
}
class XPoint extends Structure {
public short x, y;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "x", "y" });
}
public XPoint() { this((short)0, (short)0); }
public XPoint(short x, short y) {
this.x = x;
this.y = y;
}
}
class XRectangle extends Structure {
public short x, y;
public short width, height;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "x", "y", "width", "height" });
}
public XRectangle() { this((short)0, (short)0, (short)0, (short)0); }
public XRectangle(short x, short y, short width, short height) {
this.x = x; this.y = y;
this.width = width; this.height = height;
}
}
Atom XA_PRIMARY = new Atom(1);
Atom XA_SECONDARY = new Atom(2);
Atom XA_ARC = new Atom(3);
Atom XA_ATOM = new Atom(4);
Atom XA_BITMAP = new Atom(5);
Atom XA_CARDINAL = new Atom(6);
Atom XA_COLORMAP = new Atom(7);
Atom XA_CURSOR = new Atom(8);
Atom XA_CUT_BUFFER0 = new Atom(9);
Atom XA_CUT_BUFFER1 = new Atom(10);
Atom XA_CUT_BUFFER2 = new Atom(11);
Atom XA_CUT_BUFFER3 = new Atom(12);
Atom XA_CUT_BUFFER4 = new Atom(13);
Atom XA_CUT_BUFFER5 = new Atom(14);
Atom XA_CUT_BUFFER6 = new Atom(15);
Atom XA_CUT_BUFFER7 = new Atom(16);
Atom XA_DRAWABLE = new Atom(17);
Atom XA_FONT = new Atom(18);
Atom XA_INTEGER = new Atom(19);
Atom XA_PIXMAP = new Atom(20);
Atom XA_POINT = new Atom(21);
Atom XA_RECTANGLE = new Atom(22);
Atom XA_RESOURCE_MANAGER = new Atom(23);
Atom XA_RGB_COLOR_MAP = new Atom(24);
Atom XA_RGB_BEST_MAP = new Atom(25);
Atom XA_RGB_BLUE_MAP = new Atom(26);
Atom XA_RGB_DEFAULT_MAP = new Atom(27);
Atom XA_RGB_GRAY_MAP = new Atom(28);
Atom XA_RGB_GREEN_MAP = new Atom(29);
Atom XA_RGB_RED_MAP = new Atom(30);
Atom XA_STRING = new Atom(31);
Atom XA_VISUALID = new Atom(32);
Atom XA_WINDOW = new Atom(33);
Atom XA_WM_COMMAND = new Atom(34);
Atom XA_WM_HINTS = new Atom(35);
Atom XA_WM_CLIENT_MACHINE = new Atom(36);
Atom XA_WM_ICON_NAME = new Atom(37);
Atom XA_WM_ICON_SIZE = new Atom(38);
Atom XA_WM_NAME = new Atom(39);
Atom XA_WM_NORMAL_HINTS = new Atom(40);
Atom XA_WM_SIZE_HINTS = new Atom(41);
Atom XA_WM_ZOOM_HINTS = new Atom(42);
Atom XA_MIN_SPACE = new Atom(43);
Atom XA_NORM_SPACE = new Atom(44);
Atom XA_MAX_SPACE = new Atom(45);
Atom XA_END_SPACE = new Atom(46);
Atom XA_SUPERSCRIPT_X = new Atom(47);
Atom XA_SUPERSCRIPT_Y = new Atom(48);
Atom XA_SUBSCRIPT_X = new Atom(49);
Atom XA_SUBSCRIPT_Y = new Atom(50);
Atom XA_UNDERLINE_POSITION = new Atom(51);
Atom XA_UNDERLINE_THICKNESS = new Atom(52);
Atom XA_STRIKEOUT_ASCENT = new Atom(53);
Atom XA_STRIKEOUT_DESCENT = new Atom(54);
Atom XA_ITALIC_ANGLE = new Atom(55);
Atom XA_X_HEIGHT = new Atom(56);
Atom XA_QUAD_WIDTH = new Atom(57);
Atom XA_WEIGHT = new Atom(58);
Atom XA_POINT_SIZE = new Atom(59);
Atom XA_RESOLUTION = new Atom(60);
Atom XA_COPYRIGHT = new Atom(61);
Atom XA_NOTICE = new Atom(62);
Atom XA_FONT_NAME = new Atom(63);
Atom XA_FAMILY_NAME = new Atom(64);
Atom XA_FULL_NAME = new Atom(65);
Atom XA_CAP_HEIGHT = new Atom(66);
Atom XA_WM_CLASS = new Atom(67);
Atom XA_WM_TRANSIENT_FOR = new Atom(68);
Atom XA_LAST_PREDEFINED = XA_WM_TRANSIENT_FOR;
Display XOpenDisplay(String name);
int XGetErrorText(Display display, int code, byte[] buffer, int len);
int XDefaultScreen(Display display);
Screen DefaultScreenOfDisplay(Display display);
Visual XDefaultVisual(Display display, int screen);
Colormap XDefaultColormap(Display display, int screen);
int XDisplayWidth(Display display, int screen);
int XDisplayHeight(Display display, int screen);
Window XDefaultRootWindow(Display display);
Window XRootWindow(Display display, int screen);
int XAllocNamedColor(Display display, int colormap, String color_name,
Pointer screen_def_return, Pointer exact_def_return);
XSizeHints XAllocSizeHints();
void XSetWMProperties(Display display, Window window, String window_name,
String icon_name, String[] argv, int argc,
XSizeHints normal_hints, Pointer wm_hints,
Pointer class_hints);
int XFree(Pointer data);
Window XCreateSimpleWindow(Display display, Window parent, int x, int y,
int width, int height, int border_width,
int border, int background);
Pixmap XCreateBitmapFromData(Display display, Window window, Pointer data,
int width, int height);
int XMapWindow(Display display, Window window);
int XMapRaised(Display display, Window window);
int XMapSubwindows(Display display, Window window);
/** Flushes the output buffer. Most client applications need not use this function because the output buffer is automatically flushed as needed by calls to XPending, XNextEvent, and XWindowEvent. Events generated by the server may be enqueued into the library's event queue. */
int XFlush(Display display);
/** Flushes the output buffer and then waits until all requests have been received and processed by the X server. Any errors generated must be handled by the error handler. For each protocol error received by Xlib, XSync calls the client application's error handling routine (see section 11.8.2). Any events generated by the server are enqueued into the library's event queue.<br/>Finally, if you passed False, XSync does not discard the events in the queue. If you passed True, XSync discards all events in the queue, including those events that were on the queue before XSync was called. Client applications seldom need to call XSync. */
int XSync(Display display, boolean discard);
/** If mode is QueuedAlready, XEventsQueued returns the number of events already in the event queue (and never performs a system call). If mode is QueuedAfterFlush, XEventsQueued returns the number of events already in the queue if the number is nonzero. If there are no events in the queue, XEventsQueued flushes the output buffer, attempts to read more events out of the application's connection, and returns the number read. If mode is QueuedAfterReading, XEventsQueued returns the number of events already in the queue if the number is nonzero. If there are no events in the queue, XEventsQueued attempts to read more events out of the application's connection without flushing the output buffer and returns the number read.<br/>XEventsQueued always returns immediately without I/O if there are events already in the queue. XEventsQueued with mode QueuedAfterFlush is identical in behavior to XPending. XEventsQueued with mode QueuedAlready is identical to the XQLength function. */
int XEventsQueued(Display display, int mode);
/** Returns the number of events that have been received from the X server but have not been removed from the event queue. XPending is identical to XEventsQueued with the mode QueuedAfterFlush specified. */
int XPending(Display display);
int XUnmapWindow(Display display, Window window);
int XDestroyWindow(Display display, Window window);
int XCloseDisplay(Display display);
int XClearWindow(Display display, Window window);
int XClearArea(Display display, Window window, int x, int y, int w, int h, int exposures);
Pixmap XCreatePixmap(Display display, Drawable drawable, int width, int height, int depth);
int XFreePixmap(Display display, Pixmap pixmap);
class XGCValues extends Structure {
public int function; /* logical operation */
public NativeLong plane_mask;/* plane mask */
public NativeLong foreground;/* foreground pixel */
public NativeLong background;/* background pixel */
public int line_width; /* line width (in pixels) */
public int line_style; /* LineSolid, LineOnOffDash, LineDoubleDash*/
public int cap_style; /* CapNotLast, CapButt, CapRound, CapProjecting */
public int join_style; /* JoinMiter, JoinRound, JoinBevel */
public int fill_style; /* FillSolid, FillTiled, FillStippled FillOpaqueStippled*/
public int fill_rule; /* EvenOddRule, WindingRule */
public int arc_mode; /* ArcChord, ArcPieSlice */
public Pixmap tile; /* tile pixmap for tiling operations */
public Pixmap stipple; /* stipple 1 plane pixmap for stippling */
public int ts_x_origin; /* offset for tile or stipple operations */
public int ts_y_origin;
public Font font; /* default text font for text operations */
public int subwindow_mode; /* ClipByChildren, IncludeInferiors */
public boolean graphics_exposures; /* boolean, should exposures be generated */
public int clip_x_origin; /* origin for clipping */
public int clip_y_origin;
public Pixmap clip_mask; /* bitmap clipping; other calls for rects */
public int dash_offset; /* patterned/dashed line information */
public byte dashes;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "function", "plane_mask", "foreground", "background", "line_width", "line_style", "cap_style", "join_style", "fill_style", "fill_rule", "arc_mode", "tile", "stipple", "ts_x_origin", "ts_y_origin", "font", "subwindow_mode", "graphics_exposures", "clip_x_origin", "clip_y_origin", "clip_mask", "dash_offset", "dashes" });
}
}
GC XCreateGC(Display display, Drawable drawable, NativeLong mask, XGCValues values);
int XSetFillRule(Display display, GC gc, int fill_rule);
int XFreeGC(Display display, GC gc);
int XDrawPoint(Display display, Drawable drawable, GC gc, int x, int y);
int XDrawPoints(Display display, Drawable drawable, GC gc,
XPoint[] points, int npoints, int mode);
int XFillRectangle(Display display, Drawable drawable, GC gc,
int x, int y, int width, int height);
int XFillRectangles(Display display, Drawable drawable, GC gc,
XRectangle[] rectangles, int nrectangles);
int XSetForeground(Display display, GC gc, NativeLong color);
int XSetBackground(Display display, GC gc, NativeLong color);
int XFillArc(Display display, Drawable drawable, GC gc, int x, int y,
int width, int height, int angle1, int angle2);
int XFillPolygon(Display dpy, Drawable drawable, GC gc, XPoint[] points,
int npoints, int shape, int mode);
int XQueryTree(Display display, Window window, WindowByReference root,
WindowByReference parent, PointerByReference children,
IntByReference childCount);
boolean XQueryPointer(Display display, Window window,
WindowByReference root_return,
WindowByReference child_return,
IntByReference root_x_return,
IntByReference root_y_return,
IntByReference win_x_return,
IntByReference win_y_return,
IntByReference mask_return);
int XGetWindowAttributes(Display display, Window window, XWindowAttributes attributes);
int XChangeWindowAttributes(Display display, Window window, NativeLong valuemask, XSetWindowAttributes attributes);
// Status XGetGeometry(Display *display, Drawable d, Window *root_return, int *x_return, int *y_return, unsigned int *width_return,
// unsigned int *height_return, unsigned int *border_width_return, unsigned int *depth_return);
int XGetGeometry(Display display, Drawable d, WindowByReference w, IntByReference x, IntByReference y, IntByReference width,
IntByReference heigth, IntByReference border_width, IntByReference depth);
// Bool XTranslateCoordinates(Display *display, Window src_w, dest_w, int src_x, int src_y,
// int *dest_x_return, int *dest_y_return, Window *child_return);
boolean XTranslateCoordinates(Display display, Window src_w, Window dest_w, int src_x, int src_y,
IntByReference dest_x_return, IntByReference dest_y_return, WindowByReference child_return);
int None = 0; /* universal null resource or null atom */
int ParentRelative = 1; /* background pixmap in CreateWindow and ChangeWindowAttributes */
int CopyFromParent = 0; /* border pixmap in CreateWindow
and ChangeWindowAttributes
special VisualID and special window
class passed to CreateWindow */
int PointerWindow = 0; /* destination window in SendEvent */
int InputFocus = 1; /* destination window in SendEvent */
int PointerRoot = 1; /* focus window in SetInputFocus */
int AnyPropertyType = 0; /* special Atom, passed to GetProperty */
int AnyKey = 0; /* special Key Code, passed to GrabKey */
int AnyButton = 0; /* special Button Code, passed to GrabButton */
int AllTemporary = 0; /* special Resource ID passed to KillClient */
int CurrentTime = 0; /* special Time */
int NoSymbol = 0; /* special KeySym */
/* Input Event Masks. Used as event-mask window attribute and as arguments
to Grab requests. Not to be confused with event names. */
int NoEventMask = 0;
int KeyPressMask = (1<<0);
int KeyReleaseMask = (1<<1);
int ButtonPressMask = (1<<2);
int ButtonReleaseMask = (1<<3);
int EnterWindowMask = (1<<4);
int LeaveWindowMask = (1<<5);
int PointerMotionMask = (1<<6);
int PointerMotionHintMask = (1<<7);
int Button1MotionMask = (1<<8);
int Button2MotionMask = (1<<9);
int Button3MotionMask = (1<<10);
int Button4MotionMask = (1<<11);
int Button5MotionMask = (1<<12);
int ButtonMotionMask = (1<<13);
int KeymapStateMask = (1<<14);
int ExposureMask = (1<<15);
int VisibilityChangeMask = (1<<16);
int StructureNotifyMask = (1<<17);
int ResizeRedirectMask = (1<<18);
int SubstructureNotifyMask = (1<<19);
int SubstructureRedirectMask = (1<<20);
int FocusChangeMask = (1<<21);
int PropertyChangeMask = (1<<22);
int ColormapChangeMask = (1<<23);
int OwnerGrabButtonMask = (1<<24);
/* Event names. Used in "type" field in XEvent structures. Not to be
confused with event masks above. They start from 2 because 0 and 1
are reserved in the protocol for errors and replies. */
int KeyPress = 2;
int KeyRelease = 3;
int ButtonPress = 4;
int ButtonRelease = 5;
int MotionNotify = 6;
int EnterNotify = 7;
int LeaveNotify = 8;
int FocusIn = 9;
int FocusOut = 10;
int KeymapNotify = 11;
int Expose = 12;
int GraphicsExpose = 13;
int NoExpose = 14;
int VisibilityNotify = 15;
int CreateNotify = 16;
int DestroyNotify = 17;
int UnmapNotify = 18;
int MapNotify = 19;
int MapRequest = 20;
int ReparentNotify = 21;
int ConfigureNotify = 22;
int ConfigureRequest = 23;
int GravityNotify = 24;
int ResizeRequest = 25;
int CirculateNotify = 26;
int CirculateRequest = 27;
int PropertyNotify = 28;
int SelectionClear = 29;
int SelectionRequest = 30;
int SelectionNotify = 31;
int ColormapNotify = 32;
int ClientMessage = 33;
int MappingNotify = 34;
int LASTEvent = 35; // must be bigger than any event
/* Key masks. Used as modifiers to GrabButton and GrabKey, results of QueryPointer,
state in various key-, mouse-, and button-related events. */
int ShiftMask = (1 << 0);
int LockMask = (1 << 1);
int ControlMask = (1 << 2);
int Mod1Mask = (1 << 3);
int Mod2Mask = (1 << 4);
int Mod3Mask = (1 << 5);
int Mod4Mask = (1 << 6);
int Mod5Mask = (1 << 7);
/* modifier names. Used to build a SetModifierMapping request or
to read a GetModifierMapping request. These correspond to the
masks defined above. */
int ShiftMapIndex = 0;
int LockMapIndex = 1;
int ControlMapIndex = 2;
int Mod1MapIndex = 3;
int Mod2MapIndex = 4;
int Mod3MapIndex = 5;
int Mod4MapIndex = 6;
int Mod5MapIndex = 7;
/* button masks. Used in same manner as Key masks above. Not to be confused
with button names below. */
int Button1Mask = (1 << 8);
int Button2Mask = (1 << 9);
int Button3Mask = (1 << 10);
int Button4Mask = (1 << 11);
int Button5Mask = (1 << 12);
int AnyModifier = (1 << 15); /* used in GrabButton, GrabKey */
/* button names. Used as arguments to GrabButton and as detail in ButtonPress
and ButtonRelease events. Not to be confused with button masks above.
Note that 0 is already defined above as "AnyButton". */
int Button1 = 1;
int Button2 = 2;
int Button3 = 3;
int Button4 = 4;
int Button5 = 5;
/* Notify modes */
int NotifyNormal = 0;
int NotifyGrab = 1;
int NotifyUngrab = 2;
int NotifyWhileGrabbed = 3;
int NotifyHint = 1; /* for MotionNotify events */
/* Notify detail */
int NotifyAncestor = 0;
int NotifyVirtual = 1;
int NotifyInferior = 2;
int NotifyNonlinear = 3;
int NotifyNonlinearVirtual = 4;
int NotifyPointer = 5;
int NotifyPointerRoot = 6;
int NotifyDetailNone = 7;
/* Visibility notify */
int VisibilityUnobscured = 0;
int VisibilityPartiallyObscured = 1;
int VisibilityFullyObscured = 2;
/* Circulation request */
int PlaceOnTop = 0;
int PlaceOnBottom = 1;
/* protocol families */
int FamilyInternet = 0; /* IPv4 */
int FamilyDECnet = 1;
int FamilyChaos = 2;
int FamilyInternet6 = 6; /* IPv6 */
/* authentication families not tied to a specific protocol */
int FamilyServerInterpreted = 5;
/* Property notification */
int PropertyNewValue = 0;
int PropertyDelete = 1;
/* Color Map notification */
int ColormapUninstalled = 0;
int ColormapInstalled = 1;
/* GrabPointer, GrabButton, GrabKeyboard, GrabKey Modes */
int GrabModeSync = 0;
int GrabModeAsync = 1;
/* GrabPointer, GrabKeyboard reply status */
int GrabSuccess = 0;
int AlreadyGrabbed = 1;
int GrabInvalidTime = 2;
int GrabNotViewable = 3;
int GrabFrozen = 4;
/* AllowEvents modes */
int AsyncPointer = 0;
int SyncPointer = 1;
int ReplayPointer = 2;
int AsyncKeyboard = 3;
int SyncKeyboard = 4;
int ReplayKeyboard = 5;
int AsyncBoth = 6;
int SyncBoth = 7;
/* Used in SetInputFocus, GetInputFocus */
int RevertToNone = None;
int RevertToPointerRoot = PointerRoot;
int RevertToParent = 2;
int Success = 0; /* everything's okay */
int BadRequest = 1; /* bad request code */
int BadValue = 2; /* int parameter out of range */
int BadWindow = 3; /* parameter not a Window */
int BadPixmap = 4; /* parameter not a Pixmap */
int BadAtom = 5; /* parameter not an Atom */
int BadCursor = 6; /* parameter not a Cursor */
int BadFont = 7; /* parameter not a Font */
int BadMatch = 8; /* parameter mismatch */
int BadDrawable = 9; /* parameter not a Pixmap or Window */
int BadAlloc = 11; /* insufficient resources */
int BadColor = 12; /* no such colormap */
int BadGC = 13; /* parameter not a GC */
int BadIDChoice = 14; /* choice not in range or already used */
int BadName = 15; /* font or color name doesn't exist */
int BadLength = 16; /* Request length incorrect */
int BadImplementation = 17; /* server is defective */
int FirstExtensionError = 128;
int LastExtensionError = 255;
/* Window classes used by CreateWindow */
/* Note that CopyFromParent is already defined as 0 above */
int InputOutput = 1;
int InputOnly = 2;
/* Window attributes for CreateWindow and ChangeWindowAttributes */
int CWBackPixmap = (1<<0);
int CWBackPixel = (1<<1);
int CWBorderPixmap = (1<<2);
int CWBorderPixel = (1<<3);
int CWBitGravity = (1<<4);
int CWWinGravity = (1<<5);
int CWBackingStore = (1<<6);
int CWBackingPlanes = (1<<7);
int CWBackingPixel = (1<<8);
int CWOverrideRedirect = (1<<9);
int CWSaveUnder = (1<<10);
int CWEventMask = (1<<11);
int CWDontPropagate = (1<<12);
int CWColormap = (1<<13);
int CWCursor = (1<<14);
/* ConfigureWindow structure */
int CWX = (1<<0);
int CWY = (1<<1);
int CWWidth = (1<<2);
int CWHeight = (1<<3);
int CWBorderWidth = (1<<4);
int CWSibling = (1<<5);
int CWStackMode = (1<<6);
/* Bit Gravity */
int ForgetGravity = 0;
int NorthWestGravity = 1;
int NorthGravity = 2;
int NorthEastGravity = 3;
int WestGravity = 4;
int CenterGravity = 5;
int EastGravity = 6;
int SouthWestGravity = 7;
int SouthGravity = 8;
int SouthEastGravity = 9;
int StaticGravity = 10;
/* Window gravity + bit gravity above */
int UnmapGravity = 0;
/* Used in CreateWindow for backing-store hint */
int NotUseful = 0;
int WhenMapped = 1;
int Always = 2;
/* Used in GetWindowAttributes reply */
int IsUnmapped = 0;
int IsUnviewable = 1;
int IsViewable = 2;
/* Used in ChangeSaveSet */
int SetModeInsert = 0;
int SetModeDelete = 1;
/* Used in ChangeCloseDownMode */
int DestroyAll = 0;
int RetainPermanent = 1;
int RetainTemporary = 2;
/* Window stacking method (in configureWindow) */
int Above = 0;
int Below = 1;
int TopIf = 2;
int BottomIf = 3;
int Opposite = 4;
/* Circulation direction */
int RaiseLowest = 0;
int LowerHighest = 1;
/* Property modes */
int PropModeReplace = 0;
int PropModePrepend = 1;
int PropModeAppend = 2;
/* graphics functions, as in GC.alu */
int GXclear = 0x0;
int GXand = 0x1; /* src AND dst */
int GXandReverse = 0x2; /* src AND NOT dst */
int GXcopy = 0x3; /* src */
int GXandInverted = 0x4; /* NOT src AND dst */
int GXnoop = 0x5; /* dst */
int GXxor = 0x6; /* src XOR dst */
int GXor = 0x7; /* src OR dst */
int GXnor = 0x8; /* NOT src AND NOT dst */
int GXequiv = 0x9; /* NOT src XOR dst */
int GXinvert = 0xa; /* NOT dst */
int GXorReverse = 0xb; /* src OR NOT dst */
int GXcopyInverted = 0xc; /* NOT src */
int GXorInverted = 0xd; /* NOT src OR dst */
int GXnand = 0xe; /* NOT src OR NOT dst */
int GXset = 0xf;
/* LineStyle */
int LineSolid = 0;
int LineOnOffDash = 1;
int LineDoubleDash = 2;
/* capStyle */
int CapNotLast = 0;
int CapButt = 1;
int CapRound = 2;
int CapProjecting = 3;
/* joinStyle */
int JoinMiter = 0;
int JoinRound = 1;
int JoinBevel = 2;
/* fillStyle */
int FillSolid = 0;
int FillTiled = 1;
int FillStippled = 2;
int FillOpaqueStippled = 3;
/* fillRule */
int EvenOddRule = 0;
int WindingRule = 1;
/* subwindow mode */
int ClipByChildren = 0;
int IncludeInferiors = 1;
/* SetClipRectangles ordering */
int Unsorted = 0;
int YSorted = 1;
int YXSorted = 2;
int YXBanded = 3;
/* CoordinateMode for drawing routines */
int CoordModeOrigin = 0; /* relative to the origin */
int CoordModePrevious = 1; /* relative to previous point */
/* Polygon shapes */
int Complex = 0; /* paths may intersect */
int Nonconvex = 1; /* no paths intersect, but not convex */
int Convex = 2; /* wholly convex */
/* Arc modes for PolyFillArc */
int ArcChord = 0; /* join endpoints of arc */
int ArcPieSlice = 1; /* join endpoints to center of arc */
/* GC components: masks used in CreateGC, CopyGC, ChangeGC, OR'ed into
GC.stateChanges */
int GCFunction = (1<<0);
int GCPlaneMask = (1<<1);
int GCForeground = (1<<2);
int GCBackground = (1<<3);
int GCLineWidth = (1<<4);
int GCLineStyle = (1<<5);
int GCCapStyle = (1<<6);
int GCJoinStyle = (1<<7);
int GCFillStyle = (1<<8);
int GCFillRule = (1<<9);
int GCTile = (1<<10);
int GCStipple = (1<<11);
int GCTileStipXOrigin = (1<<12);
int GCTileStipYOrigin = (1<<13);
int GCFont = (1<<14);
int GCSubwindowMode = (1<<15);
int GCGraphicsExposures = (1<<16);
int GCClipXOrigin = (1<<17);
int GCClipYOrigin = (1<<18);
int GCClipMask = (1<<19);
int GCDashOffset = (1<<20);
int GCDashList = (1<<21);
int GCArcMode = (1<<22);
int GCLastBit = 22;
/* used in QueryFont -- draw direction */
int FontLeftToRight = 0;
int FontRightToLeft = 1;
int FontChange = 255;
/* ImageFormat -- PutImage, GetImage */
int XYBitmap = 0; /* depth 1, XYFormat */
int XYPixmap = 1; /* depth == drawable depth */
int ZPixmap = 2; /* depth == drawable depth */
/* For CreateColormap */
int AllocNone = 0; /* create map with no entries */
int AllocAll = 1; /* allocate entire map writeable */
/* Flags used in StoreNamedColor, StoreColors */
int DoRed = (1<<0);
int DoGreen = (1<<1);
int DoBlue = (1<<2);
/* QueryBestSize Class */
int CursorShape = 0; /* largest size that can be displayed */
int TileShape = 1; /* size tiled fastest */
int StippleShape = 2; /* size stippled fastest */
int AutoRepeatModeOff = 0;
int AutoRepeatModeOn = 1;
int AutoRepeatModeDefault = 2;
int LedModeOff = 0;
int LedModeOn = 1;
/* masks for ChangeKeyboardControl */
int KBKeyClickPercent = (1<<0);
int KBBellPercent = (1<<1);
int KBBellPitch = (1<<2);
int KBBellDuration = (1<<3);
int KBLed = (1<<4);
int KBLedMode = (1<<5);
int KBKey = (1<<6);
int KBAutoRepeatMode = (1<<7);
int MappingSuccess = 0;
int MappingBusy = 1;
int MappingFailed = 2;
int MappingModifier = 0;
int MappingKeyboard = 1;
int MappingPointer = 2;
int DontPreferBlanking = 0;
int PreferBlanking = 1;
int DefaultBlanking = 2;
int DisableScreenSaver = 0;
int DisableScreenInterval = 0;
int DontAllowExposures = 0;
int AllowExposures = 1;
int DefaultExposures = 2;
/* for ForceScreenSaver */
int ScreenSaverReset = 0;
int ScreenSaverActive = 1;
/* for ChangeHosts */
int HostInsert = 0;
int HostDelete = 1;
/* for ChangeAccessControl */
int EnableAccess = 1;
int DisableAccess = 0;
/* Display classes used in opening the connection
* Note that the statically allocated ones are even numbered and the
* dynamically changeable ones are odd numbered */
int StaticGray = 0;
int GrayScale = 1;
int StaticColor = 2;
int PseudoColor = 3;
int TrueColor = 4;
int DirectColor = 5;
/* Byte order used in imageByteOrder and bitmapBitOrder */
int LSBFirst = 0;
int MSBFirst = 1;
public static class XEvent extends Union {
public int type;
public XAnyEvent xany;
public XKeyEvent xkey;
public XButtonEvent xbutton;
public XMotionEvent xmotion;
public XCrossingEvent xcrossing;
public XFocusChangeEvent xfocus;
public XExposeEvent xexpose;
public XGraphicsExposeEvent xgraphicsexpose;
public XNoExposeEvent xnoexpose;
public XVisibilityEvent xvisibility;
public XCreateWindowEvent xcreatewindow;
public XDestroyWindowEvent xdestroywindow;
public XUnmapEvent xunmap;
public XMapEvent xmap;
public XMapRequestEvent xmaprequest;
public XReparentEvent xreparent;
public XConfigureEvent xconfigure;
public XGravityEvent xgravity;
public XResizeRequestEvent xresizerequest;
public XConfigureRequestEvent xconfigurerequest;
public XCirculateEvent xcirculate;
public XCirculateRequestEvent xcirculaterequest;
public XPropertyEvent xproperty;
public XSelectionClearEvent xselectionclear;
public XSelectionRequestEvent xselectionrequest;
public XSelectionEvent xselection;
public XColormapEvent xcolormap;
public XClientMessageEvent xclient;
public XMappingEvent xmapping;
public XErrorEvent xerror;
public XKeymapEvent xkeymap;
public NativeLong[] pad = new NativeLong[24];
}
public static class XAnyEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window; // window on which event was requested in event mask
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window" });
}
}
class XKeyEvent extends Structure {
public int type; // of event
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // public Display the event was read from
public Window window; // "event" window it is reported relative to
public Window root; // root window that the event occurred on
public Window subwindow; // child window
public NativeLong time; // milliseconds
public int x, y; // pointer x, y coordinates in event window
public int x_root, y_root; // coordinates relative to root
public int state; // key or button mask
public int keycode; // detail
public int same_screen; // same screen flag
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "root", "subwindow", "time", "x", "y", "x_root", "y_root", "state", "keycode", "same_screen" });
}
}
class XButtonEvent extends Structure {
public int type; // of event
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window; // "event" window it is reported relative to
public Window root; // root window that the event occurred on
public Window subwindow; // child window
public NativeLong time; // milliseconds
public int x, y; // pointer x, y coordinates in event window
public int x_root, y_root; // coordinates relative to root
public int state; // key or button mask
public int button; // detail
public int same_screen; // same screen flag
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "root", "subwindow", "time", "x", "y", "x_root", "y_root", "state", "button", "same_screen" });
}
}
class XButtonPressedEvent extends XButtonEvent {
}
class XButtonReleasedEvent extends XButtonEvent {
}
public static class XClientMessageEvent extends Structure {
public int type; // ClientMessage
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window;
public Atom message_type;
public int format;
public Data data;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "message_type", "format", "data" });
}
public static class Data extends Union {
public byte b[] = new byte[20];
public short s[] = new short[10];
public NativeLong[] l = new NativeLong[5];
}
}
class XMotionEvent extends Structure {
public int type; // of event
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window; // "event" window reported relative to
public Window root; // root window that the event occurred on
public Window subwindow; // child window
public NativeLong time; // milliseconds
public int x, y; // pointer x, y coordinates in event window
public int x_root, y_root; // coordinates relative to root
public int state; // key or button mask
public byte is_hint; // detail
public int same_screen; // same screen flag
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "root", "subwindow", "time", "x", "y", "x_root", "y_root", "state", "is_hint", "same_screen" });
}
}
class XPointerMovedEvent extends XMotionEvent {
}
class XCrossingEvent extends Structure {
public int type; // of event
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window; // "event" window reported relative to
public Window root; // root window that the event occurred on
public Window subwindow; // child window
public NativeLong time; // milliseconds
public int x, y; // pointer x, y coordinates in event window
public int x_root, y_root; // coordinates relative to root
public int mode; // NotifyNormal, NotifyGrab, NotifyUngrab
public int detail;
/*
* NotifyAncestor, NotifyVirtual, NotifyInferior,
* NotifyNonlinear,NotifyNonlinearVirtual
*/
public int same_screen; // same screen flag
public int focus; // boolean focus
public int state; // key or button mask
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "root", "subwindow", "time", "x", "y", "x_root", "y_root", "mode", "detail", "same_screen", "focus", "state" });
}
}
class XEnterWindowEvent extends XCrossingEvent {
}
class XLeaveWindowEvent extends XCrossingEvent {
}
class XFocusChangeEvent extends Structure {
public int type; // FocusIn or FocusOut
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window; // window of event
public int mode; // NotifyNormal, NotifyWhileGrabbed, NotifyGrab, NotifyUngrab
public int detail;
/*
* NotifyAncestor, NotifyVirtual, NotifyInferior,
* NotifyNonlinear,NotifyNonlinearVirtual, NotifyPointer,
* NotifyPointerRoot, NotifyDetailNone
*/
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "mode", "detail" });
}
}
class XFocusInEvent extends XFocusChangeEvent {
}
class XFocusOutEvent extends XFocusChangeEvent {
}
class XExposeEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window;
public int x, y;
public int width, height;
public int count; // if non-zero, at least this many more
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "x", "y", "width", "height", "count" });
}
}
class XGraphicsExposeEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Drawable drawable;
public int x, y;
public int width, height;
public int count; // if non-zero, at least this many more
public int major_code; // core is CopyArea or CopyPlane
public int minor_code; // not defined in the core
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "drawable", "x", "y", "width", "height", "count", "major_code", "minor_code" });
}
}
class XNoExposeEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Drawable drawable;
public int major_code; // core is CopyArea or CopyPlane
public int minor_code; // not defined in the core
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "drawable", "major_code", "minor_code" });
}
}
class XVisibilityEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window;
public int state; // Visibility state
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "state" });
}
}
class XCreateWindowEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window parent; // parent of the window
public Window window; // window id of window created
public int x, y; // window location
public int width, height; // size of window
public int border_width; // border width
public int override_redirect; // creation should be overridden
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "parent", "window", "x", "y", "width", "height", "border_width", "override_redirect" });
}
}
class XDestroyWindowEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window event;
public Window window;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "event", "window" }); }
}
class XUnmapEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window event;
public Window window;
public int from_configure;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "event", "window", "from_configure" });
}
}
class XMapEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window event;
public Window window;
public int override_redirect; // boolean, is override set...
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "event", "window", "override_redirect" });
}
}
class XMapRequestEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window parent;
public Window window;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "parent", "window" });
}
}
class XReparentEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window event;
public Window window;
public Window parent;
public int x, y;
public int override_redirect;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "event", "window", "parent", "x", "y", "override_redirect" });
}
}
class XConfigureEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window event;
public Window window;
public int x, y;
public int width, height;
public int border_width;
public Window above;
public int override_redirect;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display","event", "window", "x", "y", "width", "height", "border_width", "above", "override_redirect" });
}
}
class XGravityEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window event;
public Window window;
public int x, y;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "event", "window", "x", "y" });
}
}
class XResizeRequestEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window;
public int width, height;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "width", "height" });
}
}
class XConfigureRequestEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window parent;
public Window window;
public int x, y;
public int width, height;
public int border_width;
public Window above;
public int detail; // Above, Below, TopIf, BottomIf, Opposite
public NativeLong value_mask;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "parent", "window", "x", "y", "width", "height", "border_width", "above", "detail", "value_mask" });
}
}
class XCirculateEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window event;
public Window window;
public int place; // PlaceOnTop, PlaceOnBottom
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "event", "window", "place" });
}
}
class XCirculateRequestEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window parent;
public Window window;
public int place; // PlaceOnTop, PlaceOnBottom
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "parent", "window", "place" });
}
}
class XPropertyEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window;
public Atom atom;
public NativeLong time;
public int state; // NewValue, Deleted
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "atom", "time", "state" });
}
}
class XSelectionClearEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window;
public Atom selection;
public NativeLong time;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "selection", "time" });
}
}
class XSelectionRequestEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window owner;
public Window requestor;
public Atom selection;
public Atom target;
public Atom property;
public NativeLong time;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "owner", "requestor", "selection", "target", "property", "time" });
}
}
class XSelectionEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window requestor;
public Atom selection;
public Atom target;
public Atom property; // ATOM or None
public NativeLong time;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "requestor", "selection", "target", "property", "time" });
}
}
class XColormapEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window;
public Colormap colormap; // COLORMAP or None
public int c_new;
public int state; // ColormapInstalled, ColormapUninstalled
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "colormap", "c_new", "state" });
}
}
class XMappingEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window; // unused
public int request; // one of MappingModifier, MappingKeyboard, MappingPointer
public int first_keycode; // first keycode
public int count; // defines range of change w. first_keycode*/
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "request", "first_keycode", "count" });
}
}
class XErrorEvent extends Structure {
public int type;
public Display display; // Display the event was read from
public NativeLong serial; // serial number of failed request
public byte error_code; // error code of failed request
public byte request_code; // Major op-code of failed request
public byte minor_code; // Minor op-code of failed request
public XID resourceid; // resource id
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "display", "serial", "error_code", "request_code", "minor_code", "resourceid" });
}
}
// generated on EnterWindow and FocusIn when KeyMapState selected
class XKeymapEvent extends Structure {
public int type;
public NativeLong serial; // # of last request processed by server
public int send_event; // true if this came from a SendEvent request
public Display display; // Display the event was read from
public Window window;
public byte key_vector[] = new byte[32];
protected List getFieldOrder() {
return Arrays.asList(new String[] { "type", "serial", "send_event", "display", "window", "key_vector" });
}
}
int XSelectInput(Display display, Window window, NativeLong eventMask);
int XSendEvent(Display display, Window w, int propagate, NativeLong event_mask, XEvent event_send);
int XNextEvent(Display display, XEvent event_return);
int XPeekEvent(Display display, XEvent event_return);
int XWindowEvent(Display display, Window w, NativeLong event_mask, XEvent event_return);
boolean XCheckWindowEvent(Display display, Window w, NativeLong event_mask, XEvent event_return);
int XMaskEvent(Display display, NativeLong event_mask, XEvent event_return);
boolean XCheckMaskEvent(Display display, NativeLong event_mask, XEvent event_return);
boolean XCheckTypedEvent(Display display, int event_type, XEvent event_return);
boolean XCheckTypedWindowEvent(Display display, Window w, int event_type, XEvent event_return);
/** Returns an {@link XWMHints} which must be freed by {@link #XFree}. */
XWMHints XGetWMHints(Display display, Window window);
int XGetWMName(Display display, Window window,
XTextProperty text_property_return);
/** Returns an array of {@link XVisualInfo} which must be freed by {@link #XFree}.
* Use {@link XVisualInfo#toArray(int)
* toArray(nitems_return.getValue()} to obtain the array.
*/
XVisualInfo XGetVisualInfo(Display display, NativeLong vinfo_mask,
XVisualInfo vinfo_template,
IntByReference nitems_return);
Colormap XCreateColormap(Display display, Window w, Visual visual, int alloc);
int XGetWindowProperty(Display display, Window w, Atom property,
NativeLong long_offset,
NativeLong long_length, boolean delete,
Atom reg_type,
AtomByReference actual_type_return,
IntByReference actual_format_return,
NativeLongByReference nitems_return,
NativeLongByReference bytes_after_return,
PointerByReference prop_return);
int XChangeProperty(Display display, Window w, Atom property, Atom type,
int format, int mode, Pointer data, int nelements);
int XDeleteProperty(Display display, Window w, Atom property);
// Atom XInternAtom(Display *display, char *atom_name, Bool only_if_exists);
Atom XInternAtom(Display display, String name, boolean only_if_exists);
// char *XGetAtomName(Display *display, Atom atom);
String XGetAtomName(Display display, Atom atom);
int XCopyArea(Display dpy, Drawable src, Drawable dst, GC gc,
int src_x, int src_y, int w, int h, int dst_x, int dst_y);
XImage XCreateImage(Display dpy, Visual visual, int depth, int format,
int offset, Pointer data, int width, int height,
int bitmap_pad, int bytes_per_line);
int XPutImage(Display dpy, Drawable d, GC gc, XImage image,
int src_x, int src_y, int dest_x, int dest_y,
int width, int height);
int XDestroyImage(XImage image);
/**
* Installs an error handler
*
* @param handler Specifies the program's supplied error handler
* @return The previous error handler
*/
XErrorHandler XSetErrorHandler(XErrorHandler handler);
public interface XErrorHandler extends Callback {
public int apply(Display display, XErrorEvent errorEvent);
}
String XKeysymToString(KeySym keysym);
KeySym XStringToKeysym(String string);
byte XKeysymToKeycode(Display display, KeySym keysym);
KeySym XKeycodeToKeysym(Display display, byte keycode, int index);
/**
* Establishes a passive grab on the keyboard
*
* @param display Specifies the connection to the X server.
* @param keyCode Specifies the KeyCode or {@link #AnyKey}.
* @param modifiers Specifies the set of keymasks or {@link #AnyModifier}.
* The mask is the bitwise inclusive OR of the valid keymask bits.
* @param grab_window Specifies the grab window.
* @param ownerEvents Specifies a Boolean value that indicates whether the keyboard events are to be reported as usual.
* @param pointerMode Specifies further processing of pointer events. You can pass {@link #GrabModeSync} or {@link #GrabModeAsync}.
* @param keyBoardMode Specifies further processing of keyboard events. You can pass {@link #GrabModeSync} or {@link #GrabModeAsync}.
* @return nothing
*/
int XGrabKey(Display display, int keyCode, int modifiers, Window grab_window, int ownerEvents, int pointerMode, int keyBoardMode);
/**
* The XUngrabKey() function releases the key combination on the specified window if it was grabbed by this client.
*
* @param display Specifies the connection to the X server.
* @param keyCode Specifies the KeyCode or {@link #AnyKey}.
* @param modifiers Specifies the set of keymasks or {@link #AnyModifier}.
* The mask is the bitwise inclusive OR of the valid keymask bits
* @param grab_window Specifies the grab window.
* @return nothing
*/
int XUngrabKey(Display display, int keyCode, int modifiers, Window grab_window);
//int XChangeKeyboardMapping(Display display, int first_keycode, int keysyms_per_keycode, KeySym *keysyms, int num_codes);
/** Defines the symbols for the specified number of KeyCodes starting with first_keycode. The symbols for KeyCodes outside this range remain unchanged. The number of elements in keysyms must be: num_codes * keysyms_per_keycode. The specified first_keycode must be greater than or equal to min_keycode returned by XDisplayKeycodes, or a BadValue error results. In addition, the following expression must be less than or equal to max_keycode as returned by XDisplayKeycodes, or a BadValue error results: first_keycode + num_codes - 1. */
int XChangeKeyboardMapping(Display display, int first_keycode, int keysyms_per_keycode, KeySym[] keysyms, int num_codes);
/** Returns the symbols for the specified number of KeyCodes starting with first_keycode. The value specified in first_keycode must be greater than or equal to min_keycode as returned by XDisplayKeycodes, or a BadValue error results. In addition, the following expression must be less than or equal to max_keycode as returned by XDisplayKeycodes: first_keycode + keycode_count - 1. If this is not the case, a BadValue error results. The number of elements in the KeySyms list is: keycode_count * keysyms_per_keycode_return. KeySym number N, counting from zero, for KeyCode K has the following index in the list, counting from zero: (K - first_code) * keysyms_per_code_return + N. The X server arbitrarily chooses the keysyms_per_keycode_return value to be large enough to report all requested symbols. A special KeySym value of NoSymbol is used to fill in unused elements for individual KeyCodes. To free the storage returned by XGetKeyboardMapping, use XFree. */
KeySym XGetKeyboardMapping(Display display, byte first_keycode, int keycode_count, IntByReference keysyms_per_keycode_return);
/** Returns the min-keycodes and max-keycodes supported by the specified display. The minimum number of KeyCodes returned is never less than 8, and the maximum number of KeyCodes returned is never greater than 255. Not all KeyCodes in this range are required to have corresponding keys. */
int XDisplayKeycodes(Display display, IntByReference min_keycodes_return, IntByReference max_keycodes_return);
/** Specifies the KeyCodes of the keys (if any) that are to be used as modifiers. If it succeeds, the X server generates a MappingNotify event, and XSetModifierMapping returns MappingSuccess. X permits at most 8 modifier keys. If more than 8 are specified in the XModifierKeymap structure, a BadLength error results. */
int XSetModifierMapping(Display display, XModifierKeymapRef modmap);
/** The XGetModifierMapping function returns a pointer to a newly created XModifierKeymap structure that contains the keys being used as modifiers. The structure should be freed after use by calling XFreeModifiermap. If only zero values appear in the set for any modifier, that modifier is disabled. */
XModifierKeymapRef XGetModifierMapping(Display display);
/** Returns a pointer to XModifierKeymap structure for later use. */
XModifierKeymapRef XNewModifiermap(int max_keys_per_mod);
/** Adds the specified KeyCode to the set that controls the specified modifier and returns the resulting XModifierKeymap structure (expanded as needed). */
XModifierKeymapRef XInsertModifiermapEntry(XModifierKeymapRef modmap, byte keycode_entry, int modifier);
/** Deletes the specified KeyCode from the set that controls the specified modifier and returns a pointer to the resulting XModifierKeymap structure. */
XModifierKeymapRef XDeleteModifiermapEntry(XModifierKeymapRef modmap, byte keycode_entry, int modifier);
/** Frees the specified XModifierKeymap structure. */
int XFreeModifiermap(XModifierKeymapRef modmap);
/** Changes the keyboard control state.
* @param display display
* @param value_mask disjunction of KBKeyClickPercent, KBBellPercent, KBBellPitch, KBBellDuration, KBLed, KBLedMode, KBKey, KBAutoRepeatMode
*/
int XChangeKeyboardControl(Display display, NativeLong value_mask, XKeyboardControlRef values);
/** Returns the current control values for the keyboard to the XKeyboardState structure. */
int XGetKeyboardControl(Display display, XKeyboardStateRef values_return);
/** Turns on auto-repeat for the keyboard on the specified display. */
int XAutoRepeatOn(Display display);
/** Turns off auto-repeat for the keyboard on the specified display. */
int XAutoRepeatOff(Display display);
/** Rings the bell on the keyboard on the specified display, if possible. The specified volume is relative to the base volume for the keyboard. If the value for the percent argument is not in the range -100 to 100 inclusive, a BadValue error results. The volume at which the bell rings when the percent argument is nonnegative is: base - [(base * percent) / 100] + percent. The volume at which the bell rings when the percent argument is negative is: base + [(base * percent) / 100]. To change the base volume of the bell, use XChangeKeyboardControl. */
int XBell(Display display, int percent);
/** Returns a bit vector for the logical state of the keyboard, where each bit set to 1 indicates that the corresponding key is currently pressed down. The vector is represented as 32 bytes. Byte N (from 0) contains the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing key 8N. Note that the logical state of a device (as seen by client applications) may lag the physical state if device event processing is frozen. */
int XQueryKeymap(Display display, byte[] keys_return);
/** The modifiermap member of the XModifierKeymap structure contains 8 sets of max_keypermod KeyCodes, one for each modifier in the order Shift, Lock, Control, Mod1, Mod2, Mod3, Mod4, and Mod5. Only nonzero KeyCodes have meaning in each set, and zero KeyCodes are ignored. In addition, all of the nonzero KeyCodes must be in the range specified by min_keycode and max_keycode in the Display structure, or a BadValue error results. */
class XModifierKeymapRef extends Structure implements Structure.ByReference{
public int max_keypermod; /* The server's max # of keys per modifier */
public Pointer modifiermap; /* An 8 by max_keypermod array of modifiers */
protected List getFieldOrder() {
return Arrays.asList(new String[] { "max_keypermod", "modifiermap" });
}
}
class XKeyboardControlRef extends Structure implements Structure.ByReference {
/** Volume for key clicks between 0 (off) and 100 (loud) inclusive, if possible. A setting of -1 restores the default. */
public int key_click_percent;
/** Base volume for the bell between 0 (off) and 100 (loud) inclusive, if possible. A setting of -1 restores the default. */
public int bell_percent;
/** Pitch (specified in Hz) of the bell, if possible. A setting of -1 restores the default. */
public int bell_pitch;
/** Duration of the bell specified in milliseconds, if possible. A setting of -1 restores the default. */
public int bell_duration;
/** State of the LEDs. At most 32 LEDs numbered from one are supported. */
public int led;
/** LED mode: LedModeOn or LedModeOff. */
public int led_mode;
/** <code>auto_repeat_mode</code> can change the auto repeat settings of this key. */
public int key;
/** AutoRepeatModeOff, AutoRepeatModeOn, AutoRepeatModeDefault. */
public int auto_repeat_mode;
protected List getFieldOrder() {
return Arrays.asList(new String[] { "key_click_percent", "bell_percent", "bell_pitch", "bell_duration", "led", "led_mode", "key", "auto_repeat_mode" });
}
public String toString() {
return "XKeyboardControlByReference{" +
"key_click_percent=" + key_click_percent +
", bell_percent=" + bell_percent +
", bell_pitch=" + bell_pitch +
", bell_duration=" + bell_duration +
", led=" + led +
", led_mode=" + led_mode +
", key=" + key +
", auto_repeat_mode=" + auto_repeat_mode +
'}';
}
}
class XKeyboardStateRef extends Structure implements Structure.ByReference {
/** Volume for key clicks between 0 (off) and 100 (loud) inclusive, if possible. */
public int key_click_percent;
/** Base volume for the bell between 0 (off) and 100 (loud) inclusive, if possible. */
public int bell_percent;
/** Pitch (specified in Hz) of the bell, if possible. A setting of -1 restores the default. */
public int bell_pitch;
/** Duration of the bell specified in milliseconds, if possible. A setting of -1 restores the default. */
public int bell_duration;
/** State of the LEDs. At most 32 LEDs numbered from one are supported. */
public NativeLong led_mask;
/** Global auto repeat mode: AutoRepeatModeOff or AutoRepeatModeOn. */
public int global_auto_repeat;
/** Bit vector. Each bit set to 1 indicates that auto-repeat is enabled for the corresponding key. The vector is represented as 32 bytes. Byte N (from 0) contains the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing key 8N. */
public byte auto_repeats[] = new byte[32];
protected List getFieldOrder() {
return Arrays.asList(new String[] { "key_click_percent", "bell_percent", "bell_pitch", "bell_duration", "led_mask", "global_auto_repeat", "auto_repeats" });
}
public String toString() {
return "XKeyboardStateByReference{" +
"key_click_percent=" + key_click_percent +
", bell_percent=" + bell_percent +
", bell_pitch=" + bell_pitch +
", bell_duration=" + bell_duration +
", led_mask=" + led_mask +
", global_auto_repeat=" + global_auto_repeat +
", auto_repeats=" + auto_repeats +
'}';
}
}
} |
package org.intermine.web.logic;
/**
* Container for ServletContext and Session attribute names used by the webapp
*
* @author Kim Rutherford
* @author Thomas Riley
*/
public final class Constants
{
private Constants() {
// Hidden constructor.
}
/**
* ServletContext attribute used to store web.properties
*/
public static final String WEB_PROPERTIES = "WEB_PROPERTIES";
/**
* ServletContext attribute, List of category names.
*/
public static final String CATEGORIES = "CATEGORIES";
/**
* ServletContext attribute, autocompletion.
*/
public static final String AUTO_COMPLETER = "AUTO_COMPLETER";
/**
* ServletContext attribute, Map from unqualified type name to list of subclass names.
*/
public static final String SUBCLASSES = "SUBCLASSES";
/**
* Session attribute, name of tab selected on MyMine page.
*/
public static final String MYMINE_PAGE = "MYMINE_PAGE"; // serializes
/**
* ServletContext attribute used to store the WebConfig object for the Model.
*/
public static final String WEBCONFIG = "WEBCONFIG";
/**
* Session attribute used to store the user's Profile
*/
public static final String PROFILE = "PROFILE"; // serialized as 'username'
/**
* Session attribute used to store the current query
*/
public static final String QUERY = "QUERY";
/**
* Session attribute used to store the status new template
*/
public static final String NEW_TEMPLATE = "NEW_TEMPLATE";
/**
* Session attribute used to store the status editing template
*/
public static final String EDITING_TEMPLATE = "EDITING_TEMPLATE";
/**
* Session attribute used to store the previous template name
*/
public static final String PREV_TEMPLATE_NAME = "PREV_TEMPLATE_NAME";
/**
* Servlet context attribute - map from aspect set name to Aspect object.
*/
public static final String ASPECTS = "ASPECTS";
/**
* Session attribute equals Boolean.TRUE when logged in user is superuser.
*/
public static final String IS_SUPERUSER = "IS_SUPERUSER";
/**
* Session attribute that temporarily holds a Vector of messages that will be displayed by the
* errorMessages.jsp on the next page viewed by the user and then removed (allows message
* after redirect).
*/
public static final String MESSAGES = "MESSAGES";
/**
* Session attribute that temporarily holds a Vector of errors that will be displayed by the
* errorMessages.jsp on the next page viewed by the user and then removed (allows errors
* after redirect).
*/
public static final String ERRORS = "ERRORS";
/**
* Session attribute that temporarily holds messages from the Portal
*/
public static final String PORTAL_MSG = "PORTAL_MSG";
/**
* Session attribute that holds message when a lookup constraint has been used
*/
public static final String LOOKUP_MSG = "LOOKUP_MSG";
/**
* The name of the property to look up to find the maximum size of an inline table.
*/
public static final String INLINE_TABLE_SIZE = "inline.table.size";
/**
* Session attribut containing the default operator name, either 'and' or 'or'.
*/
public static final String DEFAULT_OPERATOR = "DEFAULT_OPERATOR";
/**
* Period of time to wait for client to poll a running query before cancelling the query.
*/
public static final int QUERY_TIMEOUT_SECONDS = 20;
/**
* Refresh period specified on query poll page.
*/
public static final int POLL_REFRESH_SECONDS = 2;
/**
* The session attribute that holds the ReportObjectCache object for the session.
*/
public static final String REPORT_OBJECT_CACHE = "REPORT_OBJECT_CACHE";
/**
* Session attribute that holds cache of table identifiers to PagedTable objects.
*/
public static final String TABLE_MAP = "TABLE_MAP";
/**
* Session attribute. A Map from query id to QueryMonitor.
*/
public static final String RUNNING_QUERIES = "RUNNING_QUERIES";
/**
* Servlet attribute. Map from MultiKey(experiment, gene) id to temp file name.
*/
public static final String GRAPH_CACHE = "GRAPH_CACHE";
/**
* Servlet attribute. Map from class name to Set of leaf class descriptors.
*/
public static final String LEAF_DESCRIPTORS_MAP = "LEAF_DESCRIPTORS_MAP";
/**
* Servlet attribute. The global webapp cache - a InterMineCache object.
*/
public static final String GLOBAL_CACHE = "GLOBAL_CACHE";
/**
* Maximum size a bag should have if the user is not logged in (to save memory)
*/
public static final int MAX_NOT_LOGGED_BAG_SIZE = 500;
/**
* Servlet attribute. Contains the SearchRepository for global/public WebSearchable objects.
*/
public static final String GLOBAL_SEARCH_REPOSITORY = "GLOBAL_SEARCH_REPOSITORY";
/**
* Default size of table implemented by PagedTable.
*/
public static final int DEFAULT_TABLE_SIZE = 25;
/**
* Session attribute used to store the size of table with results.
*/
public static final String RESULTS_TABLE_SIZE = "RESULTS_TABLE_SIZE";
/**
* Session attribute used to store WebState object.
*/
public static final String WEB_STATE = "WEB_STATE";
/**
* Current version of the InterMine WebService.
* This constant must changed every time the API changes, either by addition
* or deletion of features.
*/
public static final int WEB_SERVICE_VERSION = 10;
/**
* Key for a Map from class name to Boolean.TRUE for all classes in the model that do not have
* any class keys.
*/
public static final String KEYLESS_CLASSES_MAP = "KEYLESS_CLASSES_MAP";
/**
* Key for the InterMine API object
*/
public static final String INTERMINE_API = "INTERMINE_API";
/** Key for the initialiser error **/
public static final String INITIALISER_KEY_ERROR = "INITIALISER_KEY_ERROR";
/**
* key for the map saved in the session containing the status of saved bags
*/
public static final String SAVED_BAG_STATUS = "SAVED_BAG_STATUS";
/** Key for the upgrading bag on the session **/
public static final String UPGRADING_BAG = "UPGRADING";
/** The replay-attack prevention nonces **/
public static final String NONCES = "NONCES";
/** The display name of the current user **/
public static final String USERNAME = "USERNAME";
/** The name of the current open-id provider **/
public static final String PROVIDER = "PROVIDER";
/**
* The key for the open-id providers located in the servlet context.
*/
public static final String OPENID_PROVIDERS = "OPENID_PROVIDERS";
} |
package org.rti.webgenome.webui.struts;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.Action;
import org.rti.webgenome.domain.Principal;
import org.rti.webgenome.domain.ShoppingCart;
import org.rti.webgenome.service.analysis.AnalysisService;
import org.rti.webgenome.service.dao.AnnotatedGenomeFeatureDao;
import org.rti.webgenome.service.dao.CytologicalMapDao;
import org.rti.webgenome.service.data.DataSource;
import org.rti.webgenome.service.io.DataFileManager;
import org.rti.webgenome.service.io.IOService;
import org.rti.webgenome.service.io.ImageFileManager;
import org.rti.webgenome.service.job.JobManager;
import org.rti.webgenome.service.plot.PlotService;
import org.rti.webgenome.service.session.Authenticator;
import org.rti.webgenome.service.session.SecurityMgr;
import org.rti.webgenome.service.session.SessionMode;
import org.rti.webgenome.service.session.WebGenomeDbService;
import org.rti.webgenome.service.util.IdGenerator;
import org.rti.webgenome.webui.SessionTimeoutException;
import org.rti.webgenome.webui.util.PageContext;
/**
* Abstract base class for webGenome Struts actions.
* @author dhall
*
*/
public abstract class BaseAction extends Action {
// C O M M O N C O N S T A N T S
/** Common value for a forward related to a success on the Action. */
public static final String FORWARDTO_SUCCESS = "success" ;
/** Common value for a forward related to a failure on the Action. */
public static final String FORWARDTO_FAILURE = "failure" ;
// A T T R I B U T E S
/** Service facade for transactional database operations. */
protected WebGenomeDbService dbService = null;
/** Cytological map data access object. */
private CytologicalMapDao cytologicalMapDao = null;
/**
* DAO for getting annotated genome features. This property
* must be set via dependency injection.
*/
private AnnotatedGenomeFeatureDao annotatedGenomeFeatureDao = null;
/** Manager of compute-intensive jobs. */
private JobManager jobManager = null;
/** Service for performing analyses. */
private AnalysisService analysisService = null;
/** Manages serialized data files. */
private DataFileManager dataFileManager = null;
/** File I/O service. */
private IOService ioService = null;
/** Experiment ID generator. */
private IdGenerator experimentIdGenerator = null;
/** Bioassay ID generator. */
private IdGenerator bioAssayIdGenerator = null;
/**
* Service for creating plots. This service is
* only used directly when session is CLIENT mode
* or the size of the data set is sufficiently small
* to generate the plot immediately.
*/
private PlotService plotService = null;
/** Manager for image files. */
private ImageFileManager imageFileManager = null;
/** Index of configured external data sources. */
private Map<String, DataSource> dataSourcesIndex = null;
/** Account manager. This property should be injected. */
private SecurityMgr securityMgr = null;
/**
* Authenticator of user credentials.
* This property should be injected.
*/
private Authenticator authenticator = null;
// I N J E C T O R S
/**
* Inject a data source index.
* @param dataSourcesIndex An index to external data sources.
*/
public void setDataSourcesIndex(
final Map<String, DataSource> dataSourcesIndex) {
this.dataSourcesIndex = dataSourcesIndex;
}
/**
* Set authenticator of user credentials.
* @param authenticator An authenticator
*/
public void setAuthenticator(final Authenticator authenticator) {
this.authenticator = authenticator;
}
/**
* Set service for creating plots.
* @param plotService Plot service
*/
public void setPlotService(final PlotService plotService) {
this.plotService = plotService;
}
/**
* Set manager of image files.
* @param imageFileManager Image file manager
*/
public void setImageFileManager(final ImageFileManager imageFileManager) {
this.imageFileManager = imageFileManager;
}
/**
* Set bioassay ID generator.
* @param bioAssayIdGenerator ID generator
*/
public void setBioAssayIdGenerator(
final IdGenerator bioAssayIdGenerator) {
this.bioAssayIdGenerator = bioAssayIdGenerator;
}
/**
* Set experiment ID generator.
* @param experimentIdGenerator ID generator
*/
public void setExperimentIdGenerator(
final IdGenerator experimentIdGenerator) {
this.experimentIdGenerator = experimentIdGenerator;
}
/**
* Set service for performing analysis via injection.
* @param analysisService Service for performing analysis.
*/
public void setAnalysisService(final AnalysisService analysisService) {
this.analysisService = analysisService;
}
/**
* Set manager for serialized data files.
* @param dataFileManager Data file manager
*/
public void setDataFileManager(final DataFileManager dataFileManager) {
this.dataFileManager = dataFileManager;
}
/**
* Inject data file I/O service.
* @param ioService Data file I/O service
*/
public void setIoService(final IOService ioService) {
this.ioService = ioService;
}
/**
* Set manager of compute-intensive jobs.
* @param jobManager Compute-intensive job manager
*/
public void setJobManager(final JobManager jobManager) {
this.jobManager = jobManager;
}
/**
* Set cytological map data access object.
* @param cytologicalMapDao Cytological map data access object.
*/
public void setCytologicalMapDao(
final CytologicalMapDao cytologicalMapDao) {
this.cytologicalMapDao = cytologicalMapDao;
}
/**
* Inject service for transactional database operations.
* @param dbService Service for transactional database operations
*/
public void setDbService(final WebGenomeDbService dbService) {
this.dbService = dbService;
}
/**
* Set DAO for getting annotated genome features. This property
* must be set via dependency injection.
* @param annotatedGenomeFeatureDao DAO for getting annotated
* genome features
*/
public void setAnnotatedGenomeFeatureDao(
final AnnotatedGenomeFeatureDao annotatedGenomeFeatureDao) {
this.annotatedGenomeFeatureDao = annotatedGenomeFeatureDao;
}
/**
* Set account manager.
* @param securityMgr Security manager for user accounts.
*/
public void setSecurityMgr(final SecurityMgr securityMgr) {
this.securityMgr = securityMgr;
}
// A C C E S S O R S
/**
* Get service for transactional database operations.
* @return Service for transactional database operations
*/
protected WebGenomeDbService getDbService() {
return this.dbService;
}
/**
* Get credentials authenticator.
* @return Credentials authenticator
*/
protected Authenticator getAuthenticator() {
return authenticator;
}
/**
* Get index of data sources keyed on data source name.
* @return Index of data sources
*/
protected Map<String, DataSource> getDataSourcesIndex() {
return dataSourcesIndex;
}
/**
* Get manager of image files.
* @return Image file manager
*/
protected ImageFileManager getImageFileManager() {
return imageFileManager;
}
/**
* Get plotting service.
* @return Plotting service
*/
protected PlotService getPlotService() {
return plotService;
}
/**
* Get manager of data files.
* @return Data file manager
*/
protected DataFileManager getDataFileManager() {
return dataFileManager;
}
/**
* Get file I/O service.
* @return File I/O service
*/
protected IOService getIoService() {
return ioService;
}
/**
* Get service for performing analytic operations.
* @return Analysis service
*/
protected AnalysisService getAnalysisService() {
return this.analysisService;
}
/**
* Get annotated genome feature data access object.
* @return Annotated genome feature data access object
*/
protected AnnotatedGenomeFeatureDao getAnnotatedGenomeFeatureDao() {
return annotatedGenomeFeatureDao;
}
/**
* Get manager of compute-intensive jobs.
* @return Manager of compute-intensive jobs
*/
protected JobManager getJobManager() {
return jobManager;
}
/**
* Get generator of bioassay IDs.
* @return Generator of bioassay IDs
*/
protected IdGenerator getBioAssayIdGenerator() {
return bioAssayIdGenerator;
}
/**
* Get generator of experiment IDs.
* @return Generator of experiment IDs
*/
protected IdGenerator getExperimentIdGenerator() {
return experimentIdGenerator;
}
/**
* Get cytological map data access object.
* @return Cytological map data access object
*/
protected CytologicalMapDao getCytologicalMapDao() {
return cytologicalMapDao;
}
/**
* Get account manager.
* @return Account manager.
*/
protected SecurityMgr getSecurityMgr() {
return securityMgr;
}
// B U S I N E S S M E T H O D S
/**
* Get shopping cart. If the session mode is
* {@code CLIENT}, the cart will be cached in the
* session object. If the mode is {@code STAND_ALONE},
* the cart will be obtained from persistent storage.
* @param request Servlet request
* @return Shopping cart
* @throws SessionTimeoutException If any necessary
* session attributes are not found, which indicates the
* session has timed ouit.
*/
protected ShoppingCart getShoppingCart(
final HttpServletRequest request)
throws SessionTimeoutException {
ShoppingCart cart = null;
SessionMode mode = PageContext.getSessionMode(request);
if (mode == SessionMode.CLIENT) {
cart = PageContext.getShoppingCart(request);
} else if (mode == SessionMode.STAND_ALONE) {
Principal principal = PageContext.getPrincipal(request);
cart = this.getDbService().loadShoppingCart(principal.getId(), principal.getDomain());
}
return cart;
}
/**
* Are data in memory for this session?
* @param request A request
* @return T/F
* @throws SessionTimeoutException If the method cannot
* determine the session mode, which would occur if
* for some reason the session timed out.
*/
protected boolean dataInMemory(final HttpServletRequest request)
throws SessionTimeoutException {
return PageContext.getSessionMode(request) == SessionMode.CLIENT;
}
// C O N V E N I E N C E M E T H O D S
/**
* Convenience method for checking whether a form field is empty.
*
* @param fieldValue
* @return true, if the field is empty, false if it contains some non-space characters
*/
protected boolean isEmpty ( final String fieldValue ) {
return fieldValue == null || fieldValue.trim().length() < 1 ;
}
} |
package cn.net.openid.jos.domain;
import java.net.URL;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
public class Domain extends BaseEntity {
private static final long serialVersionUID = 7341781651134648946L;
/**
* The prime value for {@code #hashCode()}.
*/
private static final int PRIME = 31;
/**
* Username as a subdomain.
*/
public static final int TYPE_SUBDOMAIN = 1;
/**
* Username as a subdirectory.
*/
public static final int TYPE_SUBDIRECTORY = 2;
/**
* your-domain.
*/
private String name;
/**
* Domain type.
*/
private int type;
/**
* The server host of the domain.
*/
private String serverHost;
/**
* Member page path.
*/
private String memberPath;
/**
* Username configuration.
*/
private UsernameConfiguration usernameConfiguration =
new UsernameConfiguration();
/**
* Extended configuration.
*/
private Map<String, String> configuration;
/**
* Domain runtime inforation.
*/
private DomainRuntime runtime = new DomainRuntime();
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(final String name) {
this.name = name;
}
/**
* @return the type
*/
public int getType() {
return type;
}
/**
* @param type
* the type to set
*/
public void setType(final int type) {
this.type = type;
}
/**
* @return the serverHost
*/
public String getServerHost() {
return serverHost;
}
/**
* @param serverHost
* the serverHost to set
*/
public void setServerHost(final String serverHost) {
this.serverHost = serverHost;
}
/**
* @return the memberPath
*/
public String getMemberPath() {
return memberPath;
}
/**
* @param memberPath
* the memberPath to set
*/
public void setMemberPath(final String memberPath) {
this.memberPath = memberPath;
}
/**
* @return the usernameConfiguration
*/
public UsernameConfiguration getUsernameConfiguration() {
return usernameConfiguration;
}
/**
* @param usernameConfiguration
* the usernameConfiguration to set
*/
public void setUsernameConfiguration(
final UsernameConfiguration usernameConfiguration) {
this.usernameConfiguration = usernameConfiguration;
usernameConfiguration.setDomain(this);
}
/**
* @return the configuration
*/
public Map<String, String> getConfiguration() {
return configuration;
}
/**
* @param configuration
* the configuration to set
*/
public void setConfiguration(final Map<String, String> configuration) {
this.configuration = configuration;
}
/**
* @return the runtime
*/
public DomainRuntime getRuntime() {
return runtime;
}
/**
* @param runtime
* the runtime to set
*/
public void setRuntime(final DomainRuntime runtime) {
this.runtime = runtime;
}
/**
* @return the identifierPrefix
*/
public String getIdentifierPrefix() {
StringBuilder sb = new StringBuilder();
URL baseUrl = this.getRuntime().getServerBaseUrl();
switch (getType()) {
case Domain.TYPE_SUBDOMAIN:
sb.append(baseUrl.getProtocol()).append(":
break;
case Domain.TYPE_SUBDIRECTORY:
sb.append(baseUrl.getProtocol()).append(":
sb.append(getName());
appendPort(sb, baseUrl);
sb.append(baseUrl.getPath());
appendMemberPath(sb);
break;
default:
break;
}
return sb.toString();
}
/**
* @return the identifierSuffix
*/
public String getIdentifierSuffix() {
StringBuilder sb = new StringBuilder();
URL baseUrl = this.getRuntime().getServerBaseUrl();
switch (getType()) {
case Domain.TYPE_SUBDOMAIN:
sb.append('.').append(getName());
appendPort(sb, baseUrl);
sb.append(baseUrl.getPath());
appendMemberPath(sb);
break;
case Domain.TYPE_SUBDIRECTORY:
break;
default:
break;
}
return sb.toString();
}
/**
* Get boolean value of an extended attribute.
*
* @param attributeName
* the attribute name
* @return boolean value of the attribute
*/
public boolean getBooleanAttribute(final String attributeName) {
String attributeValue = this.getConfiguration().get(attributeName);
return Boolean.parseBoolean(attributeValue);
}
/**
* Get int value of an extended attribute.
*
* @param attributeName
* the attribute name
* @return int value of the attribute
*/
public int getIntAttribute(final String attributeName) {
return NumberUtils.toInt(this.getConfiguration().get(attributeName));
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int result = 1;
result = PRIME * result
+ ((getName() == null) ? 0 : getName().hashCode());
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Domain)) {
return false;
}
Domain other = (Domain) obj;
if (getName() == null) {
if (other.getName() != null) {
return false;
}
} else if (!getName().equals(other.getName())) {
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return getName();
}
/**
* Append the port, if the port is not the default port.
*
* @param sb
* the {@code StringBuilder} to appended to
* @param serverBaseUrl
* the base url of the server
*/
private void appendPort(final StringBuilder sb, final URL serverBaseUrl) {
int port = serverBaseUrl.getPort();
if (port != -1 && port != serverBaseUrl.getDefaultPort()) {
sb.append(':').append(port);
}
}
/**
* Append member path if the memberPath is not empty.
*
* @param sb
* the {@code StringBuilder} to appended to
*/
private void appendMemberPath(final StringBuilder sb) {
if (!StringUtils.isEmpty(this.getMemberPath())) {
sb.append(this.getMemberPath()).append('/');
}
}
} |
package kikaha.urouting;
import static java.lang.String.format;
import java.lang.annotation.Annotation;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.MirroredTypeException;
import javax.lang.model.type.TypeMirror;
import kikaha.urouting.api.Consumes;
import kikaha.urouting.api.Context;
import kikaha.urouting.api.CookieParam;
import kikaha.urouting.api.FormParam;
import kikaha.urouting.api.HeaderParam;
import kikaha.urouting.api.MultiPartFormData;
import kikaha.urouting.api.Path;
import kikaha.urouting.api.PathParam;
import kikaha.urouting.api.Produces;
import kikaha.urouting.api.QueryParam;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import trip.spi.Singleton;
import trip.spi.Stateless;
@Getter
@EqualsAndHashCode( exclude = "identifier" )
@RequiredArgsConstructor
public class RoutingMethodData {
final static String METHOD_PARAM_EOL = "\n\t\t\t";
final String type;
final String packageName;
final String methodName;
final String methodParams;
final String returnType;
final String responseContentType;
final String httpPath;
final String httpMethod;
final String serviceInterface;
final boolean hasIOBound;
final boolean isMultiPart;
@Getter( lazy = true )
private final Long identifier = createIdentifier();
private Long createIdentifier() {
return hashCode() & 0xffffffffl;
}
public static RoutingMethodData from(
final ExecutableElement method, final Class<? extends Annotation> httpMethodAnnotation ) {
final String type = method.getEnclosingElement().asType().toString();
final String methodParams = extractMethodParamsFrom( method );
final boolean isMultiPart = httpMethodAnnotation.equals( MultiPartFormData.class )
|| methodParams.contains( "methodDataProvider.getFormParam" );
final String httpMethod = isMultiPart
? "POST" : httpMethodAnnotation.getSimpleName();
return createRouteMethodData( method, isMultiPart, httpMethod, type, methodParams );
}
private static RoutingMethodData createRouteMethodData(
final ExecutableElement method, final boolean isMultiPart,
final String httpMethod, final String type, final String methodParams ) {
return new RoutingMethodData(
type, extractPackageName( type ), method.getSimpleName().toString(),
methodParams, extractReturnTypeFrom( method ), extractResponseContentTypeFrom( method ),
measureHttpPathFrom( method ), httpMethod, extractServiceInterfaceFrom( method ),
hasIOBlockingOperations( methodParams ), isMultiPart );
}
private static boolean hasIOBlockingOperations( final String methodParams ) {
return methodParams.contains( "methodDataProvider.getBody" )
|| methodParams.contains( "methodDataProvider.getFormParam" );
}
public static String extractPackageName( final String canonicalName ) {
return canonicalName.replaceAll( "^(.*)\\.[^\\.]+", "$1" );
}
static String extractReturnTypeFrom( final ExecutableElement method ) {
final String returnTypeAsString = method.getReturnType().toString();
if ( "void".equals( returnTypeAsString ) )
return null;
return returnTypeAsString;
}
static String extractMethodParamsFrom( final ExecutableElement method ) {
final StringBuilder buffer = new StringBuilder().append( METHOD_PARAM_EOL );
boolean first = true;
for ( final VariableElement parameter : method.getParameters() ) {
if ( !first )
buffer.append( ',' );
buffer.append( extractMethodParamFrom( method, parameter ) ).append( METHOD_PARAM_EOL );
first = false;
}
return buffer.toString();
}
/**
* Extract method parameter for a given {@VariableElement}
* argument. The returned method parameter will be passed as argument to a
* routing method.
*
* @param method
* @param parameter
* @return
*/
// XXX: bad, ugly and huge method
static String extractMethodParamFrom( final ExecutableElement method, final VariableElement parameter ) {
final String targetType = parameter.asType().toString();
final PathParam pathParam = parameter.getAnnotation( PathParam.class );
if ( pathParam != null )
return getParam( PathParam.class, pathParam.value(), targetType );
final QueryParam queryParam = parameter.getAnnotation( QueryParam.class );
if ( queryParam != null )
return getParam( QueryParam.class, queryParam.value(), targetType );
final HeaderParam headerParam = parameter.getAnnotation( HeaderParam.class );
if ( headerParam != null )
return getParam( HeaderParam.class, headerParam.value(), targetType );
final CookieParam cookieParam = parameter.getAnnotation( CookieParam.class );
if ( cookieParam != null )
return getParam( CookieParam.class, cookieParam.value(), targetType );
final FormParam formParam = parameter.getAnnotation( FormParam.class );
if ( formParam != null )
return getFormParam( formParam.value(), targetType );
final Context dataParam = parameter.getAnnotation( Context.class );
if ( dataParam != null )
return format( "methodDataProvider.getData( exchange, %s.class )", targetType );
return getBodyParam( method, targetType );
}
static String getFormParam( final String param, final String targetType ) {
return format( "methodDataProvider.getFormParam( formData, \"%s\", %s.class )",
param, targetType );
}
static String getParam( final Class<?> targetAnnotation, final String param, final String targetType ) {
return format( "methodDataProvider.get%s( exchange, \"%s\", %s.class )",
targetAnnotation.getSimpleName(), param, targetType );
}
static String getBodyParam( final ExecutableElement method, final String targetType ) {
final String consumingContentType = extractConsumingContentTypeFrom( method );
if ( consumingContentType != null )
return format( "methodDataProvider.getBody( exchange, %s.class, \"%s\" )", targetType, consumingContentType );
return format( "methodDataProvider.getBody( exchange, %s.class )", targetType );
}
static String extractConsumingContentTypeFrom( final ExecutableElement method ) {
Consumes consumesAnnotation = method.getAnnotation( Consumes.class );
if ( consumesAnnotation == null )
consumesAnnotation = method.getEnclosingElement().getAnnotation( Consumes.class );
if ( consumesAnnotation != null )
return consumesAnnotation.value();
return null;
}
static String extractResponseContentTypeFrom( final ExecutableElement method ) {
Produces producesAnnotation = method.getAnnotation( Produces.class );
if ( producesAnnotation == null )
producesAnnotation = method.getEnclosingElement().getAnnotation( Produces.class );
if ( producesAnnotation != null )
return producesAnnotation.value();
return null;
}
static String measureHttpPathFrom( final ExecutableElement method ) {
final Element classElement = method.getEnclosingElement();
final Path pathAnnotationOfClass = classElement.getAnnotation( Path.class );
final String rootPath = pathAnnotationOfClass != null ? pathAnnotationOfClass.value() : "/";
final Path pathAnnotationOfMethod = method.getAnnotation( Path.class );
final String methodPath = pathAnnotationOfMethod != null ? pathAnnotationOfMethod.value() : "/";
return generateHttpPath( rootPath, methodPath );
}
public static String generateHttpPath( final String rootPath, final String methodPath ) {
return String.format( "/%s/%s/", rootPath, methodPath )
.replaceAll( "
}
static String extractServiceInterfaceFrom( final ExecutableElement method ) {
final TypeElement classElement = (TypeElement)method.getEnclosingElement();
final String canonicalName = getServiceInterfaceProviderClass( classElement ).toString();
if ( Singleton.class.getCanonicalName().equals( canonicalName )
|| Stateless.class.getCanonicalName().equals( canonicalName ) )
return classElement.asType().toString();
return canonicalName;
}
static TypeMirror getServiceInterfaceProviderClass( final TypeElement service ) {
try {
final Singleton singleton = service.getAnnotation( Singleton.class );
if ( singleton != null )
singleton.exposedAs();
final Stateless stateless = service.getAnnotation( Stateless.class );
if ( stateless != null )
stateless.exposedAs();
return service.asType();
} catch ( final MirroredTypeException cause ) {
return cause.getTypeMirror();
}
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package kinect.controller;
import java.io.File;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
/**
*
* @author navin
*/
public class KinectController extends Application {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
WebView wb = new WebView();
WebEngine we = wb.getEngine();
File file = new File("web/main.html");
System.out.println(file.toURI());
we.load(file.toURI().toString());
Scene scene = new Scene(wb, 300, 250);
//scene.getStylesheets().add("web/css/style.css");
primaryStage.setScene(scene);
primaryStage.show();
}
private class JavaApp {
public void exit() {
//Platform.exit();
System.out.println("Cool");
}
}
} |
package org.apache.avro;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.IntNode;
import org.codehaus.jackson.node.TextNode;
public abstract class LogicalType extends JsonProperties {
protected LogicalType(Set<String> reserved, String logicalTypeName) {
super(reserved);
props.put("logicalType", TextNode.valueOf(logicalTypeName.toLowerCase()));
this.logicalTypeName = logicalTypeName;
}
protected final String logicalTypeName;
/** Validate this logical type for the given Schema */
public abstract void validate(Schema schema);
/** Return the set of properties that a reserved for this type */
public abstract Set<String> reserved();
/** get java type */
public abstract Class<?> getLogicalJavaType();
public abstract Object deserialize(Schema.Type type, Object object);
public abstract Object serialize(Schema.Type type, Object object);
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj.getClass() != this.getClass()) return false;
LogicalType other = (LogicalType) obj;
// equal if properties are the same
return this.props.equals(other.props);
}
@Override
public int hashCode() {
return props.hashCode();
}
private static final Map<String, Constructor<? extends LogicalType>> LOGICAL_TYPE_TO_CLASS =
new HashMap<String, Constructor<? extends LogicalType>>();
private static final Logger LOG = Logger.getLogger(LogicalType.class.getName());
static {
try {
final Constructor<Decimal> constructor = Decimal.class.getConstructor(JsonNode.class);
constructor.setAccessible(true);
LOGICAL_TYPE_TO_CLASS.put("decimal", constructor);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
} catch (SecurityException ex) {
throw new RuntimeException(ex);
}
Enumeration<URL> logTypesResources = null;
try {
logTypesResources
= LogicalType.class.getClassLoader().getResources("org/apache/avro/logical_types.properties");
} catch (IOException ex) {
LOG.log(Level.INFO, "No external logical types registered", ex);
}
if (logTypesResources != null) {
Properties props = new Properties();
while (logTypesResources.hasMoreElements()) {
URL url = logTypesResources.nextElement();
LOG.info("Loading logical type registrations from " + url);
try {
BufferedReader is
= new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName("US-ASCII")));
try {
props.load(is);
for (Map.Entry<Object, Object> entry : props.entrySet()) {
try {
final Constructor<? extends LogicalType> constructor
= ((Class<? extends LogicalType>) Class.forName((String) entry.getValue())).
getConstructor(JsonNode.class);
constructor.setAccessible(true);
LOGICAL_TYPE_TO_CLASS.put((String) entry.getKey(), constructor);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
} catch (SecurityException ex) {
throw new RuntimeException(ex);
}
}
} finally {
props.clear();
is.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}
public static LogicalType fromJsonNode(JsonNode node) {
final JsonNode logicalTypeNode = node.get("logicalType");
if (logicalTypeNode == null) {
return null;
}
Constructor<? extends LogicalType> constr = LOGICAL_TYPE_TO_CLASS.get(logicalTypeNode.asText());
if (constr != null) {
try {
return constr.newInstance(node);
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
} else {
throw new RuntimeException("Undefined logical type " + logicalTypeNode.asText());
}
}
/** Create a Decimal LogicalType with the given precision and scale 0 */
static Decimal decimal(int precision) {
return decimal(precision, 0);
}
/** Create a Decimal LogicalType with the given precision and scale */
static Decimal decimal(int precision, int scale) {
return new Decimal(precision, scale);
}
/** Decimal represents arbitrary-precision fixed-scale decimal numbers */
public static class Decimal extends LogicalType {
private static final Set<String> RESERVED = reservedSet("precision", "scale");
private final MathContext mc;
private final int scale;
private Decimal(int precision, int scale) {
super(RESERVED, "decimal");
if (precision <= 0) {
throw new IllegalArgumentException("Invalid " + this.logicalTypeName + " precision: " +
precision + " (must be positive)");
}
if (scale < 0) {
throw new IllegalArgumentException("Invalid " + this.logicalTypeName + " scale: " +
scale + " (must be positive)");
} else if (scale > precision) {
throw new IllegalArgumentException("Invalid " + this.logicalTypeName + " scale: " +
scale + " (greater than precision: " + precision + ")");
}
props.put("precision", IntNode.valueOf(precision));
props.put("scale", IntNode.valueOf(scale));
mc = new MathContext(precision, RoundingMode.HALF_EVEN);
this.scale = scale;
}
public Decimal(JsonNode node) {
this(node.get("precision").asInt(), node.get("scale").asInt());
}
@Override
public void validate(Schema schema) {
// validate the type
if (schema.getType() != Schema.Type.FIXED &&
schema.getType() != Schema.Type.BYTES &&
schema.getType() != Schema.Type.STRING) {
throw new IllegalArgumentException(this.logicalTypeName + " must be backed by fixed or bytes");
}
int precision = mc.getPrecision();
if (precision > maxPrecision(schema)) {
throw new IllegalArgumentException(
"fixed(" + schema.getFixedSize() + ") cannot store " +
precision + " digits (max " + maxPrecision(schema) + ")");
}
}
@Override
public Set<String> reserved() {
return RESERVED;
}
private long maxPrecision(Schema schema) {
if (schema.getType() == Schema.Type.BYTES
|| schema.getType() == Schema.Type.STRING) {
// not bounded
return Integer.MAX_VALUE;
} else if (schema.getType() == Schema.Type.FIXED) {
int size = schema.getFixedSize();
return Math.round( // convert double to long
Math.floor(Math.log10( // number of base-10 digits
Math.pow(2, 8 * size - 1) - 1) // max value stored
));
} else {
// not valid for any other type
return 0;
}
}
@Override
public Class<?> getLogicalJavaType() {
return BigDecimal.class;
}
@Override
public Object deserialize(Schema.Type type, Object object) {
switch (type) {
case STRING:
BigDecimal result = new BigDecimal(((CharSequence) object).toString(), mc);
if (result.scale() > scale) {
// Rounding might be an option.
// this will probably need to be made configurable in the future.
throw new AvroRuntimeException("Received Decimal " + object + " is not compatible with scale " + scale);
}
return result;
case BYTES:
//ByteBuffer buf = ByteBuffer.wrap((byte []) object);
ByteBuffer buf = (ByteBuffer) object;
buf.rewind();
int lscale = buf.getInt();
if (lscale > scale) {
// Rounding might be an option.
// this will probably need to be made configurable in the future.
throw new AvroRuntimeException("Received Decimal " + object + " is not compatible with scale " + scale);
}
byte[] unscaled = new byte[buf.remaining()];
buf.get(unscaled);
BigInteger unscaledBi = new BigInteger(unscaled);
return new BigDecimal(unscaledBi, lscale);
default:
throw new UnsupportedOperationException("Unsupported type " + type + " for " + this);
}
}
@Override
public Object serialize(Schema.Type type, Object object) {
switch (type) {
case STRING:
return object.toString();
case BYTES:
BigDecimal decimal = (BigDecimal) object;
int scale = decimal.scale();
byte[] unscaledValue = decimal.unscaledValue().toByteArray();
ByteBuffer buf = ByteBuffer.allocate(4 + unscaledValue.length);
buf.putInt(scale);
buf.put(unscaledValue);
buf.rewind();
return buf;
default:
throw new UnsupportedOperationException("Unsupported type " + type + " for " + this);
}
}
}
/** Helper method to build reserved property sets */
private static Set<String> reservedSet(String... properties) {
Set<String> reserved = new HashSet<String>();
reserved.add("logicalType");
Collections.addAll(reserved, properties);
return reserved;
}
} |
package com.expidev.gcmapp.json;
import android.util.Log;
import com.expidev.gcmapp.model.Assignment;
import com.expidev.gcmapp.model.Ministry;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class AssignmentsJsonParser
{
private static String TAG = AssignmentsJsonParser.class.getSimpleName();
public static List<Assignment> parseAssignments(JSONArray jsonArray)
{
List<Assignment> assignments = new ArrayList<Assignment>();
try
{
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject assignmentJson = jsonArray.getJSONObject(i);
Assignment assignment = new Assignment();
assignment.setId(assignmentJson.getString("id"));
assignment.setTeamRole(assignmentJson.getString("team_role"));
JSONObject location = assignmentJson.optJSONObject("location");
if(location != null)
{
assignment.setLatitude(location.getDouble("latitude"));
assignment.setLongitude(location.getDouble("longitude"));
assignment.setLocationZoom(assignmentJson.optInt("location_zoom"));
}
Ministry ministry = MinistryJsonParser.parseMinistry(assignmentJson);
if(assignmentJson.has("sub_ministries"))
{
JSONArray subMinistriesJson = assignmentJson.getJSONArray("sub_ministries");
List<Ministry> subMinistries = MinistryJsonParser.parseMinistriesJson(subMinistriesJson);
ministry.setSubMinistries(subMinistries);
}
assignment.setMinistry(ministry);
assignments.add(assignment);
}
}
catch(Exception e)
{
Log.e(TAG, e.getMessage());
}
return assignments;
}
} |
package imagej.legacy;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import javassist.CannotCompileException;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.CodeIterator;
import javassist.bytecode.ConstPool;
import javassist.bytecode.InstructionPrinter;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.Opcode;
import javassist.expr.ConstructorCall;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.Handler;
import javassist.expr.MethodCall;
import javassist.expr.NewExpr;
import org.scijava.util.ClassUtils;
import org.scijava.util.FileUtils;
/**
* The code hacker provides a mechanism for altering the behavior of classes
* before they are loaded, for the purpose of injecting new methods and/or
* altering existing ones.
* <p>
* In ImageJ, this mechanism is used to provide new seams into legacy ImageJ1
* code, so that (e.g.) the modern UI is aware of legacy ImageJ events as they
* occur.
* </p>
*
* @author Curtis Rueden
* @author Rick Lentz
* @author Johannes Schindelin
*/
public class CodeHacker {
private static final String PATCH_PKG = "imagej.legacy.patches";
private static final String PATCH_SUFFIX = "Methods";
private final ClassPool pool;
protected final ClassLoader classLoader;
private final Set<CtClass> handledClasses = new LinkedHashSet<CtClass>();
private boolean onlyLogExceptions;
public CodeHacker(final ClassLoader classLoader, final ClassPool classPool) {
this.classLoader = classLoader;
pool = classPool != null ? classPool : ClassPool.getDefault();
pool.appendClassPath(new ClassClassPath(getClass()));
pool.appendClassPath(new LoaderClassPath(classLoader));
// the CodeHacker offers the LegacyService instance, therefore it needs to add that field here
if (!hasField("ij.IJ", "_legacyService")) {
insertPrivateStaticField("ij.IJ", LegacyService.class, "_legacyService");
insertNewMethod("ij.IJ",
"public static imagej.legacy.LegacyService getLegacyService()",
"return _legacyService;");
}
onlyLogExceptions = !LegacyExtensions.stackTraceContains("junit.");
}
public CodeHacker(ClassLoader classLoader) {
this(classLoader, null);
}
private void maybeThrow(final IllegalArgumentException e) {
if (onlyLogExceptions) e.printStackTrace();
else throw e;
}
/**
* Modifies a class by injecting additional code at the end of the specified
* method's body.
* <p>
* The extra code is defined in the imagej.legacy.patches package, as
* described in the documentation for {@link #insertNewMethod(String, String)}.
* </p>
*
* @param fullClass Fully qualified name of the class to modify.
* @param methodSig Method signature of the method to modify; e.g.,
* "public void updateAndDraw()"
*/
public void
insertAtBottomOfMethod(final String fullClass, final String methodSig)
{
insertAtBottomOfMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string at the end of the
* specified method's body.
*
* @param fullClass Fully qualified name of the class to modify.
* @param methodSig Method signature of the method to modify; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertAtBottomOfMethod(final String fullClass,
final String methodSig, final String newCode)
{
try {
getBehavior(fullClass, methodSig).insertAfter(expand(newCode));
}
catch (final Throwable e) {
maybeThrow(new IllegalArgumentException("Cannot modify method: "
+ methodSig, e));
}
}
/**
* Modifies a class by injecting additional code at the start of the specified
* method's body.
* <p>
* The extra code is defined in the imagej.legacy.patches package, as
* described in the documentation for {@link #insertNewMethod(String, String)}.
* </p>
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
*/
public void
insertAtTopOfMethod(final String fullClass, final String methodSig)
{
insertAtTopOfMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string at the start of the
* specified method's body.
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertAtTopOfMethod(final String fullClass,
final String methodSig, final String newCode)
{
try {
final CtBehavior behavior = getBehavior(fullClass, methodSig);
if (behavior instanceof CtConstructor) {
((CtConstructor)behavior).insertBeforeBody(expand(newCode));
} else {
behavior.insertBefore(expand(newCode));
}
}
catch (final Throwable e) {
maybeThrow(new IllegalArgumentException("Cannot modify method: " + methodSig,
e));
}
}
/**
* Modifies a class by injecting a new method.
* <p>
* The body of the method is defined in the imagej.legacy.patches package, as
* described in the {@link #insertNewMethod(String, String)} method
* documentation.
* <p>
* The new method implementation should be declared in the
* imagej.legacy.patches package, with the same name as the original class
* plus "Methods"; e.g., overridden ij.gui.ImageWindow methods should be
* placed in the imagej.legacy.patches.ImageWindowMethods class.
* </p>
* <p>
* New method implementations must be public static, with an additional first
* parameter: the instance of the class on which to operate.
* </p>
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void setVisible(boolean vis)"
*/
public void insertNewMethod(final String fullClass, final String methodSig) {
insertNewMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string as a new method.
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertNewMethod(final String fullClass, final String methodSig,
final String newCode)
{
final CtClass classRef = getClass(fullClass);
final String methodBody = methodSig + " { " + expand(newCode) + " } ";
try {
final CtMethod methodRef = CtNewMethod.make(methodBody, classRef);
classRef.addMethod(methodRef);
}
catch (final Throwable e) {
maybeThrow(new IllegalArgumentException("Cannot add method: "
+ methodSig, e));
}
}
/*
* Works around a bug where the horizontal scroll wheel of the mighty mouse is mistaken for a popup trigger.
*/
public void handleMightyMousePressed(final String fullClass) {
ExprEditor editor = new ExprEditor() {
@Override
public void edit(MethodCall call) throws CannotCompileException {
if (call.getMethodName().equals("isPopupTrigger"))
call.replace("$_ = $0.isPopupTrigger() && $0.getButton() != 0;");
}
};
final CtClass classRef = getClass(fullClass);
for (final String methodName : new String[] { "mousePressed", "mouseDragged" }) try {
final CtMethod method = classRef.getMethod(methodName, "(Ljava/awt/event/MouseEvent;)V");
method.instrument(editor);
} catch (final NotFoundException e) {
/* ignore */
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(
"Cannot instrument method: " + methodName, e));
}
}
public void insertPrivateStaticField(final String fullClass,
final Class<?> clazz, final String name) {
insertStaticField(fullClass, Modifier.PRIVATE, clazz, name, null);
}
public void insertPublicStaticField(final String fullClass,
final Class<?> clazz, final String name, final String initializer) {
insertStaticField(fullClass, Modifier.PUBLIC, clazz, name, initializer);
}
public void insertStaticField(final String fullClass, int modifiers,
final Class<?> clazz, final String name, final String initializer) {
final CtClass classRef = getClass(fullClass);
try {
final CtField field = new CtField(pool.get(clazz.getName()), name,
classRef);
field.setModifiers(modifiers | Modifier.STATIC);
classRef.addField(field);
if (initializer != null) {
addToClassInitializer(fullClass, name + " = " + initializer + ";");
}
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException("Cannot add field " + name
+ " to " + fullClass, e));
}
}
public void addToClassInitializer(final String fullClass, final String code) {
final CtClass classRef = getClass(fullClass);
try {
CtConstructor method = classRef.getClassInitializer();
if (method != null) {
method.insertAfter(code);
} else {
method = CtNewConstructor.make(new CtClass[0], new CtClass[0], code, classRef);
method.getMethodInfo().setName("<clinit>");
method.setModifiers(Modifier.STATIC);
classRef.addConstructor(method);
}
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException("Cannot add " + code
+ " to class initializer of " + fullClass, e));
}
}
public void addCatch(final String fullClass, final String methodSig, final String exceptionClassName, final String src) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.addCatch(src, getClass(exceptionClassName), "$e");
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(
"Cannot add catch for exception of type'"
+ exceptionClassName + " in " + fullClass + "'s "
+ methodSig, e));
}
}
public void insertAtTopOfExceptionHandlers(final String fullClass, final String methodSig, final String exceptionClassName, final String src) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
new EagerExprEditor() {
@Override
public void edit(Handler handler) throws CannotCompileException {
try {
if (handler.getType().getName().equals(exceptionClassName)) {
handler.insertBefore(src);
markEdited();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.instrument(method);
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(
"Cannot edit exception handler for type'"
+ exceptionClassName + " in " + fullClass + "'s "
+ methodSig, e));
}
}
/**
* Replaces the application name in the given method in the given parameter
* to the given constructor call.
*
* Fails silently if the specified method does not exist (e.g.
* CommandFinder's export() function just went away in 1.47i).
*
* @param fullClass
* Fully qualified name of the class to override.
* @param methodSig
* Method signature of the method to override; e.g.,
* "public void showMessage(String title, String message)"
* @param newClassName
* the name of the class which is to be constructed by the new
* operator
* @param parameterIndex
* the index of the parameter containing the application name
* @param replacement
* the code to use instead of the specified parameter
* @throws CannotCompileException
*/
protected void replaceParameterInNew(final String fullClass,
final String methodSig, final String newClassName,
final int parameterIndex, final String replacement) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(NewExpr expr) throws CannotCompileException {
if (expr.getClassName().equals(newClassName))
try {
final CtClass[] parameterTypes = expr
.getConstructor().getParameterTypes();
if (parameterTypes[parameterIndex - 1] != CodeHacker.this
.getClass("java.lang.String")) {
maybeThrow(new IllegalArgumentException("Parameter "
+ parameterIndex + " of "
+ expr.getConstructor() + " is not a String!"));
return;
}
final String replace = replaceParameter(
parameterIndex, parameterTypes.length, replacement);
expr.replace("$_ = new " + newClassName + replace
+ ";");
} catch (NotFoundException e) {
maybeThrow(new IllegalArgumentException(
"Cannot find the parameters of the constructor of "
+ newClassName, e));
}
}
});
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException("Cannot handle app name in " + fullClass
+ "'s " + methodSig, e));
}
}
/**
* Replaces the application name in the given method in the given parameter
* to the given method call.
*
* Fails silently if the specified method does not exist (e.g.
* CommandFinder's export() function just went away in 1.47i).
*
* @param fullClass
* Fully qualified name of the class to override.
* @param methodSig
* Method signature of the method to override; e.g.,
* "public void showMessage(String title, String message)"
* @param calledMethodName
* the name of the method to which the application name is passed
* @param parameterIndex
* the index of the parameter containing the application name
* @param replacement
* the code to use instead of the specified parameter
* @throws CannotCompileException
*/
protected void replaceParameterInCall(final String fullClass,
final String methodSig, final String calledMethodName,
final int parameterIndex, final String replacement) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(MethodCall call) throws CannotCompileException {
if (call.getMethodName().equals(calledMethodName)) try {
final boolean isSuper = call.isSuper();
final CtClass[] parameterTypes = isSuper ?
((ConstructorCall) call).getConstructor().getParameterTypes() :
call.getMethod().getParameterTypes();
if (parameterTypes.length < parameterIndex) {
maybeThrow(new IllegalArgumentException(
"Index " + parameterIndex
+ " is outside of "
+ call.getMethod()
+ "'s parameter list!"));
return;
}
if (parameterTypes[parameterIndex - 1] != CodeHacker.this.getClass("java.lang.String")) {
maybeThrow(new IllegalArgumentException(
"Parameter " + parameterIndex + " of "
+ call.getMethod()
+ " is not a String!"));
return;
}
final String replace = replaceParameter(
parameterIndex, parameterTypes.length, replacement);
call.replace((isSuper ? "" : "$0.") + calledMethodName + replace + ";");
} catch (NotFoundException e) {
maybeThrow(new IllegalArgumentException(
"Cannot find the parameters of the method "
+ calledMethodName, e));
}
}
@Override
public void edit(final ConstructorCall call) throws CannotCompileException {
edit((MethodCall)call);
}
});
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException("Cannot handle app name in " + fullClass
+ "'s " + methodSig, e));
}
}
private String replaceParameter(final int parameterIndex, final int parameterCount, final String replacement) {
final StringBuilder builder = new StringBuilder();
builder.append("(");
for (int i = 1; i <= parameterCount; i++) {
if (i > 1) {
builder.append(", ");
}
builder.append("$").append(i);
if (i == parameterIndex) {
builder.append(".replace(\"ImageJ\", " + replacement + ")");
}
}
builder.append(")");
return builder.toString();
}
/**
* Patches the bytecode of the given method to not return on a null check.
*
* This is needed to patch support for alternative editors into ImageJ 1.x.
*
* @param fullClass the class of the method to instrument
* @param methodSig the signature of the method to instrument
*/
public void dontReturnOnNull(final String fullClass, final String methodSig) {
final CtBehavior behavior = getBehavior(fullClass, methodSig);
final MethodInfo info = behavior.getMethodInfo();
final CodeIterator iterator = info.getCodeAttribute().iterator();
while (iterator.hasNext()) try {
int pos = iterator.next();
final int c = iterator.byteAt(pos);
if (c == Opcode.IFNONNULL && iterator.byteAt(pos + 3) == Opcode.RETURN) {
iterator.writeByte(Opcode.POP, pos++);
iterator.writeByte(Opcode.NOP, pos++);
iterator.writeByte(Opcode.NOP, pos++);
iterator.writeByte(Opcode.NOP, pos++);
return;
}
}
catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(e));
return;
}
maybeThrow(new IllegalArgumentException("Method " + methodSig + " in "
+ fullClass + " does not return on null"));
}
/**
* Replaces the given methods with stub methods.
*
* @param fullClass the class to patch
* @param methodNames the names of the methods to replace
* @throws NotFoundException
* @throws CannotCompileException
*/
public void replaceWithStubMethods(final String fullClass, final String... methodNames) {
final CtClass clazz = getClass(fullClass);
final Set<String> override = new HashSet<String>(Arrays.asList(methodNames));
for (final CtMethod method : clazz.getMethods())
if (override.contains(method.getName())) try {
final CtMethod stub = makeStubMethod(clazz, method);
method.setBody(stub, null);
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(
"Cannot instrument method: " + method.getName(), e));
}
}
/**
* Replaces the superclass.
*
* @param fullClass
* @param fullNewSuperclass
* @throws NotFoundException
*/
public void replaceSuperclass(String fullClass, String fullNewSuperclass) {
final CtClass clazz = getClass(fullClass);
try {
CtClass originalSuperclass = clazz.getSuperclass();
clazz.setSuperclass(getClass(fullNewSuperclass));
for (final CtConstructor ctor : clazz.getConstructors())
ctor.instrument(new ExprEditor() {
@Override
public void edit(final ConstructorCall call) throws CannotCompileException {
if (call.getMethodName().equals("super"))
call.replace("super();");
}
});
letSuperclassMethodsOverride(clazz);
addMissingMethods(clazz, originalSuperclass);
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(
"Could not replace superclass of " + fullClass + " with "
+ fullNewSuperclass, e));
}
}
/**
* Replaces all instantiations of a subset of AWT classes with nulls.
*
* This is used by the partial headless support of legacy code.
*
* @param fullClass
* @throws CannotCompileException
* @throws NotFoundException
*/
public void skipAWTInstantiations(String fullClass) {
try {
skipAWTInstantiations(getClass(fullClass));
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(
"Could not skip AWT class instantiations in " + fullClass,
e));
}
}
/**
* Replaces every field write access to the specified field in the specified method.
*
* @param fullClass the full class
* @param methodSig the signature of the method to instrument
* @param fieldName the field whose write access to override
* @param newCode the code to run instead of the field access
*/
public void overrideFieldWrite(final String fullClass, final String methodSig, final String fieldName, final String newCode) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(final FieldAccess access) throws CannotCompileException {
if (access.getFieldName().equals(access)) {
access.replace(newCode);
}
}
});
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(
"Cannot override field access to " + fieldName + " in "
+ fullClass + "'s " + methodSig, e));
}
}
/**
* Replaces a call in the given method.
*
* @param fullClass the class of the method to edit
* @param methodSig the signature of the method to edit
* @param calledClass the class of the called method to replace
* @param calledMethodName the name of the called method to replace
* @param newCode the code to replace the call with
*/
public void replaceCallInMethod(final String fullClass,
final String methodSig, final String calledClass,
final String calledMethodName, final String newCode) {
replaceCallInMethod(fullClass, methodSig, calledClass, calledMethodName, newCode, -1);
}
/**
* Replaces a call in the given method.
*
* @param fullClass the class of the method to edit
* @param methodSig the signature of the method to edit
* @param calledClass the class of the called method to replace
* @param calledMethodName the name of the called method to replace
* @param newCode the code to replace the call with
* @param onlyNth if positive, only replace the <i>n</i>th call
*/
public void replaceCallInMethod(final String fullClass,
final String methodSig, final String calledClass,
final String calledMethodName, final String newCode, final int onlyNth) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
new EagerExprEditor() {
private int counter = 0;
private final boolean debug = false;
@Override
public void edit(MethodCall call) throws CannotCompileException {
if (debug) {
System.err.println("editing call " + call.getClassName() + "
+ call.getMethodName() + " (wanted " + calledClass
+ "#" + calledMethodName + ")");
}
if (call.getMethodName().equals(calledMethodName)
&& call.getClassName().equals(calledClass)) {
if (onlyNth > 0 && ++counter != onlyNth) return;
call.replace(newCode);
markEdited();
}
}
@Override
public void edit(NewExpr expr) throws CannotCompileException {
if (debug) {
System.err.println("editing call " + expr.getClassName() + "
+ "<init>" + " (wanted " + calledClass
+ "#" + calledMethodName + ")");
}
if ("<init>".equals(calledMethodName)
&& expr.getClassName().equals(calledClass)) {
if (onlyNth > 0 && ++counter != onlyNth) return;
expr.replace(newCode);
markEdited();
}
}
}.instrument(method);
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(
"Cannot handle replace call to " + calledMethodName
+ " in " + fullClass + "'s " + methodSig, e));
}
}
/**
* Loads the given, possibly modified, class.
* <p>
* This method must be called to confirm any changes made with
* {@link #insertAfterMethod}, {@link #insertBeforeMethod},
* or {@link #insertMethod}.
* </p>
*
* @param fullClass Fully qualified class name to load.
* @return the loaded class
*/
public Class<?> loadClass(final String fullClass) {
final CtClass classRef = getClass(fullClass);
return loadClass(classRef);
}
/**
* Loads the given, possibly modified, class.
* <p>
* This method must be called to confirm any changes made with
* {@link #insertAfterMethod}, {@link #insertBeforeMethod},
* or {@link #insertMethod}.
* </p>
*
* @param classRef class to load.
* @return the loaded class
*/
public Class<?> loadClass(final CtClass classRef) {
try {
return classRef.toClass(classLoader, null);
}
catch (final CannotCompileException e) {
// Cannot use LogService; it will not be initialized by the time the DefaultLegacyService
// class is loaded, which is when the CodeHacker is run
if (e.getCause() != null && e.getCause() instanceof LinkageError) {
final URL url = ClassUtils.getLocation(LegacyJavaAgent.class);
final String path = url != null && "file".equals(url.getProtocol()) && url.getPath().endsWith(".jar")?
url.getPath() : "/path/to/ij-legacy.jar";
throw new RuntimeException("Cannot load class: " + classRef.getName() + "\n"
+ "It appears that this class was already defined in the class loader!\n"
+ "Please make sure that you initialize the LegacyService before using\n"
+ "any ImageJ 1.x class. You can do that by adding this static initializer:\n\n"
+ "\tstatic {\n"
+ "\t\tDefaultLegacyService.preinit();\n"
+ "\t}\n\n"
+ "To debug this issue, start the JVM with the option:\n\n"
+ "\t-javaagent:" + path + "\n\n"
+ "To enforce pre-initialization, start the JVM with the option:\n\n"
+ "\t-javaagent:" + path + "=init\n", e.getCause());
}
System.err.println("Warning: Cannot load class: " + classRef.getName() + " into " + classLoader);
e.printStackTrace();
return null;
} finally {
classRef.freeze();
}
}
public void loadClasses() {
try {
LegacyJavaAgent.stop();
} catch (Throwable t) {
// ignore
}
final Iterator<CtClass> iter = handledClasses.iterator();
while (iter.hasNext()) {
final CtClass classRef = iter.next();
if (!classRef.isFrozen() && classRef.isModified()) {
loadClass(classRef);
}
iter.remove();
}
}
/** Gets the Javassist class object corresponding to the given class name. */
private CtClass getClass(final String fullClass) {
try {
final CtClass classRef = pool.get(fullClass);
if (classRef.getClassPool() == pool) handledClasses.add(classRef);
return classRef;
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such class: " + fullClass, e);
}
}
/**
* Gets the method or constructor of the specified class and signature.
*
* @param fullClass the class containing the method or constructor
* @param methodSig the method (or if the name is <code><init></code>, the constructor)
* @return the method or constructor
*/
private CtBehavior getBehavior(final String fullClass, final String methodSig) {
if (methodSig.indexOf("<init>") < 0) {
return getMethod(fullClass, methodSig);
} else {
return getConstructor(fullClass, methodSig);
}
}
/**
* Gets the Javassist method object corresponding to the given method
* signature of the specified class name.
*/
private CtMethod getMethod(final String fullClass, final String methodSig) {
final CtClass cc = getClass(fullClass);
final String name = getMethodName(methodSig);
final String[] argTypes = getMethodArgTypes(methodSig);
final CtClass[] params = new CtClass[argTypes.length];
for (int i = 0; i < params.length; i++) {
params[i] = getClass(argTypes[i]);
}
try {
return cc.getDeclaredMethod(name, params);
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such method: " + methodSig, e);
}
}
/**
* Gets the Javassist constructor object corresponding to the given constructor
* signature of the specified class name.
*/
private CtConstructor getConstructor(final String fullClass, final String constructorSig) {
final CtClass cc = getClass(fullClass);
final String[] argTypes = getMethodArgTypes(constructorSig);
final CtClass[] params = new CtClass[argTypes.length];
for (int i = 0; i < params.length; i++) {
params[i] = getClass(argTypes[i]);
}
try {
return cc.getDeclaredConstructor(params);
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such method: " + constructorSig, e);
}
}
/**
* Generates a new line of code calling the {@link imagej.legacy.patches}
* class and method corresponding to the given method signature.
*/
private String newCode(final String fullClass, final String methodSig) {
final int dotIndex = fullClass.lastIndexOf(".");
final String className = fullClass.substring(dotIndex + 1);
final String methodName = getMethodName(methodSig);
final boolean isStatic = isStatic(methodSig);
final boolean isVoid = isVoid(methodSig);
final String patchClass = PATCH_PKG + "." + className + PATCH_SUFFIX;
for (final CtMethod method : getClass(patchClass).getMethods()) try {
if ((method.getModifiers() & Modifier.STATIC) == 0) continue;
final CtClass[] types = method.getParameterTypes();
if (types.length == 0 || !types[0].getName().equals("imagej.legacy.LegacyService")) {
throw new UnsupportedOperationException("Method " + method + " of class " + patchClass + " has wrong type!");
}
} catch (NotFoundException e) {
e.printStackTrace();
}
final StringBuilder newCode =
new StringBuilder((isVoid ? "" : "return ") + patchClass + "." + methodName + "(");
newCode.append("$service");
if (!isStatic) {
newCode.append(", this");
}
final int argCount = getMethodArgTypes(methodSig).length;
for (int i = 1; i <= argCount; i++) {
newCode.append(", $" + i);
}
newCode.append(");");
return newCode.toString();
}
/** Patches in the current legacy service for '$service' */
private String expand(final String code) {
return code
.replace("$isLegacyMode()", "$service.isLegacyMode()")
.replace("$service", "ij.IJ.getLegacyService()");
}
/** Extracts the method name from the given method signature. */
private String getMethodName(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final int spaceIndex = methodSig.lastIndexOf(" ", parenIndex);
return methodSig.substring(spaceIndex + 1, parenIndex);
}
private String[] getMethodArgTypes(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodArgs =
methodSig.substring(parenIndex + 1, methodSig.length() - 1);
final String[] args =
methodArgs.equals("") ? new String[0] : methodArgs.split(",");
for (int i = 0; i < args.length; i++) {
args[i] = args[i].trim().split(" ")[0];
}
return args;
}
/** Returns true if the given method signature is static. */
private boolean isStatic(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodPrefix = methodSig.substring(0, parenIndex);
for (final String token : methodPrefix.split(" ")) {
if (token.equals("static")) return true;
}
return false;
}
/** Returns true if the given method signature returns void. */
private boolean isVoid(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodPrefix = methodSig.substring(0, parenIndex);
return methodPrefix.startsWith("void ") ||
methodPrefix.indexOf(" void ") > 0;
}
/**
* Determines whether the specified class has the specified field.
*
* @param fullName the class name
* @param fieldName the field name
* @return whether the field exists
*/
public boolean hasField(final String fullName, final String fieldName) {
final CtClass clazz = getClass(fullName);
try {
return clazz.getField(fieldName) != null;
} catch (final Throwable e) {
return false;
}
}
/**
* Determines whether the specified class has the specified method.
*
* @param fullName the class name
* @param methodSig the signature of the method
* @return whether the class has the specified method
*/
public boolean hasMethod(final String fullClass, final String methodSig) {
try {
return getBehavior(fullClass, methodSig) != null;
} catch (final Throwable e) {
return false;
}
}
/**
* Determines whether the specified class is known to Javassist.
*
* @param fullClass
* the class name
* @return whether the class exists
*/
public boolean existsClass(final String fullClass) {
try {
return pool.get(fullClass) != null;
} catch (final Throwable e) {
return false;
}
}
public boolean hasSuperclass(final String fullClass, final String fullSuperclass) {
try {
final CtClass clazz = getClass(fullClass);
return fullSuperclass.equals(clazz.getSuperclass().getName());
} catch (final Throwable e) {
return false;
}
}
private static int verboseLevel = 0;
private static CtMethod makeStubMethod(CtClass clazz, CtMethod original) throws CannotCompileException, NotFoundException {
// add a stub
String prefix = "";
if (verboseLevel > 0) {
prefix = "System.err.println(\"Called " + original.getLongName() + "\\n\"";
if (verboseLevel > 1) {
prefix += "+ \"\\t(\" + fiji.Headless.toString($args) + \")\\n\"";
}
prefix += ");";
}
CtClass type = original.getReturnType();
String body = "{" +
prefix +
(type == CtClass.voidType ? "" : "return " + defaultReturnValue(type) + ";") +
"}";
CtClass[] types = original.getParameterTypes();
return CtNewMethod.make(type, original.getName(), types, new CtClass[0], body, clazz);
}
private static String defaultReturnValue(CtClass type) {
return (type == CtClass.booleanType ? "false" :
(type == CtClass.byteType ? "(byte)0" :
(type == CtClass.charType ? "'\0'" :
(type == CtClass.doubleType ? "0.0" :
(type == CtClass.floatType ? "0.0f" :
(type == CtClass.intType ? "0" :
(type == CtClass.longType ? "0l" :
(type == CtClass.shortType ? "(short)0" : "null"))))))));
}
private void addMissingMethods(CtClass fakeClass, CtClass originalClass) throws CannotCompileException, NotFoundException {
if (verboseLevel > 0)
System.err.println("adding missing methods from " + originalClass.getName() + " to " + fakeClass.getName());
Set<String> available = new HashSet<String>();
for (CtMethod method : fakeClass.getMethods())
available.add(stripPackage(method.getLongName()));
for (CtMethod original : originalClass.getDeclaredMethods()) {
if (available.contains(stripPackage(original.getLongName()))) {
if (verboseLevel > 1)
System.err.println("Skipping available method " + original);
continue;
}
CtMethod method = makeStubMethod(fakeClass, original);
fakeClass.addMethod(method);
if (verboseLevel > 1)
System.err.println("adding missing method " + method);
}
// interfaces
Set<CtClass> availableInterfaces = new HashSet<CtClass>();
for (CtClass iface : fakeClass.getInterfaces())
availableInterfaces.add(iface);
for (CtClass iface : originalClass.getInterfaces())
if (!availableInterfaces.contains(iface))
fakeClass.addInterface(iface);
CtClass superClass = originalClass.getSuperclass();
if (superClass != null && !superClass.getName().equals("java.lang.Object"))
addMissingMethods(fakeClass, superClass);
}
private void letSuperclassMethodsOverride(CtClass clazz) throws CannotCompileException, NotFoundException {
for (CtMethod method : clazz.getSuperclass().getDeclaredMethods()) {
CtMethod method2 = clazz.getMethod(method.getName(), method.getSignature());
if (method2.getDeclaringClass().equals(clazz)) {
method2.setBody(method, null); // make sure no calls/accesses to GUI components are remaining
method2.setName("narf" + method.getName());
}
}
}
private static String stripPackage(String className) {
int lastDot = -1;
for (int i = 0; ; i++) {
if (i >= className.length())
return className.substring(lastDot + 1);
char c = className.charAt(i);
if (c == '.' || c == '$')
lastDot = i;
else if (c >= 'A' && c <= 'Z')
; // continue
else if (c >= 'a' && c <= 'z')
; // continue
else if (i > lastDot + 1 && c >= '0' && c <= '9')
; // continue
else
return className.substring(lastDot + 1);
}
}
private void skipAWTInstantiations(CtClass clazz) throws CannotCompileException, NotFoundException {
clazz.instrument(new ExprEditor() {
@Override
public void edit(NewExpr expr) throws CannotCompileException {
String name = expr.getClassName();
if (name.startsWith("java.awt.Menu") || name.equals("java.awt.PopupMenu") ||
name.startsWith("java.awt.Checkbox") || name.equals("java.awt.Frame")) {
expr.replace("$_ = null;");
} else if (expr.getClassName().equals("ij.gui.StackWindow")) {
expr.replace("$1.show(); $_ = null;");
}
}
@Override
public void edit(MethodCall call) throws CannotCompileException {
final String className = call.getClassName();
final String methodName = call.getMethodName();
if (className.startsWith("java.awt.Menu") || className.equals("java.awt.PopupMenu") ||
className.startsWith("java.awt.Checkbox")) try {
CtClass type = call.getMethod().getReturnType();
if (type == CtClass.voidType) {
call.replace("");
} else {
call.replace("$_ = " + defaultReturnValue(type) + ";");
}
} catch (NotFoundException e) {
e.printStackTrace();
} else if (methodName.equals("put") && className.equals("java.util.Properties")) {
call.replace("if ($1 != null && $2 != null) $_ = $0.put($1, $2); else $_ = null;");
} else if (methodName.equals("get") && className.equals("java.util.Properties")) {
call.replace("$_ = $1 != null ? $0.get($1) : null;");
} else if (className.equals("java.lang.Integer") && methodName.equals("intValue")) {
call.replace("$_ = $0 == null ? 0 : $0.intValue();");
} else if (methodName.equals("addTextListener")) {
call.replace("");
} else if (methodName.equals("elementAt")) {
call.replace("$_ = $0 == null ? null : $0.elementAt($$);");
}
}
});
}
public void handleHTTPS(final String fullClass, final String methodSig) {
try {
final CtBehavior method = getBehavior(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(MethodCall call) throws CannotCompileException {
try {
if (call.getMethodName().equals("startsWith") &&
"http://".equals(getLastConstantArgument(call, 0)))
call.replace("$_ = $0.startsWith($1) || $0.startsWith(\"https:
} catch (BadBytecode e) {
e.printStackTrace();
}
}
});
} catch (final Throwable e) {
maybeThrow(new IllegalArgumentException(
"Could not handle HTTPS in " + methodSig + " in "
+ fullClass));
}
}
private String getLastConstantArgument(final MethodCall call, final int skip) throws BadBytecode {
final int[] indices = new int[skip + 1];
int counter = 0;
final MethodInfo info = ((CtMethod)call.where()).getMethodInfo();
final CodeIterator iterator = info.getCodeAttribute().iterator();
int currentPos = call.indexOfBytecode();
while (iterator.hasNext()) {
int pos = iterator.next();
if (pos >= currentPos)
break;
switch (iterator.byteAt(pos)) {
case Opcode.LDC:
indices[(counter++) % indices.length] = iterator.byteAt(pos + 1);
break;
case Opcode.LDC_W:
indices[(counter++) % indices.length] = iterator.u16bitAt(pos + 1);
break;
}
}
if (counter < skip) {
return null;
}
counter %= indices.length;
if (skip > 0) {
counter -= skip;
if (counter < 0) counter += indices.length;
}
return info.getConstPool().getStringInfo(indices[counter]);
}
/**
* An {@link ExprEditor} that complains when it did not edit anything.
*
* @author Johannes Schindelin
*/
private abstract static class EagerExprEditor extends ExprEditor {
private int count = 0;
protected void markEdited() {
count++;
}
protected boolean wasSuccessful() {
return count > 0;
}
public void instrument(final CtBehavior behavior) throws CannotCompileException {
count = 0;
behavior.instrument(this);
if (!wasSuccessful()) {
throw new CannotCompileException("No code replaced!");
}
}
}
/**
* Disassembles all methods of a class.
*
* @param fullName
* the class name
* @param out
* the output stream
*/
public void disassemble(final String fullName, final PrintStream out) {
disassemble(fullName, out, false);
}
/**
* Disassembles all methods of a class, optionally including superclass
* methods.
*
* @param fullName
* the class name
* @param out
* the output stream
* @param evenSuperclassMethods
* whether to disassemble methods defined in superclasses
*/
public void disassemble(final String fullName, final PrintStream out, final boolean evenSuperclassMethods) {
CtClass clazz = getClass(fullName);
out.println("Class " + clazz.getName());
for (CtConstructor ctor : clazz.getConstructors()) {
disassemble(ctor, out);
}
for (CtMethod method : clazz.getDeclaredMethods())
if (evenSuperclassMethods || method.getDeclaringClass().equals(clazz))
disassemble(method, out);
}
private void disassemble(CtBehavior method, PrintStream out) {
out.println(method.getLongName());
MethodInfo info = method.getMethodInfo2();
ConstPool pool = info.getConstPool();
CodeAttribute code = info.getCodeAttribute();
if (code == null)
return;
CodeIterator iterator = code.iterator();
while (iterator.hasNext()) {
int pos;
try {
pos = iterator.next();
} catch (BadBytecode e) {
throw new RuntimeException(e);
}
out.println(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool));
}
out.println("");
}
/**
* Writes a .jar file with the modified classes.
*
* <p>
* This comes in handy e.g. when ImageJ is to be run in an environment where
* redefining classes is not allowed. If users need to run, say, the legacy
* headless support in such an environment, they need to generate a
* <i>headless.jar</i> file using this method and prepend it to the class
* path (so that the classes of <i>ij.jar</i> are overridden by
* <i>headless.jar</i>'s classes).
* </p>
*
* @param path
* the <i>.jar</i> file to write to
* @throws IOException
*/
public void writeJar(final File path) throws IOException {
final JarOutputStream jar = new JarOutputStream(new FileOutputStream(path));
final DataOutputStream dataOut = new DataOutputStream(jar);
for (final CtClass clazz : handledClasses) {
final ZipEntry entry = new ZipEntry(clazz.getName().replace('.', '/') + ".class");
jar.putNextEntry(entry);
clazz.getClassFile().write(dataOut);
dataOut.flush();
}
jar.close();
}
private void verify(CtClass clazz, PrintWriter output) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(stream);
clazz.getClassFile().write(out);
out.flush();
out.close();
verify(stream.toByteArray(), output);
} catch(Exception e) {
e.printStackTrace();
}
}
private void verify(byte[] bytecode, PrintWriter out) {
try {
Collection<URL> urls;
urls = FileUtils.listContents(new File(System.getProperty("user.home"), "fiji/jars/").toURI().toURL());
if (urls.size() == 0) {
urls = FileUtils.listContents(new File(System.getProperty("user.home"), "Fiji.app/jars/").toURI().toURL());
if (urls.size() == 0) {
urls = FileUtils.listContents(new File("/Applications/Fiji.app/jars/").toURI().toURL());
}
}
ClassLoader loader = new java.net.URLClassLoader(urls.toArray(new URL[urls.size()]));
Class<?> readerClass = null, checkerClass = null;
for (final String prefix : new String[] { "org.", "jruby.", "org.jruby.org." }) try {
readerClass = loader.loadClass(prefix + "objectweb.asm.ClassReader");
checkerClass = loader.loadClass(prefix + "objectweb.asm.util.CheckClassAdapter");
break;
} catch (ClassNotFoundException e) { /* ignore */ }
java.lang.reflect.Constructor<?> ctor = readerClass.getConstructor(new Class[] { bytecode.getClass() });
Object reader = ctor.newInstance(bytecode);
java.lang.reflect.Method verify = checkerClass.getMethod("verify", new Class[] { readerClass, Boolean.TYPE, PrintWriter.class });
verify.invoke(null, new Object[] { reader, false, out });
} catch (Throwable e) {
if (e.getClass().getName().endsWith(".AnalyzerException")) {
final Pattern pattern = Pattern.compile("Error at instruction (\\d+): Argument (\\d+): expected L([^ ,;]+);, but found L(.*);");
final Matcher matcher = pattern.matcher(e.getMessage());
if (matcher.matches()) {
final CtClass clazz1 = getClass(matcher.group(3));
final CtClass clazz2 = getClass(matcher.group(4));
try {
if (clazz2.subtypeOf(clazz1)) return;
} catch (NotFoundException e1) {
e1.printStackTrace();
}
}
}
e.printStackTrace();
}
}
protected void verify(PrintWriter out) {
out.println("Verifying " + handledClasses.size() + " classes");
for (final CtClass clazz : handledClasses) {
out.println("Verifying class " + clazz.getName());
out.flush();
verify(clazz, out);
}
}
/**
* Applies legacy patches, optionally including the headless ones.
*
* <p>
* Intended to be used in unit tests only, for newly-created class loaders,
* via reflection.
* </p>
*
* @param forceHeadless
* also apply the headless patches
*/
@SuppressWarnings("unused")
private static void patch(final boolean forceHeadless) {
final ClassLoader loader = CodeHacker.class.getClassLoader();
final CodeHacker hacker = new CodeHacker(loader, new ClassPool(false));
if (forceHeadless) {
new LegacyHeadless(hacker).patch();
}
new LegacyInjector().injectHooks(hacker);
hacker.loadClasses();
}
} |
package liquibase.database;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import liquibase.database.sql.RawSqlStatement;
import liquibase.database.sql.SqlStatement;
import liquibase.database.structure.DatabaseSnapshot;
import liquibase.database.structure.SybaseASADatabaseSnapshot;
import liquibase.diff.DiffStatusListener;
import liquibase.exception.JDBCException;
/**
* @author otaranenko
*
*/
public class SybaseASADatabase extends AbstractDatabase {
private static final Set<String> systemTablesAndViews;
static {
systemTablesAndViews = new HashSet<String>();
systemTablesAndViews.add("dummy");
systemTablesAndViews.add("sysarticle");
systemTablesAndViews.add("sysarticlecol");
systemTablesAndViews.add("sysarticlecols");
systemTablesAndViews.add("sysarticles");
systemTablesAndViews.add("sysattribute");
systemTablesAndViews.add("sysattributename");
systemTablesAndViews.add("syscapabilities");
systemTablesAndViews.add("syscapability");
systemTablesAndViews.add("syscapabilityname");
systemTablesAndViews.add("syscatalog");
systemTablesAndViews.add("syscolauth");
systemTablesAndViews.add("syscollation");
systemTablesAndViews.add("syscollationmappings");
systemTablesAndViews.add("syscolperm");
systemTablesAndViews.add("syscolstat");
systemTablesAndViews.add("syscolstats");
systemTablesAndViews.add("syscolumn");
systemTablesAndViews.add("syscolumns");
systemTablesAndViews.add("sysdomain");
systemTablesAndViews.add("sysevent");
systemTablesAndViews.add("syseventtype");
systemTablesAndViews.add("sysextent");
systemTablesAndViews.add("sysexternlogins");
systemTablesAndViews.add("sysfile");
systemTablesAndViews.add("sysfkcol");
systemTablesAndViews.add("sysforeignkey");
systemTablesAndViews.add("sysforeignkeys");
systemTablesAndViews.add("sysgroup");
systemTablesAndViews.add("sysgroups");
systemTablesAndViews.add("sysindex");
systemTablesAndViews.add("sysindexes");
systemTablesAndViews.add("sysinfo");
systemTablesAndViews.add("sysixcol");
systemTablesAndViews.add("sysjar");
systemTablesAndViews.add("sysjarcomponent");
systemTablesAndViews.add("sysjavaclass");
systemTablesAndViews.add("syslogin");
systemTablesAndViews.add("sysoptblock");
systemTablesAndViews.add("sysoption");
systemTablesAndViews.add("sysoptions");
systemTablesAndViews.add("sysoptjoinstrategy");
systemTablesAndViews.add("sysoptorder");
systemTablesAndViews.add("sysoptorders");
systemTablesAndViews.add("sysoptplans");
systemTablesAndViews.add("sysoptquantifier");
systemTablesAndViews.add("sysoptrequest");
systemTablesAndViews.add("sysoptrewrite");
systemTablesAndViews.add("sysoptstat");
systemTablesAndViews.add("sysoptstrategies");
systemTablesAndViews.add("sysprocauth");
systemTablesAndViews.add("sysprocedure");
systemTablesAndViews.add("sysprocparm");
systemTablesAndViews.add("sysprocparms");
systemTablesAndViews.add("sysprocperm");
systemTablesAndViews.add("syspublication");
systemTablesAndViews.add("syspublications");
systemTablesAndViews.add("sysremoteoption");
systemTablesAndViews.add("sysremoteoptions");
systemTablesAndViews.add("sysremoteoptiontype");
systemTablesAndViews.add("sysremotetype");
systemTablesAndViews.add("sysremotetypes");
systemTablesAndViews.add("sysremoteuser");
systemTablesAndViews.add("sysremoteusers");
systemTablesAndViews.add("sysschedule");
systemTablesAndViews.add("sysservers");
systemTablesAndViews.add("syssqlservertype");
systemTablesAndViews.add("syssubscription");
systemTablesAndViews.add("syssubscriptions");
systemTablesAndViews.add("syssync");
systemTablesAndViews.add("syssyncdefinitions");
systemTablesAndViews.add("syssyncpublicationdefaults");
systemTablesAndViews.add("syssyncs");
systemTablesAndViews.add("syssyncsites");
systemTablesAndViews.add("syssyncsubscriptions");
systemTablesAndViews.add("syssynctemplates");
systemTablesAndViews.add("syssyncusers");
systemTablesAndViews.add("systabauth");
systemTablesAndViews.add("systable");
systemTablesAndViews.add("systableperm");
systemTablesAndViews.add("systrigger");
systemTablesAndViews.add("systriggers");
systemTablesAndViews.add("systypemap");
systemTablesAndViews.add("sysuserauth");
systemTablesAndViews.add("sysuserlist");
systemTablesAndViews.add("sysusermessages");
systemTablesAndViews.add("sysuseroptions");
systemTablesAndViews.add("sysuserperm");
systemTablesAndViews.add("sysuserperms");
systemTablesAndViews.add("sysusertype");
systemTablesAndViews.add("sysviews");
}
public SybaseASADatabase() {
super();
}
/* (non-Javadoc)
* @see liquibase.database.AbstractDatabase#createDatabaseSnapshot(java.lang.String, java.util.Set)
*/
@Override
public DatabaseSnapshot createDatabaseSnapshot(String schema,
Set<DiffStatusListener> statusListeners) throws JDBCException {
return new SybaseASADatabaseSnapshot(this, statusListeners, schema);
}
@Override
public String escapeIndexName(String schema, String indexName) {
return escapeName(indexName);
}
/* (non-Javadoc)
* @see liquibase.database.Database#getBlobType()
*/
public String getBlobType() {
return "LONG BINARY";
}
/* (non-Javadoc)
* @see liquibase.database.Database#getBooleanType()
*/
public String getBooleanType() {
return "BIT";
}
/* (non-Javadoc)
* @see liquibase.database.Database#getClobType()
*/
public String getClobType() {
return "LONG VARCHAR";
}
/* (non-Javadoc)
* @see liquibase.database.Database#getCurrencyType()
*/
public String getCurrencyType() {
return "MONEY";
}
/* (non-Javadoc)
* @see liquibase.database.Database#getCurrentDateTimeFunction()
*/
public String getCurrentDateTimeFunction() {
return "now()";
}
/* (non-Javadoc)
* @see liquibase.database.Database#getDateTimeType()
*/
public String getDateTimeType() {
return "DATETIME";
}
/* (non-Javadoc)
* @see liquibase.database.Database#getDefaultDriver(java.lang.String)
*/
public String getDefaultDriver(String url) {
return "com.sybase.jdbc3.jdbc.SybDriver";
}
/* (non-Javadoc)
* @see liquibase.database.Database#getProductName()
*/
public String getProductName() {
return "Sybase ASAny";
}
/* (non-Javadoc)
* @see liquibase.database.Database#getTypeName()
*/
public String getTypeName() {
return "asany";
}
/* (non-Javadoc)
* @see liquibase.database.Database#getUUIDType()
*/
public String getUUIDType() {
return "UNIQUEIDENTIFIER";
}
/* (non-Javadoc)
* @see liquibase.database.Database#isCorrectDatabaseImplementation(java.sql.Connection)
*/
public boolean isCorrectDatabaseImplementation(Connection conn) throws JDBCException {
return "Adaptive Server Anywhere".equalsIgnoreCase(getDatabaseProductName(conn))
|| "SQL Anywhere".equalsIgnoreCase(getDatabaseProductName(conn));
}
@Override
public String getDefaultCatalogName() throws JDBCException {
try {
return getConnection().getCatalog();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
@Override
protected String getDefaultDatabaseSchemaName() throws JDBCException {
return null;
}
@Override
public String convertRequestedSchemaToSchema(String requestedSchema)
throws JDBCException {
if (requestedSchema == null) {
return "DBA";
}
return requestedSchema;
}
@Override
public String getDefaultSchemaName() {
// TODO Auto-generated method stub
return super.getDefaultSchemaName();
}
@Override
public String escapeColumnName(String schemaName, String tableName,
String columnName) {
return "[" + columnName + "]";
}
@Override
public String getViewDefinition(String schemaName, String viewName)
throws JDBCException {
// TODO Auto-generated method stub
return super.getViewDefinition(schemaName, viewName);
}
/* (non-Javadoc)
* @see liquibase.database.Database#supportsInitiallyDeferrableColumns()
*/
public boolean supportsInitiallyDeferrableColumns() {
return false;
}
/* (non-Javadoc)
* @see liquibase.database.Database#supportsTablespaces()
*/
public boolean supportsTablespaces() {
return true;
}
@Override
public String convertRequestedSchemaToCatalog(String requestedSchema)
throws JDBCException {
// like in MS SQL
return getDefaultCatalogName();
}
@Override
public Set<String> getSystemTablesAndViews() {
return systemTablesAndViews;
}
@Override
public String getTrueBooleanValue() {
return "1";
}
@Override
public String getFalseBooleanValue() {
return "0";
}
public boolean supportsSequences() {
return false;
}
/* (non-Javadoc)
* @see liquibase.database.AbstractDatabase#getAutoIncrementClause()
*/
@Override
public String getAutoIncrementClause() {
return "default autoincrement";
}
@Override
public SqlStatement getViewDefinitionSql(String schemaName, String viewName) throws JDBCException {
String sql = "select viewtext from sysviews where upper(viewname)='" + viewName.toUpperCase() + "' and upper(vcreator) = '" + schemaName.toUpperCase() + '\'';
return new RawSqlStatement(sql);
}
private String escapeName(String indexName) {
return '[' + indexName + ']';
}
} |
package com.satsumasoftware.timetable.ui;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import com.satsumasoftware.timetable.R;
public abstract class BaseActivity extends AppCompatActivity {
protected static final int NAVDRAWER_ITEM_HOME = R.id.navigation_item_home;
protected static final int NAVDRAWER_ITEM_SCHEDULE = R.id.navigation_item_schedule;
protected static final int NAVDRAWER_ITEM_CLASSES = R.id.navigation_item_classes;
protected static final int NAVDRAWER_ITEM_TODO = R.id.navigation_item_todo;
protected static final int NAVDRAWER_ITEM_ASSIGNMENTS = R.id.navigation_item_assignments;
protected static final int NAVDRAWER_ITEM_EXAMS = R.id.navigation_item_exams;
protected static final int NAVDRAWER_ITEM_MANAGE_TIMETABLES = R.id.navigation_item_manage_timetables;
protected static final int NAVDRAWER_ITEM_SETTINGS = R.id.navigation_item_settings;
protected static final int NAVDRAWER_ITEM_INVALID = -1;
private static final int NAVDRAWER_LAUNCH_DELAY = 250;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private NavigationView mNavigationView;
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerLayout = getSelfDrawerLayout();
if (mDrawerLayout == null) {
return;
}
setupLayout();
}
/**
* This method should be overridden in subclasses of BaseActivity to use the Toolbar
* Return null if there is no Toolbar
*/
protected Toolbar getSelfToolbar() {
return null;
}
/**
* This method should be overridden in subclasses of BaseActivity to use the DrawerLayout
* Return null if there is no DrawerLayout
*/
protected DrawerLayout getSelfDrawerLayout() {
return null;
}
/**
* Returns the navigation drawer item that corresponds to this Activity. Subclasses
* of BaseActivity override this to indicate what nav drawer item corresponds to them
* Return NAVDRAWER_ITEM_INVALID to mean that this Activity should not have a Nav Drawer.
*/
protected int getSelfNavDrawerItem() {
return NAVDRAWER_ITEM_INVALID;
}
/**
* Returns the NavigationView that corresponds to this Activity. Subclasses
* of BaseActivity override this to indicate what nav drawer item corresponds to them
* Return null to mean that this Activity should not have a Nav Drawer.
*/
protected NavigationView getSelfNavigationView() {
return null;
}
private void setupLayout() {
Toolbar toolbar = getSelfToolbar();
if (toolbar != null) {
setSupportActionBar(toolbar);
}
mNavigationView = getSelfNavigationView();
if (mNavigationView == null) {
return;
}
mNavigationView.getMenu().findItem(getSelfNavDrawerItem()).setChecked(true);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
handleNavigationSelection(menuItem);
return true;
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
private void handleNavigationSelection(final MenuItem menuItem) {
if (menuItem.getItemId() == getSelfNavDrawerItem()) {
mDrawerLayout.closeDrawers();
return;
}
// Launch the target Activity after a short delay, to allow the close animation to play
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
goToNavDrawerItem(menuItem.getItemId());
}
}, NAVDRAWER_LAUNCH_DELAY);
if (menuItem.isCheckable()) {
mNavigationView.getMenu().findItem(getSelfNavDrawerItem()).setChecked(false);
menuItem.setChecked(true);
}
mDrawerLayout.closeDrawers();
}
private void goToNavDrawerItem(int menuItem) {
Intent intent = null;
switch (menuItem) {
case NAVDRAWER_ITEM_HOME:
intent = new Intent(this, MainActivity.class);
break;
case NAVDRAWER_ITEM_SCHEDULE:
intent = new Intent(this, ScheduleActivity.class);
break;
case NAVDRAWER_ITEM_CLASSES:
intent = new Intent(this, ClassesActivity.class);
break;
case NAVDRAWER_ITEM_TODO:
intent = new Intent(this, AssignmentsActivity.class);
intent.putExtra(AssignmentsActivity.EXTRA_MODE, AssignmentsActivity.DISPLAY_TODO);
break;
case NAVDRAWER_ITEM_ASSIGNMENTS:
intent = new Intent(this, AssignmentsActivity.class);
break;
case NAVDRAWER_ITEM_EXAMS:
intent = new Intent(this, ExamsActivity.class);
break;
case NAVDRAWER_ITEM_MANAGE_TIMETABLES:
intent = new Intent(this, TimetablesActivity.class);
break;
case NAVDRAWER_ITEM_SETTINGS:
intent = new Intent(this, SettingsActivity.class);
break;
}
if (intent == null) {
return;
}
startActivity(intent);
overridePendingTransition(0, 0);
finish();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggle
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
} |
package cz.vutbr.fit.iha.widget;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.SparseArray;
import cz.vutbr.fit.iha.R;
import cz.vutbr.fit.iha.adapter.Adapter;
import cz.vutbr.fit.iha.adapter.device.Device;
import cz.vutbr.fit.iha.adapter.device.DeviceType;
import cz.vutbr.fit.iha.adapter.device.Facility;
import cz.vutbr.fit.iha.adapter.device.RefreshInterval;
import cz.vutbr.fit.iha.controller.Controller;
import cz.vutbr.fit.iha.util.Log;
import cz.vutbr.fit.iha.util.TimeHelper;
import cz.vutbr.fit.iha.util.UnitsHelper;
public class WidgetUpdateService extends Service {
private static final String TAG = WidgetUpdateService.class.getSimpleName();
private static final String EXTRA_FORCE_UPDATE = "cz.vutbr.fit.iha.forceUpdate";
public static final int UPDATE_INTERVAL_DEFAULT = 5; // in seconds
public static final int UPDATE_INTERVAL_MIN = 1; // in seconds
/** Helpers for managing service updating **/
public static void startUpdating(Context context, int[] appWidgetIds) {
final Intent intent = getUpdateIntent(context);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
// Start update service
context.startService(intent);
}
public static void stopUpdating(Context context) {
// Cancel already planned alarm
AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
m.cancel(getUpdatePendingIntent(context));
// Stop update service
final Intent intent = getUpdateIntent(context);
context.stopService(intent);
}
private void setAlarm(long triggerAtMillis) {
// Set new alarm time
Context context = getApplicationContext();
AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
m.set(AlarmManager.ELAPSED_REALTIME, triggerAtMillis, getUpdatePendingIntent(context));
}
/** Intent factories **/
private static Intent getUpdateIntent(Context context) {
return new Intent(context, WidgetUpdateService.class);
}
private static PendingIntent getUpdatePendingIntent(Context context) {
final Intent intent = getUpdateIntent(context);
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
public static Intent getForceUpdateIntent(Context context, int widgetId) {
Intent intent = new Intent(context, WidgetUpdateService.class);
intent.putExtra(WidgetUpdateService.EXTRA_FORCE_UPDATE, true);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
widgetId
});
return intent;
}
public static PendingIntent getForceUpdatePendingIntent(Context context, int widgetId) {
final Intent intent = getForceUpdateIntent(context, widgetId);
return PendingIntent.getService(context, widgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
/** Service override methods **/
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
boolean forceUpdate = intent.getBooleanExtra(EXTRA_FORCE_UPDATE, false);
Log.v(TAG, String.format("onStartCommand(), startId = %d, forceUpdate = %b", startId, forceUpdate));
if (!forceUpdate) {
// set alarm for next update
long nextUpdate = calcNextUpdate();
if (nextUpdate > 0) {
Log.d(TAG, String.format("Next update in %d seconds", (int) (nextUpdate - SystemClock.elapsedRealtime()) / 1000));
setAlarm(nextUpdate);
} else {
Log.d(TAG, "No planned next update");
}
}
// don't update when screen is off
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (!pm.isScreenOn()) {
Log.v(TAG, "Screen is off, exiting...");
stopSelf();
return START_NOT_STICKY;
}
// start new thread for processing
new Thread(new Runnable() {
@Override
public void run() {
updateWidgets(intent);
stopSelf();
}
}).start();
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null; // we don't use binding
}
private void updateWidgets(Intent intent) {
// get ids from intent
int[] widgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
if (widgetIds == null || widgetIds.length == 0) {
// if there are no ids, get ids of all widgets
widgetIds = getAllWidgetIds();
}
SensorWidgetProvider widgetProvider = new SensorWidgetProvider();
long now = SystemClock.elapsedRealtime();
Controller controller = Controller.getInstance(getApplicationContext());
SharedPreferences userSettings = controller.getUserSettings();
// UserSettings can be null when user is not logged in!
UnitsHelper unitsHelper = (userSettings == null) ? null : new UnitsHelper(userSettings, getApplicationContext());
TimeHelper timeHelper = (userSettings == null) ? null : new TimeHelper(userSettings);
// Reload adapters to have data about Timezone offset
controller.reloadAdapters(false);
boolean forceUpdate = intent.getBooleanExtra(EXTRA_FORCE_UPDATE, false);
SparseArray<WidgetData> widgetsToUpdate = new SparseArray<WidgetData>();
// Reload facilities data
List<Facility> facilities = new ArrayList<Facility>();
for (int widgetId : widgetIds) {
WidgetData widgetData = new WidgetData(widgetId);
widgetData.loadData(this);
// Ignore uninitialized widgets
if (!widgetData.initialized) {
Log.v(TAG, String.format("Ignoring widget %d (not initialized)", widgetId));
continue;
}
// Don't update widgets until their interval elapsed or we have force update
if (!forceUpdate && !widgetData.isExpired(now)) {
Log.v(TAG, String.format("Ignoring widget %d (not expired nor forced)", widgetId));
continue;
}
// Remember we're updating this widget
widgetsToUpdate.put(widgetId, widgetData);
// Prepare list of facilities for network request
if (!widgetData.deviceId.isEmpty() && !widgetData.deviceAdapterId.isEmpty()) {
String[] ids = widgetData.deviceId.split(Device.ID_SEPARATOR, 2);
Facility facility = new Facility();
facility.setAdapterId(widgetData.deviceAdapterId);
facility.setAddress(ids[0]);
facility.setLastUpdate(new DateTime(widgetData.deviceLastUpdateTime, DateTimeZone.UTC));
facility.setRefresh(RefreshInterval.fromInterval(widgetData.deviceRefresh));
int type = Integer.parseInt(ids[1]);
facility.addDevice(DeviceType.createDeviceFromType(type));
facilities.add(facility);
}
}
if (!facilities.isEmpty()) {
controller.updateFacilities(facilities, forceUpdate);
}
for (int i = 0; i < widgetsToUpdate.size(); i++) {
WidgetData widgetData = widgetsToUpdate.valueAt(i);
int widgetId = widgetData.getWidgetId();
Adapter adapter = controller.getAdapter(widgetData.deviceAdapterId);
Device device = controller.getDevice(widgetData.deviceAdapterId, widgetData.deviceId);
if (device != null) {
// Get fresh data from device
widgetData.deviceIcon = device.getIconResource();
widgetData.deviceName = device.getName();
widgetData.deviceAdapterId = device.getFacility().getAdapterId();
widgetData.deviceId = device.getId();
widgetData.lastUpdate = now;
widgetData.deviceLastUpdateTime = device.getFacility().getLastUpdate().getMillis();
widgetData.deviceRefresh = device.getFacility().getRefresh().getInterval();
// Check if we can format device's value (unitsHelper is null when user is not logged in)
if (unitsHelper != null) {
widgetData.deviceValue = unitsHelper.getStringValueUnit(device.getValue());
}
// Check if we can format device's last update (timeHelper is null when user is not logged in)
if (timeHelper != null) {
// NOTE: This should use always absolute time, because widgets aren't updated so often
widgetData.deviceLastUpdateText = timeHelper.formatLastUpdate(device.getFacility().getLastUpdate(), adapter);
}
// Save fresh data
widgetData.saveData(getApplicationContext());
Log.v(TAG, String.format("Updating widget (%d) with fresh data", widgetId));
} else {
// NOTE: just temporary solution until it will be showed better on widget
widgetData.deviceLastUpdateText = String
.format("%s %s", widgetData.deviceLastUpdateText, getString(R.string.widget_cached));
Log.v(TAG, String.format("Updating widget (%d) with cached data", widgetId));
}
// Update widget
widgetProvider.updateWidget(this, widgetData);
}
}
private long calcNextUpdate() {
int minInterval = 0;
long nextUpdate = 0;
long now = SystemClock.elapsedRealtime();
boolean first = true;
for (int widgetId : getAllWidgetIds()) {
WidgetData widgetData = new WidgetData(widgetId);
widgetData.loadData(this);
if (!widgetData.initialized) {
// widget is not added yet (probably only configuration activity is showed)
continue;
}
if (first) {
minInterval = widgetData.interval;
nextUpdate = widgetData.getNextUpdate(now);
first = false;
} else {
minInterval = Math.min(minInterval, widgetData.interval);
nextUpdate = Math.min(nextUpdate, widgetData.getNextUpdate(now));
}
}
minInterval = Math.max(minInterval, UPDATE_INTERVAL_MIN);
return first ? 0 : Math.max(nextUpdate, SystemClock.elapsedRealtime() + minInterval * 1000);
}
private List<Integer> getWidgetIds(Class<?> cls) {
ComponentName thisWidget = new ComponentName(this, cls);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
List<Integer> arr = new ArrayList<Integer>();
for (int i : appWidgetManager.getAppWidgetIds(thisWidget)) {
arr.add(i);
}
return arr;
}
private int[] getAllWidgetIds() {
List<Integer> ids = new ArrayList<Integer>();
ids.addAll(getWidgetIds(SensorWidgetProviderSmall.class));
ids.addAll(getWidgetIds(SensorWidgetProviderMedium.class));
ids.addAll(getWidgetIds(SensorWidgetProviderLarge.class));
int[] arr = new int[ids.size()];
for (int i = 0; i < ids.size(); i++) {
arr[i] = ids.get(i);
}
return arr;
}
} |
package com.wsfmn.habitcontroller;
import android.util.Log;
import com.wsfmn.habit.Date;
import com.wsfmn.habit.Habit;
import com.wsfmn.habit.HabitList;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class HabitListController {
private static HabitList habitList = null;
public HabitListController(){
getInstance();
}
public static HabitList getInstance() {
if (habitList == null) {
habitList = new HabitList();
init();
}
return habitList;
}
public void addHabit(Habit habit) {
// Added by nmayne on 2017-11-07
OnlineController.StoreHabits storeHabitsOnline =
new OnlineController.StoreHabits();
storeHabitsOnline.execute(habit);
habitList.addHabit(habit);
}
public void deleteHabit(Habit habit){
// Added by nmayne on 2017-11-07
OnlineController.DeleteHabits deleteHabitsOnline =
new OnlineController.DeleteHabits();
deleteHabitsOnline.execute(habit);
habitList.deleteHabit(habit);
}
public void deleteHabitAt(int index){
// Added by nmayne on 2017-11-07
OnlineController.DeleteHabits deleteHabitsOnline =
new OnlineController.DeleteHabits();
deleteHabitsOnline.execute(habitList.getHabit(index));
habitList.deleteHabitAt(index);
}
public int getSize() {
return habitList.getSize();
}
public void addAllHabits(List<Habit> habitsToAdd) {
// Added by nmayne on 2017-11-07
OnlineController.StoreHabits storeHabitsOnline =
new OnlineController.StoreHabits();
Habit[] habitArray = new Habit[habitsToAdd.size()];
for (int i = 0; i < habitsToAdd.size(); i++) {
habitArray[i] = habitsToAdd.get(i);
}
storeHabitsOnline.execute(habitArray);
habitList.addAllHabits(habitsToAdd);
}
public Habit getHabit(int index){
return habitList.getHabit(index);
}
public void setHabit(int index, Habit habit){
habitList.setHabit(index, habit);
}
public boolean hasHabit(Habit habit){
return habitList.hasHabit(habit);
}
public ArrayList<Habit> getHabitList(){
return habitList.getHabitList();
}
public ArrayList<Habit> getHabitsForToday(){
return habitList.getHabitsForToday();
}
/**
* Used to load local data into habitList once it is first created.
*/
public static void init() {
try {
OfflineController.GetHabitList getHabitListOffline =
new OfflineController.GetHabitList();
getHabitListOffline.execute();
habitList = getHabitListOffline.get();
} catch (InterruptedException e) {
Log.i("Error", e.getMessage());
} catch (ExecutionException e) {
Log.i("Error", e.getMessage());
}
}
/**
* Stores HabitList data locally.
*/
public void store(){
OfflineController.StoreHabitList storeHabitListOffline =
new OfflineController.StoreHabitList();
storeHabitListOffline.execute(habitList);
}
/**
* Updates a Habit online
* @param h a habit to update online
*/
public void updateOnline(Habit h) {
OnlineController.StoreHabits storeHabitsOnline =
new OnlineController.StoreHabits();
storeHabitsOnline.execute(h);
}
} |
package fr.isen.cir58.teamregalad.regaplay.audio;
import android.os.Parcel;
import android.os.Parcelable;
public class Song implements Parcelable {
public static final Creator<Song> CREATOR = new Creator<Song>() {
@Override
public Song createFromParcel(Parcel in) {
return new Song(in);
}
@Override
public Song[] newArray(int size) {
return new Song[size];
}
};
private long ID;
private String title;
private String path;
private int artistID;
private String artist;
private int albumID;
private String album;
private int year;
private int duration;
private String genre;
private String coverPath;
public Song(long ID, String title, String path, int artistID, String artist, int albumID, String album, int year, int duration, String genre, String coverPath) {
this.ID = ID;
this.title = title;
this.path = path;
this.artistID = artistID;
this.artist = artist;
this.albumID = albumID;
this.album = album;
this.year = year;
this.duration = duration;
this.genre = genre;
this.coverPath = coverPath;
}
protected Song(Parcel in) {
ID = in.readLong();
title = in.readString();
path = in.readString();
artistID = in.readInt();
artist = in.readString();
albumID = in.readInt();
album = in.readString();
year = in.readInt();
duration = in.readInt();
genre = in.readString();
coverPath = in.readString();
}
public long getID() {
return ID;
}
public void setID(long ID) {
this.ID = ID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getArtistID() {
return artistID;
}
public void setArtistID(int artistID) {
this.artistID = artistID;
}
public int getAlbumID() {
return albumID;
}
public void setAlbumID(int albumID) {
this.albumID = albumID;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getCoverPath() {
return coverPath;
}
public void setCoverPath(String coverPath) {
this.coverPath = coverPath;
}
@Override
public String toString() {
return title + " (ID " + String.valueOf(ID) + ") " + "\n" +
artist + " (ID " + String.valueOf(artistID) + ") " + "\n" +
album + " (ID " + String.valueOf(albumID) + ") " + "\n" +
year + "\n" +
duration + "\n" +
genre + "\n " +
path;
}
public String shareSongInfos() {
return "I'm listening to " + title + " - " + artist + " (" + album + " - " + year + ") with RegaPlay";
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(ID);
parcel.writeString(title);
parcel.writeString(path);
parcel.writeInt(artistID);
parcel.writeString(artist);
parcel.writeInt(albumID);
parcel.writeString(album);
parcel.writeInt(year);
parcel.writeInt(duration);
parcel.writeString(genre);
parcel.writeString(coverPath);
}
} |
package gregpearce.archivorg.ui.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.bluelinelabs.conductor.Conductor;
import com.bluelinelabs.conductor.Router;
import com.bluelinelabs.conductor.RouterTransaction;
import gregpearce.archivorg.R;
import gregpearce.archivorg.di.ControllerComponent;
import gregpearce.archivorg.ui.BaseController;
import gregpearce.archivorg.ui.OverlayChildRouter;
import gregpearce.archivorg.ui.discover.DiscoverController;
import java.util.List;
import timber.log.Timber;
public class MainActivity extends AppCompatActivity implements DrawerLayoutProvider {
@BindView(R.id.controller_container) ViewGroup container;
@BindView(R.id.drawer_layout) DrawerLayout drawerLayout;
private Router router;
private enum RootController {Discover, Bookmarks, Downloads}
private RootController rootController;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// Set up the navigation drawer.
drawerLayout.setStatusBarBackground(R.color.colorPrimaryDark);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
router = Conductor.attachRouter(this, container, savedInstanceState);
if (!router.hasRootController()) {
rootController = RootController.Discover;
router.setRoot(RouterTransaction.with(new DiscoverController()));
}
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(menuItem -> {
switch (menuItem.getItemId()) {
case R.id.drawer_discover:
if (rootController != RootController.Discover) {
rootController = RootController.Discover;
router.setRoot(RouterTransaction.with(new DiscoverController()));
}
break;
case R.id.drawer_bookmarks:
if (rootController != RootController.Bookmarks) {
rootController = RootController.Bookmarks;
//router.setRoot(RouterTransaction.with(new DiscoverController()));
}
break;
case R.id.drawer_downloads:
if (rootController != RootController.Downloads) {
rootController = RootController.Downloads;
//router.setRoot(RouterTransaction.with(new DiscoverController()));
}
break;
default:
Timber.e("Unknown drawer option");
break;
}
// Close the navigation drawer when an item is selected.
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
});
}
@Override public void onBackPressed() {
if (drawerLayout != null && drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else if (!router.handleBack()) {
super.onBackPressed();
} else {
super.onBackPressed();
}
}
public BaseController getActivityController() {
List<RouterTransaction> backstack = router.getBackstack();
return (BaseController) backstack.get(backstack.size() - 1).controller();
}
@Override public DrawerLayout getDrawerLayout() {
return drawerLayout;
}
} |
package jp.hazuki.yuzubrowser.download;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import jp.hazuki.yuzubrowser.R;
import jp.hazuki.yuzubrowser.settings.data.AppData;
import jp.hazuki.yuzubrowser.utils.HttpUtils;
import jp.hazuki.yuzubrowser.utils.WebDownloadUtils;
import jp.hazuki.yuzubrowser.utils.view.filelist.FileListButton;
import jp.hazuki.yuzubrowser.utils.view.filelist.FileListViewController;
import jp.hazuki.yuzubrowser.webkit.CustomWebView;
public class DownloadDialog {
private final DownloadRequestInfo mInfo;
private final Context mContext;
private CustomWebView mWebView;
private EditText filenameEditText;
private FileListButton folderButton;
private CheckBox saveArchiveCheckBox;
public DownloadDialog(final Context context, DownloadRequestInfo info) {
mInfo = info;
mContext = context;
}
public void show() {
View view = LayoutInflater.from(mContext).inflate(R.layout.download_dialog, null);
filenameEditText = (EditText) view.findViewById(R.id.filenameEditText);
filenameEditText.setText(mInfo.getFile().getName());
setRealItemName();
folderButton = (FileListButton) view.findViewById(R.id.folderButton);
folderButton.setText(mInfo.getFile().getParentFile().getName());
folderButton.setFilePath(mInfo.getFile().getParentFile());
folderButton.setShowDirectoryOnly(true);
folderButton.setOnFileSelectedListener(new FileListViewController.OnFileSelectedListener() {
@Override
public void onFileSelected(File file) {
if (file != null)
folderButton.setText(file.getName());
}
@Override
public boolean onDirectorySelected(File file) {
return false;
}
});
saveArchiveCheckBox = (CheckBox) view.findViewById(R.id.saveArchiveCheckBox);
setCanSaveArchive(mWebView);
saveArchiveCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mInfo.setFile(WebDownloadUtils.guessDownloadFile(mInfo.getFile().getParent(), mInfo.getUrl(), null, "application/x-webarchive-xml"));//TODO contentDisposition
} else {
mInfo.setFile(WebDownloadUtils.guessDownloadFile(mInfo.getFile().getParent(), mInfo.getUrl(), null, null));//TODO contentDisposition, mimetype
}
filenameEditText.setText(mInfo.getFile().getName());
}
});
new AlertDialog.Builder(mContext)
.setTitle(R.string.download)
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String filename = filenameEditText.getText().toString();
if (TextUtils.isEmpty(filename)) {
show();
return;
}
File file = new File(folderButton.getCurrentFolder(), filename);
mInfo.setFile(file);
if (!file.exists()) {
startDownload(mInfo);
} else {
new AlertDialog.Builder(mContext)
.setTitle(R.string.confirm)
.setMessage(R.string.download_file_overwrite)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startDownload(mInfo);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
show();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
show();
}
})
.show();
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void setRealItemName() {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(mInfo.getUrl());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
String cookie = CookieManager.getInstance().getCookie(mInfo.getUrl());
if (!TextUtils.isEmpty(cookie)) {
conn.setRequestProperty("Cookie", cookie);
}
String referer = mInfo.getReferer();
if (!TextUtils.isEmpty(referer)) {
conn.setRequestProperty("Referer", referer);
}
conn.connect();
final File file = HttpUtils.getFileName(mInfo.getUrl(), null, conn.getHeaderFields());
handler.post(new Runnable() {
@Override
public void run() {
if (filenameEditText.getText().toString().equals(mInfo.getFile().getName()))
filenameEditText.setText(file.getName());
}
});
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
protected Context getContext() {
return mContext;
}
protected DownloadInfo getDownloadInfo() {
return mInfo;
}
protected void startDownload(DownloadInfo info) {
if (isSaveArchive()) {
File file = info.getFile();
mWebView.saveWebArchiveMethod(file.getAbsolutePath());
Context context = getContext().getApplicationContext();
if (file.exists())
Toast.makeText(context, context.getString(R.string.saved_file) + info.getFile().getAbsolutePath(), Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, context.getString(R.string.failed), Toast.LENGTH_SHORT).show();
} else {
DownloadService.startDownloadService(mContext, mInfo);
}
}
public void setCanSaveArchive(CustomWebView webview) {
mWebView = webview;
if (saveArchiveCheckBox != null) {
saveArchiveCheckBox.setVisibility((webview != null) ? View.VISIBLE : View.GONE);
}
}
protected boolean isSaveArchive() {
return saveArchiveCheckBox.getVisibility() == View.VISIBLE && saveArchiveCheckBox.isChecked();
}
public static DownloadDialog showDownloadDialog(Context context, String url, String userAgent, String contentDisposition, String mimetype, long contentLength, String referer) {
File file = WebDownloadUtils.guessDownloadFile(AppData.download_folder.get(), url, contentDisposition, mimetype);
DownloadRequestInfo info = new DownloadRequestInfo(url, file, null, contentLength);//TODO referer
return showDownloadDialog(context, info);
}
public static DownloadDialog showDownloadDialog(Context context, String url) {
return showDownloadDialog(context, url, null, null);
}
public static DownloadDialog showDownloadDialog(Context context, String url, String referer, String defaultExt) {
File file = WebDownloadUtils.guessDownloadFile(AppData.download_folder.get(), url, null, null, defaultExt);
DownloadRequestInfo info = new DownloadRequestInfo(url, file, referer, -1);
return showDownloadDialog(context, info);
}
public static DownloadDialog showDownloadDialog(Context context, DownloadRequestInfo info) {
DownloadDialog dialog = new DownloadDialog(context, info);
dialog.show();
return dialog;
}
public static DownloadDialog showArchiveDownloadDialog(Context context, String url, CustomWebView webview) {
DownloadDialog dialog = showDownloadDialog(context, url);
dialog.setCanSaveArchive(webview);
return dialog;
}
} |
package me.devsaki.hentoid.activities;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.customview.widget.ViewDragHelper;
import androidx.documentfile.provider.DocumentFile;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import com.mikepenz.fastadapter.select.SelectExtension;
import com.skydoves.balloon.ArrowOrientation;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.devsaki.hentoid.BuildConfig;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.database.CollectionDAO;
import me.devsaki.hentoid.database.ObjectBoxDAO;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.enums.Grouping;
import me.devsaki.hentoid.events.AppUpdatedEvent;
import me.devsaki.hentoid.events.CommunicationEvent;
import me.devsaki.hentoid.fragments.library.LibraryContentFragment;
import me.devsaki.hentoid.fragments.library.LibraryGroupsFragment;
import me.devsaki.hentoid.fragments.library.UpdateSuccessDialogFragment;
import me.devsaki.hentoid.notification.archive.ArchiveCompleteNotification;
import me.devsaki.hentoid.notification.archive.ArchiveNotificationChannel;
import me.devsaki.hentoid.notification.archive.ArchiveProgressNotification;
import me.devsaki.hentoid.notification.archive.ArchiveStartNotification;
import me.devsaki.hentoid.notification.delete.DeleteCompleteNotification;
import me.devsaki.hentoid.notification.delete.DeleteNotificationChannel;
import me.devsaki.hentoid.notification.delete.DeleteProgressNotification;
import me.devsaki.hentoid.notification.delete.DeleteStartNotification;
import me.devsaki.hentoid.util.ContentHelper;
import me.devsaki.hentoid.util.Debouncer;
import me.devsaki.hentoid.util.FileHelper;
import me.devsaki.hentoid.util.PermissionHelper;
import me.devsaki.hentoid.util.Preferences;
import me.devsaki.hentoid.util.TooltipHelper;
import me.devsaki.hentoid.util.exception.ContentNotRemovedException;
import me.devsaki.hentoid.util.exception.FileNotRemovedException;
import me.devsaki.hentoid.util.notification.NotificationManager;
import me.devsaki.hentoid.viewmodels.LibraryViewModel;
import me.devsaki.hentoid.viewmodels.ViewModelFactory;
import timber.log.Timber;
import static com.google.android.material.snackbar.BaseTransientBottomBar.LENGTH_LONG;
import static me.devsaki.hentoid.events.CommunicationEvent.EV_ADVANCED_SEARCH;
import static me.devsaki.hentoid.events.CommunicationEvent.EV_CLOSED;
import static me.devsaki.hentoid.events.CommunicationEvent.EV_DISABLE;
import static me.devsaki.hentoid.events.CommunicationEvent.EV_ENABLE;
import static me.devsaki.hentoid.events.CommunicationEvent.EV_SEARCH;
import static me.devsaki.hentoid.events.CommunicationEvent.EV_UPDATE_SORT;
import static me.devsaki.hentoid.events.CommunicationEvent.RC_CONTENTS;
import static me.devsaki.hentoid.events.CommunicationEvent.RC_DRAWER;
import static me.devsaki.hentoid.events.CommunicationEvent.RC_GROUPS;
@SuppressLint("NonConstantResourceId")
public class LibraryActivity extends BaseActivity {
private DrawerLayout drawerLayout;
// Viewmodel
private LibraryViewModel viewModel;
// Settings listener
private final SharedPreferences.OnSharedPreferenceChangeListener prefsListener = (p, k) -> onSharedPreferenceChanged(k);
// Action view associated with search menu button
private SearchView actionSearchView;
// Grey background of the advanced search / sort bar
private View searchSortBar;
// Advanced search text button
private View advancedSearchButton;
// Show artists / groups button
private TextView showArtistsGroupsButton;
// CLEAR button
private View searchClearButton;
// Sort direction button
private ImageView sortDirectionButton;
// Sort reshuffle button
private ImageView sortReshuffleButton;
// Sort field button
private TextView sortFieldButton;
// Background and text of the alert bar
private TextView alertTxt;
// Icon of the alert bar
private View alertIcon;
// Action button ("fix") of the alert bar
private View alertFixBtn;
private Toolbar toolbar;
// "Search" button on top menu
private MenuItem searchMenu;
// "Edit mode" / "Validate edit" button on top menu
private MenuItem reorderMenu;
// "Cancel edit" button on top menu
private MenuItem reorderCancelMenu;
// "Create new group" button on top menu
private MenuItem newGroupMenu;
// "Toggle completed" button on top menu
private MenuItem completedFilterMenu;
// "Toggle favourites" button on top menu
private MenuItem favsMenu;
// "Sort" button on top menu
private MenuItem sortMenu;
// Alert bars
private PopupMenu autoHidePopup;
private Toolbar selectionToolbar;
private MenuItem editNameMenu;
private MenuItem deleteMenu;
private MenuItem completedMenu;
private MenuItem shareMenu;
private MenuItem archiveMenu;
private MenuItem changeGroupMenu;
private MenuItem folderMenu;
private MenuItem redownloadMenu;
private MenuItem coverMenu;
private ViewPager2 viewPager;
// Deletion activities
private NotificationManager deleteNotificationManager;
private int deleteProgress;
private int deleteMax;
// Notification for book archival
private NotificationManager archiveNotificationManager;
private int archiveProgress;
private int archiveMax;
// Used to ignore native calls to onQueryTextChange
private boolean invalidateNextQueryTextChange = false;
// Current text search query
private String query = "";
// Current metadata search query
private List<Attribute> metadata = Collections.emptyList();
// True if item positioning edit mode is on (only available for specific groupings)
private boolean editMode = false;
// True if there's at least one existing custom group; false instead
private boolean isCustomGroupingAvailable;
// Titles of each of the Viewpager2's tabs
private final Map<Integer, String> titles = new HashMap<>();
// TODO doc
private boolean isGroupFavsChecked = false;
// Used to auto-hide the sort controls bar when no activity is detected
private Debouncer<Boolean> sortCommandsAutoHide;
public Toolbar getSelectionToolbar() {
return selectionToolbar;
}
public ImageView getSortDirectionButton() {
return sortDirectionButton;
}
public View getSortReshuffleButton() {
return sortReshuffleButton;
}
public TextView getSortFieldButton() {
return sortFieldButton;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public List<Attribute> getMetadata() {
return metadata;
}
public void setMetadata(List<Attribute> metadata) {
this.metadata = metadata;
}
public boolean isEditMode() {
return editMode;
}
public void setEditMode(boolean editMode) {
this.editMode = editMode;
updateToolbar();
}
public void toggleEditMode() {
setEditMode(!editMode);
}
public boolean isGroupFavsChecked() {
return isGroupFavsChecked;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_library);
drawerLayout = findViewById(R.id.drawer_layout);
drawerLayout.addDrawerListener(new ActionBarDrawerToggle(this, drawerLayout,
toolbar, R.string.open_drawer, R.string.close_drawer) {
/** Called when a drawer has settled in a completely closed state. */
@Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
EventBus.getDefault().post(new CommunicationEvent(EV_CLOSED, RC_DRAWER, ""));
}
});
// Hack DrawerLayout to make the drag zone larger
try {
// get dragger responsible for the dragging of the left drawer
Field draggerField = DrawerLayout.class.getDeclaredField("mLeftDragger");
draggerField.setAccessible(true);
ViewDragHelper vdh = (ViewDragHelper) draggerField.get(drawerLayout);
// get access to the private field which defines
// how far from the edge dragging can start
Field edgeSizeField = ViewDragHelper.class.getDeclaredField("mEdgeSize");
edgeSizeField.setAccessible(true);
// increase the edge size - while x2 should be good enough,
// try bigger values to easily see the difference
Integer origEdgeSizeInt = (Integer) edgeSizeField.get(vdh);
if (origEdgeSizeInt != null) {
int origEdgeSize = origEdgeSizeInt;
int newEdgeSize = origEdgeSize * 2;
edgeSizeField.setInt(vdh, newEdgeSize);
Timber.d("Left drawer : new drag size of %d pixels", newEdgeSize);
}
} catch (Exception e) {
Timber.e(e);
}
// When the user runs the app for the first time, we want to land them with the
// navigation drawer open. But just the first time.
if (!Preferences.isFirstRunProcessComplete()) {
// first run of the app starts with the nav drawer open
openNavigationDrawer();
Preferences.setIsFirstRunProcessComplete(true);
}
ViewModelFactory vmFactory = new ViewModelFactory(getApplication());
viewModel = new ViewModelProvider(this, vmFactory).get(LibraryViewModel.class);
viewModel.isCustomGroupingAvailable().observe(this, b -> this.isCustomGroupingAvailable = b);
if (!Preferences.getRecentVisibility()) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
}
Preferences.registerPrefsChangedListener(prefsListener);
initUI();
initToolbar();
initSelectionToolbar();
onCreated();
sortCommandsAutoHide = new Debouncer<>(this, 3000, this::hideSearchSortBar);
EventBus.getDefault().register(this);
}
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onAppUpdated(AppUpdatedEvent event) {
EventBus.getDefault().removeStickyEvent(event);
// Display the "update success" dialog when an update is detected on a release version
if (!BuildConfig.DEBUG) UpdateSuccessDialogFragment.invoke(getSupportFragmentManager());
}
@Override
public void onDestroy() {
Preferences.unregisterPrefsChangedListener(prefsListener);
EventBus.getDefault().unregister(this);
if (archiveNotificationManager != null) archiveNotificationManager.cancel();
if (deleteNotificationManager != null) deleteNotificationManager.cancel();
// Empty all handlers to avoid leaks
if (toolbar != null) toolbar.setOnMenuItemClickListener(null);
if (selectionToolbar != null) {
selectionToolbar.setOnMenuItemClickListener(null);
selectionToolbar.setNavigationOnClickListener(null);
}
super.onDestroy();
}
private void onCreated() {
// Display search bar tooltip _after_ the left drawer closes (else it displays over it)
if (Preferences.isFirstRunProcessComplete())
TooltipHelper.showTooltip(this, R.string.help_search, ArrowOrientation.TOP, toolbar, this);
if (!PermissionHelper.checkExternalStorageReadWritePermission(this)) {
((TextView) findViewById(R.id.library_alert_txt)).setText(R.string.permissions_lost);
findViewById(R.id.library_alert_fix_btn).setOnClickListener(v -> fixPermissions());
alertTxt.setVisibility(View.VISIBLE);
alertIcon.setVisibility(View.VISIBLE);
alertFixBtn.setVisibility(View.VISIBLE);
} else if (isLowOnSpace()) { // Else display low space alert
((TextView) findViewById(R.id.library_alert_txt)).setText(R.string.low_memory);
alertTxt.setVisibility(View.VISIBLE);
alertIcon.setVisibility(View.VISIBLE);
alertFixBtn.setVisibility(View.GONE);
}
}
@Override
protected void onStart() {
super.onStart();
final long previouslyViewedContent = Preferences.getViewerCurrentContent();
final int previouslyViewedPage = Preferences.getViewerCurrentPageNum();
if (previouslyViewedContent > -1 && previouslyViewedPage > -1 && !ImageViewerActivity.isRunning) {
Snackbar snackbar = Snackbar.make(viewPager, R.string.resume_closed, BaseTransientBottomBar.LENGTH_LONG);
snackbar.setAction(R.string.resume, v -> {
Timber.i("Reopening books %d from page %d", previouslyViewedContent, previouslyViewedPage);
CollectionDAO dao = new ObjectBoxDAO(this);
try {
Content c = dao.selectContent(previouslyViewedContent);
if (c != null)
ContentHelper.openHentoidViewer(this, c, previouslyViewedPage, null);
} finally {
dao.cleanup();
}
});
snackbar.show();
// Only show that once
Preferences.setViewerCurrentContent(-1);
Preferences.setViewerCurrentPageNum(-1);
}
}
/**
* Initialize the UI components
*/
private void initUI() {
alertTxt = findViewById(R.id.library_alert_txt);
alertIcon = findViewById(R.id.library_alert_icon);
alertFixBtn = findViewById(R.id.library_alert_fix_btn);
// Search bar
searchSortBar = findViewById(R.id.advanced_search_background);
// "Group by" menu
View groupByButton = findViewById(R.id.group_by_btn);
groupByButton.setOnClickListener(this::onGroupByButtonClick);
// Link to advanced search
advancedSearchButton = findViewById(R.id.advanced_search_btn);
advancedSearchButton.setOnClickListener(v -> onAdvancedSearchButtonClick());
// "Show artists/groups" menu (group tab only when Grouping.ARTIST is on)
showArtistsGroupsButton = findViewById(R.id.groups_visibility_btn);
showArtistsGroupsButton.setText(getArtistsGroupsTextFromPrefs());
showArtistsGroupsButton.setOnClickListener(this::onGroupsVisibilityButtonClick);
// Clear search
searchClearButton = findViewById(R.id.search_clear_btn);
searchClearButton.setOnClickListener(v -> {
query = "";
metadata.clear();
actionSearchView.setQuery("", false);
hideSearchSortBar(false);
signalCurrentFragment(EV_SEARCH, "");
});
// Sort controls
sortDirectionButton = findViewById(R.id.sort_direction_btn);
sortReshuffleButton = findViewById(R.id.sort_reshuffle_btn);
sortFieldButton = findViewById(R.id.sort_field_btn);
// Main tabs
viewPager = findViewById(R.id.library_pager);
viewPager.setUserInputEnabled(false); // Disable swipe to change tabs
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
enableCurrentFragment();
hideSearchSortBar(false);
updateToolbar();
updateSelectionToolbar(0, 0);
}
});
updateDisplay();
}
private void updateDisplay() {
FragmentStateAdapter pagerAdapter = new LibraryPagerAdapter(this);
viewPager.setAdapter(pagerAdapter);
pagerAdapter.notifyDataSetChanged();
enableCurrentFragment();
}
private void initToolbar() {
toolbar = findViewById(R.id.library_toolbar);
toolbar.setNavigationOnClickListener(v -> openNavigationDrawer());
searchMenu = toolbar.getMenu().findItem(R.id.action_search);
searchMenu.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
showSearchSortBar(true, false, null);
invalidateNextQueryTextChange = true;
// Re-sets the query on screen, since default behaviour removes it right after collapse _and_ expand
if (!query.isEmpty())
// Use of handler allows to set the value _after_ the UI has auto-cleared it
// Without that handler the view displays with an empty value
new Handler(Looper.getMainLooper()).postDelayed(() -> {
invalidateNextQueryTextChange = true;
actionSearchView.setQuery(query, false);
}, 100);
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
if (!isSearchQueryActive()) {
hideSearchSortBar(false);
}
invalidateNextQueryTextChange = true;
return true;
}
});
completedFilterMenu = toolbar.getMenu().findItem(R.id.action_completed_filter);
favsMenu = toolbar.getMenu().findItem(R.id.action_favourites);
updateFavouriteFilter();
reorderMenu = toolbar.getMenu().findItem(R.id.action_edit);
reorderCancelMenu = toolbar.getMenu().findItem(R.id.action_edit_cancel);
newGroupMenu = toolbar.getMenu().findItem(R.id.action_group_new);
sortMenu = toolbar.getMenu().findItem(R.id.action_order);
actionSearchView = (SearchView) searchMenu.getActionView();
actionSearchView.setIconifiedByDefault(true);
actionSearchView.setQueryHint(getString(R.string.search_hint));
// Change display when text query is typed
actionSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
query = s;
signalCurrentFragment(EV_SEARCH, query);
actionSearchView.clearFocus();
return true;
}
@Override
public boolean onQueryTextChange(String s) {
if (invalidateNextQueryTextChange) { // Should not happen when search panel is closing or opening
invalidateNextQueryTextChange = false;
} else if (s.isEmpty()) {
query = "";
signalCurrentFragment(EV_SEARCH, query);
searchClearButton.setVisibility(View.GONE);
}
return true;
}
});
// Update icons visibility
updateToolbar();
}
public void initFragmentToolbars(
@NonNull final SelectExtension<?> selectExtension,
@NonNull final Toolbar.OnMenuItemClickListener toolbarOnItemClicked,
@NonNull final Toolbar.OnMenuItemClickListener selectionToolbarOnItemClicked
) {
toolbar.setOnMenuItemClickListener(toolbarOnItemClicked);
if (selectionToolbar != null) {
selectionToolbar.setOnMenuItemClickListener(selectionToolbarOnItemClicked);
selectionToolbar.setNavigationOnClickListener(v -> {
selectExtension.deselect(selectExtension.getSelections());
selectionToolbar.setVisibility(View.GONE);
});
}
}
public void sortCommandsAutoHide(boolean hideSortOnly, PopupMenu popup) {
this.autoHidePopup = popup;
sortCommandsAutoHide.submit(hideSortOnly);
}
public void updateSearchBarOnResults(boolean nonEmptyResults) {
if (isSearchQueryActive()) {
showSearchSortBar(true, true, false);
if (nonEmptyResults) collapseSearchMenu();
} else {
searchClearButton.setVisibility(View.GONE);
}
}
/**
* Callback method used when a sort method is selected in the sort drop-down menu
* Updates the UI according to the chosen sort method
*
* @param menuItem Toolbar of the fragment
*/
public boolean toolbarOnItemClicked(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_completed_filter:
if (!menuItem.isChecked())
askFilterCompleted();
else {
completedFilterMenu.setChecked(!completedFilterMenu.isChecked());
updateCompletedFilter();
viewModel.resetCompletedFilter();
}
break;
case R.id.action_favourites:
menuItem.setChecked(!menuItem.isChecked());
updateFavouriteFilter();
if (isGroupDisplayed()) {
isGroupFavsChecked = menuItem.isChecked();
viewModel.searchGroup(Preferences.getGroupingDisplay(), query, Preferences.getGroupSortField(), Preferences.isGroupSortDesc(), Preferences.getArtistGroupVisibility(), isGroupFavsChecked);
} else
viewModel.toggleContentFavouriteFilter();
break;
case R.id.action_order:
showSearchSortBar(null, null, true);
sortCommandsAutoHide.submit(true);
break;
default:
return false;
}
return true;
}
private void showSearchSortBar(Boolean showAdvancedSearch, Boolean showClear, Boolean showSort) {
if (showSort != null && showSort && View.VISIBLE == sortFieldButton.getVisibility()) {
hideSearchSortBar(View.GONE != advancedSearchButton.getVisibility());
return;
}
searchSortBar.setVisibility(View.VISIBLE);
if (showAdvancedSearch != null)
advancedSearchButton.setVisibility(showAdvancedSearch && !isGroupDisplayed() ? View.VISIBLE : View.GONE);
if (showClear != null)
searchClearButton.setVisibility(showClear ? View.VISIBLE : View.GONE);
if (showSort != null) {
sortFieldButton.setVisibility(showSort ? View.VISIBLE : View.GONE);
if (showSort) {
boolean isRandom = (!isGroupDisplayed() && Preferences.Constant.ORDER_FIELD_RANDOM == Preferences.getContentSortField());
sortDirectionButton.setVisibility(isRandom ? View.GONE : View.VISIBLE);
sortReshuffleButton.setVisibility(isRandom ? View.VISIBLE : View.GONE);
searchClearButton.setVisibility(View.GONE);
} else {
sortDirectionButton.setVisibility(View.GONE);
sortReshuffleButton.setVisibility(View.GONE);
}
}
if (isGroupDisplayed() && Preferences.getGroupingDisplay().equals(Grouping.ARTIST)) {
showArtistsGroupsButton.setVisibility(View.VISIBLE);
} else {
showArtistsGroupsButton.setVisibility(View.GONE);
}
}
public void hideSearchSortBar(boolean hideSortOnly) {
boolean isSearchVisible = (View.VISIBLE == advancedSearchButton.getVisibility() || View.VISIBLE == searchClearButton.getVisibility());
if (!hideSortOnly || !isSearchVisible)
searchSortBar.setVisibility(View.GONE);
if (!hideSortOnly) {
advancedSearchButton.setVisibility(View.GONE);
searchClearButton.setVisibility(View.GONE);
}
sortDirectionButton.setVisibility(View.GONE);
sortReshuffleButton.setVisibility(View.GONE);
sortFieldButton.setVisibility(View.GONE);
showArtistsGroupsButton.setVisibility(View.GONE);
if (autoHidePopup != null) autoHidePopup.dismiss();
// Restore CLEAR button if it's needed
if (hideSortOnly && isSearchQueryActive()) searchClearButton.setVisibility(View.VISIBLE);
}
public boolean closeLeftDrawer() {
if (drawerLayout != null && drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
return false;
}
public boolean collapseSearchMenu() {
if (searchMenu != null && searchMenu.isActionViewExpanded()) {
searchMenu.collapseActionView();
return true;
}
return false;
}
private void initSelectionToolbar() {
selectionToolbar = findViewById(R.id.library_selection_toolbar);
selectionToolbar.getMenu().clear();
selectionToolbar.inflateMenu(R.menu.library_selection_menu);
editNameMenu = selectionToolbar.getMenu().findItem(R.id.action_edit_name);
deleteMenu = selectionToolbar.getMenu().findItem(R.id.action_delete);
completedMenu = selectionToolbar.getMenu().findItem(R.id.action_completed);
shareMenu = selectionToolbar.getMenu().findItem(R.id.action_share);
archiveMenu = selectionToolbar.getMenu().findItem(R.id.action_archive);
changeGroupMenu = selectionToolbar.getMenu().findItem(R.id.action_change_group);
folderMenu = selectionToolbar.getMenu().findItem(R.id.action_open_folder);
redownloadMenu = selectionToolbar.getMenu().findItem(R.id.action_redownload);
coverMenu = selectionToolbar.getMenu().findItem(R.id.action_set_cover);
updateSelectionToolbar(0, 0);
}
private Grouping getGroupingFromMenuId(@IdRes int menuId) {
switch (menuId) {
case (R.id.groups_flat):
return Grouping.FLAT;
case (R.id.groups_by_artist):
return Grouping.ARTIST;
case (R.id.groups_by_dl_date):
return Grouping.DL_DATE;
case (R.id.groups_custom):
return Grouping.CUSTOM;
default:
return Grouping.NONE;
}
}
private @IdRes
int getMenuIdFromGrouping(Grouping grouping) {
switch (grouping) {
case ARTIST:
return R.id.groups_by_artist;
case DL_DATE:
return R.id.groups_by_dl_date;
case CUSTOM:
return R.id.groups_custom;
case FLAT:
case NONE:
default:
return R.id.groups_flat;
}
}
private int getVisibilityCodeFromMenuId(@IdRes int menuId) {
switch (menuId) {
case (R.id.show_artists):
return Preferences.Constant.ARTIST_GROUP_VISIBILITY_ARTISTS;
case (R.id.show_groups):
return Preferences.Constant.ARTIST_GROUP_VISIBILITY_GROUPS;
case (R.id.show_artists_and_groups):
default:
return Preferences.Constant.ARTIST_GROUP_VISIBILITY_ARTISTS_GROUPS;
}
}
/**
* Update completed filter button appearance on the action bar
*/
private void updateCompletedFilter() {
completedFilterMenu.setIcon(completedFilterMenu.isChecked() ? R.drawable.ic_completed_filter_on : R.drawable.ic_completed_filter_off);
}
/**
* Update favourite filter button appearance on the action bar
*/
private void updateFavouriteFilter() {
favsMenu.setIcon(favsMenu.isChecked() ? R.drawable.ic_filter_favs_on : R.drawable.ic_filter_favs_off);
}
/**
* Callback for any change in Preferences
*/
private void onSharedPreferenceChanged(String key) {
Timber.i("Prefs change detected : %s", key);
switch (key) {
case Preferences.Key.COLOR_THEME:
case Preferences.Key.LIBRARY_DISPLAY:
// Restart the app with the library activity on top
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
finish();
startActivity(intent);
break;
case Preferences.Key.SD_STORAGE_URI:
case Preferences.Key.EXTERNAL_LIBRARY_URI:
Preferences.setGroupingDisplay(Grouping.FLAT.getId());
viewModel.setGroup(null);
updateDisplay();
break;
case Preferences.Key.GROUPING_DISPLAY:
case Preferences.Key.ARTIST_GROUP_VISIBILITY:
viewModel.setGrouping(Preferences.getGroupingDisplay(), Preferences.getGroupSortField(), Preferences.isGroupSortDesc(), Preferences.getArtistGroupVisibility(), isGroupFavsChecked);
break;
default:
// Nothing to handle there
}
}
/**
* Handler for the "Advanced search" button
*/
private void onAdvancedSearchButtonClick() {
signalCurrentFragment(EV_ADVANCED_SEARCH, null);
}
/**
* Handler for the "Group by" button
*/
private void onGroupByButtonClick(View groupByButton) {
// Load and display the field popup menu
PopupMenu popup = new PopupMenu(this, groupByButton);
popup.getMenuInflater()
.inflate(R.menu.library_groups_popup, popup.getMenu());
popup.getMenu().findItem(R.id.groups_custom).setVisible(isCustomGroupingAvailable);
// Mark current grouping
MenuItem currentItem = popup.getMenu().findItem(getMenuIdFromGrouping(Preferences.getGroupingDisplay()));
currentItem.setTitle(currentItem.getTitle() + " <");
popup.setOnMenuItemClickListener(item -> {
Grouping currentGrouping = Preferences.getGroupingDisplay();
Grouping selectedGrouping = getGroupingFromMenuId(item.getItemId());
// Don't do anything if the current group is selected
if (currentGrouping.equals(selectedGrouping)) return false;
Preferences.setGroupingDisplay(selectedGrouping.getId());
isGroupFavsChecked = false;
favsMenu.setChecked(false);
updateFavouriteFilter();
// Reset custom book ordering if reverting to a grouping where that doesn't apply
if (!selectedGrouping.canReorderBooks()
&& Preferences.Constant.ORDER_FIELD_CUSTOM == Preferences.getContentSortField()) {
Preferences.setContentSortField(Preferences.Default.ORDER_CONTENT_FIELD);
}
// Reset custom group ordering if reverting to a grouping where that doesn't apply
if (!selectedGrouping.canReorderGroups()
&& Preferences.Constant.ORDER_FIELD_CUSTOM == Preferences.getGroupSortField()) {
Preferences.setGroupSortField(Preferences.Default.ORDER_GROUP_FIELD);
}
// Go back to groups tab if we're not
goBackToGroups();
// Update screen display if needed (flat <-> the rest)
if (currentGrouping.equals(Grouping.FLAT) || selectedGrouping.equals(Grouping.FLAT))
updateDisplay();
sortCommandsAutoHide(true, popup);
return true;
});
popup.show(); //showing popup menu
sortCommandsAutoHide(true, popup);
}
private String getArtistsGroupsTextFromPrefs() {
switch (Preferences.getArtistGroupVisibility()) {
case Preferences.Constant.ARTIST_GROUP_VISIBILITY_ARTISTS:
return getResources().getString(R.string.show_artists);
case Preferences.Constant.ARTIST_GROUP_VISIBILITY_GROUPS:
return getResources().getString(R.string.show_groups);
case Preferences.Constant.ARTIST_GROUP_VISIBILITY_ARTISTS_GROUPS:
return getResources().getString(R.string.show_artists_and_groups);
default:
return "";
}
}
/**
* Handler for the "Show artists/groups" button
*/
private void onGroupsVisibilityButtonClick(View groupsVisibilityButton) {
// Load and display the visibility popup menu
PopupMenu popup = new PopupMenu(this, groupsVisibilityButton);
popup.getMenuInflater().inflate(R.menu.library_groups_visibility_popup, popup.getMenu());
popup.setOnMenuItemClickListener(item -> {
item.setChecked(true);
int code = getVisibilityCodeFromMenuId(item.getItemId());
Preferences.setArtistGroupVisibility(code);
showArtistsGroupsButton.setText(getArtistsGroupsTextFromPrefs());
sortCommandsAutoHide(true, popup);
return true;
});
popup.show();
sortCommandsAutoHide(true, popup);
}
/**
* Update the screen title according to current search filter (#TOTAL BOOKS) if no filter is
* enabled (#FILTERED / #TOTAL BOOKS) if a filter is enabled
*/
public void updateTitle(long totalSelectedCount, long totalCount) {
String title;
if (totalSelectedCount == totalCount)
title = totalCount + " items";
else {
title = getResources().getQuantityString(R.plurals.number_of_book_search_results, (int) totalSelectedCount, (int) totalSelectedCount, totalCount);
}
toolbar.setTitle(title);
titles.put(viewPager.getCurrentItem(), title);
}
/**
* Indicates whether a search query is active (using universal search or advanced search) or not
*
* @return True if a search query is active (using universal search or advanced search); false if not (=whole unfiltered library selected)
*/
public boolean isSearchQueryActive() {
return (!query.isEmpty() || !metadata.isEmpty());
}
private void fixPermissions() {
PermissionHelper.requestExternalStorageReadWritePermission(this, PermissionHelper.RQST_STORAGE_PERMISSION);
}
private boolean isLowOnSpace() {
DocumentFile rootFolder = FileHelper.getFolderFromTreeUriString(this, Preferences.getStorageUri());
if (null == rootFolder) return false;
double freeSpaceRatio = new FileHelper.MemoryUsageFigures(this, rootFolder).getFreeUsageRatio100();
return (freeSpaceRatio < 100 - Preferences.getMemoryAlertThreshold());
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != PermissionHelper.RQST_STORAGE_PERMISSION) return;
if (permissions.length < 2) return;
if (grantResults.length == 0) return;
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
alertTxt.setVisibility(View.GONE);
alertIcon.setVisibility(View.GONE);
alertFixBtn.setVisibility(View.GONE);
} // Don't show rationales here; the alert still displayed on screen should be enough
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
public void closeNavigationDrawer() {
drawerLayout.closeDrawer(GravityCompat.START);
}
public void openNavigationDrawer() {
drawerLayout.openDrawer(GravityCompat.START);
}
private boolean isGroupDisplayed() {
return (0 == viewPager.getCurrentItem() && !Preferences.getGroupingDisplay().equals(Grouping.FLAT));
}
public void goBackToGroups() {
if (isGroupDisplayed()) return;
enableFragment(0);
viewModel.searchGroup(Preferences.getGroupingDisplay(), query, Preferences.getGroupSortField(), Preferences.isGroupSortDesc(), Preferences.getArtistGroupVisibility(), isGroupFavsChecked);
viewPager.setCurrentItem(0);
if (titles.containsKey(0)) toolbar.setTitle(titles.get(0));
}
public void showBooksInGroup(me.devsaki.hentoid.database.domains.Group group) {
enableFragment(1);
viewModel.setGroup(group);
viewPager.setCurrentItem(1);
}
private void updateToolbar() {
Grouping currentGrouping = Preferences.getGroupingDisplay();
searchMenu.setVisible(!editMode);
newGroupMenu.setVisible(!editMode && isGroupDisplayed() && currentGrouping.canReorderGroups()); // Custom groups only
favsMenu.setVisible(!editMode);
reorderMenu.setIcon(editMode ? R.drawable.ic_check : R.drawable.ic_reorder_lines);
reorderCancelMenu.setVisible(editMode);
sortMenu.setVisible(!editMode);
completedFilterMenu.setVisible(!editMode && !isGroupDisplayed());
if (isGroupDisplayed()) reorderMenu.setVisible(currentGrouping.canReorderGroups());
else reorderMenu.setVisible(currentGrouping.canReorderBooks());
signalCurrentFragment(EV_UPDATE_SORT, null);
}
public void updateSelectionToolbar(long selectedTotalCount, long selectedLocalCount) {
boolean isMultipleSelection = selectedTotalCount > 1;
selectionToolbar.setTitle(getResources().getQuantityString(R.plurals.items_selected, (int) selectedTotalCount, (int) selectedTotalCount));
if (isGroupDisplayed()) {
editNameMenu.setVisible(!isMultipleSelection && Preferences.getGroupingDisplay().canReorderGroups());
deleteMenu.setVisible(true);
shareMenu.setVisible(false);
completedMenu.setVisible(false);
archiveMenu.setVisible(true);
changeGroupMenu.setVisible(false);
folderMenu.setVisible(false);
redownloadMenu.setVisible(false);
coverMenu.setVisible(false);
} else {
editNameMenu.setVisible(false);
deleteMenu.setVisible(selectedLocalCount > 0 || Preferences.isDeleteExternalLibrary());
completedMenu.setVisible(true);
shareMenu.setVisible(!isMultipleSelection && 1 == selectedLocalCount);
archiveMenu.setVisible(true);
changeGroupMenu.setVisible(true);
folderMenu.setVisible(!isMultipleSelection);
redownloadMenu.setVisible(selectedLocalCount > 0);
coverMenu.setVisible(!isMultipleSelection && !Preferences.getGroupingDisplay().equals(Grouping.FLAT));
}
}
public void askFilterCompleted() {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
String title = getString(R.string.ask_filter_completed);
builder.setMessage(title)
.setPositiveButton(R.string.filter_not_completed,
(dialog, which) -> {
completedFilterMenu.setChecked(!completedFilterMenu.isChecked());
updateCompletedFilter();
viewModel.toggleNotCompletedFilter();
})
.setNegativeButton(R.string.filter_completed,
(dialog, which) -> {
completedFilterMenu.setChecked(!completedFilterMenu.isChecked());
updateCompletedFilter();
viewModel.toggleCompletedFilter();
})
.create().show();
}
/**
* Display the yes/no dialog to make sure the user really wants to delete selected items
*
* @param contents Items to be deleted if the answer is yes
*/
public void askDeleteItems(
@NonNull final List<Content> contents,
@NonNull final List<me.devsaki.hentoid.database.domains.Group> groups,
@Nullable final Runnable onSuccess,
@NonNull final SelectExtension<?> selectExtension) {
// TODO display the number of books and groups that will be deleted
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
int count = !groups.isEmpty() ? groups.size() : contents.size();
String title = getResources().getQuantityString(R.plurals.ask_delete_multiple, count);
builder.setMessage(title)
.setPositiveButton(R.string.yes,
(dialog, which) -> {
selectExtension.deselect(selectExtension.getSelections());
deleteItems(contents, groups, false, onSuccess);
})
.setNegativeButton(R.string.no,
(dialog, which) -> selectExtension.deselect(selectExtension.getSelections()))
.setOnCancelListener(dialog -> selectExtension.deselect(selectExtension.getSelections()))
.create().show();
}
public void deleteItems(
@NonNull final List<Content> contents,
@NonNull final List<me.devsaki.hentoid.database.domains.Group> groups,
boolean deleteGroupsOnly,
@Nullable final Runnable onSuccess
) {
DeleteNotificationChannel.init(this);
deleteNotificationManager = new NotificationManager(this, R.id.delete_processing);
deleteNotificationManager.cancel();
deleteProgress = 0;
deleteMax = contents.size() + groups.size();
deleteNotificationManager.notify(new DeleteStartNotification());
viewModel.deleteItems(contents, groups, deleteGroupsOnly,
this::onDeleteProgress,
() -> {
onDeleteSuccess(contents.size(), groups.size());
if (onSuccess != null) onSuccess.run();
},
this::onDeleteError);
}
/**
* Callback for the failure of the "delete item" action
*/
private void onDeleteError(Throwable t) {
Timber.e(t);
if (t instanceof ContentNotRemovedException) {
ContentNotRemovedException e = (ContentNotRemovedException) t;
String message = (null == e.getMessage()) ? "Content removal failed" : e.getMessage();
Snackbar.make(viewPager, message, BaseTransientBottomBar.LENGTH_LONG).show();
// If the cause if not the file not being removed, keep the item on screen, not blinking
if (!(t instanceof FileNotRemovedException))
viewModel.flagContentDelete(e.getContent(), false);
}
}
/**
* Callback for the progress of the "delete item" action
*/
private void onDeleteProgress(Object item) {
String title = null;
if (item instanceof Content) title = ((Content) item).getTitle();
else if (item instanceof me.devsaki.hentoid.database.domains.Group)
title = ((me.devsaki.hentoid.database.domains.Group) item).name;
if (title != null) {
deleteProgress++;
deleteNotificationManager.notify(new DeleteProgressNotification(title, deleteProgress, deleteMax));
}
}
/**
* Callback for the success of the "delete item" action
*/
private void onDeleteSuccess(int nbContent, int nbGroups) {
deleteNotificationManager.notify(new DeleteCompleteNotification(deleteProgress, false));
String msg = "";
if (nbGroups > 0)
msg += getResources().getQuantityString(R.plurals.delete_success_groups, nbGroups, nbGroups);
if (nbContent > 0) {
if (!msg.isEmpty()) msg += " and ";
msg += getResources().getQuantityString(R.plurals.delete_success_books, nbContent, nbContent);
}
msg += " " + getResources().getString(R.string.delete_success);
Snackbar.make(viewPager, msg, LENGTH_LONG).show();
}
/**
* Display the yes/no dialog to make sure the user really wants to archive selected items
*
* @param items Items to be archived if the answer is yes
*/
public void askArchiveItems(@NonNull final List<Content> items,
@NonNull final SelectExtension<?> selectExtension) {
// TODO display the number of books to archive
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
String title = getResources().getQuantityString(R.plurals.ask_archive_multiple, items.size());
builder.setMessage(title)
.setPositiveButton(R.string.yes,
(dialog, which) -> {
selectExtension.deselect(selectExtension.getSelections());
ArchiveNotificationChannel.init(this);
archiveNotificationManager = new NotificationManager(this, R.id.archive_processing);
archiveNotificationManager.cancel();
archiveProgress = 0;
archiveMax = items.size();
archiveNotificationManager.notify(new ArchiveStartNotification());
viewModel.archiveContents(items, this::onContentArchiveProgress, this::onContentArchiveSuccess, this::onContentArchiveError);
})
.setNegativeButton(R.string.no,
(dialog, which) -> selectExtension.deselect(selectExtension.getSelections()))
.create().show();
}
private void onContentArchiveProgress(Content content) {
archiveProgress++;
archiveNotificationManager.notify(new ArchiveProgressNotification(content.getTitle(), archiveProgress, archiveMax));
}
/**
* Callback for the success of the "archive item" action
*/
private void onContentArchiveSuccess() {
archiveNotificationManager.notify(new ArchiveCompleteNotification(archiveProgress, false));
Snackbar.make(viewPager, getResources().getQuantityString(R.plurals.archive_success, archiveProgress, archiveProgress), LENGTH_LONG)
.setAction("OPEN FOLDER", v -> FileHelper.openFile(this, FileHelper.getDownloadsFolder()))
.show();
}
/**
* Callback for the success of the "archive item" action
*/
private void onContentArchiveError(Throwable e) {
Timber.e(e);
archiveNotificationManager.notify(new ArchiveCompleteNotification(archiveProgress, true));
}
private void signalCurrentFragment(int eventType, @Nullable String message) {
signalFragment(isGroupDisplayed() ? 0 : 1, eventType, message);
}
private void signalFragment(int fragmentIndex, int eventType, @Nullable String message) {
EventBus.getDefault().post(new CommunicationEvent(eventType, (0 == fragmentIndex) ? RC_GROUPS : RC_CONTENTS, message));
}
private void enableCurrentFragment() {
if (isGroupDisplayed()) enableFragment(0);
else enableFragment(1);
}
private void enableFragment(int fragmentIndex) {
EventBus.getDefault().post(new CommunicationEvent(EV_ENABLE, (0 == fragmentIndex) ? RC_GROUPS : RC_CONTENTS, null));
EventBus.getDefault().post(new CommunicationEvent(EV_DISABLE, (0 == fragmentIndex) ? RC_CONTENTS : RC_GROUPS, null));
}
private static class LibraryPagerAdapter extends FragmentStateAdapter {
LibraryPagerAdapter(FragmentActivity fa) {
super(fa);
}
@NonNull
@Override
public Fragment createFragment(int position) {
if (Grouping.FLAT.equals(Preferences.getGroupingDisplay())) {
return new LibraryContentFragment();
} else {
if (0 == position) {
return new LibraryGroupsFragment();
} else {
return new LibraryContentFragment();
}
}
}
@Override
public int getItemCount() {
return (Grouping.FLAT.equals(Preferences.getGroupingDisplay())) ? 1 : 2;
}
}
} |
package org.openlmis.core.model.service;
import com.google.inject.Inject;
import org.joda.time.DateTime;
import org.openlmis.core.LMISApp;
import org.openlmis.core.exceptions.LMISException;
import org.openlmis.core.model.Period;
import org.openlmis.core.model.RnRForm;
import org.openlmis.core.model.repository.RnrFormRepository;
import org.openlmis.core.model.repository.StockRepository;
import org.openlmis.core.utils.DateUtil;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class PeriodService {
@Inject
RnrFormRepository rnrFormRepository;
@Inject
StockRepository stockRepository;
public Period generateNextPeriod(String programCode, Date physicalInventoryDate) throws LMISException {
List<RnRForm> rnRForms = rnrFormRepository.list(programCode);
if (rnRForms.isEmpty()) {
return generatePeriodBasedOnDefaultDates(physicalInventoryDate, programCode);
}
RnRForm lastRnR = rnRForms.get(rnRForms.size() - 1);
return generatePeriodBasedOnPreviousRnr(lastRnR, physicalInventoryDate);
}
private Period generatePeriodBasedOnPreviousRnr(RnRForm lastRnR, Date physicalInventoryDate) {
DateTime periodBeginDate, periodEndDate;
periodBeginDate = new DateTime(lastRnR.getPeriodEnd());
if (physicalInventoryDate == null) {
Calendar date = Calendar.getInstance();
date.set(periodBeginDate.getYear(), periodBeginDate.getMonthOfYear(), Period.END_DAY);
periodEndDate = DateUtil.cutTimeStamp(new DateTime(date));
} else {
periodEndDate = new DateTime(physicalInventoryDate);
}
return new Period(periodBeginDate, periodEndDate);
}
private Period generatePeriodBasedOnDefaultDates(Date physicalInventoryDate, String programCode) throws LMISException {
DateTime periodBeginDate = calculatePeriodBeginDate(programCode);
DateTime periodEndDate;
if (physicalInventoryDate == null) {
periodEndDate = defaultEndDateTo20th(periodBeginDate);
} else {
periodEndDate = new DateTime(physicalInventoryDate);
}
return new Period(periodBeginDate, periodEndDate);
}
private DateTime calculatePeriodBeginDate(String programCode) throws LMISException {
DateTime initializeDateTime = new DateTime(stockRepository.queryEarliestStockMovementDateByProgram(programCode));
int initializeDayOfMonth = initializeDateTime.getDayOfMonth();
Calendar currentBeginDate = Calendar.getInstance();
if (initializeDayOfMonth >= Period.INVENTORY_BEGIN_DAY && initializeDayOfMonth < Period.INVENTORY_END_DAY_NEXT) {
currentBeginDate.set(initializeDateTime.getYear(), initializeDateTime.getMonthOfYear() - 1, initializeDayOfMonth);
} else {
currentBeginDate.set(initializeDateTime.getYear(), initializeDateTime.getMonthOfYear() - 1, Period.BEGIN_DAY);
}
DateTime periodBeginDate = DateUtil.cutTimeStamp(new DateTime(currentBeginDate));
if (initializeDayOfMonth < Period.INVENTORY_BEGIN_DAY) {
periodBeginDate = periodBeginDate.minusMonths(1);
}
return periodBeginDate;
}
private DateTime defaultEndDateTo20th(DateTime periodBeginDate) {
Calendar date = Calendar.getInstance();
date.set(periodBeginDate.getYear(), periodBeginDate.getMonthOfYear(), Period.END_DAY);
return DateUtil.cutTimeStamp(new DateTime(date));
}
public boolean hasMissedPeriod(String programCode) throws LMISException {
List<RnRForm> rnRForms = rnrFormRepository.list(programCode);
if (rnRForms.size() == 0 || rnRForms.get(rnRForms.size() - 1).isAuthorized()) {
DateTime nextPeriodInScheduleEnd = generateNextPeriod(programCode, null).getEnd();
DateTime lastInventoryDateForNextPeriodInSchedule = nextPeriodInScheduleEnd
.withDate(nextPeriodInScheduleEnd.getYear(),
nextPeriodInScheduleEnd.getMonthOfYear(),
Period.INVENTORY_END_DAY_NEXT);
return lastInventoryDateForNextPeriodInSchedule.isBefore(LMISApp.getInstance().getCurrentTimeMillis());
}
Date lastRnrPeriodEndDate = rnRForms.get(rnRForms.size() - 1).getPeriodEnd();
return new DateTime(lastRnrPeriodEndDate).isBefore(LMISApp.getInstance().getCurrentTimeMillis());
}
public int getMissedPeriodOffsetMonth(String programCode) throws LMISException {
DateTime nextPeriodInScheduleBegin = generateNextPeriod(programCode, null).getBegin();
DateTime currentMonthInventoryBeginDate;
currentMonthInventoryBeginDate = getCurrentMonthInventoryBeginDate();
return (currentMonthInventoryBeginDate.getYear() * 12 + currentMonthInventoryBeginDate.getMonthOfYear()) - (nextPeriodInScheduleBegin.getYear() * 12 + nextPeriodInScheduleBegin.getMonthOfYear());
}
public DateTime getCurrentMonthInventoryBeginDate() {
DateTime currentDate = new DateTime(LMISApp.getInstance().getCurrentTimeMillis());
DateTime currentMonthInventoryBeginDate;
if (currentDate.getDayOfMonth() >= Period.INVENTORY_BEGIN_DAY) {
currentMonthInventoryBeginDate = currentDate
.withDate(currentDate.getYear(),
currentDate.getMonthOfYear(),
Period.INVENTORY_BEGIN_DAY);
} else {
currentMonthInventoryBeginDate = currentDate
.withDate(currentDate.getYear(),
currentDate.getMonthOfYear() - 1,
Period.INVENTORY_BEGIN_DAY);
}
return currentMonthInventoryBeginDate;
}
} |
package pl.com.chodera.myweather;
import android.app.Application;
import com.crashlytics.android.Crashlytics;
import com.squareup.leakcanary.LeakCanary;
import io.fabric.sdk.android.Fabric;
public class MyWeatherApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
startLeakCanary();
} else {
Fabric.with(this, new Crashlytics());
}
}
private void startLeakCanary() {
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
}
} |
package VASSAL.command;
import java.awt.Point;
import VASSAL.build.GameModule;
import VASSAL.build.module.GlobalOptions;
import VASSAL.build.module.Map;
import VASSAL.build.module.map.HighlightLastMoved;
import VASSAL.counters.BoundsTracker;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.DeckVisitorDispatcher;
import VASSAL.counters.GamePiece;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.Stack;
/**
* Command that moves a piece to a new location and position within a stack.
* While this can be accomplished with a {@link ChangePiece} command, this
* command is safer in terms of recovering from changes to the game state that may have occurred
* since the command was created. For instance, A {@link ChangePiece} command that adds
* a piece to a {@link VASSAL.counters.Stack} will cause the piece to disappear if the
* stack has been deleted. This Command will recover more gracefully.
*/
public class MovePiece extends Command {
private String id;
private String newMapId;
private String oldMapId;
private Point newPosition;
private Point oldPosition;
private String newUnderneathId;
private String oldUnderneathId;
private String playerId;
/**
*
* @param id The id of the piece being moved
* @param newMapId The id of the map being moved to
* @param newPosition the new position
* @param newUnderneathId The id of the piece which will be immediately beneath this piece in any containing Stack. May be null
* @param oldMapId The id of the map being moved from
* @param oldPosition the old position
* @param oldUnderneathId The id of the piece which was immediately beneath this piece in its original containing Stack.
* @param playerId the id of the player making this move
*/
public MovePiece(String id, String newMapId, Point newPosition, String newUnderneathId, String oldMapId, Point oldPosition, String oldUnderneathId, String playerId) {
this.id = id;
this.newMapId = newMapId;
this.oldMapId = oldMapId;
this.newPosition = newPosition;
this.oldPosition = oldPosition;
this.newUnderneathId = newUnderneathId;
this.oldUnderneathId = oldUnderneathId;
this.playerId = playerId;
}
public String getId() {
return id;
}
public String getNewMapId() {
return newMapId;
}
public String getOldMapId() {
return oldMapId;
}
public Point getNewPosition() {
return newPosition;
}
public Point getOldPosition() {
return oldPosition;
}
public String getNewUnderneathId() {
return newUnderneathId;
}
public String getOldUnderneathId() {
return oldUnderneathId;
}
public String getPlayerId() {
return playerId;
}
@Override
protected void executeCommand() {
GamePiece piece = GameModule.getGameModule().getGameState().getPieceForId(id);
if (piece != null) {
BoundsTracker bounds = new BoundsTracker();
bounds.addPiece(piece);
Map newMap = Map.getMapById(newMapId);
if (newMap != null) {
PieceVisitorDispatcher mergeFinder = createMergeFinder(newMap, piece, newPosition);
if (newUnderneathId != null) {
GamePiece under = GameModule.getGameModule().getGameState().getPieceForId(newUnderneathId);
if (under != null
&& under.getPosition().equals(newPosition)
&& under.getMap() == newMap) { //BR// lest someone have simultaneously moved or deleted the piece.
newMap.getStackMetrics().merge(under, piece);
}
else {
if (newMap.apply(mergeFinder) == null) {
newMap.placeAt(piece, newPosition);
}
}
}
else {
if (newMap.apply(mergeFinder) == null) {
newMap.placeAt(piece, newPosition);
}
if (piece.getParent() != null) {
piece.getParent().insert(piece, 0);
}
}
}
else {
Map oldMap = Map.getMapById(oldMapId);
if (oldMap != null) {
oldMap.removePiece(piece);
}
}
bounds.addPiece(piece);
// Highlight the stack the piece was moved to
HighlightLastMoved.setLastMoved(piece);
bounds.repaint();
if (piece.getMap() != null
&& GlobalOptions.getInstance().centerOnOpponentsMove()
&& !Boolean.TRUE.equals(piece.getProperty(Properties.INVISIBLE_TO_ME))) {
piece.getMap().ensureVisible(piece.getMap().selectionBoundsOf(piece));
}
}
}
@Override
protected Command myUndoCommand() {
return new MovePiece(id, oldMapId, oldPosition, oldUnderneathId, newMapId, newPosition, newUnderneathId, playerId);
}
/**
* Creates a new {@link PieceVisitorDispatcher} that will create a {@link Command} object
* to merge the target piece with any applicable pieces at the target location
* @param map
* @param p
* @param pt
* @return
*/
protected PieceVisitorDispatcher createMergeFinder(final Map map, final GamePiece p, final Point pt) {
PieceVisitorDispatcher dispatch = new DeckVisitorDispatcher(new DeckVisitor() {
@Override
public Object visitDeck(Deck d) {
if (d.getPosition().equals(pt)) {
return map.getStackMetrics().merge(d, p);
}
else {
return null;
}
}
@Override
public Object visitStack(Stack s) {
if (s.getPosition().equals(pt)
&& map.getStackMetrics().isStackingEnabled()
&& !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))
&& s.topPiece(playerId) != null
&& map.getPieceCollection().canMerge(p, s)) {
return map.getStackMetrics().merge(s, p);
}
else {
return null;
}
}
@Override
public Object visitDefault(GamePiece piece) {
if (piece.getPosition().equals(pt)
&& map.getStackMetrics().isStackingEnabled()
&& !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))
&& !Boolean.TRUE.equals(piece.getProperty(Properties.NO_STACK))
&& map.getPieceCollection().canMerge(p, piece)) {
String hiddenBy = (String) piece.getProperty(Properties.HIDDEN_BY);
if (hiddenBy == null
|| hiddenBy.equals(playerId)) {
return map.getStackMetrics().merge(piece, p);
}
else {
return null;
}
}
else {
return null;
}
}
});
return dispatch;
}
@Override
public String getDetails() {
return "id=" + id + ",map=" + newMapId + ",position=" + newPosition + ",under=" + newUnderneathId;
}
} |
package org.mozartoz.truffle.translator;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.mozartoz.bootcompiler.Main;
import org.mozartoz.bootcompiler.ast.BinaryOp;
import org.mozartoz.bootcompiler.ast.BindStatement;
import org.mozartoz.bootcompiler.ast.CallStatement;
import org.mozartoz.bootcompiler.ast.CompoundStatement;
import org.mozartoz.bootcompiler.ast.Constant;
import org.mozartoz.bootcompiler.ast.Expression;
import org.mozartoz.bootcompiler.ast.IfStatement;
import org.mozartoz.bootcompiler.ast.LocalStatement;
import org.mozartoz.bootcompiler.ast.MatchStatement;
import org.mozartoz.bootcompiler.ast.MatchStatementClause;
import org.mozartoz.bootcompiler.ast.NoElseStatement;
import org.mozartoz.bootcompiler.ast.ProcExpression;
import org.mozartoz.bootcompiler.ast.Record;
import org.mozartoz.bootcompiler.ast.RecordField;
import org.mozartoz.bootcompiler.ast.SkipStatement;
import org.mozartoz.bootcompiler.ast.Statement;
import org.mozartoz.bootcompiler.ast.TryStatement;
import org.mozartoz.bootcompiler.ast.UnboundExpression;
import org.mozartoz.bootcompiler.ast.Variable;
import org.mozartoz.bootcompiler.ast.VariableOrRaw;
import org.mozartoz.bootcompiler.oz.False;
import org.mozartoz.bootcompiler.oz.OzArity;
import org.mozartoz.bootcompiler.oz.OzAtom;
import org.mozartoz.bootcompiler.oz.OzBuiltin;
import org.mozartoz.bootcompiler.oz.OzFeature;
import org.mozartoz.bootcompiler.oz.OzInt;
import org.mozartoz.bootcompiler.oz.OzLiteral;
import org.mozartoz.bootcompiler.oz.OzPatMatCapture;
import org.mozartoz.bootcompiler.oz.OzPatMatWildcard;
import org.mozartoz.bootcompiler.oz.OzRecord;
import org.mozartoz.bootcompiler.oz.OzRecordField;
import org.mozartoz.bootcompiler.oz.OzValue;
import org.mozartoz.bootcompiler.oz.True;
import org.mozartoz.bootcompiler.oz.UnitVal;
import org.mozartoz.bootcompiler.parser.OzParser;
import org.mozartoz.bootcompiler.symtab.Builtin;
import org.mozartoz.bootcompiler.symtab.Program;
import org.mozartoz.bootcompiler.symtab.Symbol;
import org.mozartoz.bootcompiler.transform.ConstantFolding;
import org.mozartoz.bootcompiler.transform.Desugar;
import org.mozartoz.bootcompiler.transform.DesugarClass;
import org.mozartoz.bootcompiler.transform.DesugarFunctor;
import org.mozartoz.bootcompiler.transform.Namer;
import org.mozartoz.bootcompiler.transform.PatternMatcher;
import org.mozartoz.bootcompiler.transform.Unnester;
import org.mozartoz.bootcompiler.util.FilePosition;
import org.mozartoz.truffle.nodes.OzNode;
import org.mozartoz.truffle.nodes.OzRootNode;
import org.mozartoz.truffle.nodes.builtins.BuiltinsManager;
import org.mozartoz.truffle.nodes.builtins.IntBuiltinsFactory.DivNodeFactory;
import org.mozartoz.truffle.nodes.builtins.IntBuiltinsFactory.ModNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ListBuiltinsFactory.HeadNodeGen;
import org.mozartoz.truffle.nodes.builtins.ListBuiltinsFactory.TailNodeGen;
import org.mozartoz.truffle.nodes.builtins.NumberBuiltinsFactory.AddNodeFactory;
import org.mozartoz.truffle.nodes.builtins.NumberBuiltinsFactory.MulNodeFactory;
import org.mozartoz.truffle.nodes.builtins.NumberBuiltinsFactory.SubNodeFactory;
import org.mozartoz.truffle.nodes.builtins.RecordBuiltinsFactory.LabelNodeFactory;
import org.mozartoz.truffle.nodes.builtins.SystemBuiltinsFactory.ShowNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltins.DotNode;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.DotNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.EqualNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.GreaterThanNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.LesserThanNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.LesserThanOrEqualNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.NotEqualNodeFactory;
import org.mozartoz.truffle.nodes.call.CallProcNodeGen;
import org.mozartoz.truffle.nodes.call.ReadArgumentNode;
import org.mozartoz.truffle.nodes.control.AndNode;
import org.mozartoz.truffle.nodes.control.IfNode;
import org.mozartoz.truffle.nodes.control.SequenceNode;
import org.mozartoz.truffle.nodes.control.SkipNode;
import org.mozartoz.truffle.nodes.control.TryNode;
import org.mozartoz.truffle.nodes.literal.BooleanLiteralNode;
import org.mozartoz.truffle.nodes.literal.ConsLiteralNodeGen;
import org.mozartoz.truffle.nodes.literal.LiteralNode;
import org.mozartoz.truffle.nodes.literal.LongLiteralNode;
import org.mozartoz.truffle.nodes.literal.ProcDeclarationNode;
import org.mozartoz.truffle.nodes.literal.RecordLiteralNode;
import org.mozartoz.truffle.nodes.literal.UnboundLiteralNode;
import org.mozartoz.truffle.nodes.local.BindNodeGen;
import org.mozartoz.truffle.nodes.local.BindVarValueNodeGen;
import org.mozartoz.truffle.nodes.local.InitializeArgNodeGen;
import org.mozartoz.truffle.nodes.local.InitializeTmpNode;
import org.mozartoz.truffle.nodes.local.InitializeVarNode;
import org.mozartoz.truffle.nodes.local.ReadLocalVariableNode;
import org.mozartoz.truffle.nodes.pattern.PatternMatchCaptureNodeGen;
import org.mozartoz.truffle.nodes.pattern.PatternMatchConsNodeGen;
import org.mozartoz.truffle.nodes.pattern.PatternMatchEqualNodeGen;
import org.mozartoz.truffle.nodes.pattern.PatternMatchRecordNodeGen;
import org.mozartoz.truffle.runtime.Arity;
import org.mozartoz.truffle.runtime.OzCons;
import org.mozartoz.truffle.runtime.OzFunction;
import org.mozartoz.truffle.runtime.Unit;
import scala.collection.JavaConversions;
import scala.collection.immutable.HashSet;
import scala.util.parsing.combinator.Parsers.ParseResult;
import scala.util.parsing.input.CharSequenceReader;
import scala.util.parsing.input.Position;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.nodes.NodeUtil;
import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.source.SourceSection;
public class Translator {
static class Environment {
private final Environment parent;
private final FrameDescriptor frameDescriptor;
public Environment(Environment parent, FrameDescriptor frameDescriptor) {
this.parent = parent;
this.frameDescriptor = frameDescriptor;
}
}
private Environment environment = new Environment(null, new FrameDescriptor());
private final Environment rootEnvironment = environment;
private static long id = 0;
public Translator() {
}
private void pushEnvironment(FrameDescriptor frameDescriptor) {
environment = new Environment(environment, frameDescriptor);
}
private void popEnvironment() {
environment = environment.parent;
}
private long nextID() {
return id++;
}
public FrameSlotAndDepth findVariable(Symbol symbol) {
int depth = 0;
Environment environment = this.environment;
while (environment != null) {
FrameSlot slot = environment.frameDescriptor.findFrameSlot(symbol);
if (slot != null) {
return new FrameSlotAndDepth(slot, depth);
} else {
environment = environment.parent;
depth++;
}
}
throw new AssertionError(symbol.fullName());
}
public OzRootNode parseAndTranslate(String code) {
Program program = new Program(false);
program.baseDeclarations().$plus$eq("Show").$plus$eq("Label").$plus$eq("ByNeedDot");
OzParser parser = new OzParser();
loadBuiltinModules(program);
BuiltinsManager.defineBuiltins();
CharSequenceReader reader = new CharSequenceReader(code);
HashSet<String> defines = new HashSet<String>();// .$plus("Show");
ParseResult<Statement> result = parser.parseStatement(reader, new File("test.oz"), defines);
if (!result.successful()) {
System.err.println("Parse error at " + result.next().pos().toString() + "\n" + result + "\n" + result.next().pos().longString());
throw new RuntimeException();
}
program.rawCode_$eq(result.get());
Namer.apply(program);
DesugarFunctor.apply(program);
DesugarClass.apply(program);
Desugar.apply(program);
PatternMatcher.apply(program);
ConstantFolding.apply(program);
Unnester.apply(program);
// Flattener.apply(program);
Statement ast = program.rawCode();
// System.out.println(ast);
FrameSlot baseSlot = rootEnvironment.frameDescriptor.addFrameSlot(program.baseEnvSymbol());
OzNode translated = translate(ast);
OzNode showNode = ShowNodeFactory.create(new ReadArgumentNode(0));
OzNode labelNode = BindVarValueNodeGen.create(new ReadArgumentNode(1),
LabelNodeFactory.create(new ReadArgumentNode(0)));
OzNode byNeedDotNode = BindVarValueNodeGen.create(new ReadArgumentNode(2),
DotNodeFactory.create(new ReadArgumentNode(0), new ReadArgumentNode(1)));
Arity baseArity = Arity.build("base", "Show", "Label", "ByNeedDot");
SourceSection sourceSection = SourceSection.createUnavailable("builtin", "TODO");
OzNode initializeBaseNode = new RecordLiteralNode(baseArity, new OzNode[] {
new ProcDeclarationNode(sourceSection, new FrameDescriptor(), showNode),
new ProcDeclarationNode(sourceSection, new FrameDescriptor(), labelNode),
new ProcDeclarationNode(sourceSection, new FrameDescriptor(), byNeedDotNode)
});
translated = SequenceNode.sequence(
new InitializeTmpNode(baseSlot, initializeBaseNode),
translated);
SourceSection topSourceSection = SourceSection.createUnavailable("top-level", "<top>");
return new OzRootNode(topSourceSection, environment.frameDescriptor, translated);
}
private void loadBuiltinModules(Program program) {
String[] builtinModules = { "Value", "Number", "Float", "Int", "Exception", "Record", "Name", "Object", "Thread" };
List<String> builtins = new ArrayList<>();
for (String buitinType : builtinModules) {
builtins.add("/home/eregon/code/mozart-graal/mozart-graal/builtins/Mod" + buitinType + "-builtin.json");
}
Main.loadModuleDefs(program, JavaConversions.asScalaBuffer(builtins).toList());
}
OzNode translate(Statement statement) {
if (statement instanceof SkipStatement) {
return new SkipNode();
} else if (statement instanceof CompoundStatement) {
CompoundStatement compound = (CompoundStatement) statement;
return SequenceNode.sequence(map(compound.statements(), this::translate));
} else if (statement instanceof LocalStatement) {
LocalStatement local = (LocalStatement) statement;
FrameDescriptor frameDescriptor = environment.frameDescriptor;
OzNode[] decls = map(local.declarations(), variable -> {
FrameSlot slot = frameDescriptor.addFrameSlot(variable.symbol());
return new InitializeVarNode(slot);
});
return SequenceNode.sequence(decls, translate(local.statement()));
} else if (statement instanceof BindStatement) {
BindStatement bind = (BindStatement) statement;
Expression left = bind.left();
Expression right = bind.right();
FrameSlotAndDepth leftSlot = null;
if (left instanceof Variable) {
leftSlot = findVariable(((Variable) left).symbol());
}
return t(statement, BindNodeGen.create(leftSlot, leftSlot.createReadNode(), translate(right)));
} else if (statement instanceof IfStatement) {
IfStatement ifStatement = (IfStatement) statement;
return new IfNode(translate(ifStatement.condition()),
translate(ifStatement.trueStatement()),
translate(ifStatement.falseStatement()));
} else if (statement instanceof TryStatement) {
TryStatement tryStatement = (TryStatement) statement;
FrameSlotAndDepth exceptionVarSlot = findVariable(((Variable) tryStatement.exceptionVar()).symbol());
return new TryNode(
exceptionVarSlot,
translate(tryStatement.body()),
translate(tryStatement.catchBody()));
} else if (statement instanceof MatchStatement) {
MatchStatement matchStatement = (MatchStatement) statement;
FrameSlot valueSlot = environment.frameDescriptor.addFrameSlot("MatchExpression-value" + nextID());
OzNode valueNode = translate(matchStatement.value());
Statement elseStatement = matchStatement.elseStatement();
assert !(elseStatement instanceof NoElseStatement);
OzNode elseNode = translate(elseStatement);
OzNode caseNode = elseNode;
for (MatchStatementClause clause : toJava(matchStatement.clauses())) {
assert !clause.hasGuard();
ReadLocalVariableNode value = new ReadLocalVariableNode(valueSlot);
List<OzNode> checks = new ArrayList<>();
List<OzNode> bindings = new ArrayList<>();
translatePattern(clause.pattern(), value, checks, bindings);
OzNode body = translate(clause.body());
caseNode = new IfNode(
new AndNode(checks.toArray(new OzNode[checks.size()])),
SequenceNode.sequence(bindings.toArray(new OzNode[bindings.size()]), body),
caseNode);
}
return SequenceNode.sequence(
new InitializeTmpNode(valueSlot, valueNode),
caseNode);
} else if (statement instanceof CallStatement) {
CallStatement callStatement = (CallStatement) statement;
Expression callable = callStatement.callable();
List<Expression> args = new ArrayList<>(toJava(callStatement.args()));
OzNode[] argsNodes = new OzNode[args.size()];
for (int i = 0; i < args.size(); i++) {
argsNodes[i] = translate(args.get(i));
}
return t(statement, CallProcNodeGen.create(argsNodes, translate(callable)));
}
throw unknown("statement", statement);
}
OzNode translate(Expression expression) {
if (expression instanceof Constant) {
Constant constant = (Constant) expression;
return translateConstantNode(constant.value());
} else if (expression instanceof Record) {
Record record = (Record) expression;
List<RecordField> fields = new ArrayList<>(toJava(record.fields()));
if (record.isCons()) {
return buildCons(translate(fields.get(0).value()), translate(fields.get(1).value()));
} else {
if (record.hasConstantArity()) {
OzNode[] values = new OzNode[fields.size()];
for (int i = 0; i < values.length; i++) {
values[i] = translate(fields.get(i).value());
}
return new RecordLiteralNode(buildArity(record.getConstantArity()), values);
}
}
} else if (expression instanceof Variable) {
Variable variable = (Variable) expression;
return findVariable(variable.symbol()).createReadNode();
} else if (expression instanceof UnboundExpression) {
return new UnboundLiteralNode();
} else if (expression instanceof BinaryOp) {
BinaryOp binaryOp = (BinaryOp) expression;
return translateBinaryOp(binaryOp.operator(),
translate(binaryOp.left()),
translate(binaryOp.right()));
} else if (expression instanceof ProcExpression) { // proc/fun literal
ProcExpression procExpression = (ProcExpression) expression;
FrameDescriptor frameDescriptor = new FrameDescriptor();
OzNode[] nodes = new OzNode[procExpression.args().size() + 1];
int i = 0;
for (VariableOrRaw variable : toJava(procExpression.args())) {
if (variable instanceof Variable) {
FrameSlot argSlot = frameDescriptor.addFrameSlot(((Variable) variable).symbol());
nodes[i] = InitializeArgNodeGen.create(argSlot, new ReadArgumentNode(i));
i++;
} else {
throw unknown("variable", variable);
}
}
pushEnvironment(frameDescriptor);
try {
nodes[i] = translate(procExpression.body());
} finally {
popEnvironment();
}
OzNode procBody = SequenceNode.sequence(nodes);
SourceSection sourceSection = t(expression);
return new ProcDeclarationNode(sourceSection, frameDescriptor, procBody);
}
throw unknown("expression", expression);
}
private void translatePattern(Expression pattern, OzNode valueNode, List<OzNode> checks, List<OzNode> bindings) {
if (pattern instanceof Constant) {
OzValue matcher = ((Constant) pattern).value();
translateMatcher(matcher, valueNode, checks, bindings);
} else {
throw unknown("pattern", pattern);
}
}
private void translateMatcher(OzValue matcher, OzNode valueNode, List<OzNode> checks, List<OzNode> bindings) {
if (matcher instanceof OzPatMatWildcard) {
// Nothing to do
} else if (matcher instanceof OzPatMatCapture) {
FrameSlotAndDepth slot = findVariable(((OzPatMatCapture) matcher).variable());
bindings.add(PatternMatchCaptureNodeGen.create(slot.createReadNode(), copy(valueNode)));
} else if (matcher instanceof OzFeature) {
Object feature = translateFeature((OzFeature) matcher);
checks.add(PatternMatchEqualNodeGen.create(feature, copy(valueNode)));
} else if (matcher instanceof OzRecord) {
OzRecord record = (OzRecord) matcher;
if (record.isCons()) {
checks.add(PatternMatchConsNodeGen.create(copy(valueNode)));
OzValue head = record.values().apply(0);
translateMatcher(head, HeadNodeGen.create(copy(valueNode)), checks, bindings);
OzValue tail = record.values().apply(1);
translateMatcher(tail, TailNodeGen.create(copy(valueNode)), checks, bindings);
} else {
Arity arity = buildArity(record.arity());
checks.add(PatternMatchRecordNodeGen.create(arity, copy(valueNode)));
for (OzRecordField field : toJava(record.fields())) {
Object feature = translateFeature(field.feature());
DotNode dotNode = DotNodeFactory.create(copy(valueNode), new LiteralNode(feature));
translateMatcher(field.value(), dotNode, checks, bindings);
}
}
} else {
throw unknown("pattern matcher", matcher);
}
}
private OzNode translateConstantNode(OzValue value) {
if (value instanceof OzInt) {
return new LongLiteralNode(((OzInt) value).value());
} else if (value instanceof True) {
return new BooleanLiteralNode(true);
} else if (value instanceof False) {
return new BooleanLiteralNode(false);
} else {
return new LiteralNode(translateConstantValue(value));
}
}
private Object translateConstantValue(OzValue value) {
if (value instanceof OzFeature) {
return translateFeature((OzFeature) value);
} else if (value instanceof OzRecord) {
OzRecord ozRecord = (OzRecord) value;
if (ozRecord.isCons()) {
Object left = translateConstantValue(ozRecord.fields().apply(0).value());
Object right = translateConstantValue(ozRecord.fields().apply(1).value());
return new OzCons(left, right);
} else {
Arity arity = buildArity(ozRecord.arity());
Object[] values = mapObjects(ozRecord.values(), this::translateConstantValue);
return RecordLiteralNode.buildRecord(arity, values);
}
} else if (value instanceof OzBuiltin) {
Builtin builtin = ((OzBuiltin) value).builtin();
OzFunction function = BuiltinsManager.getBuiltin(builtin.moduleName(), builtin.name());
if (function != null) {
return function;
} else {
throw unknown("builtin", builtin);
}
}
throw unknown("value", value);
}
private static Object translateFeature(OzFeature feature) {
if (feature instanceof OzInt) {
return ((OzInt) feature).value();
} else if (feature instanceof True) {
return true;
} else if (feature instanceof False) {
return false;
} else if (feature instanceof UnitVal) {
return Unit.INSTANCE;
} else if (feature instanceof OzAtom) {
return translateAtom((OzAtom) feature);
} else {
throw unknown("feature", feature);
}
}
private static Object translateLiteral(OzLiteral literal) {
if (literal instanceof OzAtom) {
return translateAtom((OzAtom) literal);
} else {
throw unknown("literal", literal);
}
}
private static String translateAtom(OzAtom atom) {
return atom.value().intern();
}
private OzNode buildCons(OzNode head, OzNode tail) {
return ConsLiteralNodeGen.create(head, tail);
}
private Arity buildArity(OzArity arity) {
Object[] features = mapObjects(arity.features(), Translator::translateFeature);
return Arity.build(translateLiteral(arity.label()), features);
}
private OzNode translateBinaryOp(String operator, OzNode left, OzNode right) {
switch (operator) {
case "+":
return AddNodeFactory.create(left, right);
case "-":
return SubNodeFactory.create(left, right);
case "*":
return MulNodeFactory.create(left, right);
case "div":
return DivNodeFactory.create(left, right);
case "mod":
return ModNodeFactory.create(left, right);
case "==":
return EqualNodeFactory.create(left, right);
case "\\=":
return NotEqualNodeFactory.create(left, right);
case "<":
return LesserThanNodeFactory.create(left, right);
case "=<":
return LesserThanOrEqualNodeFactory.create(left, right);
case ">":
return GreaterThanNodeFactory.create(left, right);
case ".":
return DotNodeFactory.create(left, right);
default:
throw unknown("operator", operator);
}
}
private OzNode copy(OzNode node) {
return NodeUtil.cloneNode(node);
}
private static <E> Collection<E> toJava(scala.collection.immutable.Iterable<E> scalaIterable) {
return JavaConversions.asJavaCollection(scalaIterable);
}
private static <E> OzNode[] map(scala.collection.immutable.Iterable<E> scalaIterable, Function<E, OzNode> apply) {
Collection<E> collection = toJava(scalaIterable);
OzNode[] result = new OzNode[collection.size()];
int i = 0;
for (E element : collection) {
result[i++] = apply.apply(element);
}
return result;
}
private static <E> Object[] mapObjects(scala.collection.immutable.Iterable<E> scalaIterable, Function<E, Object> apply) {
Collection<E> collection = toJava(scalaIterable);
Object[] result = new Object[collection.size()];
int i = 0;
for (E element : collection) {
result[i++] = apply.apply(element);
}
return result;
}
private static RuntimeException unknown(String type, Object description) {
return new RuntimeException("Unknown " + type + " " + description.getClass() + ": " + description);
}
private OzNode t(org.mozartoz.bootcompiler.ast.Node node, OzNode ozNode) {
SourceSection sourceSection = t(node);
ozNode.assignSourceSection(sourceSection);
return ozNode;
}
private static final Map<String, Source> SOURCES = new HashMap<>();
private SourceSection t(org.mozartoz.bootcompiler.ast.Node node) {
Position pos = node.pos();
if (pos instanceof FilePosition) {
FilePosition filePosition = (FilePosition) pos;
String canonicalPath;
try {
canonicalPath = filePosition.file().get().getCanonicalPath();
} catch (IOException e) {
throw new RuntimeException(e);
}
Source source = SOURCES.computeIfAbsent(canonicalPath, file -> {
try {
return Source.fromFileName(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
return source.createSection("", filePosition.line());
} else {
return SourceSection.createUnavailable("unavailable", "");
}
}
} |
package com.sometrik.framework;
import android.graphics.Typeface;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class FWButton extends Button implements NativeCommandHandler {
FrameWork frame;
public FWButton(FrameWork frameWork) {
super(frameWork);
this.frame = frameWork;
}
@Override
public void addChild(View view) {
System.out.println("FWButton couldn't handle command");
}
@Override
public void addOption(int optionId, String text) {
System.out.println("FWButton couldn't handle command");
}
@Override
public void setValue(String v) {
setText(v);
//FIXME Debug animation
RotateAnimation r = new RotateAnimation(-5f, 5f,50,50);
r.setDuration(100);
r.setRepeatCount(10);
r.setRepeatMode(RotateAnimation.REVERSE);
startAnimation(r);
}
@Override
public void setValue(int v) {
System.out.println("FWButton couldn't handle command");
}
@Override
public int getElementId() {
return getId();
}
@Override
public void setViewEnabled(Boolean enabled) {
setEnabled(true);
}
@Override
public void setStyle(String key, String value) {
if (key.equals("font-size")){
if (value.equals("small")){
this.setTextAppearance(frame, android.R.style.TextAppearance_DeviceDefault_Small);
} else if (value.equals("medium")){
this.setTextAppearance(frame, android.R.style.TextAppearance_DeviceDefault_Medium);
} else if (value.equals("large")){
this.setTextAppearance(frame, android.R.style.TextAppearance_DeviceDefault_Large);
}
} else if (key.equals("gravity")) {
Log.d("button", "setting gravity: ");
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.weight = 1;
if (value.equals("bottom")) {
params.gravity = Gravity.BOTTOM;
Log.d("button", " to bottom");
} else if (value.equals("top")) {
params.gravity = Gravity.TOP;
} else if (value.equals("left")) {
params.gravity = Gravity.LEFT;
} else if (value.equals("right")) {
params.gravity = Gravity.RIGHT;
}
setLayoutParams(params);
} else if (key.equals("width")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap_content")) {
params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match_parent")) {
params.width = LinearLayout.LayoutParams.MATCH_PARENT;
}
setLayoutParams(params);
} else if (key.equals("height")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap_content")) {
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match_parent")) {
params.height = LinearLayout.LayoutParams.MATCH_PARENT;
}
setLayoutParams(params);
} else if (key.equals("add_weight")){
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.weight += 1;
setLayoutParams(params);
System.out.println("button weight: " + params.weight);
}
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
@Override
public void addData(String text, int row, int column, int sheet) {
System.out.println("FWButton couldn't handle command");
}
@Override
public void setViewVisibility(boolean visibility) {
if (visibility){
this.setVisibility(VISIBLE);
} else {
this.setVisibility(INVISIBLE);
}
}
} |
package com.sometrik.framework;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewParent;
import android.widget.LinearLayout;
public class FWLayout extends LinearLayout implements NativeCommandHandler {
private FrameWork frame;
public FWLayout(FrameWork frameWork) {
super(frameWork);
this.frame = frameWork;
}
@Override
public int getElementId() {
return getId();
}
@Override
public void addChild(View view) {
addView(view);
}
@Override
public void addOption(int optionId, String text) {
System.out.println("FWLayout couldn't handle command");
}
@Override
public void setValue(String v) {
System.out.println("FWLayout couldn't handle command");
}
@Override
public void setValue(int v) {
if (v == 1){
frame.setCurrentView(this, true);
} else if (v == 2){
frame.setCurrentView(this, false);
}
}
@Override
public void setViewEnabled(Boolean enabled) {
System.out.println("FWLayout couldn't handle command");
}
@Override
public void setStyle(String key, String value) {
if (key.equals("gravity")){
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("bottom")){
params.gravity = Gravity.BOTTOM;
} else if (value.equals("top")){
params.gravity = Gravity.TOP;
} else if (value.equals("left")){
params.gravity = Gravity.LEFT;
} else if (value.equals("right")){
params.gravity = Gravity.RIGHT;
}
}
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void onScreenOrientationChange(boolean isLandscape) {
invalidate();
}
@Override
public void addData(int rowNumber, int columnNumber, String text) {
System.out.println("FWLayout couldn't handle command");
}
@Override
public void setViewVisibility(boolean visibility) {
if (visibility){
this.setVisibility(VISIBLE);
} else {
this.setVisibility(INVISIBLE);
}
}
} |
package xyz.igorgee.imagecreator3d;
import java.io.File;
public class Model {
String name;
File location;
Integer modelID;
public Model(String name, File location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getLocation() {
return location;
}
public void setLocation(File location) {
this.location = location;
}
public Integer getModelID() {
return modelID;
}
public void setModelID(Integer modelID) {
this.modelID = modelID;
}
} |
package annotator;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import plume.*;
import annotator.find.Insertion;
import annotator.find.TreeFinder;
import annotator.Source;
import annotator.Source.CompilerException;
import annotator.specification.IndexFileSpecification;
import annotator.specification.Specification;
import com.sun.source.tree.*;
import com.sun.source.util.TreePath;
import com.google.common.collect.*;
/**
* This is the main class for the annotator, which inserts annotations in
* Java source code. It takes as input
* <ul>
* <li>annotation (index) files, which indcate the annotations to insert</li>
* <li>Java source files, into which the annotator inserts annotations</li>
* </ul>
* Use the --help option for full usage details.
* <p>
*
* Annotations that are not for the specified Java files are ignored.
*/
public class Main {
public static final String INDEX_UTILS_VERSION =
"Annotation file utilities: insert-annotations-to-source v3.0";
/** Directory in which output files are written. */
@Option("-d <directory> Directory in which output files are written")
public static String outdir = "annotated/";
/**
* If true, overwrite original source files (making a backup first).
* Furthermore, if the backup files already exist, they are used instead
* of the .java files. This behavior permits a user to tweak the .jaif
* file and re-run the annotator.
* <p>
*
* Note that if the user runs the annotator with --in-place, makes edits,
* and then re-runs the annotator with this --in-place option, those
* edits are lost. Similarly, if the user runs the annotator twice in a
* row with --in-place, only the last set of annotations will appear in
* the codebase at the end.
* <p>
*
* To preserve changes when using the --in-place option, first remove the
* backup files. Or, use the <tt>-d .</tt> option, which makes (and
* reads) no backup, instead of --in-place.
*/
@Option("-i Overwrite original source files")
public static boolean in_place = false;
@Option("-h Print usage information and exit")
public static boolean help = false;
@Option("-a Abbreviate annotation names")
public static boolean abbreviate = true;
@Option("-c Insert annotations in comments")
public static boolean comments = false;
@Option("-o Omit given annotation")
public static String omit_annotation;
@Option("-v Verbose (print progress information)")
public static boolean verbose;
@Option("Debug (print debug information)")
public static boolean debug = false;
// Implementation details:
// 1. The annotator partially compiles source
// files using the compiler API (JSR-199), obtaining an AST.
// 2. The annotator reads the specification file, producing a set of
// annotator.find.Insertions. Insertions completely specify what to
// write (as a String, which is ultimately translated according to the
// keyword file) and how to write it (as annotator.find.Criteria).
// 3. It then traverses the tree, looking for nodes that satisfy the
// Insertion Criteria, translating the Insertion text against the
// keyword file, and inserting the annotations into the source file.
/**
* Runs the annotator, parsing the source and spec files and applying
* the annotations.
*/
public static void main(String[] args) {
if (verbose) {
System.out.println(INDEX_UTILS_VERSION);
}
Options options = new Options("Main [options] ann-file... java-file...", Main.class);
String[] file_args = options.parse_and_usage (args);
if (debug) {
TreeFinder.debug = true;
}
if (help) {
options.print_usage();
System.exit(0);
}
if (in_place && outdir != "annotated/") { // interned
options.print_usage("The --outdir and --in-place options are mutually exclusive.");
System.exit(1);
}
if (file_args.length < 2) {
options.print_usage("Supplied %d arguments, at least 2 needed%n", file_args.length);
System.exit(1);
}
// The insertions specified by the annotation files.
List<Insertion> insertions = new ArrayList<Insertion>();
// The Java files into which to insert.
List<String> javafiles = new ArrayList<String>();
for (String arg : file_args) {
if (arg.endsWith(".java")) {
javafiles.add(arg);
} else if (arg.endsWith(".jaif")) {
try {
Specification spec = new IndexFileSpecification(arg);
List<Insertion> parsedSpec = spec.parse();
if (verbose || debug) {
System.out.printf("Read %d annotations from %s%n",
parsedSpec.size(), arg);
}
if (omit_annotation != null) {
List<Insertion> filtered = new ArrayList<Insertion>(parsedSpec.size());
for (Insertion insertion : parsedSpec) {
if (! omit_annotation.equals(insertion.getText())) {
filtered.add(insertion);
}
}
parsedSpec = filtered;
if (verbose || debug) {
System.out.printf("After filtering: %d annotations from %s%n",
parsedSpec.size(), arg);
}
}
insertions.addAll(parsedSpec);
} catch (RuntimeException e) {
if (e.getCause() != null
&& e.getCause() instanceof FileNotFoundException) {
System.err.println("File not found: " + arg);
System.exit(1);
} else {
throw e;
}
} catch (FileIOException e) {
System.err.println("Error while parsing annotation file " + arg);
if (e.getMessage() != null) {
System.err.println(e.getMessage());
}
e.printStackTrace();
System.exit(1);
}
} else {
throw new Error("Unrecognized file extension: " + arg);
}
}
if (debug) {
System.out.printf("%d insertions, %d .java files%n", insertions.size(), javafiles.size());
}
if (debug) {
System.out.printf("Insertions:%n");
for (Insertion insertion : insertions) {
System.out.printf(" %s%n", insertion);
}
}
for (String javafilename : javafiles) {
if (verbose) {
System.out.println("Processing " + javafilename);
}
File javafile = new File(javafilename);
File outfile;
File unannotated = new File(javafilename + ".unannotated");
if (in_place) {
// It doesn't make sense to check timestamps;
// if the .java.unannotated file exists, then just use it.
// A user can rename that file back to just .java to cause the
// .java file to be read.
if (unannotated.exists()) {
if (verbose) {
System.out.printf("Renaming %s to %s%n", unannotated, javafile);
}
boolean success = unannotated.renameTo(javafile);
if (! success) {
throw new Error(String.format("Failed renaming %s to %s",
unannotated, javafile));
}
}
outfile = javafile;
} else {
String baseName;
if (javafile.isAbsolute()) {
baseName = javafile.getName();
} else {
baseName = javafile.getPath();
}
outfile = new File(outdir, baseName);
}
Set<String> imports = new LinkedHashSet<String>();
String fileLineSep = System.getProperty("line.separator");
Source src;
// Get the source file, and use it to obtain parse trees.
try {
// fileLineSep is set here so that exceptions can be caught
fileLineSep = UtilMDE.inferLineSeparator(javafilename);
src = new Source(javafilename);
} catch (CompilerException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
for (CompilationUnitTree tree : src.parse()) {
// Create a finder, and use it to get positions.
TreeFinder finder = new TreeFinder(tree);
if (debug) {
finder.debug = true;
}
SetMultimap<Integer, Insertion> positions = finder.getPositions(tree, insertions);
// Apply the positions to the source file.
if (debug) {
System.err.printf("%d positions in tree for %s%n", positions.size(), javafilename);
}
Set<Integer> positionKeysUnsorted = positions.keySet();
Set<Integer> positionKeysSorted = new TreeSet<Integer>(new TreeFinder.ReverseIntegerComparator());
positionKeysSorted.addAll(positionKeysUnsorted);
for (Integer pos : positionKeysSorted) {
List<Insertion> toInsertList = new ArrayList<Insertion>(positions.get(pos));
Collections.reverse(toInsertList);
assert pos >= 0
: "pos is negative: " + pos + " " + toInsertList.get(0) + " " + javafilename;
for (Insertion iToInsert : toInsertList) {
String toInsert = iToInsert.getText();
if (! toInsert.startsWith("@")) {
throw new Error("Insertion doesn't start with '@': " + toInsert);
}
if (abbreviate) {
Pair<String,String> ps = removePackage(toInsert);
if (ps.a != null) {
imports.add(ps.a);
}
toInsert = ps.b;
}
if (comments) {
toInsert = "/*" + toInsert + "*/";
}
// Possibly add whitespace after the insertion
boolean gotSeparateLine = false;
if (iToInsert.getSeparateLine()) {
int indentation = 0;
while ((pos - indentation != 0)
// horizontal whitespace
&& (src.charAt(pos-indentation-1) == ' '
|| src.charAt(pos-indentation-1) == '\t')) {
indentation++;
}
if ((pos - indentation == 0)
// horizontal whitespace
|| (src.charAt(pos-indentation-1) == '\f'
|| src.charAt(pos-indentation-1) == '\n'
|| src.charAt(pos-indentation-1) == '\r')) {
toInsert = toInsert + fileLineSep + src.substring(pos-indentation, pos);
gotSeparateLine = true;
}
}
// Possibly add a leading space before the insertion
if ((! gotSeparateLine) && (pos != 0)) {
char precedingChar = src.charAt(pos-1);
if (! (Character.isWhitespace(precedingChar)
// No space if it's the first formal or generic parameter
|| precedingChar == '('
|| precedingChar == '<')) {
toInsert = " " + toInsert;
}
}
// If it's already there, don't re-insert. This is a hack!
// Also, I think this is already checked when constructing the
// innertions.
int precedingTextPos = pos-toInsert.length()-1;
if (precedingTextPos >= 0) {
String precedingTextPlusChar
= src.getString().substring(precedingTextPos, pos);
// System.out.println("Inserting " + toInsert + " at " + pos + " in code of length " + src.getString().length() + " with preceding text '" + precedingTextPlusChar + "'");
if (toInsert.equals(precedingTextPlusChar.substring(0, toInsert.length()))
|| toInsert.equals(precedingTextPlusChar.substring(1))) {
if (debug) {
System.out.println("Already present, skipping");
}
continue;
}
}
// add trailing whitespace
if (! gotSeparateLine) {
toInsert = toInsert + " ";
}
src.insert(pos, toInsert);
if (debug) {
System.out.println("Post-insertion source: " + src.getString());
}
}
}
}
// insert import statements
{
if (debug) {
System.out.println(imports.size() + " imports to insert");
for (String classname : imports) {
System.out.println(" " + classname);
}
}
Pattern importPattern = Pattern.compile("(?m)^import\\b");
Pattern packagePattern = Pattern.compile("(?m)^package\\b.*;(\\n|\\r\\n?)");
int importIndex = 0; // default: beginning of file
String srcString = src.getString();
Matcher m;
m = importPattern.matcher(srcString);
if (m.find()) {
importIndex = m.start();
} else {
// if (debug) {
// System.out.println("Didn't find import in " + srcString);
m = packagePattern.matcher(srcString);
if (m.find()) {
importIndex = m.end();
}
}
String lineSep = System.getProperty("line.separator");
for (String classname : imports) {
String toInsert = "import " + classname + ";" + fileLineSep;
src.insert(importIndex, toInsert);
importIndex += toInsert.length();
}
}
// Write the source file.
try {
if (in_place) {
if (verbose) {
System.out.printf("Renaming %s to %s%n", javafile, unannotated);
}
boolean success = javafile.renameTo(unannotated);
if (! success) {
throw new Error(String.format("Failed renaming %s to %s",
javafile, unannotated));
}
} else {
outfile.getParentFile().mkdirs();
}
OutputStream output = new FileOutputStream(outfile);
if (verbose) {
System.out.printf("Writing %s%n", outfile);
}
src.write(output);
output.close();
} catch (IOException e) {
System.err.println("Problem while writing file " + outfile);
e.printStackTrace();
System.exit(1);
}
}
}
/// Utility methods
public static String pathToString(TreePath path) {
if (path == null)
return "null";
return treeToString(path.getLeaf());
}
public static String treeToString(Tree node) {
String asString = node.toString();
String oneLine = firstLine(asString);
return "\"" + oneLine + "\"";
}
/**
* Return the first non-empty line of the string, adding an ellipsis
* (...) if the string was truncated.
*/
public static String firstLine(String s) {
while (s.startsWith("\n")) {
s = s.substring(1);
}
int newlineIndex = s.indexOf('\n');
if (newlineIndex == -1) {
return s;
} else {
return s.substring(0, newlineIndex) + "...";
}
}
/**
* Removes the leading package.
*
* @return given <code>@com.foo.bar(baz)</code> it returns the pair
* <code>{ com.foo, @bar(baz) }</code>.
*/
public static Pair<String,String> removePackage(String s) {
int nameEnd = s.indexOf("(");
if (nameEnd == -1) {
nameEnd = s.length();
}
int dotIndex = s.lastIndexOf(".", nameEnd);
if (dotIndex != -1) {
String packageName = s.substring(0, nameEnd);
if (packageName.startsWith("@")) {
return Pair.of(packageName.substring(1),
"@" + s.substring(dotIndex + 1));
} else {
return Pair.of(packageName,
s.substring(dotIndex + 1));
}
} else {
return Pair.of((String)null, s);
}
}
/**
* Separates the annotation class from its arguments.
*
* @return given <code>@foo(bar)</code> it returns the pair <code>{ @foo, (bar) }</code>.
*/
public static Pair<String,String> removeArgs(String s) {
int pidx = s.indexOf("(");
return (pidx == -1) ?
Pair.of(s, (String)null) :
Pair.of(s.substring(0, pidx), s.substring(pidx));
}
} |
package lucee.runtime.config;
import static lucee.runtime.db.DatasourceManagerImpl.QOQ_DATASOURCE_NAME;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ref.SoftReference;
import java.net.InetAddress;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import org.osgi.framework.BundleException;
import org.osgi.framework.Version;
import lucee.commons.io.CharsetUtil;
import lucee.commons.io.FileUtil;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.cache.Cache;
import lucee.commons.io.log.Log;
import lucee.commons.io.log.LogEngine;
import lucee.commons.io.log.LogUtil;
import lucee.commons.io.log.LoggerAndSourceData;
import lucee.commons.io.log.log4j.layout.ClassicLayout;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.ResourceProvider;
import lucee.commons.io.res.Resources;
import lucee.commons.io.res.ResourcesImpl;
import lucee.commons.io.res.ResourcesImpl.ResourceProviderFactory;
import lucee.commons.io.res.filter.ExtensionResourceFilter;
import lucee.commons.io.res.type.compress.Compress;
import lucee.commons.io.res.util.ResourceClassLoader;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.lang.CharSet;
import lucee.commons.lang.ClassException;
import lucee.commons.lang.ClassUtil;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.Md5;
import lucee.commons.lang.PhysicalClassLoader;
import lucee.commons.lang.StringUtil;
import lucee.commons.lang.types.RefBoolean;
import lucee.commons.net.IPRange;
import lucee.loader.engine.CFMLEngine;
import lucee.runtime.CIPage;
import lucee.runtime.Component;
import lucee.runtime.Mapping;
import lucee.runtime.MappingImpl;
import lucee.runtime.Page;
import lucee.runtime.PageContext;
import lucee.runtime.PageSource;
import lucee.runtime.PageSourceImpl;
import lucee.runtime.cache.CacheConnection;
import lucee.runtime.cache.ram.RamCache;
import lucee.runtime.cache.tag.CacheHandler;
import lucee.runtime.cfx.CFXTagPool;
import lucee.runtime.cfx.customtag.CFXTagPoolImpl;
import lucee.runtime.component.ImportDefintion;
import lucee.runtime.component.ImportDefintionImpl;
import lucee.runtime.config.ConfigWebUtil.CacheElement;
import lucee.runtime.customtag.InitFile;
import lucee.runtime.db.ClassDefinition;
import lucee.runtime.db.DataSource;
import lucee.runtime.db.DataSourcePro;
import lucee.runtime.db.DatasourceConnectionFactory;
import lucee.runtime.db.JDBCDriver;
import lucee.runtime.dump.DumpWriter;
import lucee.runtime.dump.DumpWriterEntry;
import lucee.runtime.dump.HTMLDumpWriter;
import lucee.runtime.engine.ExecutionLogFactory;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.DatabaseException;
import lucee.runtime.exp.DeprecatedException;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.exp.PageRuntimeException;
import lucee.runtime.exp.SecurityException;
import lucee.runtime.exp.TemplateException;
import lucee.runtime.extension.Extension;
import lucee.runtime.extension.ExtensionProvider;
import lucee.runtime.extension.RHExtension;
import lucee.runtime.extension.RHExtensionProvider;
import lucee.runtime.functions.other.CreateUniqueId;
import lucee.runtime.functions.system.ContractPath;
import lucee.runtime.gateway.GatewayEntry;
import lucee.runtime.listener.AppListenerUtil;
import lucee.runtime.listener.ApplicationContext;
import lucee.runtime.listener.ApplicationListener;
import lucee.runtime.net.mail.Server;
import lucee.runtime.net.ntp.NtpClient;
import lucee.runtime.net.proxy.ProxyData;
import lucee.runtime.net.proxy.ProxyDataImpl;
import lucee.runtime.net.rpc.WSHandler;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Duplicator;
import lucee.runtime.orm.ORMConfiguration;
import lucee.runtime.orm.ORMEngine;
import lucee.runtime.osgi.BundleInfo;
import lucee.runtime.osgi.EnvClassLoader;
import lucee.runtime.osgi.OSGiUtil.BundleDefinition;
import lucee.runtime.regex.Regex;
import lucee.runtime.regex.RegexFactory;
import lucee.runtime.rest.RestSettingImpl;
import lucee.runtime.rest.RestSettings;
import lucee.runtime.schedule.Scheduler;
import lucee.runtime.schedule.SchedulerImpl;
import lucee.runtime.search.SearchEngine;
import lucee.runtime.security.SecurityManager;
import lucee.runtime.spooler.SpoolerEngine;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.UDF;
import lucee.runtime.type.dt.TimeSpan;
import lucee.runtime.type.dt.TimeSpanImpl;
import lucee.runtime.type.scope.ClusterNotSupported;
import lucee.runtime.type.scope.Undefined;
import lucee.runtime.type.util.KeyConstants;
import lucee.runtime.video.VideoExecuterNotSupported;
import lucee.transformer.library.function.FunctionLib;
import lucee.transformer.library.function.FunctionLibException;
import lucee.transformer.library.function.FunctionLibFactory;
import lucee.transformer.library.function.FunctionLibFunction;
import lucee.transformer.library.function.FunctionLibFunctionArg;
import lucee.transformer.library.tag.TagLib;
import lucee.transformer.library.tag.TagLibException;
import lucee.transformer.library.tag.TagLibFactory;
import lucee.transformer.library.tag.TagLibTag;
import lucee.transformer.library.tag.TagLibTagAttr;
import lucee.transformer.library.tag.TagLibTagScript;
/**
* Hold the definitions of the Lucee configuration.
*/
public abstract class ConfigImpl extends ConfigBase implements ConfigPro {
private static final RHExtension[] RHEXTENSIONS_EMPTY = new RHExtension[0];
// FUTURE add to interface
public static final short ADMINMODE_SINGLE = 1;
public static final short ADMINMODE_MULTI = 2;
public static final short ADMINMODE_AUTO = 4;
private int mode = MODE_CUSTOM;
private PhysicalClassLoader rpcClassLoader;
private Map<String, DataSource> datasources = new HashMap<String, DataSource>();
private Map<String, CacheConnection> caches = new HashMap<String, CacheConnection>();
private CacheConnection defaultCacheFunction = null;
private CacheConnection defaultCacheObject = null;
private CacheConnection defaultCacheTemplate = null;
private CacheConnection defaultCacheQuery = null;
private CacheConnection defaultCacheResource = null;
private CacheConnection defaultCacheInclude = null;
private CacheConnection defaultCacheHTTP = null;
private CacheConnection defaultCacheFile = null;
private CacheConnection defaultCacheWebservice = null;
private String cacheDefaultConnectionNameFunction = null;
private String cacheDefaultConnectionNameObject = null;
private String cacheDefaultConnectionNameTemplate = null;
private String cacheDefaultConnectionNameQuery = null;
private String cacheDefaultConnectionNameResource = null;
private String cacheDefaultConnectionNameInclude = null;
private String cacheDefaultConnectionNameHTTP = null;
private String cacheDefaultConnectionNameFile = null;
private String cacheDefaultConnectionNameWebservice = null;
private TagLib[] cfmlTlds = new TagLib[0];
private TagLib[] luceeTlds = new TagLib[0];
private FunctionLib[] cfmlFlds = new FunctionLib[0];
private FunctionLib[] luceeFlds = new FunctionLib[0];
private FunctionLib combinedCFMLFLDs;
private FunctionLib combinedLuceeFLDs;
private short type = SCOPE_STANDARD;
private boolean _allowImplicidQueryCall = true;
private boolean _mergeFormAndURL = false;
private Map<String, LoggerAndSourceData> loggers = new HashMap<String, LoggerAndSourceData>();
private int _debug;
private int debugLogOutput = SERVER_BOOLEAN_FALSE;
private int debugOptions = 0;
private boolean suppresswhitespace = false;
private boolean suppressContent = false;
private boolean showVersion = false;
private Resource tempDirectory;
private TimeSpan clientTimeout = new TimeSpanImpl(90, 0, 0, 0);
private TimeSpan sessionTimeout = new TimeSpanImpl(0, 0, 30, 0);
private TimeSpan applicationTimeout = new TimeSpanImpl(1, 0, 0, 0);
private TimeSpan requestTimeout = new TimeSpanImpl(0, 0, 0, 30);
private boolean sessionManagement = true;
private boolean clientManagement = false;
private boolean clientCookies = true;
private boolean developMode = false;
private boolean domainCookies = false;
private Resource configFile;
private Resource configDir;
private String sessionStorage = DEFAULT_STORAGE_SESSION;
private String clientStorage = DEFAULT_STORAGE_CLIENT;
private long loadTime;
private int spoolInterval = 30;
private boolean spoolEnable = true;
private boolean sendPartial = false;
private boolean userSet = true;
private Server[] mailServers;
private int mailTimeout = 30;
private TimeZone timeZone;
private String timeServer = "";
private boolean useTimeServer = true;
private long timeOffset;
private ClassDefinition<SearchEngine> searchEngineClassDef;
private String searchEngineDirectory;
private Locale locale;
private boolean psq = false;
private boolean debugShowUsage;
private Map<String, String> errorTemplates = new HashMap<String, String>();
protected Password password;
private String salt;
private Mapping[] mappings = new Mapping[0];
private Mapping[] customTagMappings = new Mapping[0];
private Mapping[] componentMappings = new Mapping[0];
private SchedulerImpl scheduler;
private CFXTagPool cfxTagPool;
private PageSource baseComponentPageSourceCFML;
private String baseComponentTemplateCFML;
private PageSource baseComponentPageSourceLucee;
private String baseComponentTemplateLucee;
private boolean restList = false;
private short clientType = CLIENT_SCOPE_TYPE_COOKIE;
private String componentDumpTemplate;
private int componentDataMemberDefaultAccess = Component.ACCESS_PRIVATE;
private boolean triggerComponentDataMember = false;
private short sessionType = SESSION_TYPE_APPLICATION;
private Resource deployDirectory;
private short compileType = RECOMPILE_NEVER;
private CharSet resourceCharset = SystemUtil.getCharSet();
private CharSet templateCharset = SystemUtil.getCharSet();
private CharSet webCharset = CharSet.UTF8;
private CharSet mailDefaultCharset = CharSet.UTF8;
private Resource tldFile;
private Resource fldFile;
private Resources resources = new ResourcesImpl();
private Map<String, Class<CacheHandler>> cacheHandlerClasses = new HashMap<String, Class<CacheHandler>>();
private ApplicationListener applicationListener;
private int scriptProtect = ApplicationContext.SCRIPT_PROTECT_ALL;
private ProxyData proxy = null;
private Resource clientScopeDir;
private Resource sessionScopeDir;
private long clientScopeDirSize = 1024 * 1024 * 10;
private long sessionScopeDirSize = 1024 * 1024 * 10;
private Resource cacheDir;
private long cacheDirSize = 1024 * 1024 * 10;
private boolean useComponentShadow = true;
private PrintWriter out = SystemUtil.getPrintWriter(SystemUtil.OUT);
private PrintWriter err = SystemUtil.getPrintWriter(SystemUtil.ERR);
private Map<String, DatasourceConnPool> pools = new HashMap<>();
private boolean doCustomTagDeepSearch = false;
private boolean doComponentTagDeepSearch = false;
private double version = 1.0D;
private boolean closeConnection = false;
private boolean contentLength = true;
private boolean allowCompression = false;
private boolean doLocalCustomTag = true;
private Struct constants = null;
private RemoteClient[] remoteClients;
private SpoolerEngine remoteClientSpoolerEngine;
private Resource remoteClientDirectory;
private boolean allowURLRequestTimeout = false;
private boolean errorStatusCode = true;
private int localMode = Undefined.MODE_LOCAL_OR_ARGUMENTS_ONLY_WHEN_EXISTS;
private RHExtensionProvider[] rhextensionProviders = Constants.RH_EXTENSION_PROVIDERS;
private RHExtension[] rhextensions = RHEXTENSIONS_EMPTY;
private boolean allowRealPath = true;
private DumpWriterEntry[] dmpWriterEntries;
private Class clusterClass = ClusterNotSupported.class;// ClusterRemoteNotSupported.class;//
private Struct remoteClientUsage;
private Class adminSyncClass = AdminSyncNotSupported.class;
private AdminSync adminSync;
private String[] customTagExtensions = Constants.getExtensions();
private Class videoExecuterClass = VideoExecuterNotSupported.class;
protected MappingImpl scriptMapping;
// private Resource tagDirectory;
protected Mapping defaultFunctionMapping;
protected Map<String, Mapping> functionMappings = new ConcurrentHashMap<String, Mapping>();
protected Mapping defaultTagMapping;
protected Map<String, Mapping> tagMappings = new ConcurrentHashMap<String, Mapping>();
private short inspectTemplate = INSPECT_ONCE;
private boolean typeChecking = true;
private String cacheMD5;
private boolean executionLogEnabled;
private ExecutionLogFactory executionLogFactory;
private Map<String, ORMEngine> ormengines = new HashMap<String, ORMEngine>();
private ClassDefinition<? extends ORMEngine> cdORMEngine;
private ORMConfiguration ormConfig;
private ResourceClassLoader resourceCL;
private ImportDefintion componentDefaultImport = new ImportDefintionImpl(Constants.DEFAULT_PACKAGE, "*");
private boolean componentLocalSearch = true;
private boolean componentRootSearch = true;
private boolean useComponentPathCache = true;
private boolean useCTPathCache = true;
private lucee.runtime.rest.Mapping[] restMappings;
protected int writerType = CFML_WRITER_REFULAR;
private long configFileLastModified;
private boolean checkForChangesInConfigFile;
// protected String apiKey=null;
private List consoleLayouts = new ArrayList();
private List resourceLayouts = new ArrayList();
private Map<Key, Map<Key, Object>> tagDefaultAttributeValues;
private boolean handleUnQuotedAttrValueAsString = true;
private Map<Integer, Object> cachedWithins = new HashMap<Integer, Object>();
private int queueMax = 100;
private long queueTimeout = 0;
private boolean queueEnable = false;
private int varUsage;
private TimeSpan cachedAfterTimeRange;
private static Map<String, Startup> startups;
private Regex regex; // TODO add possibility to configure
private long applicationPathCacheTimeout = Caster.toLongValue(SystemUtil.getSystemPropOrEnvVar("lucee.application.path.cache.timeout", null), 20000);
private ClassLoader envClassLoader;
/**
* @return the allowURLRequestTimeout
*/
@Override
public boolean isAllowURLRequestTimeout() {
return allowURLRequestTimeout;
}
/**
* @param allowURLRequestTimeout the allowURLRequestTimeout to set
*/
public void setAllowURLRequestTimeout(boolean allowURLRequestTimeout) {
this.allowURLRequestTimeout = allowURLRequestTimeout;
}
@Override
public short getCompileType() {
return compileType;
}
@Override
public void reset() {
timeServer = "";
componentDumpTemplate = "";
// resources.reset();
ormengines.clear();
compressResources.clear();
clearFunctionCache();
clearCTCache();
clearComponentCache();
clearApplicationCache();
// clearComponentMetadata();
}
@Override
public void reloadTimeServerOffset() {
timeOffset = 0;
if (useTimeServer && !StringUtil.isEmpty(timeServer, true)) {
NtpClient ntp = new NtpClient(timeServer);
timeOffset = ntp.getOffset(0);
}
}
/**
* private constructor called by factory method
*
* @param configDir - config directory
* @param configFile - config file
*/
protected ConfigImpl(Resource configDir, Resource configFile) {
this.configDir = configDir;
this.configFile = configFile;
}
@Override
public long lastModified() {
return configFileLastModified;
}
protected void setLastModified() {
this.configFileLastModified = configFile.lastModified();
}
@Override
public short getScopeCascadingType() {
return type;
}
/*
* @Override public String[] getCFMLExtensions() { return getAllExtensions(); }
*
* @Override public String getCFCExtension() { return getComponentExtension(); }
*
* @Override public String[] getAllExtensions() { return Constants.ALL_EXTENSION; }
*
* @Override public String getComponentExtension() { return Constants.COMPONENT_EXTENSION; }
*
* @Override public String[] getTemplateExtensions() { return Constants.TEMPLATE_EXTENSIONS; }
*/
protected void setFLDs(FunctionLib[] flds, int dialect) {
if (dialect == CFMLEngine.DIALECT_CFML) {
cfmlFlds = flds;
combinedCFMLFLDs = null; // TODO improve check (hash)
}
else {
luceeFlds = flds;
combinedLuceeFLDs = null; // TODO improve check (hash)
}
}
/**
* return all Function Library Deskriptors
*
* @return Array of Function Library Deskriptors
*/
@Override
public FunctionLib[] getFLDs(int dialect) {
return dialect == CFMLEngine.DIALECT_CFML ? cfmlFlds : luceeFlds;
}
@Override
public FunctionLib getCombinedFLDs(int dialect) {
if (dialect == CFMLEngine.DIALECT_CFML) {
if (combinedCFMLFLDs == null) combinedCFMLFLDs = FunctionLibFactory.combineFLDs(cfmlFlds);
return combinedCFMLFLDs;
}
if (combinedLuceeFLDs == null) combinedLuceeFLDs = FunctionLibFactory.combineFLDs(luceeFlds);
return combinedLuceeFLDs;
}
/**
* return all Tag Library Deskriptors
*
* @return Array of Tag Library Deskriptors
*/
@Override
public TagLib[] getTLDs(int dialect) {
return dialect == CFMLEngine.DIALECT_CFML ? cfmlTlds : luceeTlds;
}
protected void setTLDs(TagLib[] tlds, int dialect) {
if (dialect == CFMLEngine.DIALECT_CFML) cfmlTlds = tlds;
else luceeTlds = tlds;
}
@Override
public boolean allowImplicidQueryCall() {
return _allowImplicidQueryCall;
}
@Override
public boolean mergeFormAndURL() {
return _mergeFormAndURL;
}
@Override
public TimeSpan getApplicationTimeout() {
return applicationTimeout;
}
@Override
public TimeSpan getSessionTimeout() {
return sessionTimeout;
}
@Override
public TimeSpan getClientTimeout() {
return clientTimeout;
}
@Override
public TimeSpan getRequestTimeout() {
return requestTimeout;
}
@Override
public boolean isClientCookies() {
return clientCookies;
}
@Override
public boolean isDevelopMode() {
return developMode;
}
@Override
public boolean isClientManagement() {
return clientManagement;
}
@Override
public boolean isDomainCookies() {
return domainCookies;
}
@Override
public boolean isSessionManagement() {
return sessionManagement;
}
@Override
public boolean isMailSpoolEnable() {
return spoolEnable;
}
// FUTURE add to interface
@Override
public boolean isMailSendPartial() {
return sendPartial;
}
// FUTURE add to interface and impl
@Override
public boolean isUserset() {
return userSet;
}
@Override
public Server[] getMailServers() {
if (mailServers == null) mailServers = new Server[0];
return mailServers;
}
@Override
public int getMailTimeout() {
return mailTimeout;
}
@Override
public boolean getPSQL() {
return psq;
}
protected void setQueryVarUsage(int varUsage) {
this.varUsage = varUsage;
}
@Override
public int getQueryVarUsage() {
return varUsage;
}
@Override
public ClassLoader getClassLoader() {
ResourceClassLoader rcl = getResourceClassLoader(null);
if (rcl != null) return rcl;
return new lucee.commons.lang.ClassLoaderHelper().getClass().getClassLoader();
}
// do not remove, ised in Hibernate extension
@Override
public ClassLoader getClassLoaderEnv() {
if (envClassLoader == null) envClassLoader = new EnvClassLoader(this);
return envClassLoader;
}
@Override
public ClassLoader getClassLoaderCore() {
return new lucee.commons.lang.ClassLoaderHelper().getClass().getClassLoader();
}
/*
* public ClassLoader getClassLoaderLoader() { return new TP().getClass().getClassLoader(); }
*/
@Override
public ResourceClassLoader getResourceClassLoader() {
if (resourceCL == null) throw new RuntimeException("no RCL defined yet!");
return resourceCL;
}
@Override
public ResourceClassLoader getResourceClassLoader(ResourceClassLoader defaultValue) {
if (resourceCL == null) return defaultValue;
return resourceCL;
}
protected void setResourceClassLoader(ResourceClassLoader resourceCL) {
this.resourceCL = resourceCL;
}
@Override
public Locale getLocale() {
return locale;
}
@Override
public boolean debug() {
if (!(_debug == CLIENT_BOOLEAN_TRUE || _debug == SERVER_BOOLEAN_TRUE)) return false;
return true;
}
@Override
public boolean debugLogOutput() {
return debug() && debugLogOutput == CLIENT_BOOLEAN_TRUE || debugLogOutput == SERVER_BOOLEAN_TRUE;
}
@Override
public Resource getTempDirectory() {
if (tempDirectory == null) {
Resource tmp = SystemUtil.getTempDirectory();
if (!tmp.exists()) tmp.mkdirs();
return tmp;
}
if (!tempDirectory.exists()) tempDirectory.mkdirs();
return tempDirectory;
}
@Override
public int getMailSpoolInterval() {
return spoolInterval;
}
@Override
public TimeZone getTimeZone() {
return timeZone;
}
@Override
public long getTimeServerOffset() {
return timeOffset;
}
/**
* @return return the Scheduler
*/
@Override
public Scheduler getScheduler() {
return scheduler;
}
/**
* @return gets the password as hash
*/
protected Password getPassword() {
return password;
}
@Override
public Password isPasswordEqual(String password) {
if (this.password == null) return null;
return ((PasswordImpl) this.password).isEqual(this, password);
}
@Override
public boolean hasPassword() {
return password != null;
}
@Override
public boolean passwordEqual(Password password) {
if (this.password == null) return false;
return this.password.equals(password);
}
@Override
public Mapping[] getMappings() {
return mappings;
}
@Override
public lucee.runtime.rest.Mapping[] getRestMappings() {
if (restMappings == null) restMappings = new lucee.runtime.rest.Mapping[0];
return restMappings;
}
protected void setRestMappings(lucee.runtime.rest.Mapping[] restMappings) {
// make sure only one is default
boolean hasDefault = false;
lucee.runtime.rest.Mapping m;
for (int i = 0; i < restMappings.length; i++) {
m = restMappings[i];
if (m.isDefault()) {
if (hasDefault) m.setDefault(false);
hasDefault = true;
}
}
this.restMappings = restMappings;
}
@Override
public PageSource getPageSource(Mapping[] mappings, String realPath, boolean onlyTopLevel) {
throw new PageRuntimeException(new DeprecatedException("method not supported"));
}
@Override
public PageSource getPageSourceExisting(PageContext pc, Mapping[] mappings, String realPath, boolean onlyTopLevel, boolean useSpecialMappings, boolean useDefaultMapping,
boolean onlyPhysicalExisting) {
return ConfigWebUtil.getPageSourceExisting(pc, this, mappings, realPath, onlyTopLevel, useSpecialMappings, useDefaultMapping, onlyPhysicalExisting);
}
@Override
public PageSource[] getPageSources(PageContext pc, Mapping[] mappings, String realPath, boolean onlyTopLevel, boolean useSpecialMappings, boolean useDefaultMapping) {
return getPageSources(pc, mappings, realPath, onlyTopLevel, useSpecialMappings, useDefaultMapping, false, onlyFirstMatch);
}
@Override
public PageSource[] getPageSources(PageContext pc, Mapping[] mappings, String realPath, boolean onlyTopLevel, boolean useSpecialMappings, boolean useDefaultMapping,
boolean useComponentMappings) {
return getPageSources(pc, mappings, realPath, onlyTopLevel, useSpecialMappings, useDefaultMapping, useComponentMappings, onlyFirstMatch);
}
public PageSource[] getPageSources(PageContext pc, Mapping[] appMappings, String realPath, boolean onlyTopLevel, boolean useSpecialMappings, boolean useDefaultMapping,
boolean useComponentMappings, boolean onlyFirstMatch) {
return ConfigWebUtil.getPageSources(pc, this, appMappings, realPath, onlyTopLevel, useSpecialMappings, useDefaultMapping, useComponentMappings, onlyFirstMatch);
}
/**
* @param mappings
* @param realPath
* @param alsoDefaultMapping ignore default mapping (/) or not
* @return physical path from mapping
*/
@Override
public Resource getPhysical(Mapping[] mappings, String realPath, boolean alsoDefaultMapping) {
throw new PageRuntimeException(new DeprecatedException("method not supported"));
}
@Override
public Resource[] getPhysicalResources(PageContext pc, Mapping[] mappings, String realPath, boolean onlyTopLevel, boolean useSpecialMappings, boolean useDefaultMapping) {
// now that archives can be used the same way as physical resources, there is no need anymore to
// limit to that FUTURE remove
throw new PageRuntimeException(new DeprecatedException("method not supported"));
}
@Override
public Resource getPhysicalResourceExisting(PageContext pc, Mapping[] mappings, String realPath, boolean onlyTopLevel, boolean useSpecialMappings, boolean useDefaultMapping) {
// now that archives can be used the same way as physical resources, there is no need anymore to
// limit to that FUTURE remove
throw new PageRuntimeException(new DeprecatedException("method not supported"));
}
@Override
public PageSource toPageSource(Mapping[] mappings, Resource res, PageSource defaultValue) {
return ConfigWebUtil.toPageSource(this, mappings, res, defaultValue);
}
@Override
public Resource getConfigDir() {
return configDir;
}
@Override
public Resource getConfigFile() {
return configFile;
}
/**
* sets the password
*
* @param password
*/
@Override
public void setPassword(Password password) {
this.password = password;
}
/**
* set how lucee cascade scopes
*
* @param type cascading type
*/
protected void setScopeCascadingType(short type) {
this.type = type;
}
protected void addTag(String nameSpace, String nameSpaceSeperator, String name, int dialect, ClassDefinition cd) {
if (dialect == CFMLEngine.DIALECT_BOTH) {
addTag(nameSpace, nameSpaceSeperator, name, CFMLEngine.DIALECT_CFML, cd);
addTag(nameSpace, nameSpaceSeperator, name, CFMLEngine.DIALECT_LUCEE, cd);
return;
}
TagLib[] tlds = dialect == CFMLEngine.DIALECT_CFML ? cfmlTlds : luceeTlds;
for (int i = 0; i < tlds.length; i++) {
if (tlds[i].getNameSpaceAndSeparator().equalsIgnoreCase(nameSpace + nameSpaceSeperator)) {
TagLibTag tlt = new TagLibTag(tlds[i]);
tlt.setAttributeType(TagLibTag.ATTRIBUTE_TYPE_DYNAMIC);
tlt.setBodyContent("free");
tlt.setTagClassDefinition(cd);
tlt.setName(name);
tlds[i].setTag(tlt);
}
}
}
/**
* set the optional directory of the tag library deskriptors
*
* @param fileTld directory of the tag libray deskriptors
* @throws TagLibException
*/
protected void setTldFile(Resource fileTld, int dialect) throws TagLibException {
if (dialect == CFMLEngine.DIALECT_BOTH) {
setTldFile(fileTld, CFMLEngine.DIALECT_CFML);
setTldFile(fileTld, CFMLEngine.DIALECT_LUCEE);
return;
}
TagLib[] tlds = dialect == CFMLEngine.DIALECT_CFML ? cfmlTlds : luceeTlds;
if (fileTld == null) return;
this.tldFile = fileTld;
String key;
Map<String, TagLib> map = new HashMap<String, TagLib>();
// First fill existing to set
for (int i = 0; i < tlds.length; i++) {
key = getKey(tlds[i]);
map.put(key, tlds[i]);
}
TagLib tl;
// now overwrite with new data
if (fileTld.isDirectory()) {
Resource[] files = fileTld.listResources(new ExtensionResourceFilter(new String[] { "tld", "tldx" }));
for (int i = 0; i < files.length; i++) {
try {
tl = TagLibFactory.loadFromFile(files[i], getIdentification());
key = getKey(tl);
if (!map.containsKey(key)) map.put(key, tl);
else overwrite(map.get(key), tl);
}
catch (TagLibException tle) {
LogUtil.log(this, Log.LEVEL_ERROR, "loading", "can't load tld " + files[i]);
tle.printStackTrace(getErrWriter());
}
}
}
else if (fileTld.isFile()) {
tl = TagLibFactory.loadFromFile(fileTld, getIdentification());
key = getKey(tl);
if (!map.containsKey(key)) map.put(key, tl);
else overwrite(map.get(key), tl);
}
// now fill back to array
tlds = new TagLib[map.size()];
if (dialect == CFMLEngine.DIALECT_CFML) cfmlTlds = tlds;
else luceeTlds = tlds;
int index = 0;
Iterator<TagLib> it = map.values().iterator();
while (it.hasNext()) {
tlds[index++] = it.next();
}
}
@Override
public TagLib getCoreTagLib(int dialect) {
TagLib[] tlds = dialect == CFMLEngine.DIALECT_CFML ? cfmlTlds : luceeTlds;
for (int i = 0; i < tlds.length; i++) {
if (tlds[i].isCore()) return tlds[i];
}
throw new RuntimeException("no core taglib found"); // this should never happen
}
protected void setTagDirectory(List<Resource> listTagDirectory) {
Iterator<Resource> it = listTagDirectory.iterator();
int index = -1;
String mappingName;
Resource tagDirectory;
Mapping m;
boolean isDefault;
while (it.hasNext()) {
tagDirectory = it.next();
index++;
isDefault = index == 0;
mappingName = "/mapping-tag" + (isDefault ? "" : index) + "";
m = new MappingImpl(this, mappingName, tagDirectory.getAbsolutePath(), null, ConfigPro.INSPECT_NEVER, true, true, true, true, false, true, null, -1, -1);
if (isDefault) defaultTagMapping = m;
tagMappings.put(mappingName, m);
TagLib tlc = getCoreTagLib(CFMLEngine.DIALECT_CFML);
TagLib tll = getCoreTagLib(CFMLEngine.DIALECT_LUCEE);
// now overwrite with new data
if (tagDirectory.isDirectory()) {
String[] files = tagDirectory
.list(new ExtensionResourceFilter(getMode() == ConfigPro.MODE_STRICT ? Constants.getComponentExtensions() : Constants.getExtensions()));
for (int i = 0; i < files.length; i++) {
if (tlc != null) createTag(tlc, files[i], mappingName);
if (tll != null) createTag(tll, files[i], mappingName);
}
}
}
}
public void createTag(TagLib tl, String filename, String mappingName) {// Jira 1298
String name = toName(filename);// filename.substring(0,filename.length()-(getCFCExtension().length()+1));
TagLibTag tlt = new TagLibTag(tl);
tlt.setName(name);
tlt.setTagClassDefinition("lucee.runtime.tag.CFTagCore", getIdentification(), null);
tlt.setHandleExceptions(true);
tlt.setBodyContent("free");
tlt.setParseBody(false);
tlt.setDescription("");
tlt.setAttributeType(TagLibTag.ATTRIBUTE_TYPE_MIXED);
// read component and read setting from that component
TagLibTagScript tlts = new TagLibTagScript(tlt);
tlts.setType(TagLibTagScript.TYPE_MULTIPLE);
tlt.setScript(tlts);
TagLibTagAttr tlta = new TagLibTagAttr(tlt);
tlta.setName("__filename");
tlta.setRequired(true);
tlta.setRtexpr(true);
tlta.setType("string");
tlta.setHidden(true);
tlta.setDefaultValue(filename);
tlt.setAttribute(tlta);
tlta = new TagLibTagAttr(tlt);
tlta.setName("__name");
tlta.setRequired(true);
tlta.setRtexpr(true);
tlta.setHidden(true);
tlta.setType("string");
tlta.setDefaultValue(name);
tlt.setAttribute(tlta);
tlta = new TagLibTagAttr(tlt);
tlta.setName("__isweb");
tlta.setRequired(true);
tlta.setRtexpr(true);
tlta.setHidden(true);
tlta.setType("boolean");
tlta.setDefaultValue(this instanceof ConfigWeb ? "true" : "false");
tlt.setAttribute(tlta);
tlta = new TagLibTagAttr(tlt);
tlta.setName("__mapping");
tlta.setRequired(true);
tlta.setRtexpr(true);
tlta.setHidden(true);
tlta.setType("string");
tlta.setDefaultValue(mappingName);
tlt.setAttribute(tlta);
tl.setTag(tlt);
}
protected void setFunctionDirectory(List<Resource> listFunctionDirectory) {
Iterator<Resource> it = listFunctionDirectory.iterator();
int index = -1;
String mappingName;
Resource functionDirectory;
boolean isDefault;
while (it.hasNext()) {
functionDirectory = it.next();
index++;
isDefault = index == 0;
mappingName = "/mapping-function" + (isDefault ? "" : index) + "";
MappingImpl mapping = new MappingImpl(this, mappingName, functionDirectory.getAbsolutePath(), null, ConfigPro.INSPECT_NEVER, true, true, true, true, false, true, null,
-1, -1);
if (isDefault) defaultFunctionMapping = mapping;
this.functionMappings.put(mappingName, mapping);
FunctionLib flc = cfmlFlds[cfmlFlds.length - 1];
FunctionLib fll = luceeFlds[luceeFlds.length - 1];
// now overwrite with new data
if (functionDirectory.isDirectory()) {
String[] files = functionDirectory.list(new ExtensionResourceFilter(Constants.getTemplateExtensions()));
for (String file: files) {
if (flc != null) createFunction(flc, file, mappingName);
if (fll != null) createFunction(fll, file, mappingName);
}
combinedCFMLFLDs = null;
combinedLuceeFLDs = null;
}
}
}
public void createFunction(FunctionLib fl, String filename, String mapping) {
String name = toName(filename);// filename.substring(0,filename.length()-(getCFMLExtensions().length()+1));
FunctionLibFunction flf = new FunctionLibFunction(fl, true);
flf.setArgType(FunctionLibFunction.ARG_DYNAMIC);
flf.setFunctionClass("lucee.runtime.functions.system.CFFunction", null, null);
flf.setName(name);
flf.setReturn("object");
FunctionLibFunctionArg arg = new FunctionLibFunctionArg(flf);
arg.setName("__filename");
arg.setRequired(true);
arg.setType("string");
arg.setHidden(true);
arg.setDefaultValue(filename);
flf.setArg(arg);
arg = new FunctionLibFunctionArg(flf);
arg.setName("__name");
arg.setRequired(true);
arg.setHidden(true);
arg.setType("string");
arg.setDefaultValue(name);
flf.setArg(arg);
arg = new FunctionLibFunctionArg(flf);
arg.setName("__isweb");
arg.setRequired(true);
arg.setHidden(true);
arg.setType("boolean");
arg.setDefaultValue(this instanceof ConfigWeb ? "true" : "false");
flf.setArg(arg);
arg = new FunctionLibFunctionArg(flf);
arg.setName("__mapping");
arg.setRequired(true);
arg.setHidden(true);
arg.setType("string");
arg.setDefaultValue(mapping);
flf.setArg(arg);
fl.setFunction(flf);
}
private static String toName(String filename) {
int pos = filename.lastIndexOf('.');
if (pos == -1) return filename;
return filename.substring(0, pos);
}
private void overwrite(TagLib existingTL, TagLib newTL) {
Iterator<TagLibTag> it = newTL.getTags().values().iterator();
while (it.hasNext()) {
existingTL.setTag(it.next());
}
}
private String getKey(TagLib tl) {
return tl.getNameSpaceAndSeparator().toLowerCase();
}
protected void setFldFile(Resource fileFld, int dialect) throws FunctionLibException {
if (dialect == CFMLEngine.DIALECT_BOTH) {
setFldFile(fileFld, CFMLEngine.DIALECT_CFML);
setFldFile(fileFld, CFMLEngine.DIALECT_LUCEE);
return;
}
FunctionLib[] flds = dialect == CFMLEngine.DIALECT_CFML ? cfmlFlds : luceeFlds;
// merge all together (backward compatibility)
if (flds.length > 1) for (int i = 1; i < flds.length; i++) {
overwrite(flds[0], flds[i]);
}
flds = new FunctionLib[] { flds[0] };
if (dialect == CFMLEngine.DIALECT_CFML) {
cfmlFlds = flds;
if (cfmlFlds != flds) combinedCFMLFLDs = null;// TODO improve check
}
else {
luceeFlds = flds;
if (luceeFlds != flds) combinedLuceeFLDs = null;// TODO improve check
}
if (fileFld == null) return;
this.fldFile = fileFld;
// overwrite with additional functions
FunctionLib fl;
if (fileFld.isDirectory()) {
Resource[] files = fileFld.listResources(new ExtensionResourceFilter(new String[] { "fld", "fldx" }));
for (int i = 0; i < files.length; i++) {
try {
fl = FunctionLibFactory.loadFromFile(files[i], getIdentification());
overwrite(flds[0], fl);
}
catch (FunctionLibException fle) {
LogUtil.log(this, Log.LEVEL_ERROR, "loading", "can't load fld " + files[i]);
fle.printStackTrace(getErrWriter());
}
}
}
else {
fl = FunctionLibFactory.loadFromFile(fileFld, getIdentification());
overwrite(flds[0], fl);
}
}
private void overwrite(FunctionLib existingFL, FunctionLib newFL) {
Iterator<FunctionLibFunction> it = newFL.getFunctions().values().iterator();
while (it.hasNext()) {
existingFL.setFunction(it.next());
}
}
private String getKey(FunctionLib functionLib) {
return functionLib.getDisplayName().toLowerCase();
}
/**
* sets if it is allowed to implict query call, call a query member without define name of the
* query.
*
* @param _allowImplicidQueryCall is allowed
*/
protected void setAllowImplicidQueryCall(boolean _allowImplicidQueryCall) {
this._allowImplicidQueryCall = _allowImplicidQueryCall;
}
/**
* sets if url and form scope will be merged
*
* @param _mergeFormAndURL merge yes or no
*/
protected void setMergeFormAndURL(boolean _mergeFormAndURL) {
this._mergeFormAndURL = _mergeFormAndURL;
}
/**
* @param strApplicationTimeout The applicationTimeout to set.
* @throws PageException
*/
void setApplicationTimeout(String strApplicationTimeout) throws PageException {
setApplicationTimeout(Caster.toTimespan(strApplicationTimeout));
}
/**
* @param applicationTimeout The applicationTimeout to set.
*/
protected void setApplicationTimeout(TimeSpan applicationTimeout) {
this.applicationTimeout = applicationTimeout;
}
/**
* @param strSessionTimeout The sessionTimeout to set.
* @throws PageException
*/
protected void setSessionTimeout(String strSessionTimeout) throws PageException {
setSessionTimeout(Caster.toTimespan(strSessionTimeout));
}
/**
* @param sessionTimeout The sessionTimeout to set.
*/
protected void setSessionTimeout(TimeSpan sessionTimeout) {
this.sessionTimeout = sessionTimeout;
}
protected void setClientTimeout(String strClientTimeout) throws PageException {
setClientTimeout(Caster.toTimespan(strClientTimeout));
}
/**
* @param clientTimeout The sessionTimeout to set.
*/
protected void setClientTimeout(TimeSpan clientTimeout) {
this.clientTimeout = clientTimeout;
}
/**
* @param strRequestTimeout The requestTimeout to set.
* @throws PageException
*/
protected void setRequestTimeout(String strRequestTimeout) throws PageException {
setRequestTimeout(Caster.toTimespan(strRequestTimeout));
}
/**
* @param requestTimeout The requestTimeout to set.
*/
protected void setRequestTimeout(TimeSpan requestTimeout) {
this.requestTimeout = requestTimeout;
}
/**
* @param clientCookies The clientCookies to set.
*/
protected void setClientCookies(boolean clientCookies) {
this.clientCookies = clientCookies;
}
/**
* @param developMode
*/
protected void setDevelopMode(boolean developMode) {
this.developMode = developMode;
}
/**
* @param clientManagement The clientManagement to set.
*/
protected void setClientManagement(boolean clientManagement) {
this.clientManagement = clientManagement;
}
/**
* @param domainCookies The domainCookies to set.
*/
protected void setDomainCookies(boolean domainCookies) {
this.domainCookies = domainCookies;
}
/**
* @param sessionManagement The sessionManagement to set.
*/
protected void setSessionManagement(boolean sessionManagement) {
this.sessionManagement = sessionManagement;
}
/**
* @param spoolEnable The spoolEnable to set.
*/
protected void setMailSpoolEnable(boolean spoolEnable) {
this.spoolEnable = spoolEnable;
}
protected void setMailSendPartial(boolean sendPartial) {
this.sendPartial = sendPartial;
}
protected void setUserSet(boolean userSet) {
this.userSet = userSet;
}
/**
* @param mailTimeout The mailTimeout to set.
*/
protected void setMailTimeout(int mailTimeout) {
this.mailTimeout = mailTimeout;
}
/**
* @param psq (preserve single quote) sets if sql string inside a cfquery will be preserved for
* Single Quotes
*/
protected void setPSQL(boolean psq) {
this.psq = psq;
}
/**
* set if lucee make debug output or not
*
* @param _debug debug or not
*/
protected void setDebug(int _debug) {
this._debug = _debug;
}
protected void setDebugLogOutput(int debugLogOutput) {
this.debugLogOutput = debugLogOutput;
}
/**
* sets the temp directory
*
* @param strTempDirectory temp directory
* @throws ExpressionException
*/
protected void setTempDirectory(String strTempDirectory, boolean flush) throws ExpressionException {
setTempDirectory(resources.getResource(strTempDirectory), flush);
}
/**
* sets the temp directory
*
* @param tempDirectory temp directory
* @throws ExpressionException
*/
protected void setTempDirectory(Resource tempDirectory, boolean flush) throws ExpressionException {
if (!isDirectory(tempDirectory) || !tempDirectory.isWriteable()) {
LogUtil.log(this, Log.LEVEL_ERROR, "loading",
"temp directory [" + tempDirectory + "] is not writable or can not be created, using directory [" + SystemUtil.getTempDirectory() + "] instead");
tempDirectory = SystemUtil.getTempDirectory();
if (!tempDirectory.isWriteable()) {
LogUtil.log(this, Log.LEVEL_ERROR, "loading", "temp directory [" + tempDirectory + "] is not writable");
}
}
if (flush) ResourceUtil.removeChildrenEL(tempDirectory);// start with an empty temp directory
this.tempDirectory = tempDirectory;
}
/**
* sets the Schedule Directory
*
* @param scheduleDirectory sets the schedule Directory
* @param logger
* @throws PageException
*/
protected void setScheduler(CFMLEngine engine, Array scheduledTasks) throws PageException {
if (scheduledTasks == null) {
if (this.scheduler == null) this.scheduler = new SchedulerImpl(engine, this, new ArrayImpl());
return;
}
try {
if (this.scheduler == null) this.scheduler = new SchedulerImpl(engine, this, scheduledTasks);
}
catch (Exception e) {
throw Caster.toPageException(e);
}
}
/**
* @param spoolInterval The spoolInterval to set.
*/
protected void setMailSpoolInterval(int spoolInterval) {
this.spoolInterval = spoolInterval;
}
/**
* sets the timezone
*
* @param timeZone
*/
protected void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
/**
* sets the time server
*
* @param timeServer
*/
protected void setTimeServer(String timeServer) {
this.timeServer = timeServer;
}
/**
* sets the locale
*
* @param strLocale
*/
protected void setLocale(String strLocale) {
if (strLocale == null) {
this.locale = Locale.US;
}
else {
try {
this.locale = Caster.toLocale(strLocale);
if (this.locale == null) this.locale = Locale.US;
}
catch (ExpressionException e) {
this.locale = Locale.US;
}
}
}
/**
* sets the locale
*
* @param locale
*/
protected void setLocale(Locale locale) {
this.locale = locale;
}
/**
* @param mappings The mappings to set.
*/
protected void setMappings(Mapping[] mappings) {
this.mappings = ConfigWebUtil.sort(mappings);
}
/**
* @param datasources The datasources to set
*/
protected void setDataSources(Map<String, DataSource> datasources) {
this.datasources = datasources;
}
/**
* @param customTagMappings The customTagMapping to set.
*/
protected void setCustomTagMappings(Mapping[] customTagMappings) {
this.customTagMappings = customTagMappings;
}
@Override
public Mapping[] getCustomTagMappings() {
return customTagMappings;
}
/**
* @param mailServers The mailsServers to set.
*/
protected void setMailServers(Server[] mailServers) {
this.mailServers = mailServers;
}
/**
* is file a directory or not, touch if not exist
*
* @param directory
* @return true if existing directory or has created new one
*/
protected boolean isDirectory(Resource directory) {
if (directory.exists()) return directory.isDirectory();
try {
directory.createDirectory(true);
return true;
}
catch (IOException e) {
e.printStackTrace(getErrWriter());
}
return false;
}
@Override
public long getLoadTime() {
return loadTime;
}
/**
* @param loadTime The loadTime to set.
*/
protected void setLoadTime(long loadTime) {
this.loadTime = loadTime;
}
/**
* @return Returns the configLogger. / public Log getConfigLogger() { return configLogger; }
*/
@Override
public CFXTagPool getCFXTagPool() throws SecurityException {
return cfxTagPool;
}
/**
* @param cfxTagPool The customTagPool to set.
*/
protected void setCFXTagPool(CFXTagPool cfxTagPool) {
this.cfxTagPool = cfxTagPool;
}
/**
* @param cfxTagPool The customTagPool to set.
*/
protected void setCFXTagPool(Map cfxTagPool) {
this.cfxTagPool = new CFXTagPoolImpl(cfxTagPool);
}
@Override
public String getBaseComponentTemplate(int dialect) {
if (dialect == CFMLEngine.DIALECT_CFML) return baseComponentTemplateCFML;
return baseComponentTemplateLucee;
}
/**
* @return pagesource of the base component
*/
@Override
public PageSource getBaseComponentPageSource(int dialect) {
return getBaseComponentPageSource(dialect, ThreadLocalPageContext.get());
}
@Override
public PageSource getBaseComponentPageSource(int dialect, PageContext pc) {
PageSource base = dialect == CFMLEngine.DIALECT_CFML ? baseComponentPageSourceCFML : baseComponentPageSourceLucee;
if (base == null) {
base = PageSourceImpl.best(getPageSources(pc, null, getBaseComponentTemplate(dialect), false, false, true));
if (!base.exists()) {
String baseTemplate = getBaseComponentTemplate(dialect);
String mod = ContractPath.call(pc, baseTemplate, false);
if (!mod.equals(baseTemplate)) {
base = PageSourceImpl.best(getPageSources(pc, null, mod, false, false, true));
}
}
if (dialect == CFMLEngine.DIALECT_CFML) this.baseComponentPageSourceCFML = base;
else this.baseComponentPageSourceLucee = base;
}
return base;
}
/**
* @param template The baseComponent template to set.
*/
protected void setBaseComponentTemplate(int dialect, String template) {
if (dialect == CFMLEngine.DIALECT_CFML) {
this.baseComponentPageSourceCFML = null;
this.baseComponentTemplateCFML = template;
}
else {
this.baseComponentPageSourceLucee = null;
this.baseComponentTemplateLucee = template;
}
}
protected void setRestList(boolean restList) {
this.restList = restList;
}
@Override
public boolean getRestList() {
return restList;
}
/**
* @param clientType
*/
protected void setClientType(short clientType) {
this.clientType = clientType;
}
/**
* @param strClientType
*/
protected void setClientType(String strClientType) {
strClientType = strClientType.trim().toLowerCase();
if (strClientType.equals("file")) clientType = Config.CLIENT_SCOPE_TYPE_FILE;
else if (strClientType.equals("db")) clientType = Config.CLIENT_SCOPE_TYPE_DB;
else if (strClientType.equals("database")) clientType = Config.CLIENT_SCOPE_TYPE_DB;
else clientType = Config.CLIENT_SCOPE_TYPE_COOKIE;
}
@Override
public short getClientType() {
return this.clientType;
}
/**
* @param searchEngine The searchEngine to set.
*/
protected void setSearchEngine(ClassDefinition cd, String directory) {
this.searchEngineClassDef = cd;
this.searchEngineDirectory = directory;
}
@Override
public ClassDefinition<SearchEngine> getSearchEngineClassDefinition() {
return this.searchEngineClassDef;
}
@Override
public String getSearchEngineDirectory() {
return this.searchEngineDirectory;
}
@Override
public int getComponentDataMemberDefaultAccess() {
return componentDataMemberDefaultAccess;
}
/**
* @param componentDataMemberDefaultAccess The componentDataMemberDefaultAccess to set.
*/
protected void setComponentDataMemberDefaultAccess(int componentDataMemberDefaultAccess) {
this.componentDataMemberDefaultAccess = componentDataMemberDefaultAccess;
}
@Override
public String getTimeServer() {
return timeServer;
}
@Override
public String getComponentDumpTemplate() {
return componentDumpTemplate;
}
/**
* @param template The componentDump template to set.
*/
protected void setComponentDumpTemplate(String template) {
this.componentDumpTemplate = template;
}
public String createSecurityToken() {
try {
return Md5.getDigestAsString(getConfigDir().getAbsolutePath());
}
catch (IOException e) {
return null;
}
}
@Override
public String getDebugTemplate() {
throw new PageRuntimeException(new DeprecatedException("no longer supported, use instead getDebugEntry(ip, defaultValue)"));
}
@Override
public String getErrorTemplate(int statusCode) {
return errorTemplates.get(Caster.toString(statusCode));
}
/**
* @param errorTemplate the errorTemplate to set
*/
protected void setErrorTemplate(int statusCode, String errorTemplate) {
this.errorTemplates.put(Caster.toString(statusCode), errorTemplate);
}
@Override
public short getSessionType() {
return sessionType;
}
/**
* @param sessionType The sessionType to set.
*/
protected void setSessionType(short sessionType) {
this.sessionType = sessionType;
}
@Override
public abstract String getUpdateType();
@Override
public abstract URL getUpdateLocation();
@Override
public Resource getClassDirectory() {
return deployDirectory;
}
@Override
public Resource getLibraryDirectory() {
Resource dir = getConfigDir().getRealResource("lib");
if (!dir.exists()) dir.mkdir();
return dir;
}
@Override
public Resource getEventGatewayDirectory() {
Resource dir = getConfigDir().getRealResource("context/admin/gdriver");
if (!dir.exists()) dir.mkdir();
return dir;
}
@Override
public Resource getClassesDirectory() {
Resource dir = getConfigDir().getRealResource("classes");
if (!dir.exists()) dir.mkdir();
return dir;
}
/**
* set the deploy directory, directory where lucee deploy transalted cfml classes (java and class
* files)
*
* @param strDeployDirectory deploy directory
* @throws ExpressionException
*/
protected void setDeployDirectory(String strDeployDirectory) throws ExpressionException {
setDeployDirectory(resources.getResource(strDeployDirectory));
}
/**
* set the deploy directory, directory where lucee deploy transalted cfml classes (java and class
* files)
*
* @param deployDirectory deploy directory
* @throws ExpressionException
* @throws ExpressionException
*/
protected void setDeployDirectory(Resource deployDirectory) throws ExpressionException {
if (!isDirectory(deployDirectory)) {
throw new ExpressionException("deploy directory " + deployDirectory + " doesn't exist or is not a directory");
}
this.deployDirectory = deployDirectory;
}
@Override
public abstract Resource getRootDirectory();
/**
* sets the compileType value.
*
* @param compileType The compileType to set.
*/
protected void setCompileType(short compileType) {
this.compileType = compileType;
}
/**
* FUTHER Returns the value of suppresswhitespace.
*
* @return value suppresswhitespace
*/
@Override
public boolean isSuppressWhitespace() {
return suppresswhitespace;
}
/**
* FUTHER sets the suppresswhitespace value.
*
* @param suppresswhitespace The suppresswhitespace to set.
*/
protected void setSuppressWhitespace(boolean suppresswhitespace) {
this.suppresswhitespace = suppresswhitespace;
}
@Override
public boolean isSuppressContent() {
return suppressContent;
}
protected void setSuppressContent(boolean suppressContent) {
this.suppressContent = suppressContent;
}
@Override
public String getDefaultEncoding() {
return webCharset.name();
}
@Override
public Charset getTemplateCharset() {
return CharsetUtil.toCharset(templateCharset);
}
public CharSet getTemplateCharSet() {
return templateCharset;
}
/**
* sets the charset to read the files
*
* @param templateCharset
*/
protected void setTemplateCharset(String templateCharset) {
this.templateCharset = CharsetUtil.toCharSet(templateCharset, this.templateCharset);
}
protected void setTemplateCharset(Charset templateCharset) {
this.templateCharset = CharsetUtil.toCharSet(templateCharset);
}
@Override
public Charset getWebCharset() {
return CharsetUtil.toCharset(webCharset);
}
@Override
public CharSet getWebCharSet() {
return webCharset;
}
/**
* sets the charset to read and write resources
*
* @param resourceCharset
*/
protected void setResourceCharset(String resourceCharset) {
this.resourceCharset = CharsetUtil.toCharSet(resourceCharset, this.resourceCharset);
}
protected void setResourceCharset(Charset resourceCharset) {
this.resourceCharset = CharsetUtil.toCharSet(resourceCharset);
}
@Override
public Charset getResourceCharset() {
return CharsetUtil.toCharset(resourceCharset);
}
@Override
public CharSet getResourceCharSet() {
return resourceCharset;
}
/**
* sets the charset for the response stream
*
* @param webCharset
*/
protected void setWebCharset(String webCharset) {
this.webCharset = CharsetUtil.toCharSet(webCharset, this.webCharset);
}
protected void setWebCharset(Charset webCharset) {
this.webCharset = CharsetUtil.toCharSet(webCharset);
}
@Override
public SecurityManager getSecurityManager() {
return null;
}
@Override
public Resource getFldFile() {
return fldFile;
}
@Override
public Resource getTldFile() {
return tldFile;
}
@Override
public DataSource[] getDataSources() {
Map<String, DataSource> map = getDataSourcesAsMap();
Iterator<DataSource> it = map.values().iterator();
DataSource[] ds = new DataSource[map.size()];
int count = 0;
while (it.hasNext()) {
ds[count++] = it.next();
}
return ds;
}
@Override
public Map<String, DataSource> getDataSourcesAsMap() {
Map<String, DataSource> map = new HashMap<String, DataSource>();
Iterator<Entry<String, DataSource>> it = datasources.entrySet().iterator();
Entry<String, DataSource> entry;
while (it.hasNext()) {
entry = it.next();
if (!entry.getKey().equals(QOQ_DATASOURCE_NAME)) map.put(entry.getKey(), entry.getValue());
}
return map;
}
/**
* @return the mailDefaultCharset
*/
@Override
public Charset getMailDefaultCharset() {
return mailDefaultCharset.toCharset();
}
public CharSet getMailDefaultCharSet() {
return mailDefaultCharset;
}
/**
* @param mailDefaultEncoding the mailDefaultCharset to set
*/
protected void setMailDefaultEncoding(String mailDefaultCharset) {
this.mailDefaultCharset = CharsetUtil.toCharSet(mailDefaultCharset, this.mailDefaultCharset);
}
protected void setMailDefaultEncoding(Charset mailDefaultCharset) {
this.mailDefaultCharset = CharsetUtil.toCharSet(mailDefaultCharset);
}
protected void setDefaultResourceProvider(Class defaultProviderClass, Map arguments) throws ClassException {
Object o = ClassUtil.loadInstance(defaultProviderClass);
if (o instanceof ResourceProvider) {
ResourceProvider rp = (ResourceProvider) o;
rp.init(null, arguments);
setDefaultResourceProvider(rp);
}
else throw new ClassException("object [" + Caster.toClassName(o) + "] must implement the interface " + ResourceProvider.class.getName());
}
/**
* @param defaultResourceProvider the defaultResourceProvider to set
*/
protected void setDefaultResourceProvider(ResourceProvider defaultResourceProvider) {
resources.registerDefaultResourceProvider(defaultResourceProvider);
}
/**
* @return the defaultResourceProvider
*/
@Override
public ResourceProvider getDefaultResourceProvider() {
return resources.getDefaultResourceProvider();
}
protected void addCacheHandler(String id, ClassDefinition<CacheHandler> cd) throws ClassException, BundleException {
Class<CacheHandler> clazz = cd.getClazz();
Object o = ClassUtil.loadInstance(clazz); // just try to load and forget afterwards
if (o instanceof CacheHandler) {
addCacheHandler(id, clazz);
}
else throw new ClassException("object [" + Caster.toClassName(o) + "] must implement the interface " + CacheHandler.class.getName());
}
protected void addCacheHandler(String id, Class<CacheHandler> chc) {
cacheHandlerClasses.put(id, chc);
}
@Override
public Iterator<Entry<String, Class<CacheHandler>>> getCacheHandlers() {
return cacheHandlerClasses.entrySet().iterator();
}
protected void addResourceProvider(String strProviderScheme, ClassDefinition cd, Map arguments) throws ClassException, BundleException {
((ResourcesImpl) resources).registerResourceProvider(strProviderScheme, cd, arguments);
}
/*
* protected void addResourceProvider(ResourceProvider provider) {
* ((ResourcesImpl)resources).registerResourceProvider(provider); }
*/
public void clearResourceProviders() {
resources.reset();
}
/**
* @return return the resource providers
*/
@Override
public ResourceProvider[] getResourceProviders() {
return resources.getResourceProviders();
}
/**
* @return return the resource providers
*/
@Override
public ResourceProviderFactory[] getResourceProviderFactories() {
return ((ResourcesImpl) resources).getResourceProviderFactories();
}
@Override
public boolean hasResourceProvider(String scheme) {
ResourceProviderFactory[] factories = ((ResourcesImpl) resources).getResourceProviderFactories();
for (int i = 0; i < factories.length; i++) {
if (factories[i].getScheme().equalsIgnoreCase(scheme)) return true;
}
return false;
}
protected void setResourceProviderFactories(ResourceProviderFactory[] resourceProviderFactories) {
for (int i = 0; i < resourceProviderFactories.length; i++) {
((ResourcesImpl) resources).registerResourceProvider(resourceProviderFactories[i]);
}
}
@Override
public Resource getResource(String path) {
return resources.getResource(path);
}
@Override
public ApplicationListener getApplicationListener() {
return applicationListener;
}
/**
* @param applicationListener the applicationListener to set
*/
protected void setApplicationListener(ApplicationListener applicationListener) {
this.applicationListener = applicationListener;
}
/**
* @return the scriptProtect
*/
@Override
public int getScriptProtect() {
return scriptProtect;
}
/**
* @param scriptProtect the scriptProtect to set
*/
protected void setScriptProtect(int scriptProtect) {
this.scriptProtect = scriptProtect;
}
/**
* @return the proxyPassword
*/
@Override
public ProxyData getProxyData() {
return proxy;
}
/**
* @param proxy the proxyPassword to set
*/
protected void setProxyData(ProxyData proxy) {
this.proxy = proxy;
}
@Override
public boolean isProxyEnableFor(String host) { // FUTURE remove
return ProxyDataImpl.isProxyEnableFor(getProxyData(), host);
}
/**
* @return the triggerComponentDataMember
*/
@Override
public boolean getTriggerComponentDataMember() {
return triggerComponentDataMember;
}
/**
* @param triggerComponentDataMember the triggerComponentDataMember to set
*/
protected void setTriggerComponentDataMember(boolean triggerComponentDataMember) {
this.triggerComponentDataMember = triggerComponentDataMember;
}
@Override
public Resource getClientScopeDir() {
if (clientScopeDir == null) clientScopeDir = getConfigDir().getRealResource("client-scope");
return clientScopeDir;
}
@Override
public Resource getSessionScopeDir() {
if (sessionScopeDir == null) sessionScopeDir = getConfigDir().getRealResource("session-scope");
return sessionScopeDir;
}
@Override
public long getClientScopeDirSize() {
return clientScopeDirSize;
}
public long getSessionScopeDirSize() {
return sessionScopeDirSize;
}
/**
* @param clientScopeDir the clientScopeDir to set
*/
protected void setClientScopeDir(Resource clientScopeDir) {
this.clientScopeDir = clientScopeDir;
}
protected void setSessionScopeDir(Resource sessionScopeDir) {
this.sessionScopeDir = sessionScopeDir;
}
/**
* @param clientScopeDirSize the clientScopeDirSize to set
*/
protected void setClientScopeDirSize(long clientScopeDirSize) {
this.clientScopeDirSize = clientScopeDirSize;
}
@Override
public ClassLoader getRPCClassLoader(boolean reload) throws IOException {
if (rpcClassLoader != null && !reload) return rpcClassLoader;
Resource dir = getClassDirectory().getRealResource("RPC");
if (!dir.exists()) dir.createDirectory(true);
rpcClassLoader = new PhysicalClassLoader(this, dir, null, false);
return rpcClassLoader;
}
@Override
public ClassLoader getRPCClassLoader(boolean reload, ClassLoader[] parents) throws IOException {
if (rpcClassLoader != null && !reload) return rpcClassLoader;
Resource dir = getClassDirectory().getRealResource("RPC");
if (!dir.exists()) dir.createDirectory(true);
rpcClassLoader = new PhysicalClassLoader(this, dir, parents, false);
return rpcClassLoader;
}
public void resetRPCClassLoader() {
rpcClassLoader = null;
}
protected void setCacheDir(Resource cacheDir) {
this.cacheDir = cacheDir;
}
@Override
public Resource getCacheDir() {
return this.cacheDir;
}
@Override
public long getCacheDirSize() {
return cacheDirSize;
}
protected void setCacheDirSize(long cacheDirSize) {
this.cacheDirSize = cacheDirSize;
}
protected void setDumpWritersEntries(DumpWriterEntry[] dmpWriterEntries) {
this.dmpWriterEntries = dmpWriterEntries;
}
public DumpWriterEntry[] getDumpWritersEntries() {
return dmpWriterEntries;
}
@Override
public DumpWriter getDefaultDumpWriter(int defaultType) {
DumpWriterEntry[] entries = getDumpWritersEntries();
if (entries != null) for (int i = 0; i < entries.length; i++) {
if (entries[i].getDefaultType() == defaultType) {
return entries[i].getWriter();
}
}
return new HTMLDumpWriter();
}
@Override
public DumpWriter getDumpWriter(String name) throws DeprecatedException {
throw new DeprecatedException("this method is no longer supported");
}
@Override
public DumpWriter getDumpWriter(String name, int defaultType) throws ExpressionException {
if (StringUtil.isEmpty(name)) return getDefaultDumpWriter(defaultType);
DumpWriterEntry[] entries = getDumpWritersEntries();
for (int i = 0; i < entries.length; i++) {
if (entries[i].getName().equals(name)) {
return entries[i].getWriter();
}
}
// error
StringBuilder sb = new StringBuilder();
for (int i = 0; i < entries.length; i++) {
if (i > 0) sb.append(", ");
sb.append(entries[i].getName());
}
throw new ExpressionException("invalid format definition [" + name + "], valid definitions are [" + sb + "]");
}
@Override
public boolean useComponentShadow() {
return useComponentShadow;
}
@Override
public boolean useComponentPathCache() {
return useComponentPathCache;
}
@Override
public boolean useCTPathCache() {
return useCTPathCache;
}
public void flushComponentPathCache() {
if (componentPathCache != null) componentPathCache.clear();
}
public void flushApplicationPathCache() {
if (applicationPathCache != null) applicationPathCache.clear();
}
public void flushCTPathCache() {
if (ctPatchCache != null) ctPatchCache.clear();
}
protected void setUseCTPathCache(boolean useCTPathCache) {
this.useCTPathCache = useCTPathCache;
}
protected void setUseComponentPathCache(boolean useComponentPathCache) {
this.useComponentPathCache = useComponentPathCache;
}
/**
* @param useComponentShadow the useComponentShadow to set
*/
protected void setUseComponentShadow(boolean useComponentShadow) {
this.useComponentShadow = useComponentShadow;
}
@Override
public DataSource getDataSource(String datasource) throws DatabaseException {
DataSource ds = (datasource == null) ? null : (DataSource) datasources.get(datasource.toLowerCase());
if (ds != null) return ds;
// create error detail
DatabaseException de = new DatabaseException("datasource [" + datasource + "] doesn't exist", null, null, null);
de.setDetail(ExceptionUtil.createSoundexDetail(datasource, datasources.keySet().iterator(), "datasource names"));
de.setAdditional(KeyConstants._Datasource, datasource);
throw de;
}
@Override
public DataSource getDataSource(String datasource, DataSource defaultValue) {
DataSource ds = (datasource == null) ? null : (DataSource) datasources.get(datasource.toLowerCase());
if (ds != null) return ds;
return defaultValue;
}
@Override
public PrintWriter getErrWriter() {
return err;
}
/**
* @param err the err to set
*/
protected void setErr(PrintWriter err) {
this.err = err;
}
@Override
public PrintWriter getOutWriter() {
return out;
}
/**
* @param out the out to set
*/
protected void setOut(PrintWriter out) {
this.out = out;
}
@Override
public DatasourceConnPool getDatasourceConnectionPool(DataSource ds, String user, String pass) {
String id = DatasourceConnectionFactory.createId(ds, user, pass);
DatasourceConnPool pool = pools.get(id);
if (pool == null) {
synchronized (id) {
pool = pools.get(id);
if (pool == null) {// TODO add config but from where?
DataSourcePro dsp = (DataSourcePro) ds;
pool = new DatasourceConnPool(this, ds, user, pass, "datasource",
DatasourceConnPool.createPoolConfig(null, null, null, dsp.getMinIdle(), dsp.getMaxIdle(), dsp.getMaxTotal(), 0, 0, 0, 0, 0, null));
pools.put(id, pool);
}
}
}
return pool;
}
@Override
public MockPool getDatasourceConnectionPool() {
return new MockPool();
}
@Override
public Collection<DatasourceConnPool> getDatasourceConnectionPools() {
return pools.values();
}
@Override
public void removeDatasourceConnectionPool(DataSource ds) {
for (Entry<String, DatasourceConnPool> e: pools.entrySet()) {
if (e.getValue().getFactory().getDatasource().getName().equalsIgnoreCase(ds.getName())) {
synchronized (e.getKey()) {
pools.remove(e.getKey());
}
e.getValue().clear();
}
}
}
@Override
public boolean doLocalCustomTag() {
return doLocalCustomTag;
}
@Override
public String[] getCustomTagExtensions() {
return customTagExtensions;
}
protected void setCustomTagExtensions(String... customTagExtensions) {
this.customTagExtensions = customTagExtensions;
}
protected void setDoLocalCustomTag(boolean doLocalCustomTag) {
this.doLocalCustomTag = doLocalCustomTag;
}
@Override
public boolean doComponentDeepSearch() {
return doComponentTagDeepSearch;
}
protected void setDoComponentDeepSearch(boolean doComponentTagDeepSearch) {
this.doComponentTagDeepSearch = doComponentTagDeepSearch;
}
@Override
public boolean doCustomTagDeepSearch() {
return doCustomTagDeepSearch;
}
/**
* @param doCustomTagDeepSearch the doCustomTagDeepSearch to set
*/
protected void setDoCustomTagDeepSearch(boolean doCustomTagDeepSearch) {
this.doCustomTagDeepSearch = doCustomTagDeepSearch;
}
protected void setVersion(double version) {
this.version = version;
}
/**
* @return the version
*/
@Override
public double getVersion() {
return version;
}
@Override
public boolean closeConnection() {
return closeConnection;
}
protected void setCloseConnection(boolean closeConnection) {
this.closeConnection = closeConnection;
}
@Override
public boolean contentLength() {
return contentLength;
}
@Override
public boolean allowCompression() {
return allowCompression;
}
protected void setAllowCompression(boolean allowCompression) {
this.allowCompression = allowCompression;
}
protected void setContentLength(boolean contentLength) {
this.contentLength = contentLength;
}
/**
* @return the constants
*/
@Override
public Struct getConstants() {
return constants;
}
/**
* @param constants the constants to set
*/
protected void setConstants(Struct constants) {
this.constants = constants;
}
/**
* @return the showVersion
*/
@Override
public boolean isShowVersion() {
return showVersion;
}
/**
* @param showVersion the showVersion to set
*/
protected void setShowVersion(boolean showVersion) {
this.showVersion = showVersion;
}
protected void setRemoteClients(RemoteClient[] remoteClients) {
this.remoteClients = remoteClients;
}
@Override
public RemoteClient[] getRemoteClients() {
if (remoteClients == null) return new RemoteClient[0];
return remoteClients;
}
@Override
public SpoolerEngine getSpoolerEngine() {
return remoteClientSpoolerEngine;
}
protected void setRemoteClientDirectory(Resource remoteClientDirectory) {
this.remoteClientDirectory = remoteClientDirectory;
}
/**
* @return the remoteClientDirectory
*/
@Override
public Resource getRemoteClientDirectory() {
if (remoteClientDirectory == null) {
return ConfigWebUtil.getFile(getRootDirectory(), "client-task", "client-task", getConfigDir(), FileUtil.TYPE_DIR, this);
}
return remoteClientDirectory;
}
protected void setSpoolerEngine(SpoolerEngine spoolerEngine) {
this.remoteClientSpoolerEngine = spoolerEngine;
}
/*
* *
*
* @return the structCase / public int getStructCase() { return structCase; }
*/
/*
* *
*
* @param structCase the structCase to set / protected void setStructCase(int structCase) {
* this.structCase = structCase; }
*/
/**
* @return if error status code will be returned or not
*/
@Override
public boolean getErrorStatusCode() {
return errorStatusCode;
}
/**
* @param errorStatusCode the errorStatusCode to set
*/
protected void setErrorStatusCode(boolean errorStatusCode) {
this.errorStatusCode = errorStatusCode;
}
@Override
public int getLocalMode() {
return localMode;
}
/**
* @param localMode the localMode to set
*/
protected void setLocalMode(int localMode) {
this.localMode = localMode;
}
/**
* @param strLocalMode the localMode to set
*/
protected void setLocalMode(String strLocalMode) {
this.localMode = AppListenerUtil.toLocalMode(strLocalMode, this.localMode);
}
@Override
public Resource getVideoDirectory() {
// TODO take from tag <video>
Resource dir = getConfigDir().getRealResource("video");
if (!dir.exists()) dir.mkdirs();
return dir;
}
@Override
public Resource getExtensionDirectory() {
// TODO take from tag <extensions>
Resource dir = getConfigDir().getRealResource("extensions/installed");
if (!dir.exists()) dir.mkdirs();
return dir;
}
@Override
public ExtensionProvider[] getExtensionProviders() {
throw new RuntimeException("no longer supported, use getRHExtensionProviders() instead.");
}
protected void setRHExtensionProviders(RHExtensionProvider[] extensionProviders) {
this.rhextensionProviders = extensionProviders;
}
@Override
public RHExtensionProvider[] getRHExtensionProviders() {
return rhextensionProviders;
}
@Override
public Extension[] getExtensions() {
throw new PageRuntimeException("no longer supported");
}
@Override
public RHExtension[] getRHExtensions() {
return rhextensions;
}
protected void setExtensions(RHExtension[] extensions) {
this.rhextensions = extensions;
}
@Override
public boolean isExtensionEnabled() {
throw new PageRuntimeException("no longer supported");
}
@Override
public boolean allowRealPath() {
return allowRealPath;
}
protected void setAllowRealPath(boolean allowRealPath) {
this.allowRealPath = allowRealPath;
}
/**
* @return the classClusterScope
*/
@Override
public Class getClusterClass() {
return clusterClass;
}
/**
* @param clusterClass the classClusterScope to set
*/
protected void setClusterClass(Class clusterClass) {
this.clusterClass = clusterClass;
}
@Override
public Struct getRemoteClientUsage() {
if (remoteClientUsage == null) remoteClientUsage = new StructImpl();
return remoteClientUsage;
}
protected void setRemoteClientUsage(Struct remoteClientUsage) {
this.remoteClientUsage = remoteClientUsage;
}
@Override
public Class<AdminSync> getAdminSyncClass() {
return adminSyncClass;
}
protected void setAdminSyncClass(Class adminSyncClass) {
this.adminSyncClass = adminSyncClass;
this.adminSync = null;
}
@Override
public AdminSync getAdminSync() throws ClassException {
if (adminSync == null) {
adminSync = (AdminSync) ClassUtil.loadInstance(getAdminSyncClass());
}
return this.adminSync;
}
@Override
public Class getVideoExecuterClass() {
return videoExecuterClass;
}
protected void setVideoExecuterClass(Class videoExecuterClass) {
this.videoExecuterClass = videoExecuterClass;
}
protected void setUseTimeServer(boolean useTimeServer) {
this.useTimeServer = useTimeServer;
}
@Override
public boolean getUseTimeServer() {
return useTimeServer;
}
/**
* @return the tagMappings
*/
@Override
public Collection<Mapping> getTagMappings() {
return tagMappings.values();
}
@Override
public Mapping getTagMapping(String mappingName) {
return tagMappings.get(mappingName);
}
@Override
public Mapping getDefaultTagMapping() {
return defaultTagMapping;
}
@Override
public Mapping getFunctionMapping(String mappingName) {
return functionMappings.get(mappingName);
}
@Override
public Mapping getDefaultFunctionMapping() {
return defaultFunctionMapping;
}
@Override
public Collection<Mapping> getFunctionMappings() {
return functionMappings.values();
}
/*
* *
*
* @return the tagDirectory
*
* public Resource getTagDirectory() { return tagDirectory; }
*/
/**
* mapping used for script (JSR 223)
*
* @return
*/
public Mapping getScriptMapping() {
if (scriptMapping == null) {
// Physical resource TODO make in RAM
Resource physical = getConfigDir().getRealResource("jsr223");
if (!physical.exists()) physical.mkdirs();
this.scriptMapping = new MappingImpl(this, "/mapping-script/", physical.getAbsolutePath(), null, ConfigPro.INSPECT_NEVER, true, true, true, true, false, true, null, -1,
-1);
}
return scriptMapping;
}
@Override
public String getDefaultDataSource() {
// TODO Auto-generated method stub
return null;
}
protected void setDefaultDataSource(String defaultDataSource) {
// this.defaultDataSource=defaultDataSource;
}
/**
* @return the inspectTemplate
*/
@Override
public short getInspectTemplate() {
return inspectTemplate;
}
@Override
public boolean getTypeChecking() {
return typeChecking;
}
protected void setTypeChecking(boolean typeChecking) {
this.typeChecking = typeChecking;
}
/**
* @param inspectTemplate the inspectTemplate to set
*/
protected void setInspectTemplate(short inspectTemplate) {
this.inspectTemplate = inspectTemplate;
}
@Override
public String getSerialNumber() {
return "";
}
protected void setCaches(Map<String, CacheConnection> caches) {
this.caches = caches;
Iterator<Entry<String, CacheConnection>> it = caches.entrySet().iterator();
Entry<String, CacheConnection> entry;
CacheConnection cc;
while (it.hasNext()) {
entry = it.next();
cc = entry.getValue();
if (cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameTemplate)) {
defaultCacheTemplate = cc;
}
else if (cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameFunction)) {
defaultCacheFunction = cc;
}
else if (cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameQuery)) {
defaultCacheQuery = cc;
}
else if (cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameResource)) {
defaultCacheResource = cc;
}
else if (cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameObject)) {
defaultCacheObject = cc;
}
else if (cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameInclude)) {
defaultCacheInclude = cc;
}
else if (cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameHTTP)) {
defaultCacheHTTP = cc;
}
else if (cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameFile)) {
defaultCacheFile = cc;
}
else if (cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameWebservice)) {
defaultCacheWebservice = cc;
}
}
}
@Override
public Map<String, CacheConnection> getCacheConnections() {
return caches;
}
// used by argus cache FUTURE add to interface
/**
* creates a new RamCache, please make sure to finalize.
*
* @param arguments possible arguments are "timeToLiveSeconds", "timeToIdleSeconds" and
* "controlInterval"
* @throws IOException
*/
public Cache createRAMCache(Struct arguments) throws IOException {
RamCache rc = new RamCache();
if (arguments == null) arguments = new StructImpl();
rc.init(this, "" + CreateUniqueId.invoke(), arguments);
return rc;
}
@Override
public CacheConnection getCacheDefaultConnection(int type) {
if (type == CACHE_TYPE_FUNCTION) return defaultCacheFunction;
if (type == CACHE_TYPE_OBJECT) return defaultCacheObject;
if (type == CACHE_TYPE_TEMPLATE) return defaultCacheTemplate;
if (type == CACHE_TYPE_QUERY) return defaultCacheQuery;
if (type == CACHE_TYPE_RESOURCE) return defaultCacheResource;
if (type == CACHE_TYPE_INCLUDE) return defaultCacheInclude;
if (type == CACHE_TYPE_HTTP) return defaultCacheHTTP;
if (type == CACHE_TYPE_FILE) return defaultCacheFile;
if (type == CACHE_TYPE_WEBSERVICE) return defaultCacheWebservice;
return null;
}
protected void setCacheDefaultConnectionName(int type, String cacheDefaultConnectionName) {
if (type == CACHE_TYPE_FUNCTION) cacheDefaultConnectionNameFunction = cacheDefaultConnectionName;
else if (type == CACHE_TYPE_OBJECT) cacheDefaultConnectionNameObject = cacheDefaultConnectionName;
else if (type == CACHE_TYPE_TEMPLATE) cacheDefaultConnectionNameTemplate = cacheDefaultConnectionName;
else if (type == CACHE_TYPE_QUERY) cacheDefaultConnectionNameQuery = cacheDefaultConnectionName;
else if (type == CACHE_TYPE_RESOURCE) cacheDefaultConnectionNameResource = cacheDefaultConnectionName;
else if (type == CACHE_TYPE_INCLUDE) cacheDefaultConnectionNameInclude = cacheDefaultConnectionName;
else if (type == CACHE_TYPE_HTTP) cacheDefaultConnectionNameHTTP = cacheDefaultConnectionName;
else if (type == CACHE_TYPE_FILE) cacheDefaultConnectionNameFile = cacheDefaultConnectionName;
else if (type == CACHE_TYPE_WEBSERVICE) cacheDefaultConnectionNameWebservice = cacheDefaultConnectionName;
}
@Override
public String getCacheDefaultConnectionName(int type) {
if (type == CACHE_TYPE_FUNCTION) return cacheDefaultConnectionNameFunction;
if (type == CACHE_TYPE_OBJECT) return cacheDefaultConnectionNameObject;
if (type == CACHE_TYPE_TEMPLATE) return cacheDefaultConnectionNameTemplate;
if (type == CACHE_TYPE_QUERY) return cacheDefaultConnectionNameQuery;
if (type == CACHE_TYPE_RESOURCE) return cacheDefaultConnectionNameResource;
if (type == CACHE_TYPE_INCLUDE) return cacheDefaultConnectionNameInclude;
if (type == CACHE_TYPE_HTTP) return cacheDefaultConnectionNameHTTP;
if (type == CACHE_TYPE_FILE) return cacheDefaultConnectionNameFile;
if (type == CACHE_TYPE_WEBSERVICE) return cacheDefaultConnectionNameWebservice;
return null;
}
public String getCacheMD5() {
return cacheMD5;
}
public void setCacheMD5(String cacheMD5) {
this.cacheMD5 = cacheMD5;
}
@Override
public boolean getExecutionLogEnabled() {
return executionLogEnabled;
}
protected void setExecutionLogEnabled(boolean executionLogEnabled) {
this.executionLogEnabled = executionLogEnabled;
}
@Override
public ExecutionLogFactory getExecutionLogFactory() {
return executionLogFactory;
}
protected void setExecutionLogFactory(ExecutionLogFactory executionLogFactory) {
this.executionLogFactory = executionLogFactory;
}
@Override
public ORMEngine resetORMEngine(PageContext pc, boolean force) throws PageException {
// String name = pc.getApplicationContext().getName();
// ormengines.remove(name);
ORMEngine e = getORMEngine(pc);
e.reload(pc, force);
return e;
}
@Override
public ORMEngine getORMEngine(PageContext pc) throws PageException {
String name = pc.getApplicationContext().getName();
ORMEngine engine = ormengines.get(name);
if (engine == null) {
// try {
Throwable t = null;
try {
engine = (ORMEngine) ClassUtil.loadInstance(cdORMEngine.getClazz());
engine.init(pc);
}
catch (ClassException ce) {
t = ce;
}
catch (BundleException be) {
t = be;
}
catch (NoClassDefFoundError ncfe) {
t = ncfe;
}
if (t != null) {
ApplicationException ae = new ApplicationException("cannot initialize ORM Engine [" + cdORMEngine + "], make sure you have added all the required jar files");
ae.initCause(t);
throw ae;
}
ormengines.put(name, engine);
/*
* } catch (PageException pe) { throw pe; }
*/
}
return engine;
}
@Override
public ClassDefinition<? extends ORMEngine> getORMEngineClassDefintion() {
return cdORMEngine;
}
@Override
public Mapping[] getComponentMappings() {
return componentMappings;
}
/**
* @param componentMappings the componentMappings to set
*/
protected void setComponentMappings(Mapping[] componentMappings) {
this.componentMappings = componentMappings;
}
protected void setORMEngineClass(ClassDefinition<? extends ORMEngine> cd) {
this.cdORMEngine = cd;
}
public ClassDefinition<? extends ORMEngine> getORMEngineClass() {
return this.cdORMEngine;
}
protected void setORMConfig(ORMConfiguration ormConfig) {
this.ormConfig = ormConfig;
}
@Override
public ORMConfiguration getORMConfig() {
return ormConfig;
}
private Map<String, SoftReference<PageSource>> componentPathCache = null;// new ArrayList<Page>();
private Map<String, SoftReference<ConfigWebUtil.CacheElement>> applicationPathCache = null;// new ArrayList<Page>();
private Map<String, SoftReference<InitFile>> ctPatchCache = null;// new ArrayList<Page>();
private Map<String, SoftReference<UDF>> udfCache = new ConcurrentHashMap<String, SoftReference<UDF>>();
@Override
public CIPage getCachedPage(PageContext pc, String pathWithCFC) throws TemplateException {
if (componentPathCache == null) return null;
SoftReference<PageSource> tmp = componentPathCache.get(pathWithCFC.toLowerCase());
PageSource ps = tmp == null ? null : tmp.get();
if (ps == null) return null;
try {
return (CIPage) ps.loadPageThrowTemplateException(pc, false, (Page) null);
}
catch (PageException pe) {
throw (TemplateException) pe;
}
}
@Override
public void putCachedPageSource(String pathWithCFC, PageSource ps) {
if (componentPathCache == null) componentPathCache = new ConcurrentHashMap<String, SoftReference<PageSource>>();// MUSTMUST new
// ReferenceMap(ReferenceMap.SOFT,ReferenceMap.SOFT);
componentPathCache.put(pathWithCFC.toLowerCase(), new SoftReference<PageSource>(ps));
}
@Override
public PageSource getApplicationPageSource(PageContext pc, String path, String filename, int mode, RefBoolean isCFC) {
if (applicationPathCache == null) return null;
String id = (path + ":" + filename + ":" + mode).toLowerCase();
SoftReference<CacheElement> tmp = getApplicationPathCacheTimeout() <= 0 ? null : applicationPathCache.get(id);
if (tmp != null) {
CacheElement ce = tmp.get();
if ((ce.created + getApplicationPathCacheTimeout()) >= System.currentTimeMillis()) {
if (ce.pageSource.loadPage(pc, false, (Page) null) != null) {
if (isCFC != null) isCFC.setValue(ce.isCFC);
return ce.pageSource;
}
}
}
return null;
}
@Override
public void putApplicationPageSource(String path, PageSource ps, String filename, int mode, boolean isCFC) {
if (getApplicationPathCacheTimeout() <= 0) return;
if (applicationPathCache == null) applicationPathCache = new ConcurrentHashMap<String, SoftReference<CacheElement>>();// MUSTMUST new
String id = (path + ":" + filename + ":" + mode).toLowerCase();
applicationPathCache.put(id, new SoftReference<CacheElement>(new CacheElement(ps, isCFC)));
}
@Override
public long getApplicationPathCacheTimeout() {
return applicationPathCacheTimeout;
}
protected void setApplicationPathCacheTimeout(long applicationPathCacheTimeout) {
this.applicationPathCacheTimeout = applicationPathCacheTimeout;
}
@Override
public InitFile getCTInitFile(PageContext pc, String key) {
if (ctPatchCache == null) return null;
SoftReference<InitFile> tmp = ctPatchCache.get(key.toLowerCase());
InitFile initFile = tmp == null ? null : tmp.get();
if (initFile != null) {
if (MappingImpl.isOK(initFile.getPageSource())) return initFile;
ctPatchCache.remove(key.toLowerCase());
}
return null;
}
@Override
public void putCTInitFile(String key, InitFile initFile) {
if (ctPatchCache == null) ctPatchCache = new ConcurrentHashMap<String, SoftReference<InitFile>>();// MUSTMUST new ReferenceMap(ReferenceMap.SOFT,ReferenceMap.SOFT);
ctPatchCache.put(key.toLowerCase(), new SoftReference<InitFile>(initFile));
}
@Override
public Struct listCTCache() {
Struct sct = new StructImpl();
if (ctPatchCache == null) return sct;
Iterator<Entry<String, SoftReference<InitFile>>> it = ctPatchCache.entrySet().iterator();
Entry<String, SoftReference<InitFile>> entry;
SoftReference<InitFile> v;
InitFile initFile;
while (it.hasNext()) {
entry = it.next();
v = entry.getValue();
if (v != null) {
initFile = v.get();
if (initFile != null) sct.setEL(entry.getKey(), initFile.getPageSource().getDisplayPath());
}
}
return sct;
}
@Override
public void clearCTCache() {
if (ctPatchCache == null) return;
ctPatchCache.clear();
}
@Override
public void clearFunctionCache() {
udfCache.clear();
}
@Override
public UDF getFromFunctionCache(String key) {
SoftReference<UDF> tmp = udfCache.get(key);
if (tmp == null) return null;
return tmp.get();
}
@Override
public void putToFunctionCache(String key, UDF udf) {
udfCache.put(key, new SoftReference<UDF>(udf));
}
@Override
public Struct listComponentCache() {
Struct sct = new StructImpl();
if (componentPathCache == null) return sct;
Iterator<Entry<String, SoftReference<PageSource>>> it = componentPathCache.entrySet().iterator();
Entry<String, SoftReference<PageSource>> entry;
while (it.hasNext()) {
entry = it.next();
String k = entry.getKey();
if (k == null) continue;
SoftReference<PageSource> v = entry.getValue();
if (v == null) continue;
PageSource ps = v.get();
if (ps == null) continue;
sct.setEL(KeyImpl.init(k), ps.getDisplayPath());
}
return sct;
}
@Override
public void clearComponentCache() {
if (componentPathCache == null) return;
componentPathCache.clear();
}
@Override
public void clearApplicationCache() {
if (applicationPathCache == null) return;
applicationPathCache.clear();
}
@Override
public ImportDefintion getComponentDefaultImport() {
return componentDefaultImport;
}
protected void setComponentDefaultImport(String str) {
if (StringUtil.isEmpty(str)) return;
if ("org.railo.cfml.*".equalsIgnoreCase(str)) str = "org.lucee.cfml.*";
ImportDefintion cdi = ImportDefintionImpl.getInstance(str, null);
if (cdi != null) this.componentDefaultImport = cdi;
}
/**
* @return the componentLocalSearch
*/
@Override
public boolean getComponentLocalSearch() {
return componentLocalSearch;
}
/**
* @param componentLocalSearch the componentLocalSearch to set
*/
protected void setComponentLocalSearch(boolean componentLocalSearch) {
this.componentLocalSearch = componentLocalSearch;
}
/**
* @return the componentLocalSearch
*/
@Override
public boolean getComponentRootSearch() {
return componentRootSearch;
}
/**
* @param componentRootSearch the componentLocalSearch to set
*/
protected void setComponentRootSearch(boolean componentRootSearch) {
this.componentRootSearch = componentRootSearch;
}
private final Map<String, SoftReference<Compress>> compressResources = new ConcurrentHashMap<String, SoftReference<Compress>>();
@Override
public Compress getCompressInstance(Resource zipFile, int format, boolean caseSensitive) throws IOException {
SoftReference<Compress> tmp = compressResources.get(zipFile.getPath());
Compress compress = tmp == null ? null : tmp.get();
if (compress == null) {
compress = new Compress(zipFile, format, caseSensitive);
compressResources.put(zipFile.getPath(), new SoftReference<Compress>(compress));
}
return compress;
}
@Override
public boolean getSessionCluster() {
return false;
}
@Override
public boolean getClientCluster() {
return false;
}
@Override
public String getClientStorage() {
return clientStorage;
}
@Override
public String getSessionStorage() {
return sessionStorage;
}
protected void setClientStorage(String clientStorage) {
this.clientStorage = clientStorage;
}
protected void setSessionStorage(String sessionStorage) {
this.sessionStorage = sessionStorage;
}
private Map<String, ComponentMetaData> componentMetaData = null;
public ComponentMetaData getComponentMetadata(String key) {
if (componentMetaData == null) return null;
return componentMetaData.get(key.toLowerCase());
}
public void putComponentMetadata(String key, ComponentMetaData data) {
if (componentMetaData == null) componentMetaData = new HashMap<String, ComponentMetaData>();
componentMetaData.put(key.toLowerCase(), data);
}
public void clearComponentMetadata() {
if (componentMetaData == null) return;
componentMetaData.clear();
}
public static class ComponentMetaData {
public final Struct meta;
public final long lastMod;
public ComponentMetaData(Struct meta, long lastMod) {
this.meta = meta;
this.lastMod = lastMod;
}
}
private DebugEntry[] debugEntries;
protected void setDebugEntries(DebugEntry[] debugEntries) {
this.debugEntries = debugEntries;
}
@Override
public DebugEntry[] getDebugEntries() {
if (debugEntries == null) debugEntries = new DebugEntry[0];
return debugEntries;
}
@Override
public DebugEntry getDebugEntry(String ip, DebugEntry defaultValue) {
if (debugEntries.length == 0) return defaultValue;
InetAddress ia;
try {
ia = IPRange.toInetAddress(ip);
}
catch (IOException e) {
return defaultValue;
}
for (int i = 0; i < debugEntries.length; i++) {
if (debugEntries[i].getIpRange().inRange(ia)) return debugEntries[i];
}
return defaultValue;
}
private int debugMaxRecordsLogged = 10;
protected void setDebugMaxRecordsLogged(int debugMaxRecordsLogged) {
this.debugMaxRecordsLogged = debugMaxRecordsLogged;
}
@Override
public int getDebugMaxRecordsLogged() {
return debugMaxRecordsLogged;
}
private boolean dotNotationUpperCase = true;
protected void setDotNotationUpperCase(boolean dotNotationUpperCase) {
this.dotNotationUpperCase = dotNotationUpperCase;
}
@Override
public boolean getDotNotationUpperCase() {
return dotNotationUpperCase;
}
@Override
public boolean preserveCase() {
return !dotNotationUpperCase;
}
private boolean defaultFunctionOutput = true;
protected void setDefaultFunctionOutput(boolean defaultFunctionOutput) {
this.defaultFunctionOutput = defaultFunctionOutput;
}
@Override
public boolean getDefaultFunctionOutput() {
return defaultFunctionOutput;
}
private boolean getSuppressWSBeforeArg = true;
protected void setSuppressWSBeforeArg(boolean getSuppressWSBeforeArg) {
this.getSuppressWSBeforeArg = getSuppressWSBeforeArg;
}
@Override
public boolean getSuppressWSBeforeArg() {
return getSuppressWSBeforeArg;
}
private RestSettings restSetting = new RestSettingImpl(false, UDF.RETURN_FORMAT_JSON);
protected void setRestSetting(RestSettings restSetting) {
this.restSetting = restSetting;
}
@Override
public RestSettings getRestSetting() {
return restSetting;
}
protected void setMode(int mode) {
this.mode = mode;
}
public int getMode() {
return mode;
}
// do not move to Config interface, do instead getCFMLWriterClass
protected void setCFMLWriterType(int writerType) {
this.writerType = writerType;
}
// do not move to Config interface, do instead setCFMLWriterClass
@Override
public int getCFMLWriterType() {
return writerType;
}
private boolean bufferOutput = false;
private int externalizeStringGTE = -1;
private Map<String, BundleDefinition> extensionBundles;
private JDBCDriver[] drivers;
private Resource logDir;
@Override
public boolean getBufferOutput() {
return bufferOutput;
}
protected void setBufferOutput(boolean bufferOutput) {
this.bufferOutput = bufferOutput;
}
public int getDebugOptions() {
return debugOptions;
}
@Override
public boolean hasDebugOptions(int debugOption) {
return (debugOptions & debugOption) > 0;
}
protected void setDebugOptions(int debugOptions) {
this.debugOptions = debugOptions;
}
protected void setCheckForChangesInConfigFile(boolean checkForChangesInConfigFile) {
this.checkForChangesInConfigFile = checkForChangesInConfigFile;
}
@Override
public boolean checkForChangesInConfigFile() {
return checkForChangesInConfigFile;
}
protected void setExternalizeStringGTE(int externalizeStringGTE) {
this.externalizeStringGTE = externalizeStringGTE;
}
@Override
public int getExternalizeStringGTE() {
return externalizeStringGTE;
}
protected void addConsoleLayout(Object layout) {
consoleLayouts.add(layout);
}
protected void addResourceLayout(Object layout) {
resourceLayouts.add(layout);
}
public Object[] getConsoleLayouts() {
if (consoleLayouts.isEmpty()) consoleLayouts.add(getLogEngine().getDefaultLayout());
return consoleLayouts.toArray(new Object[consoleLayouts.size()]);
}
public Object[] getResourceLayouts() {
if (resourceLayouts.isEmpty()) resourceLayouts.add(new ClassicLayout());
return resourceLayouts.toArray(new Object[resourceLayouts.size()]);
}
protected void clearLoggers(Boolean dyn) {
if (loggers.size() == 0) return;
List<String> list = dyn != null ? new ArrayList<String>() : null;
try {
Iterator<Entry<String, LoggerAndSourceData>> it = loggers.entrySet().iterator();
Entry<String, LoggerAndSourceData> e;
while (it.hasNext()) {
e = it.next();
if (dyn == null || dyn.booleanValue() == e.getValue().getDyn()) {
e.getValue().close();
if (list != null) list.add(e.getKey());
}
}
}
catch (Exception e) {
}
if (list == null) loggers.clear();
else {
Iterator<String> it = list.iterator();
while (it.hasNext()) {
loggers.remove(it.next());
}
}
}
protected LoggerAndSourceData addLogger(String name, int level, ClassDefinition appender, Map<String, String> appenderArgs, ClassDefinition layout,
Map<String, String> layoutArgs, boolean readOnly, boolean dyn) {
LoggerAndSourceData existing = loggers.get(name.toLowerCase());
String id = LoggerAndSourceData.id(name.toLowerCase(), appender, appenderArgs, layout, layoutArgs, level, readOnly);
if (existing != null) {
if (existing.id().equals(id)) {
return existing;
}
existing.close();
}
LoggerAndSourceData las = new LoggerAndSourceData(this, id, name.toLowerCase(), appender, appenderArgs, layout, layoutArgs, level, readOnly, dyn);
loggers.put(name.toLowerCase(), las);
return las;
}
@Override
public Map<String, LoggerAndSourceData> getLoggers() {
return loggers;
}
// FUTURE add to interface
public String[] getLogNames() {
return loggers.keySet().toArray(new String[loggers.size()]);
}
@Override
public Log getLog(String name) {
return getLog(name, true);
}
@Override
public Log getLog(String name, boolean createIfNecessary) {
LoggerAndSourceData lsd = _getLoggerAndSourceData(name, createIfNecessary);
if (lsd == null) return null;
return lsd.getLog();
}
private LoggerAndSourceData _getLoggerAndSourceData(String name, boolean createIfNecessary) {
LoggerAndSourceData las = loggers.get(name.toLowerCase());
if (las == null) {
if (!createIfNecessary) return null;
return addLogger(name, Log.LEVEL_ERROR, getLogEngine().appenderClassDefintion("console"), null, getLogEngine().layoutClassDefintion("pattern"), null, true, true);
}
return las;
}
@Override
public Map<Key, Map<Key, Object>> getTagDefaultAttributeValues() {
return tagDefaultAttributeValues == null ? null : Duplicator.duplicateMap(tagDefaultAttributeValues, new HashMap<Key, Map<Key, Object>>(), true);
}
protected void setTagDefaultAttributeValues(Map<Key, Map<Key, Object>> values) {
this.tagDefaultAttributeValues = values;
}
@Override
public Boolean getHandleUnQuotedAttrValueAsString() {
return handleUnQuotedAttrValueAsString;
}
protected void setHandleUnQuotedAttrValueAsString(boolean handleUnQuotedAttrValueAsString) {
this.handleUnQuotedAttrValueAsString = handleUnQuotedAttrValueAsString;
}
protected void setCachedWithin(int type, Object value) {
cachedWithins.put(type, value);
}
@Override
public Object getCachedWithin(int type) {
return cachedWithins.get(type);
}
@Override
public Resource getPluginDirectory() {
return getConfigDir().getRealResource("context/admin/plugin");
}
@Override
public Resource getLogDirectory() {
if (logDir == null) {
logDir = getConfigDir().getRealResource("logs");
logDir.mkdir();
}
return logDir;
}
protected void setSalt(String salt) {
this.salt = salt;
}
@Override
public String getSalt() {
return this.salt;
}
@Override
public int getPasswordType() {
if (password == null) return Password.HASHED_SALTED;// when there is no password, we will have a HS password
return password.getType();
}
@Override
public String getPasswordSalt() {
if (password == null || password.getSalt() == null) return this.salt;
return password.getSalt();
}
@Override
public int getPasswordOrigin() {
if (password == null) return Password.ORIGIN_UNKNOW;
return password.getOrigin();
}
@Override
public Collection<BundleDefinition> getExtensionBundleDefintions() {
if (this.extensionBundles == null) {
RHExtension[] rhes = getRHExtensions();
Map<String, BundleDefinition> extensionBundles = new HashMap<String, BundleDefinition>();
for (RHExtension rhe: rhes) {
BundleInfo[] bis;
try {
bis = rhe.getBundles();
}
catch (Exception e) {
continue;
}
if (bis != null) {
for (BundleInfo bi: bis) {
extensionBundles.put(bi.getSymbolicName() + "|" + bi.getVersionAsString(), bi.toBundleDefinition());
}
}
}
this.extensionBundles = extensionBundles;
}
return extensionBundles.values();
}
protected void setJDBCDrivers(JDBCDriver[] drivers) {
this.drivers = drivers;
}
@Override
public JDBCDriver[] getJDBCDrivers() {
return drivers;
}
@Override
public JDBCDriver getJDBCDriverByClassName(String className, JDBCDriver defaultValue) {
for (JDBCDriver d: drivers) {
if (d.cd.getClassName().equals(className)) return d;
}
return defaultValue;
}
@Override
public JDBCDriver getJDBCDriverById(String id, JDBCDriver defaultValue) {
if (!StringUtil.isEmpty(id)) {
for (JDBCDriver d: drivers) {
if (d.id != null && d.id.equalsIgnoreCase(id)) return d;
}
}
return defaultValue;
}
@Override
public JDBCDriver getJDBCDriverByBundle(String bundleName, Version version, JDBCDriver defaultValue) {
for (JDBCDriver d: drivers) {
if (d.cd.getName().equals(bundleName) && (version == null || version.equals(d.cd.getVersion()))) return d;
}
return defaultValue;
}
@Override
public JDBCDriver getJDBCDriverByCD(ClassDefinition cd, JDBCDriver defaultValue) {
for (JDBCDriver d: drivers) {
if (d.cd.getId().equals(cd.getId())) return d; // TODO comparing cd objects directly?
}
return defaultValue;
}
@Override
public int getQueueMax() {
return queueMax;
}
protected void setQueueMax(int queueMax) {
this.queueMax = queueMax;
}
@Override
public long getQueueTimeout() {
return queueTimeout;
}
protected void setQueueTimeout(long queueTimeout) {
this.queueTimeout = queueTimeout;
}
@Override
public boolean getQueueEnable() {
return queueEnable;
}
protected void setQueueEnable(boolean queueEnable) {
this.queueEnable = queueEnable;
}
private boolean cgiScopeReadonly = true;
@Override
public boolean getCGIScopeReadonly() {
return cgiScopeReadonly;
}
protected void setCGIScopeReadonly(boolean cgiScopeReadonly) {
this.cgiScopeReadonly = cgiScopeReadonly;
}
private Resource deployDir;
@Override
public Resource getDeployDirectory() {
if (deployDir == null) {
// config web
if (this instanceof ConfigWeb) {
deployDir = getConfigDir().getRealResource("deploy");
if (!deployDir.exists()) deployDir.mkdirs();
}
// config server
else {
try {
File file = new File(ConfigWebUtil.getEngine(this).getCFMLEngineFactory().getResourceRoot(), "deploy");
if (!file.exists()) file.mkdirs();
deployDir = ResourcesImpl.getFileResourceProvider().getResource(file.getAbsolutePath());
}
catch (IOException ioe) {
deployDir = getConfigDir().getRealResource("deploy");
if (!deployDir.exists()) deployDir.mkdirs();
}
}
}
return deployDir;
}
private boolean allowLuceeDialect = false;
@Override
public boolean allowLuceeDialect() {
return allowLuceeDialect;
}
public void setAllowLuceeDialect(boolean allowLuceeDialect) {
this.allowLuceeDialect = allowLuceeDialect;
}
/*
* public boolean installExtension(ExtensionDefintion ed) throws PageException { return
* DeployHandler.deployExtension(this, ed, getLog("deploy"),true); }
*/
private Map<String, ClassDefinition> cacheDefinitions;
public void setCacheDefinitions(Map<String, ClassDefinition> caches) {
this.cacheDefinitions = caches;
}
@Override
public Map<String, ClassDefinition> getCacheDefinitions() {
return this.cacheDefinitions;
}
@Override
public ClassDefinition getCacheDefinition(String className) {
return this.cacheDefinitions.get(className);
}
@Override
public Resource getAntiSamyPolicy() {
return getConfigDir().getRealResource("security/antisamy-basic.xml");
}
protected abstract void setGatewayEntries(Map<String, GatewayEntry> gatewayEntries);
public abstract Map<String, GatewayEntry> getGatewayEntries();
private ClassDefinition wsHandlerCD;
protected WSHandler wsHandler = null;
protected void setWSHandlerClassDefinition(ClassDefinition cd) {
this.wsHandlerCD = cd;
wsHandler = null;
}
// public abstract WSHandler getWSHandler() throws PageException;
protected ClassDefinition getWSHandlerClassDefinition() {
return wsHandlerCD;
}
boolean isEmpty(ClassDefinition cd) {
return cd == null || StringUtil.isEmpty(cd.getClassName());
}
private boolean fullNullSupport = false;
protected final void setFullNullSupport(boolean fullNullSupport) {
this.fullNullSupport = fullNullSupport;
}
@Override
public final boolean getFullNullSupport() {
return fullNullSupport;
}
private LogEngine logEngine;
@Override
public LogEngine getLogEngine() {
if (logEngine == null) logEngine = LogEngine.getInstance(this);
return logEngine;
}
protected void setCachedAfterTimeRange(TimeSpan ts) {
this.cachedAfterTimeRange = ts;
}
@Override
public TimeSpan getCachedAfterTimeRange() {
if (this.cachedAfterTimeRange != null && this.cachedAfterTimeRange.getMillis() <= 0) this.cachedAfterTimeRange = null;
return this.cachedAfterTimeRange;
}
@Override
public Map<String, Startup> getStartups() {
if (startups == null) startups = new HashMap<>();
return startups;
}
@Override
public Regex getRegex() {
if (regex == null) regex = RegexFactory.toRegex(RegexFactory.TYPE_PERL, null);
return regex;
}
protected void setRegex(Regex regex) {
this.regex = regex;
}
} |
package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.UserResponse;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.user.UserAccount;
import com.cloud.user.UserContext;
@Implementation(description="Updates a user account", responseObject=UserResponse.class)
public class UpdateUserCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UpdateUserCmd.class.getName());
private static final String s_name = "updateuserresponse";
//////////////// API parameters /////////////////////
@Parameter(name=ApiConstants.API_KEY, type=CommandType.STRING, description="The API key for the user. Must be specified with secretKey")
private String apiKey;
@Parameter(name=ApiConstants.EMAIL, type=CommandType.STRING, description="email")
private String email;
@Parameter(name=ApiConstants.FIRSTNAME, type=CommandType.STRING, description="first name")
private String firstname;
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="User id")
private Long id;
@Parameter(name=ApiConstants.LASTNAME, type=CommandType.STRING, description="last name")
private String lastname;
@Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, description="Hashed password (default is MD5). If you wish to use any other hasing algorithm, you would need to write a custom authentication adapter")
private String password;
@Parameter(name=ApiConstants.SECRET_KEY, type=CommandType.STRING, description="The secret key for the user. Must be specified with apiKey")
private String secretKey;
@Parameter(name=ApiConstants.TIMEZONE, type=CommandType.STRING, description="Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.")
private String timezone;
@Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, description="Unique username")
private String username;
/////////////////// Accessors ///////////////////////
public String getApiKey() {
return apiKey;
}
public String getEmail() {
return email;
}
public String getFirstname() {
return firstname;
}
public Long getId() {
return id;
}
public String getLastname() {
return lastname;
}
public String getPassword() {
return password;
}
public String getSecretKey() {
return secretKey;
}
public String getTimezone() {
return timezone;
}
public String getUsername() {
return username;
}
/////////////// API Implementation///////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
User user = _entityMgr.findById(User.class, getId());
if (user != null) {
return user.getAccountId();
}
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
}
@Override
public void execute(){
UserContext.current().setEventDetails("UserId: "+getId());
UserAccount user = _accountService.updateUser(this);
if (user != null){
UserResponse response = _responseGenerator.createUserResponse(user);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update user");
}
}
} |
package lucee.runtime.net.mail;
import lucee.commons.io.SystemUtil;
import lucee.commons.lang.StringUtil;
import lucee.runtime.config.Config;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.PageException;
import lucee.runtime.net.http.sni.SSLConnectionSocketFactoryImpl;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.type.Array;
import lucee.runtime.type.Struct;
import lucee.runtime.type.util.ListUtil;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.net.IDN;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
public final class MailUtil {
public static final String SYSTEM_PROP_MAIL_SSL_PROTOCOLS = "mail.smtp.ssl.protocols";
public static String encode(String text, String encoding) throws UnsupportedEncodingException {
// print.ln(StringUtil.changeCharset(text,encoding));
return MimeUtility.encodeText(text, encoding, "Q");
}
public static String decode(String text) throws UnsupportedEncodingException {
return MimeUtility.decodeText(text);
}
public static InternetAddress toInternetAddress(Object emails) throws MailException, UnsupportedEncodingException, PageException {
if (emails instanceof String) return parseEmail(emails, null);
InternetAddress[] addresses = toInternetAddresses(emails);
if (addresses != null && addresses.length > 0) return addresses[0];
return null;
}
public static InternetAddress[] toInternetAddresses(Object emails) throws MailException, UnsupportedEncodingException, PageException {
if (emails instanceof InternetAddress[]) return (InternetAddress[]) emails;
else if (emails instanceof String) return fromList((String) emails);
else if (Decision.isArray(emails)) return fromArray(Caster.toArray(emails));
else if (Decision.isStruct(emails)) return new InternetAddress[] { fromStruct(Caster.toStruct(emails)) };
else throw new MailException("e-mail definitions must be one of the following types [string,array,struct], not [" + emails.getClass().getName() + "]");
}
private static InternetAddress[] fromArray(Array array) throws MailException, PageException, UnsupportedEncodingException {
Iterator it = array.valueIterator();
Object el;
ArrayList<InternetAddress> pairs = new ArrayList();
while (it.hasNext()) {
el = it.next();
if (Decision.isStruct(el)) {
pairs.add(fromStruct(Caster.toStruct(el)));
}
else {
InternetAddress addr = parseEmail(Caster.toString(el), null);
if (addr != null) pairs.add(addr);
}
}
return pairs.toArray(new InternetAddress[pairs.size()]);
}
private static InternetAddress fromStruct(Struct sct) throws MailException, UnsupportedEncodingException {
String name = Caster.toString(sct.get("label", null), null);
if (name == null) name = Caster.toString(sct.get("name", null), null);
String email = Caster.toString(sct.get("email", null), null);
if (email == null) email = Caster.toString(sct.get("e-mail", null), null);
if (email == null) email = Caster.toString(sct.get("mail", null), null);
if (StringUtil.isEmpty(email)) throw new MailException("missing e-mail definition in struct");
if (name == null) name = "";
return new InternetAddress(email, name);
}
private static InternetAddress[] fromList(String strEmails) throws MailException {
if (StringUtil.isEmpty(strEmails, true)) return new InternetAddress[0];
Array raw = ListUtil.listWithQuotesToArray(strEmails, ",;", "\"");
Iterator<Object> it = raw.valueIterator();
ArrayList<InternetAddress> al = new ArrayList();
while (it.hasNext()) {
InternetAddress addr = parseEmail(it.next(), null);
if (addr != null) al.add(addr);
}
return al.toArray(new InternetAddress[al.size()]);
}
/**
* returns true if the passed value is a in valid email address format
*
* @param value
* @return
*/
public static boolean isValidEmail(Object value) {
InternetAddress addr = parseEmail(value, null);
if (addr != null) {
String address = addr.getAddress();
if (address.contains("..")) return false;
int pos = address.indexOf('@');
if (pos < 1 || pos == address.length() - 1) return false;
String local = address.substring(0, pos);
String domain = address.substring(pos + 1);
if (domain.charAt(0) == '.' || local.charAt(0) == '.' || local.charAt(local.length() - 1) == '.') return false;
pos = domain.lastIndexOf('.');
if (pos > 0 && pos < domain.length() - 2) { // test TLD to be at
// least 2 chars all
// alpha characters
if (StringUtil.isAllAlpha(domain.substring(pos + 1))) return true;
try {
addr.validate();
return true;
}
catch (AddressException e) {}
}
}
return false;
}
public static InternetAddress parseEmail(Object value) throws MailException {
InternetAddress ia = parseEmail(value, null);
if (ia != null) return ia;
if (value instanceof CharSequence) throw new MailException("[" + value + "] cannot be converted to an email address");
throw new MailException("input cannot be converted to an email address");
}
/**
* returns an InternetAddress object or null if the parsing fails. to be be used in multiple places.
*
* @param value
* @return
*/
public static InternetAddress parseEmail(Object value, InternetAddress defaultValue) {
String str = Caster.toString(value, "");
if (str.indexOf('@') > -1) {
try {
str = fixIDN(str);
InternetAddress addr = new InternetAddress(str);
// fixIDN( addr );
return addr;
}
catch (AddressException ex) {}
}
return defaultValue;
}
/**
* converts IDN to ASCII if needed
*
* @param addr
* @return
*/
public static String fixIDN(String addr) {
int pos = addr.indexOf('@');
if (pos > 0 && pos < addr.length() - 1) {
String domain = addr.substring(pos + 1);
if (!StringUtil.isAscii(domain)) {
domain = IDN.toASCII(domain);
return addr.substring(0, pos) + "@" + domain;
}
}
return addr;
}
/**
* This method should be called when TLS is used to ensure that the supported protocols are set. Some
* servers, e.g. Outlook365, reject lists with older protocols so we only pass protocols that start with
* the prefix "TLS"
*/
public static void setSystemPropMailSslProtocols() {
String protocols = SystemUtil.getSystemPropOrEnvVar(SYSTEM_PROP_MAIL_SSL_PROTOCOLS, "");
if (protocols.isEmpty()) {
List<String> supportedProtocols = SSLConnectionSocketFactoryImpl.getSupportedSslProtocols();
protocols = supportedProtocols.stream()
.filter(el -> el.startsWith("TLS"))
.collect(Collectors.joining(" "));
if (!protocols.isEmpty()) {
System.setProperty(SYSTEM_PROP_MAIL_SSL_PROTOCOLS, protocols);
Config config = ThreadLocalPageContext.getConfig();
if (config != null)
config
.getLog("mail")
.info("mail", "Lucee system property " + SYSTEM_PROP_MAIL_SSL_PROTOCOLS + " set to [" + protocols + "]");
}
}
}
} |
package org.hyperic.sigar.cmd;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.NetConnection;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.Tcp;
/**
* Display network connections.
*/
public class Netstat extends SigarCommandBase {
private static final int LADDR_LEN = 20;
private static final int RADDR_LEN = 35;
private static final String[] HEADER = new String[] {
"Proto",
"Local Address",
"Foreign Address",
"State",
""
};
private static boolean isNumeric, wantPid, isStat;
public Netstat(Shell shell) {
super(shell);
}
public Netstat() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getUsageShort() {
return "Display network connections";
}
//poor mans getopt.
public static int getFlags(String[] args, int flags) {
int proto_flags = 0;
isNumeric = false;
wantPid = false;
isStat = false;
for (int i=0; i<args.length; i++) {
String arg = args[i];
int j = 0;
while (j<arg.length()) {
switch (arg.charAt(j++)) {
case '-':
continue;
case 'l':
flags &= ~NetFlags.CONN_CLIENT;
flags |= NetFlags.CONN_SERVER;
break;
case 'a':
flags |= NetFlags.CONN_SERVER | NetFlags.CONN_CLIENT;
break;
case 'n':
isNumeric = true;
break;
case 'p':
wantPid = true;
break;
case 's':
isStat = true;
break;
case 't':
proto_flags |= NetFlags.CONN_TCP;
break;
case 'u':
proto_flags |= NetFlags.CONN_UDP;
break;
case 'w':
proto_flags |= NetFlags.CONN_RAW;
break;
case 'x':
proto_flags |= NetFlags.CONN_UNIX;
break;
default:
System.err.println("unknown option");
}
}
}
if (proto_flags != 0) {
flags &= ~NetFlags.CONN_PROTOCOLS;
flags |= proto_flags;
}
return flags;
}
private String formatPort(int proto, long port) {
if (port == 0) {
return "*";
}
if (!isNumeric) {
String service = this.sigar.getNetServicesName(proto, port);
if (service != null) {
return service;
}
}
return String.valueOf(port);
}
private String formatAddress(int proto, String ip,
long portnum, int max) {
String port = formatPort(proto, portnum);
String address;
if (NetFlags.isAnyAddress(ip)) {
address = "*";
}
else if (isNumeric) {
address = ip;
}
else {
try {
address = InetAddress.getByName(ip).getHostName();
} catch (UnknownHostException e) {
address = ip;
}
}
max -= port.length() + 1;
if (address.length() > max) {
address = address.substring(0, max);
}
return address + ":" + port;
}
private void outputTcpStats() throws SigarException {
Tcp stat = this.sigar.getTcp();
final String dnt = " ";
println(dnt + stat.getActiveOpens() + " active connections openings");
println(dnt + stat.getPassiveOpens() + " passive connection openings");
println(dnt + stat.getAttemptFails() + " failed connection attempts");
println(dnt + stat.getEstabResets() + " connection resets received");
println(dnt + stat.getCurrEstab() + " connections established");
println(dnt + stat.getInSegs() + " segments received");
println(dnt + stat.getOutSegs() + " segments send out");
println(dnt + stat.getRetransSegs() + " segments retransmited");
println(dnt + stat.getInErrs() + " bad segments received.");
println(dnt + stat.getOutRsts() + " resets sent");
}
private void outputStats(int flags) throws SigarException {
if ((flags & NetFlags.CONN_TCP) != 0) {
println("Tcp:");
try {
outputTcpStats();
} catch (SigarException e) {
println(" " + e);
}
}
}
//XXX currently weak sauce. should end up like netstat command.
public void output(String[] args) throws SigarException {
//default
int flags = NetFlags.CONN_CLIENT | NetFlags.CONN_PROTOCOLS;
if (args.length > 0) {
flags = getFlags(args, flags);
if (isStat) {
outputStats(flags);
return;
}
}
NetConnection[] connections = this.sigar.getNetConnectionList(flags);
printf(HEADER);
for (int i=0; i<connections.length; i++) {
NetConnection conn = connections[i];
String proto = conn.getTypeString();
String state;
if (conn.getType() == NetFlags.CONN_UDP) {
state = "";
}
else {
state = conn.getStateString();
}
ArrayList items = new ArrayList();
items.add(proto);
items.add(formatAddress(conn.getType(),
conn.getLocalAddress(),
conn.getLocalPort(),
LADDR_LEN));
items.add(formatAddress(conn.getType(),
conn.getRemoteAddress(),
conn.getRemotePort(),
RADDR_LEN));
items.add(state);
String process = null;
if (wantPid &&
//XXX only works w/ listen ports
(conn.getState() == NetFlags.TCP_LISTEN))
{
try {
long pid =
this.sigar.getProcPort(conn.getType(),
conn.getLocalPort());
if (pid != 0) { //XXX another bug
String name =
this.sigar.getProcState(pid).getName();
process = pid + "/" + name;
}
} catch (SigarException e) {
}
}
if (process == null) {
process = "";
}
items.add(process);
printf(items);
}
}
public static void main(String[] args) throws Exception {
new Netstat().processCommand(args);
}
} |
package org.egordorichev.lasttry.item.block;
import com.badlogic.gdx.graphics.Texture;
import org.egordorichev.lasttry.LastTry;
import org.egordorichev.lasttry.graphics.Graphics;
import org.egordorichev.lasttry.item.Item;
import org.egordorichev.lasttry.item.items.ToolPower;
import org.egordorichev.lasttry.util.Rectangle;
public class Block extends Item {
public static final int TEX_SIZE = 16;
public static final byte MAX_HP = 4;
/** Is the block solid */
protected boolean solid;
/** The tool type to use for the block */
protected ToolPower power;
/** The block spite-sheet */
protected Texture tiles;
/** Block width in tiles */
protected int width = 1;
/** Block height in tiles */
protected int height = 1;
public Block(short id, String name, boolean solid, ToolPower requiredPower, Texture texture, Texture tiles) {
super(id, name, texture);
this.power = requiredPower;
this.tiles = tiles;
this.solid = solid;
this.useSpeed = 30;
}
@Override
public boolean isAutoUse() {
return true;
}
/**
* Calculates a number based on the edges that have blocks of the same type.
*
* @param top Top edge matches current type.
* @param right Right edge matches current type.
* @param bottom Bottom edge matches current type.
* @param left Left edge matches current type.
* @return
*/
public static byte calculateBinary(boolean top, boolean right, boolean bottom, boolean left) {
byte result = 0;
if (top)
result += 1;
if (right)
result += 2;
if (bottom)
result += 4;
if (left)
result += 8;
return result;
}
/**
* Updates the block at given coordinates
*
* @param x X-position in the world.
* @param y Y-position in the world.
*/
public void updateBlockStyle(int x, int y) {
/* TODO: if block has animation, update it */
}
public void updateBlock(int x, int y) {
}
public void onNeighborChange(int x, int y, int nx, int ny) {
}
public void die(int x, int y) {
LastTry.entityManager.spawn(new DroppedItem(new ItemHolder(this, 1)), Block.TEX_SIZE * x, Block.TEX_SIZE * y);
}
public boolean canBePlaced(int x, int y) {
return true; // TODO: placement radius
}
public void place(int x, int y) {
LastTry.world.setBlock(this.id, x, y);
}
/**
* Renders the block at the given coordinates.
*
* @param x X-position in the world.
* @param y Y-position in the world.
*/
public void renderBlock(int x, int y) {
boolean t = LastTry.world.getBlockID(x, y - 1) == this.id;
boolean r = LastTry.world.getBlockID(x + 1, y) == this.id;
boolean b = LastTry.world.getBlockID(x, y + 1) == this.id;
boolean l = LastTry.world.getBlockID(x - 1, y) == this.id;
// TODO: FIXME: replace with var
short variant = 1;
byte binary = Block.calculateBinary(t, r, b, l);
if (binary == 15) {
LastTry.batch.draw(this.tiles, x * Block.TEX_SIZE,
(LastTry.world.getHeight() - y - 1) * Block.TEX_SIZE, Block.TEX_SIZE, Block.TEX_SIZE,
Block.TEX_SIZE * (binary), 48 + variant * Block.TEX_SIZE, Block.TEX_SIZE,
Block.TEX_SIZE, false, false);
} else {
LastTry.batch.draw(this.tiles, x * Block.TEX_SIZE,
(LastTry.world.getHeight() - y - 1) * Block.TEX_SIZE, Block.TEX_SIZE, Block.TEX_SIZE,
Block.TEX_SIZE * (binary), variant * Block.TEX_SIZE, Block.TEX_SIZE,
Block.TEX_SIZE, false, false);
}
if (this.renderCracks()) {
byte hp = LastTry.world.getBlockHp(x, y);
if (hp < Block.MAX_HP) {
LastTry.batch.draw(Graphics.tileCracks[Block.MAX_HP - hp], x * Block.TEX_SIZE, (LastTry.world.getHeight() - y - 1) * Block.TEX_SIZE);
}
}
}
/** Returns true, if we allowed to draw cracks here */
protected boolean renderCracks() {
return true;
}
/**
* Attempts to place the block in the world at the player's cursor.
*/
@Override
public boolean use() {
int x = LastTry.getMouseXInWorld() / Block.TEX_SIZE;
int y = LastTry.getMouseYInWorld() / Block.TEX_SIZE;
if (this.canBePlaced(x, y) && LastTry.world.canPlaceInWorld(this, x, y)) {
Rectangle rectangle = LastTry.player.getHitbox();
if (rectangle.intersects(new Rectangle(x * TEX_SIZE, y * TEX_SIZE, this.width * TEX_SIZE,
this.height * TEX_SIZE))) {
return false;
}
this.place(x, y);
return true;
}
return false;
}
/**
* Returns required power to break this block
* @return required power to break this block
*/
public ToolPower getRequiredPower() {
return this.power;
}
/**
* Returns the solidity of the block.
* @return true if the block is solid.
*/
public boolean isSolid() {
return this.solid;
}
@Override
public int getMaxInStack() {
return 999;
}
} |
package net.stefankrause;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.NumberFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.Stream;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.json.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class App {
private final static String BINARY = "/Applications/Chromium.app/Contents/MacOS/Chromium";
//private final static String BINARY = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
//private final static String BINARY = "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary";
private final static int REPEAT_RUN = 10;
private final static int WARMUP_COUNT = 5;
private final static int DROP_WORST_RUN = 4;
private static class Framework {
private final String framework;
private final String url;
public Framework(String name) {
this.framework = name;
this.url = name;
}
public Framework(String framework, String url) {
this.framework = framework;
this.url = url;
}
}
private final static Framework frameworks[] = {
new Framework("angular-v1.5.3"),
new Framework("angular-v2.0.0-beta.15"),
new Framework("aurelia"),
new Framework("ember", "ember/dist"),
new Framework("inferno-v0.7.6"),
new Framework("mithril-v0.2.3"),
new Framework("plastiq-v1.28.0"),
new Framework("plastiq-v1.30.0"),
new Framework("preact-v2.8.3"),
new Framework("ractive-v0.7.3"),
new Framework("react-v0.14.8"),
new Framework("react-v15.0.1"),
new Framework("react-lite-v0.0.18"),
new Framework("react-lite-v0.15.9"),
new Framework("vanillajs"),
new Framework("vidom-v0.1.7"),
new Framework("vue-v1.0.21")
};
private final static Bench[] benches = new Bench[] {
new BenchRun(),
new BenchRunHot(),
new BenchUpdate(),
new BenchSelect(),
new BenchRemove(),
new BenchHideAll(),
new BenchShowAll(),
new BenchRunBig(),
new BenchRunBigHot(),
new BenchClear(),
new BenchClearHot(),
new BenchSelectBig(),
new BenchSwapRows(),
new BenchRecycle()
};
private static int BINARY_VERSION = 0;
private static class PLogEntry {
private final String name;
private final long ts;
private final long duration;
private final String message;
public PLogEntry(String name, long ts, long duration, String message) {
this.name = name;
this.ts = ts;
this.duration = duration;
this.message = message;
}
public String getName() {
return name;
}
public long getTs() {
return ts;
}
public long getDuration() {
return duration;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return "PLogEntry{" +
"name='" + name + '\'' +
", ts=" + ts +
", duration=" + duration +
", message='" + message + '\'' +
'}';
}
}
public interface Bench {
void init(WebDriver driver, String url);
void run(WebDriver driver, String url);
String getName();
}
private static class BenchRun implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
}
public void run(WebDriver driver, String url) {
WebElement element = driver.findElement(By.id("run"));
element.click();
}
public String getName() {
return "create 1000 rows";
}
}
private static class BenchRunHot implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
for (int i = 0; i< WARMUP_COUNT; i++) {
driver.findElement(By.id("run")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
}
}
public void run(WebDriver driver, String url) {
WebElement element = driver.findElement(By.id("run"));
element.click();
}
public String getName() {
return "update 1000 rows (hot)";
}
}
private static class BenchUpdate implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
element.click();
for (int i = 0; i< WARMUP_COUNT; i++) {
driver.findElement(By.id("update")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("update")));
}
}
public void run(WebDriver driver, String url) {
driver.findElement(By.id("update")).click();
}
public String getName() {
return "partial update";
}
}
private static class BenchSelect implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
element.click();
for (int i = 0; i< WARMUP_COUNT; i++) {
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//tbody/tr["+(i+1)+"]/td[2]/a")));
element.click();
}
}
public void run(WebDriver driver, String url) {
WebElement element = driver.findElement(By.xpath("//tbody/tr[1]/td[2]/a"));
element.click();
}
public String getName() {
return "select row";
}
}
private static class BenchRemove implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
element.click();
for (int i=3+WARMUP_COUNT;i>=3;i
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//tbody/tr["+i+"]/td[3]/a")));
element.click();
}
}
public void run(WebDriver driver, String url) {
WebElement element = driver.findElement(By.xpath("//tbody/tr[1]/td[3]/a"));
element.click();
}
public String getName() {
return "remove row";
}
}
private static class BenchHideAll implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
element.click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("hideall")));
}
public void run(WebDriver driver, String url) {
driver.findElement(By.id("hideall")).click();
}
public String getName() {
return "hide all";
}
}
private static class BenchShowAll implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
element.click();
element = wait.until(ExpectedConditions.elementToBeClickable(By.id("hideall")));
element.click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("showall")));
}
public void run(WebDriver driver, String url) {
driver.findElement(By.id("showall")).click();
}
public String getName() {
return "show all";
}
}
private static class BenchRunBig implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("runlots")));
}
public void run(WebDriver driver, String url) {
driver.findElement(By.id("runlots")).click();
}
public String getName() {
return "create lots of rows";
}
}
private static class BenchRunBigHot implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("runlots")));
element.click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("add")));
}
public void run(WebDriver driver, String url) {
driver.findElement(By.id("add")).click();
}
public String getName() {
return "add 1000 rows after lots of rows";
}
}
private static class BenchClear implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("runlots")));
element.click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("clear")));
}
public void run(WebDriver driver, String url) {
driver.findElement(By.id("clear")).click();
}
public String getName() {
return "clear rows";
}
}
private static class BenchClearHot implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("runlots")));
element.click();
element = wait.until(ExpectedConditions.elementToBeClickable(By.id("clear")));
element.click();
element = wait.until(ExpectedConditions.elementToBeClickable(By.id("runlots")));
element.click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("clear")));
}
public void run(WebDriver driver, String url) {
driver.findElement(By.id("clear")).click();
}
public String getName() {
return "clear rows a 2nd time";
}
}
private static class BenchSelectBig implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("runlots")));
element.click();
for (int i = 0; i< WARMUP_COUNT; i++) {
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//tbody/tr["+(i+1)+"]/td[2]/a")));
element.click();
}
}
public void run(WebDriver driver, String url) {
WebElement element = driver.findElement(By.xpath("//tbody/tr[1]/td[2]/a"));
element.click();
}
public String getName() {
return "select row on big list";
}
}
private static class BenchSwapRows implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
element.click();
for (int i = 0; i< WARMUP_COUNT; i+=2) {
driver.findElement(By.id("swaprows")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("swaprows")));
}
}
public void run(WebDriver driver, String url) {
driver.findElement(By.id("swaprows")).click();
}
public String getName() {
return "swap rows";
}
}
private static class BenchRecycle implements Bench {
public void init(WebDriver driver, String url) {
driver.get("localhost:8080/" + url + "/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
element.click();
element = wait.until(ExpectedConditions.elementToBeClickable(By.id("clear")));
element.click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
}
public void run(WebDriver driver, String url) {
driver.findElement(By.id("run")).click();
}
public String getName() {
return "recycle rows";
}
}
private void runTests() throws Exception {
DesiredCapabilities cap = setUp();
int length = REPEAT_RUN;
Table<String, String, DoubleSummaryStatistics> results = HashBasedTable.create();
for (Framework framework : frameworks) {
System.out.println(framework);
for (Bench bench : benches) {
System.out.println(bench.getName());
ChromeDriver driver = new ChromeDriver(cap);
try {
double[] data = new double[length];
double lastWait = 1000;
for (int i = 0; i < length; i++) {
System.out.println(framework.framework+" "+bench.getName()+" => init");
bench.init(driver, framework.url);
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
Thread.sleep(2000);
printLog(driver, false, "aurelia".equals(framework.framework));
System.out.println(framework.framework+" "+bench.getName()+" => run");
bench.run(driver, framework.url);
System.out.println("run " + bench.getName());
element = wait.until(ExpectedConditions.elementToBeClickable(By.id("run")));
Thread.sleep(1000 + (int) lastWait);
Double res = printLog(driver, true, "aurelia".equals(framework.framework));
if (res != null) {
data[i] = res.doubleValue();
lastWait = data[i];
}
}
System.out.println("before "+Arrays.toString(data));
if (DROP_WORST_RUN>0) {
Arrays.sort(data);
data = Arrays.copyOf(data, data.length-DROP_WORST_RUN);
System.out.println("after "+Arrays.toString(data));
}
DoubleSummaryStatistics stats = DoubleStream.of(data).summaryStatistics();
results.put(framework.framework, bench.getName(), stats);
} finally {
driver.quit();
}
}
logResult(framework.framework, results);
}
}
private void logResult(String framework, Table<String, String, DoubleSummaryStatistics> results) throws IOException {
NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
nf.setGroupingUsed(false);
if (!Files.exists(Paths.get("results"))) {
Files.createDirectories(Paths.get("results"));
}
StringBuilder line = new StringBuilder();
line.append("{").append("\"framework\": \"").append(framework).append("\", ")
.append("\"results\":[");
line.append(Arrays.stream(benches).map(bench ->
"{\"benchmark\": \""+bench.getName()+"\", "
+"\"min\": "+nf.format(results.get(framework, bench.getName()).getMin())+", "
+"\"max\": "+nf.format(results.get(framework, bench.getName()).getMax())+", "
+"\"avg\": "+nf.format(results.get(framework, bench.getName()).getAverage())+"}"
).collect(Collectors.joining(", ")));
line.append("]}");
Files.write(Paths.get("results",framework+".txt"), line.toString().getBytes("utf-8"));
System.out.println("==== Results for "+framework+" written to results directory");
}
public DesiredCapabilities setUp() throws Exception {
DesiredCapabilities cap = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
logPrefs.enable(LogType.BROWSER, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
Map<String, Object> perfLogPrefs = new HashMap<>();
perfLogPrefs.put("traceCategories", "browser,devtools.timeline,devtools"); // comma-separated trace categories
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("perfLoggingPrefs", perfLogPrefs);
options.setBinary(BINARY);
cap.setCapability(ChromeOptions.CAPABILITY, options);
return cap;
}
public String getAsString(JSONObject root, String path) {
return getAsStringRec(root, Arrays.asList(path.split("\\.")));
}
public double getAsLong(JSONObject root, String path) {
Double r = getAsLongRec(root, Arrays.asList(path.split("\\.")));
if (r==null) {
return 0;
} else {
return r.doubleValue();
}
}
public String getAsStringRec(JSONObject root, List<String> path) {
JSONObject obj = root;
if (!root.has(path.get(0)))
return null;
if (path.size()==1) {
return root.getString(path.get(0));
} else {
return getAsStringRec(root.getJSONObject(path.get(0)), path.subList(1, path.size()));
}
}
public Double getAsLongRec(JSONObject root, List<String> path) {
JSONObject obj = root;
if (!root.has(path.get(0)))
return null;
if (path.size()==1) {
return Double.valueOf(root.getDouble(path.get(0)));
} else {
return getAsLongRec(root.getJSONObject(path.get(0)), path.subList(1, path.size()));
}
}
Double printLog(WebDriver driver, boolean print, boolean isAurelia) throws Exception {
List<LogEntry> entries = driver.manage().logs().get(LogType.BROWSER).getAll();
System.out.println(entries.size() + " " + LogType.BROWSER + " log entries found");
for (LogEntry entry : entries) {
if (print) System.out.println(
new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
}
Logs logs = driver.manage().logs();
if (print) System.out.println("Log types: " + logs.getAvailableLogTypes());
List<PLogEntry> filtered = submitPerformanceResult(logs.get(LogType.PERFORMANCE).getAll(), false);
// Chrome 49 reports a Paint very short after the Event Dispatch which I can't find in the timeline
// it also seems to have a performance regression that can be seen in the timeline
// we're using the last paint event to fix measurement
Optional<PLogEntry> evt = filtered.stream().filter(pe -> "EventDispatch".equals(pe.getName())).findFirst();
long tsEvent = evt.map(pe -> pe.ts+pe.duration).orElse(0L);
// First TimerFire
Optional<PLogEntry> evtTimer = filtered.stream().filter(pe -> "TimerFire".equals(pe.getName())).filter(pe -> pe.ts > tsEvent).findFirst();
long tsEventFire = evtTimer.map(pe -> pe.ts+pe.duration).orElse(0L);
// First Paint after TimerFire only for Aurelia
long tsAfter = isAurelia && BINARY_VERSION > 48 ? tsEventFire : tsEvent;
Optional<PLogEntry> lastPaint = filtered.stream().filter(pe -> "Paint".equals(pe.getName())).
filter(pe -> pe.ts > tsAfter).reduce((p1,p2) -> p2);
if (print) System.out.println("************************ filtered events");
if (print) filtered.forEach(e -> System.out.println(e));
if (evt.isPresent() && lastPaint.isPresent()) {
if (print) System.out.println("Duration "+(lastPaint.get().ts + lastPaint.get().duration - evt.get().ts)/1000.0);
return (lastPaint.get().ts + lastPaint.get().duration - evt.get().ts)/1000.0;
}
return null;
}
List<PLogEntry> submitPerformanceResult(List<LogEntry> perfLogEntries, boolean print)
throws IOException, JSONException {
ArrayList<PLogEntry> filtered = new ArrayList<>();
if (print) System.out.println(perfLogEntries.size() + " performance log entries found");
for (LogEntry entry : perfLogEntries) {
JSONObject obj = new JSONObject(entry.getMessage());
String name = getAsString(obj, "message.params.name");
if (print) System.out.println(entry.getMessage());
if ("EventDispatch".equals(name)
&& "click".equals(getAsString(obj, "message.params.args.data.type"))
|| "Paint".equals(name)
|| "TimerFire".equals(name)) {
filtered.add(new PLogEntry(name,
(long)getAsLong(obj, "message.params.ts"),
(long)getAsLong(obj, "message.params.dur"),
entry.getMessage()));
}
}
return filtered;
}
public static void main(String[] argv) throws Exception {
Path root = Paths.get(BINARY).resolveSibling("../Versions").toAbsolutePath();
int length = root.toString().length();
Files.walk(root, 1).filter(Files::isDirectory).forEach(filePath -> {
String path = filePath.toString();
if(path.length() > length) {
path = path.substring(path.lastIndexOf("/") + 1);
int version = Integer.parseInt(path.substring(0, path.indexOf(".")));
if(version > BINARY_VERSION) {
BINARY_VERSION = version;
}
}
});
System.out.println("Running with " + Paths.get(BINARY).getFileName() + " v" + BINARY_VERSION);
System.setProperty("webdriver.chrome.driver", "node_modules/webdriver-manager/selenium/chromedriver");
App test = new App();
test.runTests();
}
} |
package to.etc.util;
import java.security.*;
import java.security.spec.*;
import javax.annotation.*;
public class SecurityUtils {
static public String encodeToHex(PrivateKey privk) {
byte[] enc = privk.getEncoded();
return StringTool.toHex(enc);
}
static public String encodeToHex(PublicKey pubk) {
byte[] enc = pubk.getEncoded();
return StringTool.toHex(enc);
}
static public String encodeToBase64(PrivateKey privk) {
byte[] enc = privk.getEncoded();
return StringTool.encodeBase64ToString(enc);
}
static public String encodeToBase64(PublicKey pubk) {
byte[] enc = pubk.getEncoded();
return StringTool.encodeBase64ToString(enc);
}
/**
* Decodes a public key from an encoded value.
* @param enc the hex string.
* @return a public key.
*/
static public PublicKey decodePublicKeyFromHex(String enc, String algo) throws Exception {
//-- 1. Decode the hex string into a byte array,
byte[] ba = StringTool.fromHex(enc);
if(!StringTool.toHex(ba).equalsIgnoreCase(enc))
throw new Exception("ASSERT: Problem with hex/binary translation");
//-- Array defined.
EncodedKeySpec pks = new X509EncodedKeySpec(ba); // Public keys are X509 encoded, of course: as clear as fog..
KeyFactory kf = KeyFactory.getInstance(algo);
return kf.generatePublic(pks);
}
/**
* Decodes a private key from an encoded value.
* @param enc the hex string.
* @return a public key.
*/
static public PrivateKey decodePrivateKeyFromHex(String enc, String algo) throws Exception {
//-- 1. Decode the hex string into a byte array,
byte[] ba = StringTool.fromHex(enc);
if(!StringTool.toHex(ba).equalsIgnoreCase(enc))
throw new Exception("ASSERT: Problem with hex/binary translation");
//-- Array defined.
EncodedKeySpec pks = new PKCS8EncodedKeySpec(ba); // Private keys are PKCS8 encoded.
KeyFactory kf = KeyFactory.getInstance(algo);
return kf.generatePrivate(pks);
}
/**
* Decodes a public key from an encoded value.
* @param enc the hex string.
* @return a public key.
*/
static public PublicKey decodePublicKeyFromHex(String enc) throws Exception {
return decodePublicKeyFromHex(enc, "DSA");
}
/**
* Decodes a private key from an encoded value.
* @param enc the hex string.
* @return a public key.
*/
static public PrivateKey decodePrivateKeyFromHex(String enc) throws Exception {
return decodePrivateKeyFromHex(enc, "DSA");
}
/**
* Decodes a public key from an encoded value.
* @param enc the hex string.
* @return a public key.
*/
static public PublicKey decodePublicKeyFromBase64(String enc) throws Exception {
return decodePublicKeyFromBase64(enc, "DSA");
}
/**
* Decodes a private key from an encoded value.
* @param enc the hex string.
* @return a public key.
*/
static public PrivateKey decodePrivateKeyFromBase64(String enc) throws Exception {
return decodePrivateKeyFromBase64(enc, "DSA");
}
/**
* Decodes a public key from an encoded value.
* @param enc the hex string.
* @return a public key.
*/
static public PublicKey decodePublicKeyFromBase64(String enc, String algo) throws Exception {
//-- 1. Decode the hex string into a byte array,
byte[] ba = StringTool.decodeBase64(enc);
EncodedKeySpec pks = new X509EncodedKeySpec(ba); // Public keys are X509 encoded, of course: as clear as fog..
KeyFactory kf = KeyFactory.getInstance(algo);
return kf.generatePublic(pks);
}
/**
* Decodes a private key from an encoded value.
* @param enc the hex string.
* @return a public key.
*/
static public PrivateKey decodePrivateKeyFromBase64(String enc, String algo) throws Exception {
//-- 1. Decode the hex string into a byte array,
byte[] ba = StringTool.decodeBase64(enc);
EncodedKeySpec pks = new PKCS8EncodedKeySpec(ba); // Private keys are PKCS8 encoded.
KeyFactory kf = KeyFactory.getInstance(algo);
return kf.generatePrivate(pks);
}
/* CODING: Hashing functions. */
/**
* Returns the MD5 hash for the data passed.
*/
static public byte[] md5Hash(byte[] data) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch(NoSuchAlgorithmException x) {
throw new RuntimeException("MISSING MANDATORY SECURITY DIGEST PROVIDER MD5: " + x.getMessage());
}
md.update(data);
return md.digest();
}
@Nonnull
static public String getMD5Hash(@Nonnull String in, @Nonnull String encoding) {
try {
byte[] hash = md5Hash(in.getBytes(encoding));
return StringTool.toHex(hash);
} catch(Exception x) {
throw WrappedException.wrap(x);
}
}
} |
package com.alfaariss.oa.sso;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.asimba.utility.web.URLPathContext;
import org.w3c.dom.Element;
import com.alfaariss.oa.OAException;
import com.alfaariss.oa.SystemErrors;
import com.alfaariss.oa.UserEvent;
import com.alfaariss.oa.UserException;
import com.alfaariss.oa.api.IComponent;
import com.alfaariss.oa.api.attribute.IAttributes;
import com.alfaariss.oa.api.attribute.ISessionAttributes;
import com.alfaariss.oa.api.attribute.ITGTAttributes;
import com.alfaariss.oa.api.authentication.IAuthenticationContexts;
import com.alfaariss.oa.api.authentication.IAuthenticationMethod;
import com.alfaariss.oa.api.authentication.IAuthenticationProfile;
import com.alfaariss.oa.api.configuration.IConfigurationManager;
import com.alfaariss.oa.api.persistence.PersistenceException;
import com.alfaariss.oa.api.requestor.IRequestor;
import com.alfaariss.oa.api.session.ISession;
import com.alfaariss.oa.api.session.SessionState;
import com.alfaariss.oa.api.tgt.ITGT;
import com.alfaariss.oa.api.user.IUser;
import com.alfaariss.oa.engine.core.Engine;
import com.alfaariss.oa.engine.core.attribute.UserAttributes;
import com.alfaariss.oa.engine.core.attribute.gather.AttributeGatherer;
import com.alfaariss.oa.engine.core.attribute.release.IAttributeReleasePolicy;
import com.alfaariss.oa.engine.core.attribute.release.factory.IAttributeReleasePolicyFactory;
import com.alfaariss.oa.engine.core.authentication.AuthenticationContexts;
import com.alfaariss.oa.engine.core.authentication.AuthenticationException;
import com.alfaariss.oa.engine.core.authentication.AuthenticationProfile;
import com.alfaariss.oa.engine.core.authentication.factory.IAuthenticationProfileFactory;
import com.alfaariss.oa.engine.core.requestor.RequestorPool;
import com.alfaariss.oa.engine.core.requestor.factory.IRequestorPoolFactory;
import com.alfaariss.oa.engine.core.session.factory.ISessionFactory;
import com.alfaariss.oa.engine.core.tgt.factory.ITGTFactory;
import com.alfaariss.oa.util.session.ProxyAttributes;
/**
* Authentication and SSO Service.
*
* Contains basic functionality that can be called from an SSO system
* e.g. WebSSO.
*
* @author mdobrinic
* @author EVB
* @author Alfa & Ariss
*
*/
public class SSOService implements IComponent
{
/**
* TGT Attribute name containing the Map<String, String> with the alias->idp.id mapping
* of remote IDPs that were used to authenticate the user in this SSO session
*/
public static final String TGT_ATTR_SHADOWED_IDPS = "shadowed_idps";
private boolean _bSingleSignOn;
private Log _systemLogger;
private IConfigurationManager _configurationManager;
private ISessionFactory<?> _sessionFactory;
private ITGTFactory<?> _tgtFactory;
private IRequestorPoolFactory _requestorPoolFactory;
private IAuthenticationProfileFactory _authenticationProfileFactory;
private AttributeGatherer _attributeGatherer;
private IAttributeReleasePolicyFactory _attributeReleasePolicyFactory;
/**
* Create a new SSO Service.
*/
public SSOService()
{
_systemLogger = LogFactory.getLog(SSOService.class);
_bSingleSignOn = true;
}
/**
* Start the SSO Service.
* @see IComponent#start(IConfigurationManager, org.w3c.dom.Element)
*/
public void start(IConfigurationManager oConfigurationManager,
Element eConfig) throws OAException
{
if(oConfigurationManager == null)
throw new IllegalArgumentException(
"Supplied ConfigurationManager is empty");
Engine engine = Engine.getInstance();
_configurationManager = oConfigurationManager;
_sessionFactory = engine.getSessionFactory();
_tgtFactory = engine.getTGTFactory();
_requestorPoolFactory = engine.getRequestorPoolFactory();
_authenticationProfileFactory =
engine.getAuthenticationProfileFactory();
_attributeGatherer = engine.getAttributeGatherer();
_attributeReleasePolicyFactory =
engine.getAttributeReleasePolicyFactory();
//SSO configuration
readDefaultConfiguration(eConfig);
_systemLogger.info("SSO Service started");
}
/**
* Restart the SSO Service.
* @see com.alfaariss.oa.api.IComponent#restart(org.w3c.dom.Element)
*/
public void restart(Element eConfig) throws OAException
{
synchronized(this)
{
//Get new components
Engine engine = Engine.getInstance();
_sessionFactory = engine.getSessionFactory();
_tgtFactory = engine.getTGTFactory();
_requestorPoolFactory = engine.getRequestorPoolFactory();
_authenticationProfileFactory =
engine.getAuthenticationProfileFactory();
//SSO
readDefaultConfiguration(eConfig);
_systemLogger.info("SSO Service restarted");
}
}
/**
* Stop the SSO Service.
* @see com.alfaariss.oa.api.IComponent#stop()
*/
public void stop()
{
_systemLogger.info("SSO Service stopped");
}
/**
* Retrieve an authentication session.
* @param sId The session ID.
* @return The session, or null if not found.
* @throws SSOException If retrieval fails.
*/
public ISession getSession(String sId) throws SSOException
{
try
{
return _sessionFactory.retrieve(sId);
}
catch (OAException e)
{
_systemLogger.warn("Could not retrieve session",e);
//wrap exception
throw new SSOException(e.getCode(), e);
}
}
/**
* Retrieve TGT.
* @param sTGTId The TGT ID.
* @return The TGT, or null if not found.
* @throws SSOException If retrieval fails.
*/
public ITGT getTGT(String sTGTId) throws SSOException
{
try
{
return _tgtFactory.retrieve(sTGTId);
}
catch (OAException e)
{
_systemLogger.warn("Could not retrieve TGT",e);
//wrap exception
throw new SSOException(e.getCode(), e);
}
}
/**
* Retrieve requestor pool for this authentication session.
* @param oSession The authentication session
* @return The requestor pool
* @throws SSOException if retrieval fails
*/
public RequestorPool getRequestorPool(ISession oSession) throws SSOException
{
try
{
return _requestorPoolFactory.getRequestorPool(
oSession.getRequestorId());
}
catch (OAException e)
{
_systemLogger.warn("Could not retrieve requestor pool",e);
//wrap exception
throw new SSOException(e.getCode(), e);
}
}
/**
* Retrieve requestor for this authentication session.
* @param sID The requestor id
* @return The requestor
* @throws SSOException if retrieval fails
* @since 1.0
*/
public IRequestor getRequestor(String sID) throws SSOException
{
try
{
return _requestorPoolFactory.getRequestor(sID);
}
catch (OAException e)
{
_systemLogger.warn("Could not retrieve requestor: " + sID, e);
//wrap exception
throw new SSOException(e.getCode());
}
}
/**
* Retrieve requestor for this authentication session.
* @param oSession The authentication session
* @return The requestor
* @throws SSOException if retrieval fails
*/
public IRequestor getRequestor(ISession oSession) throws SSOException
{
try
{
return _requestorPoolFactory.getRequestor(
oSession.getRequestorId());
}
catch (OAException e)
{
_systemLogger.warn("Could not retrieve requestor ",e);
//wrap exception
throw new SSOException(e.getCode(), e);
}
}
/**
* Retrieve all required authentication profiles for the supplied
* requestor pool.
*
* @param oRequestorPool the requestor pool
* @return List<AuthenticationProfile> containing the profiles
* @throws SSOException If retrieval fails
*/
public List<IAuthenticationProfile> getAllAuthNProfiles(
RequestorPool oRequestorPool) throws SSOException
{
try
{
List<IAuthenticationProfile> listProfiles = new Vector<IAuthenticationProfile>();
for (String sProfile: oRequestorPool.getAuthenticationProfileIDs())
{
IAuthenticationProfile oAuthNProfile =
_authenticationProfileFactory.getProfile(sProfile);
if(oAuthNProfile == null)
{
_systemLogger.warn(
"AuthN Profile not found: " + sProfile);
throw new OAException(SystemErrors.ERROR_INTERNAL);
}
if (oAuthNProfile.isEnabled())
listProfiles.add(oAuthNProfile);
}
return listProfiles;
}
catch (OAException e)
{
_systemLogger.warn("Could not retrieve AuthN profiles",e);
//wrap exception
throw new SSOException(e.getCode(), e);
}
}
/**
* Returns the authentication profile id.
* @param sID The ID of the Authentication Profile
* @return the specified IAuthenticationProfile
* @throws SSOException If authentication profile could not be retrieved.
* @since 1.0
*/
public IAuthenticationProfile getAuthNProfile(String sID)
throws SSOException
{
IAuthenticationProfile authenticationProfile = null;
try
{
authenticationProfile =
_authenticationProfileFactory.getProfile(sID);
}
catch (AuthenticationException e)
{
_systemLogger.warn("Could not retrieve AuthN profile: " + sID, e);
//wrap exception
throw new SSOException(e.getCode());
}
return authenticationProfile;
}
/**
* Retrieve selected profile.
*
* @param oSession The authentication session.
* @param sSelectedProfile The profile chosen by user
* @param bShowAllways Is the selection mandatory?
* @return Selected AuthenticationProfile or <code>null</code>
* @throws UserException If selection fails
* @throws SSOException If selection fails, due to internal error
*/
public IAuthenticationProfile getSelectedAuthNProfile(ISession oSession,
String sSelectedProfile, boolean bShowAllways)
throws UserException, SSOException
{
IAuthenticationProfile oSelectedProfile = null;
try
{
if (sSelectedProfile != null && oSession.getState() != SessionState.AUTHN_NOT_SUPPORTED)
{
List<IAuthenticationProfile> listRequiredProfiles = oSession.getAuthNProfiles();
oSelectedProfile = _authenticationProfileFactory.getProfile(sSelectedProfile);
if (oSelectedProfile == null)
{
_systemLogger.debug("Selected profile is not available: " + sSelectedProfile);
throw new UserException(UserEvent.AUTHN_PROFILE_NOT_AVAILABLE);
}
if (!oSelectedProfile.isEnabled())
{
_systemLogger.debug("Selected profile is disabled: " + sSelectedProfile);
throw new UserException(UserEvent.AUTHN_PROFILE_DISABLED);
}
if (!listRequiredProfiles.contains(oSelectedProfile))
{
_systemLogger.debug("Selected profile is not required: " + sSelectedProfile);
throw new UserException(UserEvent.AUTHN_PROFILE_INVALID);
}
oSession.setSelectedAuthNProfile(oSelectedProfile);
}
else
{
List<IAuthenticationProfile> listFilteredProfiles = filterRegisteredProfiles(oSession);
oSession.setAuthNProfiles(listFilteredProfiles);
if (oSession.getAuthNProfiles().size() == 1 && !bShowAllways)
{
oSelectedProfile = oSession.getAuthNProfiles().get(0);
oSession.setSelectedAuthNProfile(oSelectedProfile);
}
}
}
catch (UserException e)
{
throw e;
}
catch (Exception e)
{
_systemLogger.error("Internal error during retrieval the selected profile: "
+ sSelectedProfile, e);
throw new SSOException(SystemErrors.ERROR_INTERNAL);
}
return oSelectedProfile;
}
/**
* Handle the SSO process.
*
* Create or update a TGT, add all new methods to it, and persist TGT.
* @param oSession The authentication session.
* @return The created or updated TGT.
* @throws SSOException If creation fails.
*/
public ITGT handleSingleSignon(ISession oSession) throws SSOException
{
ITGT oTgt = null;
if(_bSingleSignOn) //SSO enabled
{
try
{
IAuthenticationProfile selectedAuthNProfile = oSession.getSelectedAuthNProfile();
//create or update TGT
String sTGT = oSession.getTGTId();
if(sTGT == null) //New TGT
{
oTgt = _tgtFactory.createTGT(oSession.getUser());
}
else //Update TGT
{
oTgt = _tgtFactory.retrieve(sTGT);
if (oTgt == null)
{
_systemLogger.warn("Could not retrieve TGT with id: " + sTGT);
throw new SSOException(SystemErrors.ERROR_INTERNAL);
}
}
//Add all new methods to TGT
List<IAuthenticationMethod> newMethods = selectedAuthNProfile.getAuthenticationMethods();
IAuthenticationProfile tgtProfile = oTgt.getAuthenticationProfile();
for(IAuthenticationMethod method : newMethods)
{
//DD Do not add duplicate authN methods in TGT profile
if(!tgtProfile.containsMethod(method))
{
// See whether there exists a method-specific disable sso override
if (! disableSSOForMethod(oSession, method.getID())) {
_systemLogger.debug("Adding "+method.getID()+" to TGT SSO methods");
tgtProfile.addAuthenticationMethod(method);
registerAuthenticationContext(oTgt, oSession, method);
} else {
_systemLogger.debug("Disabling SSO for method "+method.getID());
}
}
}
oTgt.setAuthenticationProfile(tgtProfile);
//Add current profile
List<String> tgtProfileIds = oTgt.getAuthNProfileIDs();
if (!tgtProfileIds.contains(selectedAuthNProfile.getID()))
{
//DD Do not add duplicate AuthN profile id in TGT
oTgt.addAuthNProfileID(selectedAuthNProfile.getID());
}
//update TGT with requestor id
addRequestorID(oTgt, oSession.getRequestorId());
//Keep track of a Shadowed IDP.id => real IDP.id mapping from the Session context
processShadowIDP(oTgt, oSession);
//Persist TGT
oTgt.persist();
oSession.setTGTId(oTgt.getId());
}
catch(SSOException e)
{
throw e;
}
catch(OAException e)
{
_systemLogger.warn("Could not update TGT", e);
//Wrap exception
throw new SSOException(e.getCode(), e);
}
catch (Exception e)
{
_systemLogger.error("Internal error during sso handling", e);
throw new SSOException(SystemErrors.ERROR_INTERNAL);
}
}
return oTgt;
}
/**
* Check the SSO session that might be present.
*
* Check the SSO session existence, expiration, and sufficiency.
* @param oSession The authentication session.
* @param sTGTId The TGT ID.
* @param oRequestorPool The requestor pool.
* @return <code>true</code> if TGT if sufficient.
* @throws SSOException If retrieval or persisting TGT fails
* @throws UserException If TGT user is invalid.
*/
public boolean checkSingleSignon(ISession oSession, String sTGTId,
RequestorPool oRequestorPool)
throws SSOException, UserException
{
boolean bTGTSufficient = false;
if(!_bSingleSignOn) //SSO enabled
{
_systemLogger.debug("SSO disabled");
}
else
{
if (sTGTId == null) // Check TGT Cookie
{
_systemLogger.debug("No valid TGT Cookie found");
}
else
{
// TGT Cookie found
try
{
//Retrieve TGT
ITGT oTgt = _tgtFactory.retrieve(sTGTId);
//Check tgt existence and expiration
if(oTgt == null || oTgt.isExpired()) //TGT valid
{
_systemLogger.debug("TGT expired and ignored");
}
else
{
//Check if a previous request was done for an other user-id
String forcedUserID = oSession.getForcedUserID();
IUser tgtUser = oTgt.getUser();
if(forcedUserID != null && tgtUser != null &&
!forcedUserID.equalsIgnoreCase(tgtUser.getID()))
//Forced user does not match TGT user
{
//Remove TGT itself
removeTGT(oTgt);
_systemLogger.warn("User in TGT and forced user do not correspond");
throw new UserException(UserEvent.TGT_USER_INVALID);
}
//Set previous TGT id and user in session
oSession.setTGTId(sTGTId);
oSession.setUser(oTgt.getUser());
//check ForcedAuthenticate
if(oSession.isForcedAuthentication()) //Forced authenticate
{
_systemLogger.debug("Forced authentication");
}
else
{
//Check if TGT profile is sufficient
IAuthenticationProfile tgtProfile = oTgt.getAuthenticationProfile();
List<String> oRequiredAuthenticationProfileIDs = oRequestorPool.getAuthenticationProfileIDs();
Iterator<String> iter = oRequiredAuthenticationProfileIDs.iterator();
while(iter.hasNext() && !bTGTSufficient)
{
//Retrieve next profile
AuthenticationProfile requiredProfile =
_authenticationProfileFactory.getProfile(iter.next());
if(requiredProfile != null && requiredProfile.isEnabled())
{
bTGTSufficient =
tgtProfile.compareTo(requiredProfile) >= 0;
}
}
// bTGTSufficient represents whether the executed authentication methods of a TGT
// are good enough for the profiles that are allowed for the requesting Requestor
// If this is the case, check if the Requestor has explicitly requested one or more
// specific AuthenticationProfiles, and if so, whether these are already performed
if (bTGTSufficient) {
@SuppressWarnings("unchecked")
List<String> requestedAuthnProfiles = (List<String>)
oSession.getAttributes().get(ProxyAttributes.class, ProxyAttributes.REQUESTED_AUTHNPROFILES);
if (requestedAuthnProfiles != null) {
iter = requestedAuthnProfiles.iterator();
boolean tgtProfileSatisfiesRequestedProfile = false;
while(iter.hasNext() && !tgtProfileSatisfiesRequestedProfile) {
AuthenticationProfile requestedAuthnProfile =
_authenticationProfileFactory.getProfile(iter.next());
if (requestedAuthnProfile != null) {
tgtProfileSatisfiesRequestedProfile =
tgtProfile.compareTo(requestedAuthnProfile) >= 0;
_systemLogger.debug("tgtProfile ("+tgtProfile.getAuthenticationMethods().toString()+") "+
(tgtProfileSatisfiesRequestedProfile ? "DOES" : "does NOT")+
" satisfy authentication profile '"+
requestedAuthnProfile.getID()+
"' ("+requestedAuthnProfile.getAuthenticationMethods().toString() + ")");
}
}
if (!tgtProfileSatisfiesRequestedProfile) {
_systemLogger.info("Do not resume SSO, as Requested AuthenticationProfile requires "+
"extra authentication methods to be performed.");
bTGTSufficient = false;
} else {
_systemLogger.info("Allow SSO, as TGT satisfies Requested AuthenticationProfile.");
}
}
}
}
if (bTGTSufficient)
{
// Is the request for a shadowed IDP, then see if this IDP was
// used before to authenticate the user. If not, do not resume session, but
// if so, set the shadowed IDP.id in the session
if (! matchShadowIDP(oTgt, oSession)) {
//Remove TGT itself
_systemLogger.warn("IDP in TGT and IDP-alias do not correspond; do not resume SSO session.");
bTGTSufficient = false;
}
}
if (bTGTSufficient)
{//update TGT with requestor id
addRequestorID(oTgt, oSession.getRequestorId());
// handle ShadowIDP feature
oTgt.persist();
}
}
}
catch(SSOException e)
{
throw e;
}
catch(OAException e)
{
_systemLogger.warn("Could not retrieve or update TGT", e);
//Wrap exception
throw new SSOException(e.getCode());
}
}
}
return bTGTSufficient;
}
/**
* Remove the TGT.
* @param oTgt The TGT to be removed.
* @throws SSOException If TGT persistance fails.
*/
public void removeTGT(ITGT oTgt) throws SSOException
{
//Remove TGT
oTgt.expire();
try
{
oTgt.persist();
}
catch (PersistenceException e)
{
_systemLogger.warn("Could not remove TGT", e);
//Wrap exception
throw new SSOException(e.getCode(), e);
}
}
/**
* Gathers attributes to the user object in the supplied session.
*
* @param oSession
* @throws OAException
* @since 1.4
*/
public void gatherAttributes(ISession oSession) throws OAException
{
if (_attributeGatherer != null &&
_attributeGatherer.isEnabled())
{
IUser oUser = oSession.getUser();
if (oUser != null)
_attributeGatherer.process(oUser.getID(), oUser.getAttributes());
}
}
/**
* Applies the attribute release policy over the userattributes available
* in the session.
*
* @param session The authentication session.
* @param sAttributeReleasePolicyID The release policy to be applied.
* @throws OAException If an internal error occurs.
* @since 1.4
*/
public void performAttributeReleasePolicy(ISession session,
String sAttributeReleasePolicyID) throws OAException
{
try
{
IAttributes oReleaseAttributes = new UserAttributes();
if (_attributeReleasePolicyFactory != null
&& _attributeReleasePolicyFactory.isEnabled()
&& sAttributeReleasePolicyID != null)
{
IAttributeReleasePolicy oAttributeReleasePolicy =
_attributeReleasePolicyFactory.getPolicy(sAttributeReleasePolicyID);
if (oAttributeReleasePolicy != null
&& oAttributeReleasePolicy.isEnabled())
{
_systemLogger.debug("applying attribute releasepolicy: " + sAttributeReleasePolicyID);
oReleaseAttributes =
oAttributeReleasePolicy.apply(session.getUser().getAttributes());
session.getUser().setAttributes(oReleaseAttributes);
}
}
//DD empty attributes object so only the attributes were the release policy is applied are available
IAttributes userAttributes = session.getUser().getAttributes();
Enumeration enumAttributes = userAttributes.getNames();
while (enumAttributes.hasMoreElements())
{
userAttributes.remove((String)enumAttributes.nextElement());
}
session.getUser().setAttributes(oReleaseAttributes);
}
catch(OAException e)
{
throw e;
}
catch (Exception e)
{
_systemLogger.fatal("Internal error during applying the attribute release policy", e);
throw new OAException(SystemErrors.ERROR_INTERNAL);
}
}
//Read standard configuration
private void readDefaultConfiguration(Element eConfig) throws OAException
{
assert eConfig != null : "Supplied config == null";
//SSO
_bSingleSignOn = true;
String sSingleSignOn = _configurationManager.getParam(eConfig, "single_sign_on");
if (sSingleSignOn != null)
{
if("false".equalsIgnoreCase(sSingleSignOn))
_bSingleSignOn = false;
else if (!"true".equalsIgnoreCase(sSingleSignOn))
{
_systemLogger.error("Invalid value for 'single_sign_on' item found in configuration: "
+ sSingleSignOn);
throw new OAException(SystemErrors.ERROR_CONFIG_READ);
}
}
_systemLogger.info("SSO enabled: " + _bSingleSignOn);
}
private List<IAuthenticationProfile> filterRegisteredProfiles(ISession oSession)
{
List<IAuthenticationProfile> listFilteredProfiles = new Vector<IAuthenticationProfile>();
IUser oUser = oSession.getUser();
if (oUser != null)
{
//AuthN Fallback: filter authN profiles with not registered methods if a user exists in session
for (IAuthenticationProfile oProfile: oSession.getAuthNProfiles())
{
boolean isRegistered = true;
for(IAuthenticationMethod oMethod : oProfile.getAuthenticationMethods())
{
if(!oUser.isAuthenticationRegistered(oMethod.getID()))
{
isRegistered = false;
break;//stop looping, check finished
}
}
if (isRegistered)
listFilteredProfiles.add(oProfile);
}
// At this point, listFilteredProfiles only contains the authentication profiles that contain all the
// authentication methods that are registered for the authenticated user
}
else
{
// Allow all profiles as set the session, if there was no user authenticated
listFilteredProfiles = oSession.getAuthNProfiles();
}
// Now apply requested authnprofiles filtering, when applicable
// Filtering here means: only allow profiles from requestedAuthnProfiles
@SuppressWarnings("unchecked")
List<String> requestedAuthnProfiles = (List<String>)
oSession.getAttributes().get(ProxyAttributes.class, ProxyAttributes.REQUESTED_AUTHNPROFILES);
if (requestedAuthnProfiles != null) {
IAuthenticationProfile authnProfile;
Iterator<IAuthenticationProfile> authnProfileIterator = listFilteredProfiles.iterator();
while (authnProfileIterator.hasNext()) {
authnProfile = authnProfileIterator.next();
if (! requestedAuthnProfiles.contains(authnProfile.getID())) {
authnProfileIterator.remove();
_systemLogger.info("Removing "+authnProfile.getID()+" from allowed authnprofiles for the user: "+
"doesn't match the requested authn profiles");
}
}
}
return listFilteredProfiles;
}
//add requestor id to the end of the list
private void addRequestorID(ITGT tgt, String requestorID)
{
List<String> listRequestorIDs = tgt.getRequestorIDs();
if (!listRequestorIDs.isEmpty() && listRequestorIDs.contains(requestorID))
tgt.removeRequestorID(requestorID);
//add to end of list
tgt.addRequestorID(requestorID);
}
/**
* Find out whether SSO should be disabled for this performed method. Decision
* is based on a Session attribute
* @param oSession
* @param sMethodId
* @return
*/
protected boolean disableSSOForMethod(ISession oSession, String sMethodId) {
ISessionAttributes oAttributes = oSession.getAttributes();
String sSessionKey = sMethodId + "." + "disable_sso";
if (oAttributes.contains(SSOService.class, sSessionKey)) {
String sSessionValue = (String) oAttributes.get(SSOService.class, sSessionKey);
if ("true".equalsIgnoreCase(sSessionValue)) {
return true;
}
}
return false;
}
/**
* Ensure that when a Shadowed IDP was used in Remote Authentication, that the alias->IDP.id
* is kept in a TGT attribute, so to be able to make the same mapping later again when an SSO-session
* is resumed.
*
* @param oTGT TGT to add the alias->IDP.id mapping to
* @param oSession Session where the IDP.id can be taken from
*/
protected void processShadowIDP(ITGT oTGT, ISession oSession)
{
ISessionAttributes oAttributes = oSession.getAttributes();
String sShadowedIDPId = (String)
oAttributes.get(ProxyAttributes.class, ProxyAttributes.PROXY_SHADOWED_IDPID);
if (sShadowedIDPId != null) {
URLPathContext oURLPathContext = (URLPathContext)
oAttributes.get(ProxyAttributes.class, ProxyAttributes.PROXY_URLPATH_CONTEXT);
String sIDPAlias = null;
if (oURLPathContext != null) sIDPAlias = oURLPathContext.getParams().get("i");
// Integrity check:
if (sIDPAlias == null) {
_systemLogger.warn("Found '"+ProxyAttributes.PROXY_SHADOWED_IDPID+"' in session but there was no '"+
ProxyAttributes.PROXY_URLPATH_CONTEXT+"' in session or no 'i'-value in URLPathContext; ignoring.");
return;
}
// Add the alias->idp.id to the map:
ITGTAttributes oTGTAttributes = oTGT.getAttributes();
@SuppressWarnings("unchecked")
Map<String, String> mShadowedIDPs = (Map<String, String>)
oTGTAttributes.get(SSOService.class, TGT_ATTR_SHADOWED_IDPS);
if (mShadowedIDPs == null) mShadowedIDPs = new HashMap<String, String>();
mShadowedIDPs.put(sIDPAlias, sShadowedIDPId);
_systemLogger.info("Adding "+sIDPAlias+"->"+sShadowedIDPId+" to TGT attribute '"+TGT_ATTR_SHADOWED_IDPS+"'");
oTGTAttributes.put(SSOService.class, TGT_ATTR_SHADOWED_IDPS, mShadowedIDPs);
return;
}
_systemLogger.debug("No '"+ProxyAttributes.PROXY_SHADOWED_IDPID+"' found in session attributes.");
}
/**
* Returns false when there is no match, or true when match was made or no match had to be made because
* not answering on behalf of a shadowed IDP
* @param oTGT
* @param oSession
*/
protected boolean matchShadowIDP(ITGT oTGT, ISession oSession)
{
ISessionAttributes oAttributes = oSession.getAttributes();
URLPathContext oURLContext = (URLPathContext) oAttributes.get(ProxyAttributes.class, ProxyAttributes.PROXY_URLPATH_CONTEXT);
if (oURLContext != null && oURLContext.getParams().containsKey("i")) {
String sIValue = oURLContext.getParams().get("i"); // contains the IDP alias
ITGTAttributes oTGTAttributes = oTGT.getAttributes();
@SuppressWarnings("unchecked")
Map<String, String> mShadowedIDPs = (Map<String, String>)
oTGTAttributes.get(SSOService.class, TGT_ATTR_SHADOWED_IDPS);
if (mShadowedIDPs == null) {
_systemLogger.warn("Found '"+ProxyAttributes.PROXY_URLPATH_CONTEXT+"' in session, but there is no" +
"record of a '"+TGT_ATTR_SHADOWED_IDPS+"' in the TGT attributes");
return false;
}
String sShadowedIDPId = (String) mShadowedIDPs.get(sIValue);
if (sShadowedIDPId == null) {
_systemLogger.warn("Did not find alias '"+sIValue+"' in map in TGT attributes");
return false;
}
// Put the shadowed IDP.id in the session
oAttributes.put(ProxyAttributes.class, ProxyAttributes.PROXY_SHADOWED_IDPID, sShadowedIDPId);
return true;
} else {
_systemLogger.debug("No '"+ProxyAttributes.PROXY_URLPATH_CONTEXT+"' or no \"i\"-value found in session attributes.");
return true;
}
}
/**
* If the session registered an AuthenticationContext, make sure that it is copied over to the
* TGT so it can later be reused.
*
* The TGT registers a Map: {String(AuthnMethod.id)->IAuthenticationContext, ...}
*
* @param oTgt TGT to store the AuthenticationContext in
* @param oSession Session to resolve the AuthenticationContext from
* @param oAuthnMethod AuthenticationMethod of which to find the AuthenticationContext
*/
private void registerAuthenticationContext(ITGT oTgt, ISession oSession, IAuthenticationMethod oAuthnMethod)
{
ISessionAttributes oSessionAttributes = oSession.getAttributes();
if (! oSessionAttributes.contains(AuthenticationContexts.class, AuthenticationContexts.ATTR_AUTHCONTEXTS)) {
_systemLogger.debug("The ISession did not contain AuthenticationContexts; skipping.");
return;
}
IAuthenticationContexts oSessionAuthenticationContexts =
(IAuthenticationContexts) oSessionAttributes.get(AuthenticationContexts.class, AuthenticationContexts.ATTR_AUTHCONTEXTS);
if (! oSessionAuthenticationContexts.contains(oAuthnMethod.getID())) {
_systemLogger.debug("The Session's AuthenticationContexts did not contain context for "
+oAuthnMethod.getID()+"; skipping.");
return;
}
IAuthenticationContexts oTGTAuthenticationContexts;
ITGTAttributes oTGTAttributes = oTgt.getAttributes();
if (! oTGTAttributes.contains(AuthenticationContexts.class, AuthenticationContexts.ATTR_AUTHCONTEXTS)) {
oTGTAuthenticationContexts = new AuthenticationContexts();
} else {
oTGTAuthenticationContexts =
(IAuthenticationContexts) oTGTAttributes.get(AuthenticationContexts.class, AuthenticationContexts.ATTR_AUTHCONTEXTS);
}
//Store Method's AuthenticationContext from Session into TGT:
oTGTAuthenticationContexts.setAuthenticationContext(
oAuthnMethod.getID(), oSessionAuthenticationContexts.getAuthenticationContext(oAuthnMethod.getID()));;
//Update the AuthenticationContexts in the TGT attributes:
oTGTAttributes.put(AuthenticationContexts.class, AuthenticationContexts.ATTR_AUTHCONTEXTS, oTGTAuthenticationContexts);
_systemLogger.debug("TGT AuthenticationContexts registered for "+oTGTAuthenticationContexts.getStoredAuthenticationMethods());
}
} |
package com.psddev.dari.db;
import java.net.URI;
import java.net.URL;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.psddev.dari.util.LocaleUtils;
import com.psddev.dari.util.ObjectToIterable;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.StringUtils;
/** Internal representations of all SQL index tables. */
public enum SqlIndex {
CUSTOM(
new AbstractTable(2, "id", "typeId", "symbolId", "value") {
@Override
public String getName(SqlDatabase database, ObjectIndex index) {
String name = SqlDatabase.Static.getIndexTable(index);
if (ObjectUtils.isBlank(name)) {
throw new IllegalStateException(String.format(
"[%s] needs @SqlDatabase.FieldIndexTable annotation!",
index));
} else {
return name;
}
}
@Override
public Object convertKey(SqlDatabase database, ObjectIndex index, String key) {
return database.getSymbolId(key);
}
@Override
public boolean isReadOnly(ObjectIndex index) {
List<String> indexFieldNames = index.getFields();
ObjectStruct parent = index.getParent();
for (String fieldName : indexFieldNames) {
ObjectField field = parent.getField(fieldName);
if (field != null) {
return field.as(SqlDatabase.FieldData.class).isIndexTableReadOnly();
}
}
return false;
}
@Override
public String getTypeIdField(SqlDatabase database, ObjectIndex index) {
if (database.hasColumn(getName(database, index), "typeId")) {
return "typeId";
} else {
return null;
}
}
}
),
LOCATION(
new NameSingleValueTable(1, "RecordLocation"),
new SymbolIdSingleValueTable(2, "RecordLocation2"),
new TypeIdSymbolIdSingleValueTable(3, "RecordLocation3")
),
REGION(
new SymbolIdSingleValueTable(1, "RecordRegion"),
new TypeIdSymbolIdSingleValueTable(2, "RecordRegion2")
),
NUMBER(
new NameSingleValueTable(1, "RecordNumber"),
new SymbolIdSingleValueTable(2, "RecordNumber2"),
new TypeIdSymbolIdSingleValueTable(3, "RecordNumber3")
),
STRING(
new NameSingleValueTable(1, "RecordString") {
@Override
protected Object convertValue(SqlDatabase database, ObjectIndex index, int fieldIndex, Object value) {
String string = value.toString();
return string.length() > 400 ? string.substring(0, 400) : string;
}
},
new SymbolIdSingleValueTable(2, "RecordString2") {
@Override
protected Object convertValue(SqlDatabase database, ObjectIndex index, int fieldIndex, Object value) {
return stringToBytes(value.toString(), 500);
}
},
new SymbolIdSingleValueTable(3, "RecordString3") {
@Override
protected Object convertValue(SqlDatabase database, ObjectIndex index, int fieldIndex, Object value) {
String valueString = value.toString().trim();
if (!index.isCaseSensitive()) {
valueString = valueString.toLowerCase(Locale.ENGLISH);
}
return stringToBytes(valueString, 500);
}
},
new TypeIdSymbolIdSingleValueTable(4, "RecordString4") {
@Override
protected Object convertValue(SqlDatabase database, ObjectIndex index, int fieldIndex, Object value) {
String valueString = StringUtils.trimAndCollapseWhitespaces(value.toString());
if (!index.isCaseSensitive()) {
valueString = valueString.toLowerCase(Locale.ENGLISH);
}
return stringToBytes(valueString, 500);
}
}
),
UUID(
new NameSingleValueTable(1, "RecordUuid"),
new SymbolIdSingleValueTable(2, "RecordUuid2"),
new TypeIdSymbolIdSingleValueTable(3, "RecordUuid3")
);
private final Table[] tables;
private SqlIndex(Table... tables) {
this.tables = tables;
}
/**
* Returns the table that can be used to read the values of the given
* {@code index} from the given {@code database}.
*/
public Table getReadTable(SqlDatabase database, ObjectIndex index) {
for (Table table : tables) {
if (database.hasTable(table.getName(database, index))) {
return table;
}
}
return tables[tables.length - 1];
}
/**
* Returns all tables that should be written to when updating the
* values of the index in the given {@code database}.
*/
public List<Table> getWriteTables(SqlDatabase database, ObjectIndex index) {
List<Table> writeTables = new ArrayList<Table>();
for (Table table : tables) {
if (database.hasTable(table.getName(database, index)) && !table.isReadOnly(index)) {
writeTables.add(table);
}
}
if (writeTables.isEmpty()) {
Table lastTable = tables[tables.length - 1];
if (!lastTable.isReadOnly(index)) {
writeTables.add(lastTable);
}
}
return writeTables;
}
public interface Table {
public int getVersion();
public boolean isReadOnly(ObjectIndex index);
public String getName(SqlDatabase database, ObjectIndex index);
public String getIdField(SqlDatabase database, ObjectIndex index);
public String getKeyField(SqlDatabase database, ObjectIndex index);
public String getValueField(SqlDatabase database, ObjectIndex index, int fieldIndex);
public String getTypeIdField(SqlDatabase database, ObjectIndex index);
public Object convertKey(SqlDatabase database, ObjectIndex index, String key);
public String prepareInsertStatement(
SqlDatabase database,
Connection connection,
ObjectIndex index) throws SQLException;
public void bindInsertValues(
SqlDatabase database,
ObjectIndex index,
UUID id,
UUID typeId,
IndexValue indexValue,
Set<String> bindKeys,
List<List<Object>> parameters) throws SQLException;
}
private abstract static class AbstractTable implements Table {
private final int version;
private final String idField;
private final String typeIdField;
private final String keyField;
private final String valueField;
public AbstractTable(int version, String idField, String typeIdField, String keyField, String valueField) {
this.version = version;
this.idField = idField;
this.typeIdField = typeIdField;
this.keyField = keyField;
this.valueField = valueField;
}
@Override
public int getVersion() {
return version;
}
@Override
public boolean isReadOnly(ObjectIndex index) {
return false;
}
@Override
public String getIdField(SqlDatabase database, ObjectIndex index) {
return idField;
}
@Override
public String getTypeIdField(SqlDatabase database, ObjectIndex index) {
return typeIdField;
}
@Override
public String getKeyField(SqlDatabase database, ObjectIndex index) {
return keyField;
}
@Override
public String getValueField(SqlDatabase database, ObjectIndex index, int fieldIndex) {
List<String> indexFieldNames = index.getFields();
ObjectStruct parent = index.getParent();
for (String fieldName : indexFieldNames) {
ObjectField field = parent.getField(fieldName);
if (field != null &&
field.as(SqlDatabase.FieldData.class).isIndexTableSameColumnNames()) {
String valueFieldName = indexFieldNames.get(fieldIndex);
int dotAt = valueFieldName.lastIndexOf(".");
if (dotAt > -1) {
valueFieldName = valueFieldName.substring(dotAt + 1);
}
return valueFieldName;
} else if (field != null &&
field.as(SqlDatabase.FieldData.class).getIndexTableColumnName() != null) {
return field.as(SqlDatabase.FieldData.class).getIndexTableColumnName();
}
}
return fieldIndex > 0 ? valueField + (fieldIndex + 1) : valueField;
}
@Override
public Object convertKey(SqlDatabase database, ObjectIndex index, String key) {
return key;
}
protected Object convertValue(SqlDatabase database, ObjectIndex index, int fieldIndex, Object value) {
ObjectStruct parent = index.getParent();
ObjectField field = parent.getField(index.getFields().get(fieldIndex));
String type = field.getInternalItemType();
if (ObjectField.DATE_TYPE.equals(type) ||
ObjectField.NUMBER_TYPE.equals(type) ||
ObjectField.LOCATION_TYPE.equals(type) ||
ObjectField.REGION_TYPE.equals(type)) {
return value;
} else if (value instanceof UUID) {
return value;
} else if (value instanceof String) {
String valueString = StringUtils.trimAndCollapseWhitespaces(value.toString());
if (!index.isCaseSensitive() && database.comparesIgnoreCase()) {
valueString = valueString.toLowerCase(Locale.ENGLISH);
}
return stringToBytes(valueString, 500);
} else {
return value.toString();
}
}
protected static byte[] stringToBytes(String value, int length) {
byte[] bytes = value.getBytes(StringUtils.UTF_8);
if (bytes.length <= length) {
return bytes;
} else {
byte[] shortened = new byte[length];
System.arraycopy(bytes, 0, shortened, 0, length);
return shortened;
}
}
@Override
public String prepareInsertStatement(
SqlDatabase database,
Connection connection,
ObjectIndex index) throws SQLException {
SqlVendor vendor = database.getVendor();
int fieldsSize = index.getFields().size();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT INTO ");
vendor.appendIdentifier(insertBuilder, getName(database, index));
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, getIdField(database, index));
insertBuilder.append(",");
if (getTypeIdField(database, index) != null) {
vendor.appendIdentifier(insertBuilder, getTypeIdField(database, index));
insertBuilder.append(",");
}
vendor.appendIdentifier(insertBuilder, getKeyField(database, index));
for (int i = 0; i < fieldsSize; ++ i) {
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, getValueField(database, index, i));
}
insertBuilder.append(") VALUES");
insertBuilder.append(" (?, ?, ");
if (getTypeIdField(database, index) != null) {
insertBuilder.append("?, ");
}
// Add placeholders for each value in this index.
for (int i = 0; i < fieldsSize; ++ i) {
if (i != 0) {
insertBuilder.append(", ");
}
if (SqlIndex.Static.getByIndex(index) == SqlIndex.LOCATION) {
vendor.appendBindLocation(insertBuilder, null, null);
} else if (SqlIndex.Static.getByIndex(index) == SqlIndex.REGION) {
vendor.appendBindRegion(insertBuilder, null, null);
} else {
insertBuilder.append("?");
}
}
insertBuilder.append(")");
return insertBuilder.toString();
}
public String prepareUpdateStatement(
SqlDatabase database,
Connection connection,
ObjectIndex index) throws SQLException {
SqlVendor vendor = database.getVendor();
int fieldsSize = index.getFields().size();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, getName(database, index));
updateBuilder.append(" SET ");
for (int i = 0; i < fieldsSize; ++ i) {
vendor.appendIdentifier(updateBuilder, getValueField(database, index, i));
updateBuilder.append(" = ");
if (SqlIndex.Static.getByIndex(index) == SqlIndex.LOCATION) {
vendor.appendBindLocation(updateBuilder, null, null);
} else if (SqlIndex.Static.getByIndex(index) == SqlIndex.REGION) {
vendor.appendBindRegion(updateBuilder, null, null);
} else {
updateBuilder.append("?");
}
updateBuilder.append(", ");
}
if (fieldsSize > 0) {
updateBuilder.setLength(updateBuilder.length() - 2);
}
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, getIdField(database, index));
updateBuilder.append(" = ?");
if (getTypeIdField(database, index) != null) {
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, getTypeIdField(database, index));
updateBuilder.append(" = ?");
}
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, getKeyField(database, index));
updateBuilder.append(" = ?");
return updateBuilder.toString();
}
@Override
public void bindInsertValues(
SqlDatabase database,
ObjectIndex index,
UUID id,
UUID typeId,
IndexValue indexValue,
Set<String> bindKeys,
List<List<Object>> parameters) throws SQLException {
SqlVendor vendor = database.getVendor();
Object indexKey = convertKey(database, index, indexValue.getUniqueName());
int fieldsSize = index.getFields().size();
StringBuilder insertBuilder = new StringBuilder();
boolean writeIndex = true;
for (Object[] valuesArray : indexValue.getValuesArray()) {
StringBuilder bindKeyBuilder = new StringBuilder();
bindKeyBuilder.append(id.toString());
bindKeyBuilder.append(indexKey);
for (int i = 0; i < fieldsSize; i++) {
Object parameter = convertValue(database, index, i, valuesArray[i]);
vendor.appendValue(bindKeyBuilder, parameter);
if (ObjectUtils.isBlank(parameter)) {
writeIndex = false;
break;
}
}
String bindKey = bindKeyBuilder.toString();
if (writeIndex && !bindKeys.contains(bindKey)) {
List<Object> rowData = new ArrayList<Object>();
vendor.appendBindValue(insertBuilder, id, rowData);
if (getTypeIdField(database, index) != null) {
vendor.appendBindValue(insertBuilder, typeId, rowData);
}
vendor.appendBindValue(insertBuilder, indexKey, rowData);
for (int i = 0; i < fieldsSize; i++) {
Object parameter = convertValue(database, index, i, valuesArray[i]);
vendor.appendBindValue(insertBuilder, parameter, rowData);
}
bindKeys.add(bindKey);
parameters.add(rowData);
}
}
}
public void bindUpdateValues(
SqlDatabase database,
ObjectIndex index,
UUID id,
UUID typeId,
IndexValue indexValue,
Set<String> bindKeys,
List<List<Object>> parameters) throws SQLException {
SqlVendor vendor = database.getVendor();
Object indexKey = convertKey(database, index, indexValue.getUniqueName());
int fieldsSize = index.getFields().size();
StringBuilder updateBuilder = new StringBuilder();
boolean writeIndex = true;
for (Object[] valuesArray : indexValue.getValuesArray()) {
StringBuilder bindKeyBuilder = new StringBuilder();
bindKeyBuilder.append(id.toString());
bindKeyBuilder.append(indexKey);
for (int i = 0; i < fieldsSize; i++) {
Object parameter = convertValue(database, index, i, valuesArray[i]);
vendor.appendValue(bindKeyBuilder, parameter);
if (ObjectUtils.isBlank(parameter)) {
writeIndex = false;
break;
}
}
String bindKey = bindKeyBuilder.toString();
if (writeIndex && !bindKeys.contains(bindKey)) {
List<Object> rowData = new ArrayList<Object>();
for (int i = 0; i < fieldsSize; i++) {
Object parameter = convertValue(database, index, i, valuesArray[i]);
vendor.appendBindValue(updateBuilder, parameter, rowData);
}
vendor.appendBindValue(updateBuilder, id, rowData);
if (getTypeIdField(database, index) != null) {
vendor.appendBindValue(updateBuilder, typeId, rowData);
}
vendor.appendBindValue(updateBuilder, indexKey, rowData);
bindKeys.add(bindKey);
parameters.add(rowData);
}
}
}
}
private static class SingleValueTable extends AbstractTable {
private String name;
public SingleValueTable(int version, String name, String idField, String typeIdField, String keyField, String valueField) {
super(version, idField, typeIdField, keyField, valueField);
this.name = name;
}
@Override
public String getName(SqlDatabase database, ObjectIndex index) {
return name;
}
}
private static class NameSingleValueTable extends SingleValueTable {
public NameSingleValueTable(int version, String name) {
super(version, name, "recordId", null, "name", "value");
}
}
private static class SymbolIdSingleValueTable extends SingleValueTable {
public SymbolIdSingleValueTable(int version, String name) {
super(version, name, "id", null, "symbolId", "value");
}
public SymbolIdSingleValueTable(int version, String name, String typeIdField) {
super(version, name, "id", typeIdField, "symbolId", "value");
}
@Override
public Object convertKey(SqlDatabase database, ObjectIndex index, String key) {
return database.getSymbolId(key);
}
}
private static class TypeIdSymbolIdSingleValueTable extends SymbolIdSingleValueTable {
public TypeIdSymbolIdSingleValueTable(int version, String name) {
super(version, name, "typeId");
}
}
public static final class IndexValue {
private final ObjectField[] prefixes;
private final ObjectIndex index;
private final Object[][] valuesArray;
private IndexValue(ObjectField[] prefixes, ObjectIndex index, Object[][] valuesArray) {
this.prefixes = prefixes;
this.index = index;
this.valuesArray = valuesArray;
}
public ObjectIndex getIndex() {
return index;
}
public Object[][] getValuesArray() {
return valuesArray;
}
/**
* Returns a unique name that identifies this index value.
* This is a helper method for database implementations and
* isn't meant for general consumption.
*/
public String getUniqueName() {
StringBuilder nameBuilder = new StringBuilder();
if (prefixes == null) {
if (index.getParent() instanceof ObjectType) {
nameBuilder.append(index.getJavaDeclaringClassName());
nameBuilder.append('/');
}
} else {
nameBuilder.append(prefixes[0].getUniqueName());
nameBuilder.append('/');
for (int i = 1, length = prefixes.length; i < length; ++ i) {
nameBuilder.append(prefixes[i].getInternalName());
nameBuilder.append('/');
}
}
Iterator<String> indexFieldsIterator = index.getFields().iterator();
nameBuilder.append(indexFieldsIterator.next());
while (indexFieldsIterator.hasNext()) {
nameBuilder.append(',');
nameBuilder.append(indexFieldsIterator.next());
}
return nameBuilder.toString();
}
public String getInternalType() {
List<String> fields = index.getFields();
return index.getParent().getField(fields.get(fields.size() - 1)).getInternalItemType();
}
}
/** {@linkplain SqlIndex} utility methods. */
public static final class Static {
/**
* Returns the instance that should be used to index values
* of the given field {@code type}.
*/
public static SqlIndex getByType(String type) {
if (ObjectField.DATE_TYPE.equals(type) ||
ObjectField.NUMBER_TYPE.equals(type)) {
return SqlIndex.NUMBER;
} else if (ObjectField.LOCATION_TYPE.equals(type)) {
return SqlIndex.LOCATION;
} else if (ObjectField.REGION_TYPE.equals(type)) {
return SqlIndex.REGION;
} else if (ObjectField.RECORD_TYPE.equals(type) ||
ObjectField.UUID_TYPE.equals(type)) {
return SqlIndex.UUID;
} else {
return SqlIndex.STRING;
}
}
/**
* Returns the instance that should be used to index values
* of the given {@code index}.
*/
public static SqlIndex getByIndex(ObjectIndex index) {
List<String> fieldNames = index.getFields();
ObjectField field = index.getParent().getField(fieldNames.get(0));
if (fieldNames.size() > 1 ||
(field != null &&
field.as(SqlDatabase.FieldData.class).getIndexTable() != null)) {
return SqlIndex.CUSTOM;
} else {
String type = field != null ? field.getInternalItemType() : index.getType();
return getByType(type);
}
}
/**
* Deletes all index rows associated with the given {@code states}.
*/
public static void deleteByStates(
SqlDatabase database,
Connection connection,
List<State> states)
throws SQLException {
deleteByStates(database, connection, null, states);
}
private static void deleteByStates(
SqlDatabase database,
Connection connection,
ObjectIndex onlyIndex,
List<State> states)
throws SQLException {
if (states == null || states.isEmpty()) {
return;
}
Set<ObjectStruct> structs = new HashSet<ObjectStruct>();
List<ObjectIndex> customIndexes = new ArrayList<ObjectIndex>();
SqlVendor vendor = database.getVendor();
StringBuilder idsBuilder = new StringBuilder(" IN (");
structs.add(database.getEnvironment());
for (State state : states) {
ObjectType type = state.getType();
if (type != null) {
structs.add(type);
}
vendor.appendUuid(idsBuilder, state.getId());
idsBuilder.append(",");
}
idsBuilder.setCharAt(idsBuilder.length() - 1, ')');
for (ObjectStruct struct : structs) {
for (ObjectIndex index : struct.getIndexes()) {
ObjectField field = index.getParent().getField(index.getFields().get(0));
if (field != null &&
(index.getFields().size() > 1 ||
field.as(SqlDatabase.FieldData.class).getIndexTable() != null)) {
customIndexes.add(index);
}
}
}
for (SqlIndex sqlIndex : SqlIndex.values()) {
if (sqlIndex != SqlIndex.CUSTOM) {
for (Table table : sqlIndex.getWriteTables(database, null)) {
StringBuilder deleteBuilder = new StringBuilder();
deleteBuilder.append("DELETE FROM ");
vendor.appendIdentifier(deleteBuilder, table.getName(database, onlyIndex));
deleteBuilder.append(" WHERE ");
vendor.appendIdentifier(deleteBuilder, table.getIdField(database, onlyIndex));
deleteBuilder.append(idsBuilder);
if (onlyIndex != null && table.getKeyField(database, onlyIndex) != null) {
deleteBuilder.append(" AND ");
vendor.appendIdentifier(deleteBuilder, table.getKeyField(database, onlyIndex));
deleteBuilder.append(" = ");
deleteBuilder.append(database.getSymbolId(onlyIndex.getUniqueName()));
}
SqlDatabase.Static.executeUpdateWithArray(connection, deleteBuilder.toString());
}
}
}
for (ObjectIndex index : customIndexes) {
if (onlyIndex != null && !onlyIndex.equals(index)) {
continue;
}
for (Table table : CUSTOM.getWriteTables(database, index)) {
StringBuilder deleteBuilder = new StringBuilder();
deleteBuilder.append("DELETE FROM ");
vendor.appendIdentifier(deleteBuilder, table.getName(database, index));
deleteBuilder.append(" WHERE ");
vendor.appendIdentifier(deleteBuilder, table.getIdField(database, index));
deleteBuilder.append(idsBuilder);
if (onlyIndex != null && table.getKeyField(database, onlyIndex) != null) {
deleteBuilder.append(" AND ");
vendor.appendIdentifier(deleteBuilder, table.getKeyField(database, onlyIndex));
deleteBuilder.append(" = ");
deleteBuilder.append(database.getSymbolId(onlyIndex.getUniqueName()));
}
SqlDatabase.Static.executeUpdateWithArray(connection, deleteBuilder.toString());
}
}
}
public static void updateByStates(
SqlDatabase database,
Connection connection,
ObjectIndex index,
List<State> states)
throws SQLException {
Map<String, String> updateQueries = new HashMap<String, String>();
Map<String, List<List<Object>>> updateParameters = new HashMap<String, List<List<Object>>>();
Map<String, Set<String>> updateBindKeys = new HashMap<String, Set<String>>();
Map<String, List<State>> updateStates = new HashMap<String, List<State>>();
Set<State> needDeletes = new HashSet<State>();
Set<State> needInserts = new HashSet<State>();
for (State state : states) {
UUID id = state.getId();
UUID typeId = state.getVisibilityAwareTypeId();
List<IndexValue> indexValues = new ArrayList<IndexValue>();
Map<String, Object> stateValues = state.getValues();
collectIndexValues(state, indexValues, null, state.getDatabase().getEnvironment(), stateValues, index);
ObjectType type = state.getType();
if (type != null) {
collectIndexValues(state, indexValues, null, type, stateValues, index);
}
for (IndexValue indexValue : indexValues) {
for (SqlIndex.Table table : getByIndex(index).getWriteTables(database, index)) {
String name = table.getName(database, index);
String sqlQuery = updateQueries.get(name);
List<List<Object>> parameters = updateParameters.get(name);
Set<String> bindKeys = updateBindKeys.get(name);
List<State> tableStates = updateStates.get(name);
if (sqlQuery == null && parameters == null && tableStates == null) {
if (table instanceof AbstractTable) {
sqlQuery = ((AbstractTable) table).prepareUpdateStatement(database, connection, index);
} else {
throw new IllegalStateException("Table " + table.getName(database, index) + " does not support updates.");
}
updateQueries.put(name, sqlQuery);
parameters = new ArrayList<List<Object>>();
updateParameters.put(name, parameters);
bindKeys = new HashSet<String>();
updateBindKeys.put(name, bindKeys);
tableStates = new ArrayList<State>();
updateStates.put(name, tableStates);
}
if (table instanceof AbstractTable) {
((AbstractTable) table).bindUpdateValues(database, index, id, typeId, indexValue, bindKeys, parameters);
tableStates.add(state);
} else {
throw new IllegalStateException("Table " + table.getName(database, index) + " does not support updates.");
}
}
}
if (indexValues.isEmpty()) {
needDeletes.add(state);
}
}
for (Map.Entry<String, String> entry : updateQueries.entrySet()) {
String name = entry.getKey();
String sqlQuery = entry.getValue();
List<List<Object>> parameters = updateParameters.get(name);
List<State> tableStates = updateStates.get(name);
try {
if (!parameters.isEmpty()) {
int[] rows = SqlDatabase.Static.executeBatchUpdate(connection, sqlQuery, parameters);
for (int i = 0; i < rows.length; i++) {
if (rows[i] == 0) {
needInserts.add(tableStates.get(i));
}
}
}
} catch (BatchUpdateException bue) {
SqlDatabase.Static.logBatchUpdateException(bue, sqlQuery, parameters);
throw bue;
}
}
if (!needDeletes.isEmpty()) {
deleteByStates(database, connection, index, new ArrayList<State>(needDeletes));
}
if (!needInserts.isEmpty()) {
List<State> insertStates = new ArrayList<State>(needInserts);
deleteByStates(database, connection, index, insertStates);
insertByStates(database, connection, index, insertStates);
}
}
/**
* Inserts all index rows associated with the given {@code states}.
*/
public static Map<State, String> insertByStates(
SqlDatabase database,
Connection connection,
List<State> states)
throws SQLException {
return insertByStates(database, connection, null, states);
}
private static Map<State, String> insertByStates(
SqlDatabase database,
Connection connection,
ObjectIndex onlyIndex,
List<State> states)
throws SQLException {
Map<State, String> inRowIndexes = new HashMap<State, String>();
if (states == null || states.isEmpty()) {
return inRowIndexes;
}
Map<String, String> insertQueries = new HashMap<String, String>();
Map<String, List<List<Object>>> insertParameters = new HashMap<String, List<List<Object>>>();
Map<String, Set<String>> insertBindKeys = new HashMap<String, Set<String>>();
for (State state : states) {
UUID id = state.getId();
UUID typeId = state.getVisibilityAwareTypeId();
for (IndexValue indexValue : getIndexValues(state)) {
ObjectIndex index = indexValue.getIndex();
if (onlyIndex != null && !onlyIndex.equals(index)) {
continue;
}
if (database.hasInRowIndex() && index.isShortConstant()) {
StringBuilder inRowIndex = new StringBuilder();
String current = inRowIndexes.get(state);
if (current != null) {
inRowIndex.append(current);
} else {
inRowIndex.append(';');
}
int nameId = database.getSymbolId(index.getUniqueName());
for (Object[] values : indexValue.getValuesArray()) {
StringBuilder tokenBuilder = new StringBuilder();
tokenBuilder.append(nameId);
tokenBuilder.append("=");
tokenBuilder.append(database.getSymbolId(values[0].toString()));
tokenBuilder.append(";");
String token = tokenBuilder.toString();
if (inRowIndex.indexOf(";" + token) < 0) {
inRowIndex.append(token);
}
}
inRowIndexes.put(state, inRowIndex.toString());
continue;
}
for (SqlIndex.Table table : getByIndex(index).getWriteTables(database, index)) {
String name = table.getName(database, index);
String sqlQuery = insertQueries.get(name);
List<List<Object>> parameters = insertParameters.get(name);
Set<String> bindKeys = insertBindKeys.get(name);
if (sqlQuery == null && parameters == null) {
sqlQuery = table.prepareInsertStatement(database, connection, index);
insertQueries.put(name, sqlQuery);
parameters = new ArrayList<List<Object>>();
insertParameters.put(name, parameters);
bindKeys = new HashSet<String>();
insertBindKeys.put(name, bindKeys);
}
table.bindInsertValues(database, index, id, typeId, indexValue, bindKeys, parameters);
}
}
}
for (Map.Entry<String, String> entry : insertQueries.entrySet()) {
String name = entry.getKey();
String sqlQuery = entry.getValue();
List<List<Object>> parameters = insertParameters.get(name);
try {
if (!parameters.isEmpty()) {
SqlDatabase.Static.executeBatchUpdate(connection, sqlQuery, parameters);
}
} catch (BatchUpdateException bue) {
SqlDatabase.Static.logBatchUpdateException(bue, sqlQuery, parameters);
throw bue;
}
}
return inRowIndexes;
}
/**
* Returns a list of indexable values in this state. This is a helper
* method for database implementations and isn't meant for general
* consumption.
*/
public static List<IndexValue> getIndexValues(State state) {
List<IndexValue> indexValues = new ArrayList<IndexValue>();
Map<String, Object> values = state.getValues();
collectIndexValues(state, indexValues, null, state.getDatabase().getEnvironment(), values);
ObjectType type = state.getType();
if (type != null) {
collectIndexValues(state, indexValues, null, type, values);
}
return indexValues;
}
private static void collectIndexValues(
State state,
List<IndexValue> indexValues,
ObjectField[] prefixes,
ObjectStruct struct,
Map<String, Object> stateValues,
ObjectIndex index) {
List<Set<Object>> valuesList = new ArrayList<Set<Object>>();
for (String fieldName : index.getFields()) {
ObjectField field = struct.getField(fieldName);
if (field == null) {
return;
}
Set<Object> values = new HashSet<Object>();
Object fieldValue = field instanceof ObjectMethod ? state.getByPath(field.getInternalName()) : stateValues.get(field.getInternalName());
collectFieldValues(state, indexValues, prefixes, struct, field, values, fieldValue);
if (values.isEmpty()) {
return;
}
valuesList.add(values);
}
int valuesListSize = valuesList.size();
int permutationSize = 1;
for (Set<Object> values : valuesList) {
permutationSize *= values.size();
}
// Calculate all permutations on multi-field indexes.
Object[][] permutations = new Object[permutationSize][valuesListSize];
int partitionSize = permutationSize;
for (int i = 0; i < valuesListSize; ++ i) {
Set<Object> values = valuesList.get(i);
int valuesSize = values.size();
partitionSize /= valuesSize;
for (int p = 0; p < permutationSize;) {
for (Object value : values) {
for (int k = 0; k < partitionSize; ++ k, ++ p) {
permutations[p][i] = value;
}
}
}
}
indexValues.add(new IndexValue(prefixes, index, permutations));
}
private static void collectIndexValues(
State state,
List<IndexValue> indexValues,
ObjectField[] prefixes,
ObjectStruct struct,
Map<String, Object> stateValues) {
for (ObjectIndex index : struct.getIndexes()) {
collectIndexValues(state, indexValues, prefixes, struct, stateValues, index);
}
}
private static void collectFieldValues(
State state,
List<IndexValue> indexValues,
ObjectField[] prefixes,
ObjectStruct struct,
ObjectField field,
Set<Object> values,
Object value) {
if (value == null) {
return;
}
Iterable<Object> valueIterable = ObjectToIterable.iterable(value);
if (valueIterable != null) {
for (Object item : valueIterable) {
collectFieldValues(state, indexValues, prefixes, struct, field, values, item);
}
} else if (value instanceof Map) {
for (Object item : ((Map<?, ?>) value).values()) {
collectFieldValues(state, indexValues, prefixes, struct, field, values, item);
}
} else if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
if (ObjectField.RECORD_TYPE.equals(field.getInternalItemType())) {
ObjectType valueType = valueState.getType();
if (field.isEmbedded() ||
(valueType != null && valueType.isEmbedded())) {
int last;
ObjectField[] newPrefixes;
if (prefixes != null) {
last = prefixes.length;
newPrefixes = new ObjectField[last + 1];
System.arraycopy(prefixes, 0, newPrefixes, 0, last);
} else {
newPrefixes = new ObjectField[1];
last = 0;
}
newPrefixes[last] = field;
collectIndexValues(state, indexValues, newPrefixes, state.getDatabase().getEnvironment(), valueState.getValues());
collectIndexValues(state, indexValues, newPrefixes, valueType, valueState.getValues());
} else {
values.add(valueState.getId());
}
} else {
values.add(valueState.getId());
}
} else if (value instanceof Character ||
value instanceof CharSequence ||
value instanceof URI ||
value instanceof URL) {
values.add(value.toString());
} else if (value instanceof Date) {
values.add(((Date) value).getTime());
} else if (value instanceof Enum) {
values.add(((Enum<?>) value).name());
} else if (value instanceof Locale) {
values.add(LocaleUtils.toLanguageTag((Locale) value));
} else {
values.add(value);
}
}
/** Use {@link #getByType} instead. */
@Deprecated
public static SqlIndex getInstance(String type) {
return getByType(type);
}
/** Use {@link #getByIndex} instead. */
@Deprecated
public static SqlIndex getInstance(ObjectIndex index) {
return getByIndex(index);
}
}
} |
package com.psddev.dari.db;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
/** Internal representation of an SQL query based on a Dari one. */
class SqlQuery {
private static final Pattern QUERY_KEY_PATTERN = Pattern.compile("\\$\\{([^}]+)\\}");
//private static final Logger LOGGER = LoggerFactory.getLogger(SqlQuery.class);
private final SqlDatabase database;
private final Query<?> query;
private final String aliasPrefix;
private final SqlVendor vendor;
private final String recordIdField;
private final String recordTypeIdField;
private final String recordInRowIndexField;
private final Map<String, Query.MappedKey> mappedKeys;
private final Map<String, ObjectIndex> selectedIndexes;
private String selectClause;
private String fromClause;
private String whereClause;
private String groupByClause;
private String havingClause;
private String orderByClause;
private String extraSourceColumns;
private final List<String> orderBySelectColumns = new ArrayList<String>();
private final Map<String, String> groupBySelectColumnAliases = new LinkedHashMap<String, String>();
private final List<Join> joins = new ArrayList<Join>();
private final Map<Query<?>, String> subQueries = new LinkedHashMap<Query<?>, String>();
private final Map<Query<?>, SqlQuery> subSqlQueries = new HashMap<Query<?>, SqlQuery>();
private boolean needsDistinct;
private Join mysqlIndexHint;
private boolean mysqlIgnoreIndexPrimaryDisabled;
private boolean forceLeftJoins;
private final List<Predicate> recordMetricDatePredicates = new ArrayList<Predicate>();
private final List<Predicate> recordMetricParentDatePredicates = new ArrayList<Predicate>();
private final List<Predicate> recordMetricDimensionPredicates = new ArrayList<Predicate>();
private final List<Predicate> recordMetricParentDimensionPredicates = new ArrayList<Predicate>();
private final List<Predicate> recordMetricHavingPredicates = new ArrayList<Predicate>();
private final List<Predicate> recordMetricParentHavingPredicates = new ArrayList<Predicate>();
private final List<Sorter> recordMetricSorters = new ArrayList<Sorter>();
private ObjectField recordMetricField;
private final Map<String, String> reverseAliasSql = new HashMap<String, String>();
private final List<Predicate> havingPredicates = new ArrayList<Predicate>();
private final List<Predicate> parentHavingPredicates = new ArrayList<Predicate>();
/**
* Creates an instance that can translate the given {@code query}
* with the given {@code database}.
*/
public SqlQuery(
SqlDatabase initialDatabase,
Query<?> initialQuery,
String initialAliasPrefix) {
database = initialDatabase;
query = initialQuery;
aliasPrefix = initialAliasPrefix;
vendor = database.getVendor();
recordIdField = aliasedField("r", SqlDatabase.ID_COLUMN);
recordTypeIdField = aliasedField("r", SqlDatabase.TYPE_ID_COLUMN);
recordInRowIndexField = aliasedField("r", SqlDatabase.IN_ROW_INDEX_COLUMN);
mappedKeys = query.mapEmbeddedKeys(database.getEnvironment());
selectedIndexes = new HashMap<String, ObjectIndex>();
for (Map.Entry<String, Query.MappedKey> entry : mappedKeys.entrySet()) {
selectIndex(entry.getKey(), entry.getValue());
}
}
private void selectIndex(String queryKey, Query.MappedKey mappedKey) {
ObjectIndex selectedIndex = null;
int maxMatchCount = 0;
for (ObjectIndex index : mappedKey.getIndexes()) {
List<String> indexFields = index.getFields();
int matchCount = 0;
for (Query.MappedKey mk : mappedKeys.values()) {
ObjectField mkf = mk.getField();
if (mkf != null && indexFields.contains(mkf.getInternalName())) {
++ matchCount;
}
}
if (matchCount > maxMatchCount) {
selectedIndex = index;
maxMatchCount = matchCount;
}
}
if (selectedIndex != null) {
if (maxMatchCount == 1) {
for (ObjectIndex index : mappedKey.getIndexes()) {
if (index.getFields().size() == 1) {
selectedIndex = index;
break;
}
}
}
selectedIndexes.put(queryKey, selectedIndex);
}
}
public SqlQuery(SqlDatabase initialDatabase, Query<?> initialQuery) {
this(initialDatabase, initialQuery, "");
}
private String aliasedField(String alias, String field) {
if (field == null) {
return null;
}
StringBuilder fieldBuilder = new StringBuilder();
fieldBuilder.append(aliasPrefix);
fieldBuilder.append(alias);
fieldBuilder.append('.');
vendor.appendIdentifier(fieldBuilder, field);
return fieldBuilder.toString();
}
private SqlQuery getOrCreateSubSqlQuery(Query<?> subQuery, boolean forceLeftJoins) {
SqlQuery subSqlQuery = subSqlQueries.get(subQuery);
if (subSqlQuery == null) {
subSqlQuery = new SqlQuery(database, subQuery, aliasPrefix + "s" + subSqlQueries.size());
subSqlQuery.forceLeftJoins = forceLeftJoins;
subSqlQuery.initializeClauses();
subSqlQueries.put(subQuery, subSqlQuery);
}
return subSqlQuery;
}
/** Initializes FROM, WHERE, and ORDER BY clauses. */
private void initializeClauses() {
// Determine whether any of the fields are sourced somewhere else.
Set<ObjectField> sourceTables = new HashSet<ObjectField>();
Set<ObjectType> queryTypes = query.getConcreteTypes(database.getEnvironment());
for (ObjectType type : queryTypes) {
for (ObjectField field : type.getFields()) {
SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class);
if (fieldData.isIndexTableSource() &&
fieldData.getIndexTable() != null &&
!field.isMetric()) {
// TODO/performance: if this is a count(), don't join to this table.
// if this is a groupBy() and they don't want to group by
// a field in this table, don't join to this table.
sourceTables.add(field);
}
}
}
@SuppressWarnings("unchecked")
Set<UUID> unresolvedTypeIds = (Set<UUID>) query.getOptions().get(State.UNRESOLVED_TYPE_IDS_QUERY_OPTION);
if (unresolvedTypeIds != null) {
DatabaseEnvironment environment = database.getEnvironment();
for (UUID typeId : unresolvedTypeIds) {
ObjectType type = environment.getTypeById(typeId);
if (type != null) {
for (ObjectField field : type.getFields()) {
SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class);
if (fieldData.isIndexTableSource() && fieldData.getIndexTable() != null && !field.isMetric()) {
sourceTables.add(field);
}
}
}
}
}
String extraJoins = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_JOINS_QUERY_OPTION));
if (extraJoins != null) {
Matcher queryKeyMatcher = QUERY_KEY_PATTERN.matcher(extraJoins);
int lastEnd = 0;
StringBuilder newExtraJoinsBuilder = new StringBuilder();
while (queryKeyMatcher.find()) {
newExtraJoinsBuilder.append(extraJoins.substring(lastEnd, queryKeyMatcher.start()));
lastEnd = queryKeyMatcher.end();
String queryKey = queryKeyMatcher.group(1);
Query.MappedKey mappedKey = query.mapEmbeddedKey(database.getEnvironment(), queryKey);
mappedKeys.put(queryKey, mappedKey);
selectIndex(queryKey, mappedKey);
Join join = getJoin(queryKey);
join.type = JoinType.LEFT_OUTER;
newExtraJoinsBuilder.append(join.getValueField(queryKey, null));
}
newExtraJoinsBuilder.append(extraJoins.substring(lastEnd));
extraJoins = newExtraJoinsBuilder.toString();
}
// Builds the WHERE clause.
StringBuilder whereBuilder = new StringBuilder();
whereBuilder.append("\nWHERE ");
String extraWhere = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_WHERE_QUERY_OPTION));
if (!ObjectUtils.isBlank(extraWhere)) {
whereBuilder.append('(');
}
whereBuilder.append("1 = 1");
if (!query.isFromAll()) {
Set<UUID> typeIds = query.getConcreteTypeIds(database);
whereBuilder.append("\nAND ");
if (typeIds.isEmpty()) {
whereBuilder.append("0 = 1");
} else {
whereBuilder.append(recordTypeIdField);
whereBuilder.append(" IN (");
for (UUID typeId : typeIds) {
vendor.appendValue(whereBuilder, typeId);
whereBuilder.append(", ");
}
whereBuilder.setLength(whereBuilder.length() - 2);
whereBuilder.append(')');
}
}
Predicate predicate = query.getPredicate();
if (predicate != null) {
StringBuilder childBuilder = new StringBuilder();
addWherePredicate(childBuilder, predicate, null, false, true);
if (childBuilder.length() > 0) {
whereBuilder.append("\nAND (");
whereBuilder.append(childBuilder);
whereBuilder.append(')');
}
}
if (!ObjectUtils.isBlank(extraWhere)) {
whereBuilder.append(") ");
whereBuilder.append(extraWhere);
}
// Builds the ORDER BY clause.
StringBuilder orderByBuilder = new StringBuilder();
for (Sorter sorter : query.getSorters()) {
addOrderByClause(orderByBuilder, sorter, true, false);
}
if (orderByBuilder.length() > 0) {
orderByBuilder.setLength(orderByBuilder.length() - 2);
orderByBuilder.insert(0, "\nORDER BY ");
}
// Builds the FROM clause.
StringBuilder fromBuilder = new StringBuilder();
HashMap<String, String> joinTableAliases = new HashMap<String, String>();
for (Join join : joins) {
if (join.indexKeys.isEmpty()) {
continue;
}
for (String indexKey : join.indexKeys) {
joinTableAliases.put(join.getTableName().toLowerCase(Locale.ENGLISH) + join.quoteIndexKey(indexKey), join.getAlias());
}
// e.g. JOIN RecordIndex AS i
fromBuilder.append('\n');
fromBuilder.append((forceLeftJoins ? JoinType.LEFT_OUTER : join.type).token);
fromBuilder.append(' ');
fromBuilder.append(join.table);
if (join.type == JoinType.INNER && join.equals(mysqlIndexHint)) {
fromBuilder.append(" /*! USE INDEX (k_name_value) */");
} else if (join.sqlIndex == SqlIndex.LOCATION &&
join.sqlIndexTable.getVersion() >= 2) {
fromBuilder.append(" /*! IGNORE INDEX (PRIMARY) */");
}
if ((join.sqlIndex == SqlIndex.LOCATION && join.sqlIndexTable.getVersion() < 3) ||
(join.sqlIndex == SqlIndex.NUMBER && join.sqlIndexTable.getVersion() < 3) ||
(join.sqlIndex == SqlIndex.STRING && join.sqlIndexTable.getVersion() < 4) ||
(join.sqlIndex == SqlIndex.UUID && join.sqlIndexTable.getVersion() < 3)) {
mysqlIgnoreIndexPrimaryDisabled = true;
}
// e.g. ON i#.recordId = r.id
fromBuilder.append(" ON ");
fromBuilder.append(join.idField);
fromBuilder.append(" = ");
fromBuilder.append(aliasPrefix);
fromBuilder.append("r.");
vendor.appendIdentifier(fromBuilder, "id");
// AND i#.typeId = r.typeId
if (join.typeIdField != null) {
fromBuilder.append(" AND ");
fromBuilder.append(join.typeIdField);
fromBuilder.append(" = ");
fromBuilder.append(aliasPrefix);
fromBuilder.append("r.");
vendor.appendIdentifier(fromBuilder, "typeId");
}
// AND i#.symbolId in (...)
fromBuilder.append(" AND ");
fromBuilder.append(join.keyField);
fromBuilder.append(" IN (");
for (String indexKey : join.indexKeys) {
fromBuilder.append(join.quoteIndexKey(indexKey));
fromBuilder.append(", ");
}
fromBuilder.setLength(fromBuilder.length() - 2);
fromBuilder.append(')');
}
StringBuilder extraColumnsBuilder = new StringBuilder();
Set<String> sourceTableColumns = new HashSet<String>();
for (ObjectField field : sourceTables) {
SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class);
StringBuilder sourceTableNameBuilder = new StringBuilder();
vendor.appendIdentifier(sourceTableNameBuilder, fieldData.getIndexTable());
String sourceTableName = sourceTableNameBuilder.toString();
String sourceTableAlias;
StringBuilder keyNameBuilder = new StringBuilder(field.getParentType().getInternalName());
keyNameBuilder.append('/');
keyNameBuilder.append(field.getInternalName());
Query.MappedKey key = query.mapEmbeddedKey(database.getEnvironment(), keyNameBuilder.toString());
ObjectIndex useIndex = null;
for (ObjectIndex index : key.getIndexes()) {
if (field.getInternalName().equals(index.getFields().get(0))) {
useIndex = index;
break;
}
}
if (useIndex == null) {
continue;
}
int symbolId = database.getSymbolId(key.getIndexKey(useIndex));
String sourceTableAndSymbol = fieldData.getIndexTable().toLowerCase(Locale.ENGLISH) + symbolId;
SqlIndex useSqlIndex = SqlIndex.Static.getByIndex(useIndex);
SqlIndex.Table indexTable = useSqlIndex.getReadTable(database, useIndex);
// This table hasn't been joined to for this symbol yet.
if (!joinTableAliases.containsKey(sourceTableAndSymbol)) {
sourceTableAlias = sourceTableAndSymbol;
fromBuilder.append(" LEFT OUTER JOIN ");
fromBuilder.append(sourceTableName);
fromBuilder.append(" AS ");
vendor.appendIdentifier(fromBuilder, sourceTableAlias);
fromBuilder.append(" ON ");
vendor.appendIdentifier(fromBuilder, sourceTableAlias);
fromBuilder.append('.');
vendor.appendIdentifier(fromBuilder, "id");
fromBuilder.append(" = ");
fromBuilder.append(aliasPrefix);
fromBuilder.append("r.");
vendor.appendIdentifier(fromBuilder, "id");
fromBuilder.append(" AND ");
vendor.appendIdentifier(fromBuilder, sourceTableAlias);
fromBuilder.append('.');
vendor.appendIdentifier(fromBuilder, "symbolId");
fromBuilder.append(" = ");
fromBuilder.append(symbolId);
joinTableAliases.put(sourceTableAndSymbol, sourceTableAlias);
} else {
sourceTableAlias = joinTableAliases.get(sourceTableAndSymbol);
}
// Add columns to select.
int fieldIndex = 0;
for (String indexFieldName : useIndex.getFields()) {
if (sourceTableColumns.contains(indexFieldName)) {
continue;
}
sourceTableColumns.add(indexFieldName);
String indexColumnName = indexTable.getValueField(database, useIndex, fieldIndex);
++ fieldIndex;
query.getExtraSourceColumns().put(indexFieldName, indexFieldName);
extraColumnsBuilder.append(sourceTableAlias);
extraColumnsBuilder.append('.');
vendor.appendIdentifier(extraColumnsBuilder, indexColumnName);
extraColumnsBuilder.append(" AS ");
vendor.appendIdentifier(extraColumnsBuilder, indexFieldName);
extraColumnsBuilder.append(", ");
}
}
if (extraColumnsBuilder.length() > 0) {
extraColumnsBuilder.setLength(extraColumnsBuilder.length() - 2);
this.extraSourceColumns = extraColumnsBuilder.toString();
}
for (Map.Entry<Query<?>, String> entry : subQueries.entrySet()) {
Query<?> subQuery = entry.getKey();
SqlQuery subSqlQuery = getOrCreateSubSqlQuery(subQuery, false);
if (subSqlQuery.needsDistinct) {
needsDistinct = true;
}
fromBuilder.append("\nINNER JOIN ");
vendor.appendIdentifier(fromBuilder, "Record");
fromBuilder.append(' ');
fromBuilder.append(subSqlQuery.aliasPrefix);
fromBuilder.append("r ON ");
fromBuilder.append(entry.getValue());
fromBuilder.append(subSqlQuery.aliasPrefix);
fromBuilder.append("r.");
vendor.appendIdentifier(fromBuilder, "id");
fromBuilder.append(subSqlQuery.fromClause);
}
if (extraJoins != null) {
fromBuilder.append(' ');
fromBuilder.append(extraJoins);
}
this.whereClause = whereBuilder.toString();
StringBuilder havingBuilder = new StringBuilder();
if (hasDeferredHavingPredicates()) {
StringBuilder childBuilder = new StringBuilder();
int i = 0;
for (Predicate havingPredicate : havingPredicates) {
addWherePredicate(childBuilder, havingPredicate, parentHavingPredicates.get(i++), false, false);
}
if (childBuilder.length() > 0) {
havingBuilder.append(" \nHAVING ");
havingBuilder.append(childBuilder);
}
}
String extraHaving = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_HAVING_QUERY_OPTION));
havingBuilder.append(ObjectUtils.isBlank(extraHaving) ? "" : ("\n" + (ObjectUtils.isBlank(this.havingClause) ? "HAVING" : "AND") + " " + extraHaving));
this.havingClause = havingBuilder.toString();
this.orderByClause = orderByBuilder.toString();
this.fromClause = fromBuilder.toString();
}
/** Adds the given {@code predicate} to the {@code WHERE} clause. */
private void addWherePredicate(
StringBuilder whereBuilder,
Predicate predicate,
Predicate parentPredicate,
boolean usesLeftJoin,
boolean deferMetricAndHavingPredicates) {
if (predicate instanceof CompoundPredicate) {
CompoundPredicate compoundPredicate = (CompoundPredicate) predicate;
String operator = compoundPredicate.getOperator();
boolean isNot = PredicateParser.NOT_OPERATOR.equals(operator);
// e.g. (child1) OR (child2) OR ... (child
if (isNot || PredicateParser.OR_OPERATOR.equals(operator)) {
StringBuilder compoundBuilder = new StringBuilder();
List<Predicate> children = compoundPredicate.getChildren();
boolean usesLeftJoinChildren;
if (children.size() > 1) {
usesLeftJoinChildren = true;
needsDistinct = true;
} else {
usesLeftJoinChildren = isNot;
}
for (Predicate child : children) {
StringBuilder childBuilder = new StringBuilder();
addWherePredicate(childBuilder, child, predicate, usesLeftJoinChildren, deferMetricAndHavingPredicates);
if (childBuilder.length() > 0) {
compoundBuilder.append('(');
compoundBuilder.append(childBuilder);
compoundBuilder.append(")\nOR ");
}
}
if (compoundBuilder.length() > 0) {
compoundBuilder.setLength(compoundBuilder.length() - 4);
// e.g. NOT ((child1) OR (child2) OR ... (child
if (isNot) {
whereBuilder.append("NOT (");
whereBuilder.append(compoundBuilder);
whereBuilder.append(')');
} else {
whereBuilder.append(compoundBuilder);
}
}
return;
// e.g. (child1) AND (child2) AND .... (child
} else if (PredicateParser.AND_OPERATOR.equals(operator)) {
StringBuilder compoundBuilder = new StringBuilder();
for (Predicate child : compoundPredicate.getChildren()) {
StringBuilder childBuilder = new StringBuilder();
addWherePredicate(childBuilder, child, predicate, usesLeftJoin, deferMetricAndHavingPredicates);
if (childBuilder.length() > 0) {
compoundBuilder.append('(');
compoundBuilder.append(childBuilder);
compoundBuilder.append(")\nAND ");
}
}
if (compoundBuilder.length() > 0) {
compoundBuilder.setLength(compoundBuilder.length() - 5);
whereBuilder.append(compoundBuilder);
}
return;
}
} else if (predicate instanceof ComparisonPredicate) {
ComparisonPredicate comparisonPredicate = (ComparisonPredicate) predicate;
String queryKey = comparisonPredicate.getKey();
Query.MappedKey mappedKey = mappedKeys.get(queryKey);
boolean isFieldCollection = mappedKey.isInternalCollectionType();
Join join = null;
if (mappedKey.getField() != null &&
parentPredicate instanceof CompoundPredicate &&
PredicateParser.OR_OPERATOR.equals(((CompoundPredicate) parentPredicate).getOperator())) {
for (Join j : joins) {
if (j.parent == parentPredicate &&
j.sqlIndex.equals(SqlIndex.Static.getByType(mappedKeys.get(queryKey).getInternalType()))) {
join = j;
join.addIndexKey(queryKey);
needsDistinct = true;
break;
}
}
if (join == null) {
join = getJoin(queryKey);
join.parent = parentPredicate;
}
} else if (isFieldCollection) {
join = createJoin(queryKey);
} else {
join = getJoin(queryKey);
}
if (usesLeftJoin) {
join.type = JoinType.LEFT_OUTER;
}
if (isFieldCollection &&
(join.sqlIndexTable == null ||
join.sqlIndexTable.getVersion() < 2)) {
needsDistinct = true;
}
if (deferMetricAndHavingPredicates) {
if (mappedKey.getField() != null) {
if (mappedKey.getField().isMetric()) {
if (recordMetricField == null) {
recordMetricField = mappedKey.getField();
} else if (!recordMetricField.equals(mappedKey.getField())) {
throw new Query.NoFieldException(query.getGroup(), recordMetricField.getInternalName() + " AND " + mappedKey.getField().getInternalName());
}
if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
recordMetricDatePredicates.add(predicate);
recordMetricParentDatePredicates.add(parentPredicate);
} else if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
recordMetricDimensionPredicates.add(predicate);
recordMetricParentDimensionPredicates.add(parentPredicate);
} else {
recordMetricHavingPredicates.add(predicate);
recordMetricParentHavingPredicates.add(parentPredicate);
}
return;
}
}
if (join.isHaving) {
// pass for now; we'll get called again later.
havingPredicates.add(predicate);
parentHavingPredicates.add(parentPredicate);
return;
}
}
String joinValueField = join.getValueField(queryKey, comparisonPredicate);
if (reverseAliasSql.containsKey(joinValueField)) {
joinValueField = reverseAliasSql.get(joinValueField);
}
String operator = comparisonPredicate.getOperator();
StringBuilder comparisonBuilder = new StringBuilder();
boolean hasMissing = false;
int subClauseCount = 0;
boolean isNotEqualsAll = PredicateParser.NOT_EQUALS_ALL_OPERATOR.equals(operator);
if (isNotEqualsAll || PredicateParser.EQUALS_ANY_OPERATOR.equals(operator)) {
Query<?> valueQuery = mappedKey.getSubQueryWithComparison(comparisonPredicate);
// e.g. field IN (SELECT ...)
if (valueQuery != null) {
if (isNotEqualsAll || isFieldCollection) {
needsDistinct = true;
}
if (findSimilarComparison(mappedKey.getField(), query.getPredicate())) {
whereBuilder.append(joinValueField);
if (isNotEqualsAll) {
whereBuilder.append(" NOT");
}
whereBuilder.append(" IN (");
whereBuilder.append(new SqlQuery(database, valueQuery).subQueryStatement());
whereBuilder.append(')');
} else {
SqlQuery subSqlQuery = getOrCreateSubSqlQuery(valueQuery, join.type == JoinType.LEFT_OUTER);
subQueries.put(valueQuery, joinValueField + (isNotEqualsAll ? " != " : " = "));
whereBuilder.append(subSqlQuery.whereClause.substring(7));
}
return;
}
for (Object value : comparisonPredicate.resolveValues(database)) {
if (value == null) {
++ subClauseCount;
comparisonBuilder.append("0 = 1");
} else if (value == Query.MISSING_VALUE) {
++ subClauseCount;
hasMissing = true;
comparisonBuilder.append(joinValueField);
if (isNotEqualsAll) {
if (isFieldCollection) {
needsDistinct = true;
}
comparisonBuilder.append(" IS NOT NULL");
} else {
join.type = JoinType.LEFT_OUTER;
comparisonBuilder.append(" IS NULL");
}
} else if (value instanceof Region) {
List<Location> locations = ((Region) value).getLocations();
if (!locations.isEmpty()) {
++ subClauseCount;
if (isNotEqualsAll) {
comparisonBuilder.append("NOT ");
}
try {
vendor.appendWhereRegion(comparisonBuilder, (Region) value, joinValueField);
} catch (UnsupportedIndexException uie) {
throw new UnsupportedIndexException(vendor, queryKey);
}
}
} else {
++ subClauseCount;
if (isNotEqualsAll) {
join.type = JoinType.LEFT_OUTER;
needsDistinct = true;
hasMissing = true;
comparisonBuilder.append('(');
comparisonBuilder.append(joinValueField);
comparisonBuilder.append(" IS NULL OR ");
comparisonBuilder.append(joinValueField);
if (join.likeValuePrefix != null) {
comparisonBuilder.append(" NOT LIKE ");
join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%");
} else {
comparisonBuilder.append(" != ");
join.appendValue(comparisonBuilder, comparisonPredicate, value);
}
comparisonBuilder.append(')');
} else {
comparisonBuilder.append(joinValueField);
if (join.likeValuePrefix != null) {
comparisonBuilder.append(" LIKE ");
join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%");
} else {
comparisonBuilder.append(" = ");
join.appendValue(comparisonBuilder, comparisonPredicate, value);
}
}
}
comparisonBuilder.append(isNotEqualsAll ? " AND " : " OR ");
}
if (comparisonBuilder.length() == 0) {
whereBuilder.append(isNotEqualsAll ? "1 = 1" : "0 = 1");
return;
}
} else {
boolean isStartsWith = PredicateParser.STARTS_WITH_OPERATOR.equals(operator);
boolean isContains = PredicateParser.CONTAINS_OPERATOR.equals(operator);
String sqlOperator =
isStartsWith ? "LIKE" :
isContains ? "LIKE" :
PredicateParser.LESS_THAN_OPERATOR.equals(operator) ? "<" :
PredicateParser.LESS_THAN_OR_EQUALS_OPERATOR.equals(operator) ? "<=" :
PredicateParser.GREATER_THAN_OPERATOR.equals(operator) ? ">" :
PredicateParser.GREATER_THAN_OR_EQUALS_OPERATOR.equals(operator) ? ">=" :
null;
Query<?> valueQuery = mappedKey.getSubQueryWithComparison(comparisonPredicate);
// e.g. field startsWith (SELECT ...)
if (valueQuery != null) {
if (isFieldCollection) {
needsDistinct = true;
}
if (findSimilarComparison(mappedKey.getField(), query.getPredicate())) {
whereBuilder.append(joinValueField);
whereBuilder.append(" IN (");
whereBuilder.append(new SqlQuery(database, valueQuery).subQueryStatement());
whereBuilder.append(')');
} else {
SqlQuery subSqlQuery = getOrCreateSubSqlQuery(valueQuery, join.type == JoinType.LEFT_OUTER);
subQueries.put(valueQuery, joinValueField + " = ");
whereBuilder.append(subSqlQuery.whereClause.substring(7));
}
return;
}
// e.g. field OP value1 OR field OP value2 OR ... field OP value
if (sqlOperator != null) {
for (Object value : comparisonPredicate.resolveValues(database)) {
++ subClauseCount;
if (value == null) {
comparisonBuilder.append("0 = 1");
} else if (value instanceof Location) {
++ subClauseCount;
if (isNotEqualsAll) {
comparisonBuilder.append("NOT ");
}
try {
vendor.appendWhereLocation(comparisonBuilder, (Location) value, joinValueField);
} catch (UnsupportedIndexException uie) {
throw new UnsupportedIndexException(vendor, queryKey);
}
} else if (value == Query.MISSING_VALUE) {
hasMissing = true;
join.type = JoinType.LEFT_OUTER;
comparisonBuilder.append(joinValueField);
comparisonBuilder.append(" IS NULL");
} else {
comparisonBuilder.append(joinValueField);
comparisonBuilder.append(' ');
comparisonBuilder.append(sqlOperator);
comparisonBuilder.append(' ');
if (isStartsWith) {
value = value.toString() + "%";
} else if (isContains) {
value = "%" + value.toString() + "%";
}
join.appendValue(comparisonBuilder, comparisonPredicate, value);
}
comparisonBuilder.append(" OR ");
}
if (comparisonBuilder.length() == 0) {
whereBuilder.append("0 = 1");
return;
}
}
}
if (comparisonBuilder.length() > 0) {
comparisonBuilder.setLength(comparisonBuilder.length() - 5);
if (!hasMissing) {
if (join.needsIndexTable) {
String indexKey = mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey));
if (indexKey != null) {
whereBuilder.append(join.keyField);
whereBuilder.append(" = ");
whereBuilder.append(join.quoteIndexKey(indexKey));
whereBuilder.append(" AND ");
}
}
if (join.needsIsNotNull) {
whereBuilder.append(joinValueField);
whereBuilder.append(" IS NOT NULL AND ");
}
if (subClauseCount > 1) {
needsDistinct = true;
whereBuilder.append('(');
comparisonBuilder.append(')');
}
}
whereBuilder.append(comparisonBuilder);
return;
}
}
throw new UnsupportedPredicateException(this, predicate);
}
private void addOrderByClause(StringBuilder orderByBuilder, Sorter sorter, boolean deferMetricPredicates, boolean useGroupBySelectAliases) {
String operator = sorter.getOperator();
boolean ascending = Sorter.ASCENDING_OPERATOR.equals(operator);
boolean descending = Sorter.DESCENDING_OPERATOR.equals(operator);
boolean closest = Sorter.CLOSEST_OPERATOR.equals(operator);
boolean farthest = Sorter.FARTHEST_OPERATOR.equals(operator);
if (ascending || descending || closest || farthest) {
String queryKey = (String) sorter.getOptions().get(0);
if (deferMetricPredicates) {
ObjectField sortField = mappedKeys.get(queryKey).getField();
if (sortField != null && sortField.isMetric()) {
if (recordMetricField == null) {
recordMetricField = sortField;
} else if (!recordMetricField.equals(sortField)) {
throw new Query.NoFieldException(query.getGroup(), recordMetricField.getInternalName() + " AND " + sortField.getInternalName());
}
recordMetricSorters.add(sorter);
return;
}
}
Join join = getSortFieldJoin(queryKey);
String joinValueField = join.getValueField(queryKey, null);
if (useGroupBySelectAliases && groupBySelectColumnAliases.containsKey(joinValueField)) {
joinValueField = groupBySelectColumnAliases.get(joinValueField);
}
Query<?> subQuery = mappedKeys.get(queryKey).getSubQueryWithSorter(sorter, 0);
if (subQuery != null) {
SqlQuery subSqlQuery = getOrCreateSubSqlQuery(subQuery, true);
subQueries.put(subQuery, joinValueField + " = ");
orderByBuilder.append(subSqlQuery.orderByClause.substring(9));
orderByBuilder.append(", ");
return;
}
if (ascending || descending) {
orderByBuilder.append(joinValueField);
if (!join.isHaving) {
orderBySelectColumns.add(joinValueField);
}
} else if (closest || farthest) {
Location location = (Location) sorter.getOptions().get(1);
StringBuilder selectBuilder = new StringBuilder();
try {
vendor.appendNearestLocation(orderByBuilder, selectBuilder, location, joinValueField);
if (!join.isHaving) {
orderBySelectColumns.add(selectBuilder.toString());
}
} catch (UnsupportedIndexException uie) {
throw new UnsupportedIndexException(vendor, queryKey);
}
}
orderByBuilder.append(' ');
orderByBuilder.append(ascending || closest ? "ASC" : "DESC");
orderByBuilder.append(", ");
return;
}
throw new UnsupportedSorterException(database, sorter);
}
private boolean findSimilarComparison(ObjectField field, Predicate predicate) {
if (field != null) {
if (predicate instanceof CompoundPredicate) {
for (Predicate child : ((CompoundPredicate) predicate).getChildren()) {
if (findSimilarComparison(field, child)) {
return true;
}
}
} else if (predicate instanceof ComparisonPredicate) {
ComparisonPredicate comparison = (ComparisonPredicate) predicate;
Query.MappedKey mappedKey = mappedKeys.get(comparison.getKey());
if (field.equals(mappedKey.getField()) &&
mappedKey.getSubQueryWithComparison(comparison) == null) {
return true;
}
}
}
return false;
}
private boolean hasDeferredHavingPredicates() {
return !havingPredicates.isEmpty();
}
private boolean hasAnyDeferredMetricPredicates() {
return !recordMetricDatePredicates.isEmpty() ||
!recordMetricDimensionPredicates.isEmpty() ||
!recordMetricHavingPredicates.isEmpty() ||
!recordMetricSorters.isEmpty();
}
/**
* Returns an SQL statement that can be used to get a count
* of all rows matching the query.
*/
public String countStatement() {
StringBuilder statementBuilder = new StringBuilder();
initializeClauses();
statementBuilder.append("SELECT COUNT(");
if (needsDistinct) {
statementBuilder.append("DISTINCT ");
}
statementBuilder.append(recordIdField);
statementBuilder.append(')');
statementBuilder.append(" \nFROM ");
vendor.appendIdentifier(statementBuilder, "Record");
statementBuilder.append(' ');
statementBuilder.append(aliasPrefix);
statementBuilder.append('r');
statementBuilder.append(fromClause.replace(" /*! USE INDEX (k_name_value) */", ""));
if (!recordMetricHavingPredicates.isEmpty()) {
statementBuilder.append(" \nJOIN (");
appendSubqueryMetricSql(statementBuilder, recordMetricField);
statementBuilder.append(") m \nON (");
appendSimpleOnClause(statementBuilder, vendor, "r", "id", "=", "m", "id");
statementBuilder.append(" AND ");
appendSimpleOnClause(statementBuilder, vendor, "r", "typeId", "=", "m", "typeId");
statementBuilder.append(')');
statementBuilder.append(whereClause);
StringBuilder havingChildBuilder = new StringBuilder();
for (int i = 0; i < recordMetricHavingPredicates.size(); i++) {
addWherePredicate(havingChildBuilder, recordMetricHavingPredicates.get(i), recordMetricParentHavingPredicates.get(i), false, false);
havingChildBuilder.append(" AND ");
}
if (havingChildBuilder.length() > 0) {
havingChildBuilder.setLength(havingChildBuilder.length() - 5); // " AND "
statementBuilder.append(" AND ");
statementBuilder.append(havingChildBuilder);
}
} else {
statementBuilder.append(whereClause);
}
return statementBuilder.toString();
}
/**
* Returns an SQL statement that can be used to delete all rows
* matching the query.
*/
public String deleteStatement() {
StringBuilder statementBuilder = new StringBuilder();
initializeClauses();
if (hasAnyDeferredMetricPredicates()) {
throw new Query.NoFieldException(query.getGroup(), recordMetricField.getInternalName());
}
statementBuilder.append("DELETE r\nFROM ");
vendor.appendIdentifier(statementBuilder, "Record");
statementBuilder.append(' ');
statementBuilder.append(aliasPrefix);
statementBuilder.append('r');
statementBuilder.append(fromClause);
statementBuilder.append(whereClause);
statementBuilder.append(havingClause);
statementBuilder.append(orderByClause);
return statementBuilder.toString();
}
/**
* Returns an SQL statement that can be used to get all objects
* grouped by the values of the given {@code groupFields}.
*/
public String groupStatement(String[] groupFields) {
Map<String, Join> groupJoins = new LinkedHashMap<String, Join>();
Map<String, SqlQuery> groupSubSqlQueries = new HashMap<String, SqlQuery>();
if (groupFields != null) {
for (String groupField : groupFields) {
Query.MappedKey mappedKey = query.mapEmbeddedKey(database.getEnvironment(), groupField);
if (mappedKey.getField() != null) {
if (mappedKey.getField().isMetric()) {
if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
// TODO: this one has to work eventually . . .
} else if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
// TODO: this one has to work eventually . . .
throw new Query.NoFieldException(query.getGroup(), groupField);
} else {
throw new RuntimeException("Unable to group by @MetricValue: " + groupField);
}
}
}
mappedKeys.put(groupField, mappedKey);
Iterator<ObjectIndex> indexesIterator = mappedKey.getIndexes().iterator();
if (indexesIterator.hasNext()) {
ObjectIndex selectedIndex = indexesIterator.next();
while (indexesIterator.hasNext()) {
ObjectIndex index = indexesIterator.next();
if (selectedIndex.getFields().size() < index.getFields().size()) {
selectedIndex = index;
}
}
selectedIndexes.put(groupField, selectedIndex);
}
Join join = getJoin(groupField);
Query<?> subQuery = mappedKey.getSubQueryWithGroupBy();
if (subQuery != null) {
SqlQuery subSqlQuery = getOrCreateSubSqlQuery(subQuery, true);
groupSubSqlQueries.put(groupField, subSqlQuery);
subQueries.put(subQuery, join.getValueField(groupField, null) + " = ");
}
groupJoins.put(groupField, join);
}
}
StringBuilder statementBuilder = new StringBuilder();
StringBuilder groupBy = new StringBuilder();
initializeClauses();
if (hasAnyDeferredMetricPredicates()) {
// add "id" and "dimensionId" to groupJoins
mappedKeys.put(Query.ID_KEY, query.mapEmbeddedKey(database.getEnvironment(), Query.ID_KEY));
groupJoins.put(Query.ID_KEY, getJoin(Query.ID_KEY));
mappedKeys.put(Query.DIMENSION_KEY, query.mapEmbeddedKey(database.getEnvironment(), Query.DIMENSION_KEY));
groupJoins.put(Query.DIMENSION_KEY, getJoin(Query.DIMENSION_KEY));
}
statementBuilder.append("SELECT COUNT(");
if (needsDistinct) {
statementBuilder.append("DISTINCT ");
}
statementBuilder.append(recordIdField);
statementBuilder.append(')');
statementBuilder.append(' ');
vendor.appendIdentifier(statementBuilder, "_count");
int columnNum = 0;
for (Map.Entry<String, Join> entry : groupJoins.entrySet()) {
statementBuilder.append(", ");
if (groupSubSqlQueries.containsKey(entry.getKey())) {
for (String subSqlSelectField : groupSubSqlQueries.get(entry.getKey()).orderBySelectColumns) {
statementBuilder.append(subSqlSelectField);
}
} else {
statementBuilder.append(entry.getValue().getValueField(entry.getKey(), null));
}
statementBuilder.append(' ');
String columnAlias = null;
if (!entry.getValue().queryKey.equals(Query.ID_KEY) && !entry.getValue().queryKey.equals(Query.DIMENSION_KEY)) { // Special case for id and dimensionId
// These column names just need to be unique if we put this statement in a subquery
columnAlias = "value" + columnNum;
groupBySelectColumnAliases.put(entry.getValue().getValueField(entry.getKey(), null), columnAlias);
}
++columnNum;
if (columnAlias != null) {
vendor.appendIdentifier(statementBuilder, columnAlias);
}
}
selectClause = statementBuilder.toString();
for (String field : orderBySelectColumns) {
statementBuilder.append(", ");
statementBuilder.append(field);
}
statementBuilder.append("\nFROM ");
vendor.appendIdentifier(statementBuilder, "Record");
statementBuilder.append(' ');
statementBuilder.append(aliasPrefix);
statementBuilder.append('r');
statementBuilder.append(fromClause.replace(" /*! USE INDEX (k_name_value) */", ""));
statementBuilder.append(whereClause);
for (Map.Entry<String, Join> entry : groupJoins.entrySet()) {
if (groupSubSqlQueries.containsKey(entry.getKey())) {
for (String subSqlSelectField : groupSubSqlQueries.get(entry.getKey()).orderBySelectColumns) {
groupBy.append(subSqlSelectField);
}
} else {
groupBy.append(entry.getValue().getValueField(entry.getKey(), null));
}
groupBy.append(", ");
}
for (String field : orderBySelectColumns) {
groupBy.append(field);
groupBy.append(", ");
}
if (groupBy.length() > 0) {
groupBy.setLength(groupBy.length() - 2);
groupBy.insert(0, " GROUP BY ");
}
groupByClause = groupBy.toString();
statementBuilder.append(groupByClause);
statementBuilder.append(havingClause);
if (!orderBySelectColumns.isEmpty()) {
if (orderByClause.length() > 0) {
statementBuilder.append(orderByClause);
statementBuilder.append(", ");
} else {
statementBuilder.append(" ORDER BY ");
}
int i = 0;
for (Map.Entry<String, Join> entry : groupJoins.entrySet()) {
if (i++ > 0) {
statementBuilder.append(", ");
}
statementBuilder.append(entry.getValue().getValueField(entry.getKey(), null));
}
} else {
statementBuilder.append(orderByClause);
}
if (hasAnyDeferredMetricPredicates()) {
// If there are deferred HAVING predicates, we need to go ahead and execute the metric query
// TODO: there might be a way to filter on more than 1 metric simultaneously.
return buildGroupedMetricSql(recordMetricField.getInternalName(), groupFields, selectClause, fromClause, whereClause, groupByClause, orderByClause);
} else {
return statementBuilder.toString();
}
}
/**
* Returns an SQL statement that can be used to get the sum
* of the specified Metric {@code metricFieldName} grouped by the values
* of the given {@code groupFields}.
*/
public String groupedMetricSql(String metricFieldName, String[] groupFields) {
int addFields = 2;
boolean addIdField = true;
boolean addDimField = true;
for (int i = 0; i < groupFields.length; i++) {
if (Query.ID_KEY.equals(groupFields[i])) {
addFields
addIdField = false;
}
if (Query.DIMENSION_KEY.equals(groupFields[i])) {
addFields
addDimField = false;
}
}
String[] innerGroupByFields = Arrays.copyOf(groupFields, groupFields.length + addFields);
if (addIdField) {
innerGroupByFields[groupFields.length] = Query.ID_KEY;
}
if (addDimField) {
innerGroupByFields[groupFields.length + 1] = Query.DIMENSION_KEY;
}
// This prepares selectClause, et al.
groupStatement(innerGroupByFields);
return buildGroupedMetricSql(metricFieldName, groupFields, selectClause, fromClause, whereClause, groupByClause, orderByClause);
}
private String buildGroupedMetricSql(String metricFieldName, String[] groupFields, String selectClause, String fromClause, String whereClause, String groupByClause, String orderByClause) {
StringBuilder selectBuilder = new StringBuilder(selectClause);
StringBuilder fromBuilder = new StringBuilder(fromClause);
StringBuilder whereBuilder = new StringBuilder(whereClause);
StringBuilder groupByBuilder = new StringBuilder(groupByClause);
StringBuilder havingBuilder = new StringBuilder(orderByClause);
StringBuilder orderByBuilder = new StringBuilder(orderByClause);
Query.MappedKey mappedKey = query.mapEmbeddedKey(database.getEnvironment(), metricFieldName);
if (mappedKey.getField() == null) {
throw new Query.NoFieldException(query.getGroup(), metricFieldName);
}
ObjectField metricField = mappedKey.getField();
String actionSymbol = metricField.getUniqueName(); // JavaDeclaringClassName() + "/" + metricField.getInternalName();
selectBuilder.insert(7, "MIN(r.data) minData, MAX(r.data) maxData, "); // Right after "SELECT " (7 chars)
fromBuilder.insert(0, "FROM " + MetricAccess.Static.getMetricTableIdentifier(database) + " r ");
whereBuilder.append(" AND r." + MetricAccess.METRIC_SYMBOL_FIELD + " = ");
vendor.appendValue(whereBuilder, database.getSymbolId(actionSymbol));
// If a dimensionId is not specified, we will append dimensionId = 00000000000000000000000000000000
if (recordMetricDimensionPredicates.isEmpty()) {
whereBuilder.append(" AND ");
appendSimpleWhereClause(whereBuilder, vendor, "r", MetricAccess.METRIC_DIMENSION_FIELD, "=", MetricAccess.getDimensionIdByValue(database, null));
}
// Apply deferred WHERE predicates (eventDates and dimensionIds)
for (int i = 0; i < recordMetricDatePredicates.size(); i++) {
whereBuilder.append(" AND ");
addWherePredicate(whereBuilder, recordMetricDatePredicates.get(i), recordMetricParentDatePredicates.get(i), false, false);
}
for (int i = 0; i < recordMetricDimensionPredicates.size(); i++) {
whereBuilder.append(" AND ");
addWherePredicate(whereBuilder, recordMetricDimensionPredicates.get(i), recordMetricParentDimensionPredicates.get(i), false, false);
}
String innerSql = selectBuilder.toString() + " " + fromBuilder.toString() + " " + whereBuilder.toString() + " " + groupByBuilder.toString() + " " + havingBuilder.toString() + " " + orderByBuilder.toString();
selectBuilder = new StringBuilder();
fromBuilder = new StringBuilder();
whereBuilder = new StringBuilder();
groupByBuilder = new StringBuilder();
havingBuilder = new StringBuilder();
orderByBuilder = new StringBuilder();
selectBuilder.append("SELECT ");
StringBuilder amountBuilder = new StringBuilder();
MetricAccess.Static.appendSelectCalculatedAmountSql(amountBuilder, vendor, "minData", "maxData", true);
selectBuilder.append(amountBuilder);
reverseAliasSql.put(metricField.getInternalName(), amountBuilder.toString());
vendor.appendAlias(selectBuilder, metricField.getInternalName());
selectBuilder.append(", COUNT(");
vendor.appendIdentifier(selectBuilder, "id");
selectBuilder.append(") ");
vendor.appendIdentifier(selectBuilder, "_count");
List<String> groupBySelectColumns = new ArrayList<String>();
for (String field : groupBySelectColumnAliases.values()) {
groupBySelectColumns.add(field);
}
// Special case for id and dimensionId
for (int i = 0; i < groupFields.length; i++) {
if (Query.ID_KEY.equals(groupFields[i])) {
groupBySelectColumns.add("id");
}
if (Query.DIMENSION_KEY.equals(groupFields[i])) {
groupBySelectColumns.add("dimensionId");
}
}
for (String field : groupBySelectColumns) {
selectBuilder.append(", ");
vendor.appendIdentifier(selectBuilder, field);
}
fromBuilder.append(" \nFROM (");
fromBuilder.append(innerSql);
fromBuilder.append(" ) x ");
if (!groupBySelectColumns.isEmpty()) {
groupByBuilder.append(" GROUP BY ");
for (String field : groupBySelectColumns) {
if (groupByBuilder.length() > 10) { // " GROUP BY ".length()
groupByBuilder.append(", ");
}
vendor.appendIdentifier(groupByBuilder, field);
}
}
// Apply deferred HAVING predicates (sums)
StringBuilder havingChildBuilder = new StringBuilder();
for (int i = 0; i < recordMetricHavingPredicates.size(); i++) {
addWherePredicate(havingChildBuilder, recordMetricHavingPredicates.get(i), recordMetricParentHavingPredicates.get(i), false, false);
havingChildBuilder.append(" AND ");
}
if (havingChildBuilder.length() > 0) {
havingChildBuilder.setLength(havingChildBuilder.length() - 5); // " AND "
havingBuilder.append(" HAVING ");
havingBuilder.append(havingChildBuilder);
}
// Apply all ORDER BY (deferred and original)
for (Sorter sorter : query.getSorters()) {
addOrderByClause(orderByBuilder, sorter, false, true);
}
if (orderByBuilder.length() > 0) {
orderByBuilder.setLength(orderByBuilder.length() - 2);
orderByBuilder.insert(0, "\nORDER BY ");
}
return selectBuilder +
" " + fromBuilder +
" " + whereBuilder +
" " + groupByBuilder +
" " + havingBuilder +
" " + orderByBuilder;
}
private void appendSubqueryMetricSql(StringBuilder sql, ObjectField metricField) {
String actionSymbol = metricField.getUniqueName(); // JavaDeclaringClassName() + "/" + metricField.getInternalName();
StringBuilder minData = new StringBuilder("MIN(");
vendor.appendIdentifier(minData, "m2");
minData.append('.');
vendor.appendIdentifier(minData, MetricAccess.METRIC_DATA_FIELD);
minData.append(')');
StringBuilder maxData = new StringBuilder("MAX(");
vendor.appendIdentifier(maxData, "m2");
maxData.append('.');
vendor.appendIdentifier(maxData, MetricAccess.METRIC_DATA_FIELD);
maxData.append(')');
sql.append("SELECT ");
appendSimpleAliasedColumn(sql, vendor, "r", SqlDatabase.ID_COLUMN);
sql.append(", ");
appendSimpleAliasedColumn(sql, vendor, "r", SqlDatabase.TYPE_ID_COLUMN);
sql.append(", ");
MetricAccess.Static.appendSelectCalculatedAmountSql(sql, vendor, minData.toString(), maxData.toString(), false);
sql.append(' ');
vendor.appendAlias(sql, metricField.getInternalName());
sql.append(" FROM ");
vendor.appendIdentifier(sql, SqlDatabase.RECORD_TABLE);
sql.append(" ");
vendor.appendIdentifier(sql, "r");
// Left joins if we're only sorting, not filtering.
if (recordMetricHavingPredicates.isEmpty()) {
sql.append(" \nLEFT OUTER JOIN ");
} else {
sql.append(" \nINNER JOIN ");
}
sql.append(MetricAccess.Static.getMetricTableIdentifier(database));
sql.append(" ");
vendor.appendIdentifier(sql, "m2");
sql.append(" ON (\n");
appendSimpleOnClause(sql, vendor, "r", SqlDatabase.ID_COLUMN, "=", "m2", MetricAccess.METRIC_ID_FIELD);
sql.append(" AND \n");
appendSimpleOnClause(sql, vendor, "r", SqlDatabase.TYPE_ID_COLUMN, "=", "m2", MetricAccess.METRIC_TYPE_FIELD);
sql.append(" AND \n");
appendSimpleWhereClause(sql, vendor, "m2", MetricAccess.METRIC_SYMBOL_FIELD, "=", database.getSymbolId(actionSymbol));
// If a dimensionId is not specified, we will append dimensionId = 00000000000000000000000000000000
if (recordMetricDimensionPredicates.isEmpty()) {
sql.append(" AND ");
appendSimpleWhereClause(sql, vendor, "m2", MetricAccess.METRIC_DIMENSION_FIELD, "=", MetricAccess.getDimensionIdByValue(database, null));
}
// Apply deferred WHERE predicates (eventDates and metric Dimensions)
for (int i = 0; i < recordMetricDatePredicates.size(); i++) {
sql.append(" AND ");
vendor.appendIdentifier(sql, "m2");
sql.append(".");
addWherePredicate(sql, recordMetricDatePredicates.get(i), recordMetricParentDatePredicates.get(i), false, false);
}
for (int i = 0; i < recordMetricDimensionPredicates.size(); i++) {
sql.append(" AND ");
vendor.appendIdentifier(sql, "m2");
sql.append(".");
addWherePredicate(sql, recordMetricDimensionPredicates.get(i), recordMetricParentDimensionPredicates.get(i), false, false);
}
sql.append(")");
// Apply the "main" JOINs
sql.append(fromClause);
// Apply the "main" WHERE clause
sql.append(whereClause);
sql.append(" GROUP BY ");
appendSimpleAliasedColumn(sql, vendor, "r", SqlDatabase.ID_COLUMN);
sql.append(", ");
appendSimpleAliasedColumn(sql, vendor, "r", SqlDatabase.TYPE_ID_COLUMN);
sql.append(", ");
appendSimpleAliasedColumn(sql, vendor, "m2", MetricAccess.METRIC_DIMENSION_FIELD);
StringBuilder havingBuilder = new StringBuilder();
StringBuilder havingChildBuilder = new StringBuilder();
for (int i = 0; i < recordMetricHavingPredicates.size(); i++) {
addWherePredicate(havingChildBuilder, recordMetricHavingPredicates.get(i), recordMetricParentHavingPredicates.get(i), false, false);
havingChildBuilder.append(" AND ");
}
if (havingChildBuilder.length() > 0) {
havingChildBuilder.setLength(havingChildBuilder.length() - 5); // " AND "
havingBuilder.append(" HAVING ");
havingBuilder.append(havingChildBuilder);
}
String extraHaving = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_HAVING_QUERY_OPTION));
havingBuilder.append(ObjectUtils.isBlank(extraHaving) ? "" : ("\n" + (ObjectUtils.isBlank(this.havingClause) ? "HAVING" : "AND") + " " + extraHaving));
havingClause = havingBuilder.toString();
sql.append(havingClause);
sql.append(orderByClause);
if (!recordMetricSorters.isEmpty()) {
StringBuilder orderByBuilder = new StringBuilder();
for (Sorter sorter : recordMetricSorters) {
addOrderByClause(orderByBuilder, sorter, false, true);
}
if (orderByBuilder.length() > 0) {
orderByBuilder.setLength(orderByBuilder.length() - 2);
orderByBuilder.insert(0, "\nORDER BY ");
sql.append(orderByBuilder);
}
}
// Add placeholder for LIMIT/OFFSET sql injected by SqlDatabase
sql.append(vendor.getLimitOffsetPlaceholder());
}
/**
* Returns an SQL statement that can be used to get when the rows
* matching the query were last updated.
*/
public String lastUpdateStatement() {
StringBuilder statementBuilder = new StringBuilder();
initializeClauses();
statementBuilder.append("SELECT MAX(r.");
vendor.appendIdentifier(statementBuilder, "updateDate");
statementBuilder.append(")\nFROM ");
vendor.appendIdentifier(statementBuilder, "RecordUpdate");
statementBuilder.append(' ');
statementBuilder.append(aliasPrefix);
statementBuilder.append('r');
statementBuilder.append(fromClause);
statementBuilder.append(whereClause);
return statementBuilder.toString();
}
/**
* Returns an SQL statement that can be used to list all rows
* matching the query.
*/
public String selectStatement() {
StringBuilder statementBuilder = new StringBuilder();
initializeClauses();
statementBuilder.append("SELECT");
if (needsDistinct && vendor.supportsDistinctBlob()) {
statementBuilder.append(" DISTINCT");
}
statementBuilder.append(" r.");
vendor.appendIdentifier(statementBuilder, "id");
statementBuilder.append(", r.");
vendor.appendIdentifier(statementBuilder, "typeId");
List<String> fields = query.getFields();
boolean cacheData = database.isCacheData();
if (fields == null) {
if (!needsDistinct || vendor.supportsDistinctBlob()) {
if (cacheData) {
statementBuilder.append(", ru.");
vendor.appendIdentifier(statementBuilder, "updateDate");
} else {
statementBuilder.append(", r.");
vendor.appendIdentifier(statementBuilder, "data");
}
}
} else if (!fields.isEmpty()) {
statementBuilder.append(", ");
vendor.appendSelectFields(statementBuilder, fields);
}
if (hasAnyDeferredMetricPredicates()) {
statementBuilder.append(", ");
vendor.appendAlias(statementBuilder, recordMetricField.getInternalName());
statementBuilder.append(' ');
query.getExtraSourceColumns().put(recordMetricField.getInternalName(), recordMetricField.getInternalName());
}
if (!orderBySelectColumns.isEmpty()) {
for (String joinValueField : orderBySelectColumns) {
statementBuilder.append(", ");
statementBuilder.append(joinValueField);
}
}
String extraColumns = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_COLUMNS_QUERY_OPTION));
if (extraColumns != null) {
statementBuilder.append(", ");
statementBuilder.append(extraColumns);
}
if (extraSourceColumns != null) {
statementBuilder.append(", ");
statementBuilder.append(extraSourceColumns);
}
if (!needsDistinct && !subSqlQueries.isEmpty()) {
for (Map.Entry<Query<?>, SqlQuery> entry : subSqlQueries.entrySet()) {
SqlQuery subSqlQuery = entry.getValue();
statementBuilder.append(", " + subSqlQuery.aliasPrefix + "r." + SqlDatabase.ID_COLUMN + " AS " + SqlDatabase.SUB_DATA_COLUMN_ALIAS_PREFIX + subSqlQuery.aliasPrefix + "_" + SqlDatabase.ID_COLUMN);
statementBuilder.append(", " + subSqlQuery.aliasPrefix + "r." + SqlDatabase.TYPE_ID_COLUMN + " AS " + SqlDatabase.SUB_DATA_COLUMN_ALIAS_PREFIX + subSqlQuery.aliasPrefix + "_" + SqlDatabase.TYPE_ID_COLUMN);
statementBuilder.append(", " + subSqlQuery.aliasPrefix + "r." + SqlDatabase.DATA_COLUMN + " AS " + SqlDatabase.SUB_DATA_COLUMN_ALIAS_PREFIX + subSqlQuery.aliasPrefix + "_" + SqlDatabase.DATA_COLUMN);
}
}
statementBuilder.append("\nFROM ");
vendor.appendIdentifier(statementBuilder, "Record");
statementBuilder.append(' ');
statementBuilder.append(aliasPrefix);
statementBuilder.append('r');
if (fromClause.length() > 0 &&
!fromClause.contains("LEFT OUTER JOIN") &&
!mysqlIgnoreIndexPrimaryDisabled) {
statementBuilder.append(" /*! IGNORE INDEX (PRIMARY) */");
}
if (cacheData) {
statementBuilder.append("\nLEFT OUTER JOIN ");
vendor.appendIdentifier(statementBuilder, "RecordUpdate");
statementBuilder.append(' ');
statementBuilder.append(aliasPrefix);
statementBuilder.append("ru");
statementBuilder.append(" ON r.");
vendor.appendIdentifier(statementBuilder, "id");
statementBuilder.append(" = ru.");
vendor.appendIdentifier(statementBuilder, "id");
}
if (hasAnyDeferredMetricPredicates()) {
statementBuilder.append(" \nJOIN (");
appendSubqueryMetricSql(statementBuilder, recordMetricField);
statementBuilder.append(") m \nON (");
appendSimpleOnClause(statementBuilder, vendor, "r", "id", "=", "m", "id");
statementBuilder.append(" AND ");
appendSimpleOnClause(statementBuilder, vendor, "r", "typeId", "=", "m", "typeId");
statementBuilder.append(')');
}
statementBuilder.append(fromClause);
statementBuilder.append(whereClause);
statementBuilder.append(havingClause);
statementBuilder.append(orderByClause);
if (needsDistinct && !vendor.supportsDistinctBlob()) {
StringBuilder distinctBuilder = new StringBuilder();
distinctBuilder.append("SELECT");
distinctBuilder.append(" r.");
vendor.appendIdentifier(distinctBuilder, "id");
distinctBuilder.append(", r.");
vendor.appendIdentifier(distinctBuilder, "typeId");
if (fields == null) {
distinctBuilder.append(", r.");
vendor.appendIdentifier(distinctBuilder, "data");
} else if (!fields.isEmpty()) {
distinctBuilder.append(", ");
vendor.appendSelectFields(distinctBuilder, fields);
}
if (!query.getExtraSourceColumns().isEmpty()) {
for (String extraSourceColumn : query.getExtraSourceColumns().keySet()) {
distinctBuilder.append(", ");
vendor.appendIdentifier(distinctBuilder, "d0");
distinctBuilder.append('.');
vendor.appendIdentifier(distinctBuilder, extraSourceColumn);
}
}
distinctBuilder.append(" FROM ");
vendor.appendIdentifier(distinctBuilder, SqlDatabase.RECORD_TABLE);
distinctBuilder.append(" r INNER JOIN (");
distinctBuilder.append(statementBuilder.toString());
distinctBuilder.append(") d0 ON (r.id = d0.id)");
statementBuilder = distinctBuilder;
} else if (!recordMetricHavingPredicates.isEmpty()) {
StringBuilder wrapperStatementBuilder = new StringBuilder();
wrapperStatementBuilder.append("SELECT * FROM (");
wrapperStatementBuilder.append(statementBuilder);
wrapperStatementBuilder.append(") d0 ");
statementBuilder = wrapperStatementBuilder;
}
if (!recordMetricHavingPredicates.isEmpty()) {
// the whole query is already aliased to d0 due to one of the above
//statementBuilder.append(" WHERE ");
StringBuilder havingChildBuilder = new StringBuilder();
for (int i = 0; i < recordMetricHavingPredicates.size(); i++) {
addWherePredicate(havingChildBuilder, recordMetricHavingPredicates.get(i), recordMetricParentHavingPredicates.get(i), false, false);
havingChildBuilder.append(" AND ");
}
if (havingChildBuilder.length() > 0) {
havingChildBuilder.setLength(havingChildBuilder.length() - 5); // " AND "
statementBuilder.append(" WHERE ");
statementBuilder.append(havingChildBuilder);
}
StringBuilder orderByBuilder = new StringBuilder();
// Apply all ORDER BY (deferred and original)
for (Sorter sorter : query.getSorters()) {
addOrderByClause(orderByBuilder, sorter, false, true);
}
if (orderByBuilder.length() > 0) {
orderByBuilder.setLength(orderByBuilder.length() - 2);
orderByBuilder.insert(0, "\nORDER BY ");
statementBuilder.append(orderByBuilder);
}
} else if (!recordMetricSorters.isEmpty()) {
StringBuilder orderByBuilder = new StringBuilder();
for (Sorter sorter : recordMetricSorters) {
addOrderByClause(orderByBuilder, sorter, false, true);
}
if (orderByBuilder.length() > 0) {
orderByBuilder.setLength(orderByBuilder.length() - 2);
orderByBuilder.insert(0, "\nORDER BY ");
statementBuilder.append(orderByBuilder);
}
}
return statementBuilder.toString();
}
/** Returns an SQL statement that can be used as a sub-query. */
public String subQueryStatement() {
StringBuilder statementBuilder = new StringBuilder();
initializeClauses();
statementBuilder.append("SELECT");
if (needsDistinct) {
statementBuilder.append(" DISTINCT");
}
statementBuilder.append(" r.");
vendor.appendIdentifier(statementBuilder, "id");
statementBuilder.append("\nFROM ");
vendor.appendIdentifier(statementBuilder, "Record");
statementBuilder.append(' ');
statementBuilder.append(aliasPrefix);
statementBuilder.append('r');
statementBuilder.append(fromClause);
statementBuilder.append(whereClause);
statementBuilder.append(havingClause);
statementBuilder.append(orderByClause);
return statementBuilder.toString();
}
private enum JoinType {
INNER("INNER JOIN"),
LEFT_OUTER("LEFT OUTER JOIN");
public final String token;
private JoinType(String token) {
this.token = token;
}
}
private Join createJoin(String queryKey) {
String alias = "i" + joins.size();
Join join = new Join(alias, queryKey);
joins.add(join);
if (queryKey.equals(query.getOptions().get(SqlDatabase.MYSQL_INDEX_HINT_QUERY_OPTION))) {
mysqlIndexHint = join;
}
return join;
}
/** Returns the column alias for the given {@code queryKey}. */
private Join getJoin(String queryKey) {
ObjectIndex index = selectedIndexes.get(queryKey);
for (Join join : joins) {
if (queryKey.equals(join.queryKey)) {
return join;
} else {
String indexKey = mappedKeys.get(queryKey).getIndexKey(index);
if (indexKey != null &&
indexKey.equals(mappedKeys.get(join.queryKey).getIndexKey(join.index)) &&
((mappedKeys.get(queryKey).getHashAttribute() != null && mappedKeys.get(queryKey).getHashAttribute().equals(join.hashAttribute)) ||
(mappedKeys.get(queryKey).getHashAttribute() == null && join.hashAttribute == null))) {
// If there's a #attribute on the mapped key, make sure we are returning the matching join.
return join;
}
}
}
return createJoin(queryKey);
}
/** Returns the column alias for the given field-based {@code sorter}. */
private Join getSortFieldJoin(String queryKey) {
ObjectIndex index = selectedIndexes.get(queryKey);
for (Join join : joins) {
if (queryKey.equals(join.queryKey)) {
return join;
} else {
String indexKey = mappedKeys.get(queryKey).getIndexKey(index);
if (indexKey != null &&
indexKey.equals(mappedKeys.get(join.queryKey).getIndexKey(join.index)) &&
((mappedKeys.get(queryKey).getHashAttribute() != null && mappedKeys.get(queryKey).getHashAttribute().equals(join.hashAttribute)) ||
(mappedKeys.get(queryKey).getHashAttribute() == null && join.hashAttribute == null))) {
// If there's a #attribute on the mapped key, make sure we are returning the matching join.
return join;
}
}
}
Join join = createJoin(queryKey);
join.type = JoinType.LEFT_OUTER;
return join;
}
public String getAliasPrefix() {
return aliasPrefix;
}
private void appendSimpleOnClause(StringBuilder sql, SqlVendor vendor, String leftTableAlias, String leftColumnName, String operator, String rightTableAlias, String rightColumnName) {
appendSimpleAliasedColumn(sql, vendor, leftTableAlias, leftColumnName);
sql.append(' ');
sql.append(operator);
sql.append(' ');
appendSimpleAliasedColumn(sql, vendor, rightTableAlias, rightColumnName);
}
private void appendSimpleWhereClause(StringBuilder sql, SqlVendor vendor, String leftTableAlias, String leftColumnName, String operator, Object value) {
appendSimpleAliasedColumn(sql, vendor, leftTableAlias, leftColumnName);
sql.append(' ');
sql.append(operator);
sql.append(' ');
vendor.appendValue(sql, value);
}
private void appendSimpleAliasedColumn(StringBuilder sql, SqlVendor vendor, String tableAlias, String columnName) {
vendor.appendIdentifier(sql, tableAlias);
sql.append('.');
vendor.appendIdentifier(sql, columnName);
}
private class Join {
public Predicate parent;
public JoinType type = JoinType.INNER;
public final boolean needsIndexTable;
public final boolean needsIsNotNull;
public final String likeValuePrefix;
public final String queryKey;
public final String indexType;
public final String table;
public final String idField;
public final String typeIdField;
public final String keyField;
public final List<String> indexKeys = new ArrayList<String>();
private final String alias;
private final String tableName;
private final ObjectIndex index;
private final SqlIndex sqlIndex;
private final SqlIndex.Table sqlIndexTable;
private final String valueField;
private final String hashAttribute;
private final boolean isHaving;
public Join(String alias, String queryKey) {
this.alias = alias;
this.queryKey = queryKey;
Query.MappedKey mappedKey = mappedKeys.get(queryKey);
this.hashAttribute = mappedKey.getHashAttribute();
this.index = selectedIndexes.get(queryKey);
this.indexType = mappedKey.getInternalType();
this.sqlIndex = this.index != null ?
SqlIndex.Static.getByIndex(this.index) :
SqlIndex.Static.getByType(this.indexType);
ObjectField joinField = null;
if (this.index != null) {
joinField = this.index.getParent().getField(this.index.getField());
}
if (Query.ID_KEY.equals(queryKey)) {
needsIndexTable = false;
likeValuePrefix = null;
valueField = recordIdField;
sqlIndexTable = null;
table = null;
tableName = null;
idField = null;
typeIdField = null;
keyField = null;
needsIsNotNull = true;
isHaving = false;
} else if (Query.TYPE_KEY.equals(queryKey)) {
needsIndexTable = false;
likeValuePrefix = null;
valueField = recordTypeIdField;
sqlIndexTable = null;
table = null;
tableName = null;
idField = null;
typeIdField = null;
keyField = null;
needsIsNotNull = true;
isHaving = false;
} else if (Query.DIMENSION_KEY.equals(queryKey)) {
needsIndexTable = false;
likeValuePrefix = null;
//valueField = MetricAccess.METRIC_DIMENSION_FIELD;
StringBuilder fieldBuilder = new StringBuilder();
vendor.appendIdentifier(fieldBuilder, "r");
fieldBuilder.append('.');
vendor.appendIdentifier(fieldBuilder, MetricAccess.METRIC_DIMENSION_FIELD);
valueField = fieldBuilder.toString();
sqlIndexTable = null;
table = null;
tableName = null;
idField = null;
typeIdField = null;
keyField = null;
needsIsNotNull = true;
isHaving = false;
} else if (Query.COUNT_KEY.equals(queryKey)) {
needsIndexTable = false;
likeValuePrefix = null;
StringBuilder fieldBuilder = new StringBuilder();
fieldBuilder.append("COUNT(");
vendor.appendIdentifier(fieldBuilder, "r");
fieldBuilder.append('.');
vendor.appendIdentifier(fieldBuilder, "id");
fieldBuilder.append(')');
valueField = fieldBuilder.toString(); // "count(r.id)";
sqlIndexTable = null;
table = null;
tableName = null;
idField = null;
typeIdField = null;
keyField = null;
needsIsNotNull = false;
isHaving = true;
} else if (Query.ANY_KEY.equals(queryKey) ||
Query.LABEL_KEY.equals(queryKey)) {
throw new UnsupportedIndexException(database, queryKey);
} else if (database.hasInRowIndex() && index.isShortConstant()) {
needsIndexTable = false;
likeValuePrefix = "%;" + database.getSymbolId(mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey))) + "=";
valueField = recordInRowIndexField;
sqlIndexTable = this.sqlIndex.getReadTable(database, index);
table = null;
tableName = null;
idField = null;
typeIdField = null;
keyField = null;
needsIsNotNull = true;
isHaving = false;
} else if (joinField != null && joinField.isMetric()) {
needsIndexTable = false;
likeValuePrefix = null;
sqlIndexTable = this.sqlIndex.getReadTable(database, index);
tableName = MetricAccess.Static.getMetricTableIdentifier(database); // Don't wrap this with appendIdentifier
table = tableName;
alias = "r";
idField = null;
typeIdField = null;
keyField = null;
needsIsNotNull = false;
if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
// for metricField#dimension, use dimensionId
valueField = MetricAccess.METRIC_DIMENSION_FIELD;
isHaving = false;
} else if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
// for metricField#date, use "data"
valueField = MetricAccess.METRIC_DATA_FIELD;
isHaving = false;
} else {
// for metricField, use internalName
StringBuilder fieldBuilder = new StringBuilder();
vendor.appendAlias(fieldBuilder, joinField.getInternalName());
valueField = fieldBuilder.toString();
isHaving = true;
}
} else {
needsIndexTable = true;
likeValuePrefix = null;
addIndexKey(queryKey);
valueField = null;
sqlIndexTable = this.sqlIndex.getReadTable(database, index);
StringBuilder tableBuilder = new StringBuilder();
tableName = sqlIndexTable.getName(database, index);
vendor.appendIdentifier(tableBuilder, tableName);
tableBuilder.append(' ');
tableBuilder.append(aliasPrefix);
tableBuilder.append(alias);
table = tableBuilder.toString();
idField = aliasedField(alias, sqlIndexTable.getIdField(database, index));
typeIdField = aliasedField(alias, sqlIndexTable.getTypeIdField(database, index));
keyField = aliasedField(alias, sqlIndexTable.getKeyField(database, index));
needsIsNotNull = true;
isHaving = false;
}
}
public String getAlias() {
return this.alias;
}
public String toString() {
return this.tableName + " (" + this.alias + ") ." + this.valueField;
}
public String getTableName() {
return this.tableName;
}
public void addIndexKey(String queryKey) {
String indexKey = mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey));
if (ObjectUtils.isBlank(indexKey)) {
throw new UnsupportedIndexException(database, indexKey);
}
if (needsIndexTable) {
indexKeys.add(indexKey);
}
}
public Object quoteIndexKey(String indexKey) {
return SqlDatabase.quoteValue(sqlIndexTable.convertKey(database, index, indexKey));
}
public void appendValue(StringBuilder builder, ComparisonPredicate comparison, Object value) {
Query.MappedKey mappedKey = mappedKeys.get(comparison.getKey());
ObjectField field = mappedKey.getField();
SqlIndex fieldSqlIndex = field != null ?
SqlIndex.Static.getByType(field.getInternalItemType()) :
sqlIndex;
if (field != null && field.isMetric()) {
if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
String stringValue = null;
if (value != null) {
stringValue = String.valueOf(value);
}
value = MetricAccess.getDimensionIdByValue(database, stringValue);
} else if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
// EventDates in MetricAccess are smaller than long
Character padChar = 'F';
if (PredicateParser.LESS_THAN_OPERATOR.equals(comparison.getOperator()) ||
PredicateParser.GREATER_THAN_OR_EQUALS_OPERATOR.equals(comparison.getOperator())) {
padChar = '0';
}
if (value instanceof DateTime) {
value = ((DateTime) value).getMillis();
}
if (value instanceof Date) {
value = ((Date) value).getTime();
}
vendor.appendMetricEncodeTimestampSql(builder, null, (Long) value, padChar);
// Taking care of the appending since it is raw SQL; return here so it isn't appended again
return;
} else {
value = ObjectUtils.to(Double.class, value);
}
} else if (fieldSqlIndex == SqlIndex.UUID) {
value = ObjectUtils.to(UUID.class, value);
} else if (fieldSqlIndex == SqlIndex.NUMBER &&
!PredicateParser.STARTS_WITH_OPERATOR.equals(comparison.getOperator())) {
if (value != null) {
Long valueLong = ObjectUtils.to(Long.class, value);
if (valueLong != null) {
value = valueLong;
} else {
value = ObjectUtils.to(Double.class, value);
}
}
} else if (fieldSqlIndex == SqlIndex.STRING) {
if (comparison.isIgnoreCase()) {
value = value.toString().toLowerCase(Locale.ENGLISH);
} else if (database.comparesIgnoreCase()) {
String valueString = StringUtils.trimAndCollapseWhitespaces(value.toString());
if (!index.isCaseSensitive()) {
valueString = valueString.toLowerCase(Locale.ENGLISH);
}
value = valueString;
}
}
vendor.appendValue(builder, value);
}
public String getValueField(String queryKey, ComparisonPredicate comparison) {
String field;
if (valueField != null) {
field = valueField;
} else if (sqlIndex != SqlIndex.CUSTOM) {
field = aliasedField(alias, sqlIndexTable.getValueField(database, index, 0));
} else {
String valueFieldName = mappedKeys.get(queryKey).getField().getInternalName();
List<String> fieldNames = index.getFields();
int fieldIndex = 0;
for (int size = fieldNames.size(); fieldIndex < size; ++ fieldIndex) {
if (valueFieldName.equals(fieldNames.get(fieldIndex))) {
break;
}
}
field = aliasedField(alias, sqlIndexTable.getValueField(database, index, fieldIndex));
}
if (comparison != null &&
comparison.isIgnoreCase() &&
(sqlIndex != SqlIndex.STRING ||
sqlIndexTable.getVersion() < 3)) {
field = "LOWER(" + vendor.convertRawToStringSql(field) + ")";
}
return field;
}
}
} |
package claw.wani.x2t.configuration;
import claw.ClawVersion;
import claw.shenron.transformation.BlockTransformation;
import claw.tatsu.TatsuConstant;
import claw.tatsu.common.CompilerDirective;
import claw.tatsu.common.Context;
import claw.tatsu.common.Target;
import claw.tatsu.directive.configuration.AcceleratorConfiguration;
import claw.tatsu.directive.configuration.OpenAccConfiguration;
import claw.tatsu.directive.configuration.OpenMpConfiguration;
import claw.tatsu.xcodeml.xnode.Xname;
import claw.wani.transformation.ClawBlockTransformation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Configuration class is used to read the configuration file and expose its
* information to the translator.
*
* @author clementval
*/
public class Configuration {
public static final String TRANSLATOR = "translator";
// Specific keys
private static final String DEFAULT_TARGET = "default_target";
private static final String DEFAULT_DIRECTIVE = "default_directive";
private static final String DEFAULT_CONFIG_FILE = "claw-default.xml";
private static final String XML_EXT = ".xml";
private static final String CONFIG_XSD = "claw_config.xsd";
private static final String SET_XSD = "claw_transformation_set.xsd";
// Element and attribute names
private static final String GLOBAL_ELEMENT = "global";
private static final String GROUPS_ELEMENT = "groups";
private static final String GROUP_ELEMENT = "group";
private static final String SETS_ELEMENT = "sets";
private static final String SET_ELEMENT = "set";
private static final String PARAMETER_ELEMENT = "parameter";
private static final String CLASS_ATTR = "class";
private static final String NAME_ATTR = "name";
private static final String TYPE_ATTR = "type";
private static final String KEY_ATTR = "key";
private static final String VALUE_ATTR = "value";
private static final String VERSION_ATTR = "version";
private static final String TRIGGER_ATTR = "trigger";
private static final String DIRECTIVE_ATTR = "directive";
private static final String EXT_CONF_TYPE = "extension";
private static final String JAR_ATTR = "jar";
// Transformation set
private static final String TRANSFORMATION_ELEMENT = "transformation";
// Specific values
private static final String DEPENDENT_GR_TYPE = "dependent";
private static final String INDEPENDENT_GR_TYPE = "independent";
private static final String DIRECTIVE_TR_TYPE = "directive";
private static final String TRANSLATION_UNIT_TR_TYPE = "translation_unit";
// OpenMP specific values
public static final String CPU_STRATEGY = "cpu_trans_strategy";
public static final String CPU_STRATEGY_SINGLE = "single";
public static final String CPU_STRATEGY_FUSION = "fusion";
// SCA configuration keys
public static final String SCA_ELEMENTAL_PROMOTION_ASSUMED =
"sca_elemental_promotion_assumed";
// env var
private static final String CLAW_TRANS_SET_PATH = "CLAW_TRANS_SET_PATH";
// Local objects
private String _configuration_path;
private Map<String, String> _parameters;
private List<GroupConfiguration> _groups;
private Map<String, GroupConfiguration> _availableGroups;
private AcceleratorConfiguration _accelerator;
private String[] _transSetPaths;
private boolean _forcePure = false;
private ModelConfig _modelConfig;
/**
* Lazy holder pattern.
*/
private static class LazyHolder {
static final Configuration INSTANCE = new Configuration();
}
/**
* Private ctor to avoid external instantiation.
*/
private Configuration() {
_modelConfig = new ModelConfig();
}
/**
* Get the unique instance.
*
* @return Unique Configuration instance.
*/
public static Configuration get() {
return LazyHolder.INSTANCE;
}
/**
* Constructs basic configuration object.
*
* @param directive Accelerator directive language.
* @param target Target architecture.
*/
public void init(CompilerDirective directive, Target target) {
_parameters = new HashMap<>();
if(directive == null) {
directive = CompilerDirective.NONE;
}
_parameters.put(DEFAULT_DIRECTIVE, directive.toString());
if(target != null) {
_parameters.put(DEFAULT_TARGET, target.toString());
}
// Init specific configuration if needed
switch(directive) {
case OPENACC:
_accelerator = new OpenAccConfiguration(_parameters);
break;
case OPENMP:
_accelerator = new OpenMpConfiguration(_parameters);
break;
default:
_accelerator = new AcceleratorConfiguration(_parameters);
break;
}
_groups = new ArrayList<>();
_availableGroups = new HashMap<>();
_configuration_path = null;
}
/**
* Constructs a new configuration object from the give configuration file.
*
* @param configPath Path to the configuration files and XSD
* schemas.
* @param userConfigFile Path to the alternative configuration.
* @param modelConfig SCA specific model configuration.
* @param userDefinedTarget Target option passed by user. Can be null.
* @param userDefinedDirective Directive option passed by user. Can be null.
* @param userMaxColumns Max column option passed by user. Can be 0.
* @throws Exception If configuration cannot be loaded properly.
*/
public void load(String configPath, String userConfigFile, String modelConfig,
String userDefinedTarget, String userDefinedDirective,
int userMaxColumns)
throws Exception
{
_configuration_path = configPath;
_parameters = new HashMap<>();
_groups = new ArrayList<>();
_availableGroups = new HashMap<>();
boolean readDefault = true;
Document userConf = null;
// Read the environment variable for external transformation sets
_transSetPaths = new String[0];
if(System.getenv(CLAW_TRANS_SET_PATH) != null) {
_transSetPaths = System.getenv(CLAW_TRANS_SET_PATH).split(";");
}
// Configuration has been given by the user. Read it first.
if(userConfigFile != null) {
File userConfiguration = Paths.get(userConfigFile).toFile();
userConf = validateConfiguration(userConfiguration);
readDefault = isExtension(userConf);
}
if(readDefault) {
// There is no user defined configuration or it is just an extension.
File defaultConfigFile =
Paths.get(_configuration_path, DEFAULT_CONFIG_FILE).toFile();
Document defaultConf = validateConfiguration(defaultConfigFile);
readConfiguration(defaultConf, false);
if(userConf != null) { // Read extension
readConfiguration(userConf, true);
}
} else {
// User defined configuration is a full configuration.
// Then the default one is not read.
readConfiguration(userConf, false);
}
setUserDefinedTarget(userDefinedTarget);
setUserDefineDirective(userDefinedDirective);
switch(getCurrentDirective()) {
case OPENACC:
_accelerator = new OpenAccConfiguration(_parameters);
break;
case OPENMP:
_accelerator = new OpenMpConfiguration(_parameters);
break;
default:
_accelerator = new AcceleratorConfiguration(_parameters);
}
Context.get().init(getCurrentDirective(), getCurrentTarget(), _accelerator,
userMaxColumns);
if(modelConfig != null) {
getModelConfig().load(modelConfig);
}
}
/**
* Check whether the configuration file is an extension of the default
* configuration or if it is a standalone configuration.
*
* @param configurationDocument XML document representing the configuration
* file.
* @return True if the configuration is an extension. False otherwise.
*/
private boolean isExtension(Document configurationDocument) {
Element root = configurationDocument.getDocumentElement();
Element global =
(Element) root.getElementsByTagName(GLOBAL_ELEMENT).item(0);
return global != null && global.hasAttribute(TYPE_ATTR)
&& global.getAttribute(TYPE_ATTR).equals(EXT_CONF_TYPE);
}
/**
* Validate configuration file against its XSD schema.
*
* @param configurationFile File object representing the configuration file.
* @return XML Document of the configuration file.
* @throws Exception If the configuration file cannot be validated.
*/
private Document validateConfiguration(File configurationFile)
throws Exception
{
File configurationSchema =
Paths.get(_configuration_path, CONFIG_XSD).toFile();
Document doc = parseAndValidate(configurationFile, configurationSchema);
Element root = doc.getDocumentElement();
checkVersion(root.getAttribute(VERSION_ATTR));
return doc;
}
/**
* Read different parts of the configuration file.
*
* @param configurationDocument XML document representing the configuration
* file.
* @param isExtension Flag stating if the configuration is an
* extension.
* @throws Exception If the configuration has errors.
*/
private void readConfiguration(Document configurationDocument,
boolean isExtension) throws Exception
{
Element root = configurationDocument.getDocumentElement();
// Read the global parameters
Element global =
(Element) root.getElementsByTagName(GLOBAL_ELEMENT).item(0);
readParameters(global, isExtension);
// Read the used transformation sets
Element sets =
(Element) root.getElementsByTagName(SETS_ELEMENT).item(0);
if(isExtension) { // Sets are overridden by extension
if(sets != null) {
_availableGroups.clear();
readSets(sets);
}
} else {
// For root configuration, the sets element is mandatory.
if(sets == null) {
throw new Exception("Root configuration must have sets element!");
}
readSets(sets);
}
// Read the transformation groups definition and order
Element groups =
(Element) root.getElementsByTagName(GROUPS_ELEMENT).item(0);
if(isExtension) {
if(groups != null) { // Groups are overridden by extension
_groups.clear();
readGroups(groups);
}
} else {
// For root configuration, the groups element is mandatory.
if(groups == null) {
throw new Exception("Root configuration must have groups element!");
}
readGroups(groups);
}
}
/**
* Parse the configuration file as an XML document and validate it against its
* XSD schema.
*
* @param xmlFile File object pointing to the configuration file.
* @param xsdSchema File object pointing to the XSD schema.
* @return XML document representing the configuration file.
* @throws Exception If the configuration file does not validate.
*/
private Document parseAndValidate(File xmlFile, File xsdSchema)
throws Exception
{
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
try {
validate(document, xsdSchema);
} catch(Exception e) {
throw new Exception("Error: Configuration file " + xmlFile.getName()
+ " is not well formatted: " + e.getMessage());
}
return document;
}
/**
* Validate the configuration file with the XSD schema.
*
* @param document XML Document.
* @param xsd File representing the XSD schema.
* @throws SAXException If configuration file is not valid.
* @throws IOException If schema is not found.
*/
private void validate(Document document, File xsd)
throws SAXException, IOException
{
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(xsd);
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));
}
/**
* Get value of a parameter.
*
* @param key Key of the parameter.
* @return Value of the parameter. Null if parameter doesn't exists.
*/
public String getParameter(String key) {
return (_parameters.containsKey(key)) ? _parameters.get(key) : null;
}
/**
* Get boolean value of a parameter.
*
* @param key Key of the parameter.
* @return Value of the parameter. False if parameter doesn't exists or its
* value is false.
*/
public boolean getBooleanParameter(String key) {
return _parameters.containsKey(key)
&& _parameters.get(key).equalsIgnoreCase(Xname.TRUE);
}
/**
* Get the GPU specific configuration information.
*
* @return The GPU configuration object.
*/
public AcceleratorConfiguration accelerator() {
return _accelerator;
}
/**
* Get all the group configuration information.
*
* @return List of group configuration.
*/
public List<GroupConfiguration> getGroups() {
return _groups;
}
/**
* Get the current directive directive defined in the configuration.
*
* @return Current directive value.
*/
public CompilerDirective getCurrentDirective() {
return CompilerDirective.fromString(getParameter(DEFAULT_DIRECTIVE));
}
/**
* Get the current target defined in the configuration or by the user on
* the command line.
*
* @return Current target value.
*/
public Target getCurrentTarget() {
return Target.fromString(getParameter(DEFAULT_TARGET));
}
/**
* Read all the transformation sets.
*
* @param sets Parent element "sets" for the transformation set.
* @throws Exception If transformation set file does not exist or not well
* formatted.
*/
private void readSets(Element sets) throws Exception {
File xsdSchema = Paths.get(_configuration_path, SET_XSD).toFile();
NodeList transformationSets = sets.getElementsByTagName(SET_ELEMENT);
for(int i = 0; i < transformationSets.getLength(); ++i) {
Element e = (Element) transformationSets.item(i);
String setName = e.getAttribute(NAME_ATTR);
File setFile = Paths.get(_configuration_path, setName + XML_EXT).toFile();
if(!setFile.exists()) {
throw new Exception("Transformation set " + setName
+ " cannot be found!");
}
Document setDocument = parseAndValidate(setFile, xsdSchema);
Element root = setDocument.getDocumentElement();
boolean isExternal = root.hasAttribute(JAR_ATTR);
// Try to locate the external jar
if(isExternal) {
String externalJar = root.getAttribute(JAR_ATTR);
URLClassLoader loader = loadExternalJar(externalJar);
readTransformations(setName, root, loader);
} else {
readTransformations(setName, root, null);
}
}
}
/**
* Load the give jar file if located in one of the defined CLAW_TRANS_SET_PATH
*
* @param jarFile Name of the jar file to load with .jar extension.
* @return The URLClassLoader associated with the jar file if found. Null
* otherwise.
* @throws FileNotFoundException If jar file not found.
* @throws MalformedURLException If classpath is malformed.
*/
private URLClassLoader loadExternalJar(String jarFile)
throws FileNotFoundException, MalformedURLException
{
if(_transSetPaths.length == 0) {
throw new FileNotFoundException("No path defined in "
+ CLAW_TRANS_SET_PATH + ". Unable to load transformation set: "
+ jarFile);
}
URLClassLoader external;
for(String path : _transSetPaths) {
Path jar = Paths.get(path, jarFile);
if(jar.toFile().exists()) {
external = new URLClassLoader(new URL[]{
new URL("file://" + jar.toString())},
this.getClass().getClassLoader());
return external;
}
}
throw new FileNotFoundException("Cannot find jar file " + jarFile);
}
/**
* Read all the parameter element and store their key/value pair in the map.
*
* @param globalElement Parent element "global" for the parameters.
*/
private void readParameters(Element globalElement, boolean overwrite) {
NodeList parameters = globalElement.getElementsByTagName(PARAMETER_ELEMENT);
for(int i = 0; i < parameters.getLength(); ++i) {
Element e = (Element) parameters.item(i);
String key = e.getAttribute(KEY_ATTR);
if(overwrite) { // Parameter overwritten
_parameters.remove(key);
}
_parameters.put(key, e.getAttribute(VALUE_ATTR));
}
}
/**
* Read all the transformation element and store their information in a list
* of available GroupConfiguration objects.
*
* @param transformationsNode Parent element "groups" for the group elements.
* @throws Exception Group information not valid.
*/
private void readTransformations(String setName, Element transformationsNode,
URLClassLoader loader) throws Exception
{
NodeList transformationElements =
transformationsNode.getElementsByTagName(TRANSFORMATION_ELEMENT);
for(int i = 0; i < transformationElements.getLength(); ++i) {
if(transformationElements.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element g = (Element) transformationElements.item(i);
String name = g.getAttribute(NAME_ATTR);
String type = g.getAttribute(TYPE_ATTR);
// Read group type
GroupConfiguration.GroupType gType;
switch(type) {
case DEPENDENT_GR_TYPE:
gType = GroupConfiguration.GroupType.DEPENDENT;
break;
case INDEPENDENT_GR_TYPE:
gType = GroupConfiguration.GroupType.INDEPENDENT;
break;
default:
throw new Exception("Invalid group type specified.");
}
// Read transformation class path
String cPath = g.getAttribute(CLASS_ATTR);
if(cPath == null || cPath.isEmpty()) {
throw new Exception("Invalid group class transformation definition.");
}
// Read trigger type
String triggerTypeAttr = g.getAttribute(TRIGGER_ATTR);
GroupConfiguration.TriggerType triggerType;
switch(triggerTypeAttr) {
case DIRECTIVE_TR_TYPE:
triggerType = GroupConfiguration.TriggerType.DIRECTIVE;
break;
case TRANSLATION_UNIT_TR_TYPE:
triggerType = GroupConfiguration.TriggerType.TRANSLATION_UNIT;
break;
default:
throw new Exception("Invalid trigger type specified.");
}
String directive = null;
if(triggerType == GroupConfiguration.TriggerType.DIRECTIVE) {
directive = g.getAttribute(DIRECTIVE_ATTR);
if(directive == null) {
throw new Exception("Transformation with trigger type directive " +
"must have the directive attribute.");
}
}
// Find actual class
Class transClass;
try {
// Check if class is there
if(loader != null) {
transClass = Class.forName(cPath, true, loader);
} else {
transClass = Class.forName(cPath);
}
} catch(ClassNotFoundException e) {
throw new Exception("Transformation class " + cPath +
" not available");
}
// Check that translation unit trigger type are not block transformation
if(triggerType == GroupConfiguration.TriggerType.TRANSLATION_UNIT
&& (transClass.getSuperclass() == BlockTransformation.class
|| transClass.getSuperclass() == ClawBlockTransformation.class))
{
throw new Exception("Translation unit trigger cannot be block " +
"transformation");
}
// Store group configuration
if(_availableGroups.containsKey(name)) {
throw new Exception("Transformation " + name + " has name conflict!");
}
_availableGroups.put(name, new GroupConfiguration(setName, name, gType,
triggerType, cPath, directive, transClass));
}
}
}
/**
* Read defined transformation groups in configuration. Order determines
* application order of transformation.
*
* @param groupsNode The "groups" element of the configuration.
* @throws Exception If the group name is not an available in any
* transformation set.
*/
private void readGroups(Element groupsNode) throws Exception {
NodeList groupElements = groupsNode.getElementsByTagName(GROUP_ELEMENT);
for(int i = 0; i < groupElements.getLength(); ++i) {
if(groupElements.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element g = (Element) groupElements.item(i);
String name = g.getAttribute(NAME_ATTR);
if(_availableGroups.containsKey(name)) {
GroupConfiguration gc = _availableGroups.get(name);
if(_groups.contains(gc)) {
throw new Exception("Duplicated transformation group creation: "
+ name);
}
_groups.add(_availableGroups.get(name));
} else {
throw new Exception("No transformation found for " + name
+ " in available transformation sets!");
}
}
}
}
/**
* Set the user defined target in the configuration.
*
* @param option Option passed as argument. Has priority over configuration
* file.
*/
private void setUserDefinedTarget(String option) {
if(option != null) {
_parameters.put(DEFAULT_TARGET, option);
}
}
/**
* Set the user defined directive in the configuration.
*
* @param option Option passed as argument. Has priority over configuration
* file.
*/
private void setUserDefineDirective(String option) {
if(option != null) {
_parameters.put(DEFAULT_DIRECTIVE, option);
}
}
/**
* Enable the force pure option.
*/
public void setForcePure() {
_forcePure = true;
}
/**
* Check whether the force pure option is enabled or not.
*
* @return If true, the function is enabled. Disabled otherwise.
*/
public boolean isForcePure() {
return _forcePure;
}
/**
* Check whether the configuration file version is high enough with the
* compiler version.
*
* @param configVersion Version string from the configuration file.
* @throws Exception If the configuration version is not high enough.
*/
protected void checkVersion(String configVersion) throws Exception {
int[] configMajMin = getMajorMinor(configVersion);
int[] compilerMajMin = getMajorMinor(ClawVersion.VERSION);
if(configMajMin[0] < compilerMajMin[0]) {
throw new Exception("Configuration version is smaller than " +
"CLAW Compiler version: " + compilerMajMin[0] + "." +
compilerMajMin[1]);
}
}
/**
* Extract major and minor version number from the full version String.
*
* @param version Full version String. Format: major.minor.fixes
* @return Two dimensional array with the major number at index 0 and the
* minor at index 1.
* @throws Exception If the version String is not of the correct format.
*/
protected int[] getMajorMinor(String version) throws Exception {
Pattern p = Pattern.compile("^(\\d+)\\.(\\d+)\\.?(\\d+)?");
Matcher m = p.matcher(version);
if(!m.matches()) {
throw new Exception("Configuration version not well formatted");
}
int major = Integer.parseInt(m.group(1));
int minor = Integer.parseInt(m.group(2));
return new int[]{major, minor};
}
/**
* Display the loaded configuration.
*/
public void displayConfig() {
System.out.println(String.format("- CLAW Compiler configuration -%n"));
System.out.println(String.format("Default directive directive: %s%n",
getCurrentDirective()));
System.out.println(String.format("Default target: %s%n",
getCurrentTarget()));
System.out.println("Current transformation order:");
int i = 0;
System.out.printf(" %3s %-20s %-20s %-15s %-20s %-10s %-60s%n",
"Id", "set", "name", "type", "trigger", "directive", "class");
System.out.printf(" %3s %-20s %-20s %-15s %-20s %-10s %-60s%n",
"
for(GroupConfiguration g : getGroups()) {
System.out.printf(" %2d) %-20s %-20s %-15s %-20s %-10s %-60s%n",
i, g.getSetName(), g.getName(), g.getType(), g.getTriggerType(),
g.getTriggerType() == GroupConfiguration.TriggerType.DIRECTIVE
? g.getDirective() : "-", g.getTransformationClassName());
++i;
}
}
/**
* Override a configuration key-value parameter.
*
* @param key Key of the parameter.
* @param value Value of the parameter.
*/
public void overrideConfigurationParameter(String key, String value) {
if(value != null && !value.isEmpty()) {
_parameters.remove(key.toLowerCase());
_parameters.put(key, value);
}
}
/**
* Get the global model configuration.
*
* @return Global model config instance.
*/
public ModelConfig getModelConfig() {
return _modelConfig;
}
} |
import java.util.*;
public class CommandProcessor
{
/*
Courtney Karppi
CISC 370
April 18, 2015
Class Variables:
commandRegistry
A map that contains all the commands and command name
noSuchCommand
A command that is used when the command doesn't exist
nothingEnteredCommand
A command that is used when nothing is entered
Constructors:
CommandProcessor(Command noSuchCommand, Command nothingEnteredCommand)
Sets the instance variable and creates a new hashmap
Methods:
public Command[] getAllCommands()
Returns all the commands in the commandRegistry in the form of a Command[]
public void register(Command command)
Registers a new command in the commandRegistry
public Command getCommand(String commandText)
Runs the command associated with the parameter
private static String convertToKey(String data)
Removes the white space from the data and converts it to lower case
*/
private Map<String,Command> commandRegistry;
private Command noSuchCommand;
private Command nothingEnteredCommand;
public CommandProcessor(Command noSuchCommand, Command nothingEnteredCommand)
{
this.noSuchCommand = noSuchCommand;
this.nothingEnteredCommand = nothingEnteredCommand;
this.commandRegistry = new HashMap<String, Command>();
}//CommandProcessor
public Command[] getAllCommands()
{
//Returns all the commands in the commandRegistry in the form of a Command[]
return commandRegistry.values().toArray(new Command[0]);
}//getAllCommands
public void register(Command command)
{
//Registers a new command in the commandRegistry
String commandText;
commandText = convertToKey(command.getCommandName());
//checks the parameter to make sure it is not blank or not in the commandRegistry
if(!(commandText.equals("")||commandRegistry.containsKey(commandText)))
{
commandRegistry.put(commandText, command);
}
}//register
public Command getCommand(String commandText)
{
//Runs the command associated with the parameter
Command command;
if(commandText.length() == 0)
{
command = this.noSuchCommand;
}
else
{
command = commandRegistry.get(convertToKey(commandText));
}
if (command == null)
{
command = this.nothingEnteredCommand;
}
return command;
}//getCommand
private static String convertToKey(String data)
{
//Removes the white space from the data and converts it to lower case
return data.trim().toLowerCase();
}//convertToKey
}//class |
package c5db.discovery;
import c5db.codec.UdpProtostuffDecoder;
import c5db.codec.UdpProtostuffEncoder;
import c5db.discovery.generated.Availability;
import c5db.discovery.generated.ModuleDescriptor;
import c5db.interfaces.C5Server;
import c5db.interfaces.DiscoveryModule;
import c5db.interfaces.discovery.NewNodeVisible;
import c5db.interfaces.discovery.NodeInfo;
import c5db.interfaces.discovery.NodeInfoReply;
import c5db.interfaces.discovery.NodeInfoRequest;
import c5db.interfaces.server.ModuleStateChange;
import c5db.messages.generated.ModuleType;
import c5db.util.FiberOnly;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.AbstractService;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.jetlang.channels.MemoryChannel;
import org.jetlang.channels.MemoryRequestChannel;
import org.jetlang.channels.Request;
import org.jetlang.channels.RequestChannel;
import org.jetlang.core.Callback;
import org.jetlang.fibers.Fiber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Uses broadcast UDP packets to discover 'adjacent' nodes in the cluster. Maintains
* a state table for them, and provides information to other modules as they request it.
* <p/>
* Currently UDP broadcast has some issues on Mac OSX vs Linux. The big question,
* specifically, is what happens when multiple processes bind to 255.255.255.255:PORT
* and send packets? Which processes receive such packets?
* <ul>
* <li>On Mac OSX 10.8/9, all processes reliably recieve all packets including
* the originating process</li>
* <li>On Linux (Ubuntu, modern) a variety of things appear to occur:
* <ul>
* <li>First to bind receives all packets</li>
* <li>All processes receives all packets</li>
* <li>No one receives any packets</li>
* <li>Please fill this doc in!</li>
* </ul></li>
* </ul>
* <p/>
* The beacon service needs to be refactored and different discovery methods need to be
* pluggable but all behind the discovery module interface.
*/
public class BeaconService extends AbstractService implements DiscoveryModule {
private static final Logger LOG = LoggerFactory.getLogger(BeaconService.class);
public static final String LOOPBACK_ADDRESS = "127.0.0.1";
public static final String BROADCAST_ADDRESS = "255.255.255.255";
@Override
public ModuleType getModuleType() {
return ModuleType.Discovery;
}
@Override
public boolean hasPort() {
return true;
}
@Override
public int port() {
return discoveryPort;
}
@Override
public String acceptCommand(String commandString) {
return null;
}
private final RequestChannel<NodeInfoRequest, NodeInfoReply> nodeInfoRequests = new MemoryRequestChannel<>();
@Override
public RequestChannel<NodeInfoRequest, NodeInfoReply> getNodeInfo() {
return nodeInfoRequests;
}
@Override
public ListenableFuture<NodeInfoReply> getNodeInfo(long nodeId, ModuleType module) {
SettableFuture<NodeInfoReply> future = SettableFuture.create();
fiber.execute(() -> {
NodeInfo peer = peers.get(nodeId);
if (peer == null) {
future.set(NodeInfoReply.NO_REPLY);
} else {
Integer servicePort = peer.modules.get(module);
if (servicePort == null) {
future.set(NodeInfoReply.NO_REPLY);
} else {
List<String> peerAddrs = peer.availability.getAddressesList();
future.set(new NodeInfoReply(true, peerAddrs, servicePort));
}
}
});
return future;
}
@FiberOnly
private void handleNodeInfoRequest(Request<NodeInfoRequest, NodeInfoReply> message) {
NodeInfoRequest req = message.getRequest();
NodeInfo peer = peers.get(req.nodeId);
if (peer == null) {
message.reply(NodeInfoReply.NO_REPLY);
return;
}
Integer servicePort = peer.modules.get(req.moduleType);
if (servicePort == null) {
message.reply(NodeInfoReply.NO_REPLY);
return;
}
List<String> peerAddrs = peer.availability.getAddressesList();
// does this module run on that peer?
message.reply(new NodeInfoReply(true, peerAddrs, servicePort));
}
@Override
public String toString() {
return "BeaconService{" +
"discoveryPort=" + discoveryPort +
", nodeId=" + nodeId +
'}';
}
// For main system modules/pubsub stuff.
private final C5Server c5Server;
private final long nodeId;
private final int discoveryPort;
private final NioEventLoopGroup eventLoop;
private final Map<ModuleType, Integer> moduleInfo = new HashMap<>();
private final Map<Long, NodeInfo> peers = new HashMap<>();
private final org.jetlang.channels.Channel<Availability> incomingMessages = new MemoryChannel<>();
private final Fiber fiber;
// These should be final, but they are initialized in doStart().
private Channel broadcastChannel = null;
private InetSocketAddress sendAddress = null;
private Bootstrap bootstrap = null;
private List<String> localIPs;
public class BeaconMessageHandler extends SimpleChannelInboundHandler<Availability> {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception, ignoring datagram", cause);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Availability msg) throws Exception {
incomingMessages.publish(msg);
}
}
/**
* @param nodeId the id of this node.
* @param discoveryPort the port to send discovery beacons on and to listen to
* @throws InterruptedException
* @throws SocketException
*/
public BeaconService(long nodeId,
int discoveryPort,
final Fiber fiber,
NioEventLoopGroup eventLoop,
Map<ModuleType, Integer> modules,
C5Server theC5Server
) throws InterruptedException, SocketException {
this.discoveryPort = discoveryPort;
this.nodeId = nodeId;
this.fiber = fiber;
moduleInfo.putAll(modules);
this.c5Server = theC5Server;
this.eventLoop = eventLoop;
}
@Override
public ListenableFuture<ImmutableMap<Long, NodeInfo>> getState() {
final SettableFuture<ImmutableMap<Long, NodeInfo>> future = SettableFuture.create();
fiber.execute(new Runnable() {
@Override
public void run() {
future.set(getCopyOfState());
}
});
return future;
}
org.jetlang.channels.Channel<NewNodeVisible> newNodeVisibleChannel = new MemoryChannel<>();
@Override
public org.jetlang.channels.Channel<NewNodeVisible> getNewNodeNotifications() {
return newNodeVisibleChannel;
}
private ImmutableMap<Long, NodeInfo> getCopyOfState() {
return ImmutableMap.copyOf(peers);
}
@FiberOnly
private void sendBeacon() {
if (broadcastChannel == null) {
LOG.debug("Channel not available yet, deferring beacon send");
return;
}
LOG.trace("Sending beacon broadcast message to {}", sendAddress);
List<ModuleDescriptor> msgModules = new ArrayList<>(moduleInfo.size());
for (ModuleType moduleType : moduleInfo.keySet()) {
msgModules.add(
new ModuleDescriptor(moduleType,
moduleInfo.get(moduleType))
);
}
Availability beaconMessage = new Availability(nodeId, 0, localIPs, msgModules);
broadcastChannel.writeAndFlush(new
UdpProtostuffEncoder.UdpProtostuffMessage<>(sendAddress, beaconMessage));
// Fix issue #76, feed back the beacon Message to our own database:
processWireMessage(beaconMessage);
}
@FiberOnly
private void processWireMessage(Availability message) {
LOG.trace("Got incoming message {}", message);
if (message.getNodeId() == 0) {
// if (!message.hasNodeId()) {
LOG.error("Incoming availability message does not have node id, ignoring!");
return;
}
// Always just overwrite what was already there for now.
// TODO consider a more sophisticated merge strategy?
NodeInfo nodeInfo = new NodeInfo(message);
if (!peers.containsKey(message.getNodeId())) {
getNewNodeNotifications().publish(new NewNodeVisible(message.getNodeId(), nodeInfo));
}
peers.put(message.getNodeId(), nodeInfo);
}
@FiberOnly
private void serviceChange(ModuleStateChange message) {
if (message.state == State.RUNNING) {
LOG.debug("BeaconService adding running module {} on port {}",
message.module.getModuleType(),
message.module.port());
moduleInfo.put(message.module.getModuleType(), message.module.port());
} else if (message.state == State.STOPPING || message.state == State.FAILED || message.state == State.TERMINATED) {
LOG.debug("BeaconService removed module {} on port {} with state {}",
message.module.getModuleType(),
message.module.port(),
message.state);
moduleInfo.remove(message.module.getModuleType());
} else {
LOG.debug("BeaconService got unknown state module change {}", message);
}
}
@Override
protected void doStart() {
eventLoop.next().execute(new Runnable() {
@Override
public void run() {
bootstrap = new Bootstrap();
bootstrap.group(eventLoop)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new ChannelInitializer<DatagramChannel>() {
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("protobufDecoder",
new UdpProtostuffDecoder<>(Availability.getSchema(), false));
p.addLast("protobufEncoder",
new UdpProtostuffEncoder<>(Availability.getSchema(), false));
p.addLast("beaconMessageHandler", new BeaconMessageHandler());
}
});
// Wait, this is why we are in a new executor...
bootstrap.bind(discoveryPort).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
broadcastChannel = future.channel();
}
});
if (c5Server.isSingleNodeMode()) {
sendAddress = new InetSocketAddress(LOOPBACK_ADDRESS, discoveryPort);
} else {
sendAddress = new InetSocketAddress(BROADCAST_ADDRESS, discoveryPort);
}
//Availability.Builder msgBuilder = Availability.newBuilder(nodeInfoFragment);
try {
localIPs = getLocalIPs();
} catch (SocketException e) {
LOG.error("SocketException:", e);
notifyFailed(e);
}
//msgBuilder.addAllAddresses(getLocalIPs());
//beaconMessage = msgBuilder.build();
// Schedule fiber tasks and subscriptions.
incomingMessages.subscribe(fiber, new Callback<Availability>() {
@Override
public void onMessage(Availability message) {
processWireMessage(message);
}
});
nodeInfoRequests.subscribe(fiber, new Callback<Request<NodeInfoRequest, NodeInfoReply>>() {
@Override
public void onMessage(Request<NodeInfoRequest, NodeInfoReply> message) {
handleNodeInfoRequest(message);
}
});
fiber.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
sendBeacon();
}
}, 2, 10, TimeUnit.SECONDS);
c5Server.getModuleStateChangeChannel().subscribe(fiber, new Callback<ModuleStateChange>() {
@Override
public void onMessage(ModuleStateChange message) {
serviceChange(message);
}
});
fiber.start();
notifyStarted();
}
});
}
@Override
protected void doStop() {
eventLoop.next().execute(new Runnable() {
@Override
public void run() {
fiber.dispose();
notifyStopped();
}
});
}
private List<String> getLocalIPs() throws SocketException {
List<String> ips = new LinkedList<>();
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
NetworkInterface iface = interfaces.nextElement();
if (iface.isPointToPoint()) {
continue; //ignore tunnel type interfaces
}
for (Enumeration<InetAddress> addrs = iface.getInetAddresses(); addrs.hasMoreElements(); ) {
InetAddress addr = addrs.nextElement();
if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isAnyLocalAddress()) {
continue;
}
ips.add(addr.getHostAddress());
}
}
return ips;
}
} |
package Controllers;
import Models.Actuators;
import Models.CarStatus;
import Models.UltraSonic;
import java.util.concurrent.ThreadLocalRandom;
/**
* @author by Group4 on 2017-01-27.
*/
public class Navigation implements NavigationInterface {
private int POSITION = 0;
private int IS_EMPTY_COUNTER = 0;
public int[] carStatus = {POSITION, IS_EMPTY_COUNTER};
private int[] parkingPlaces = new int[501];
public boolean isParked = false;
private boolean drivingForward = false;
private Actuators actuators;
private UltraSonic ultraSonic;
private CarStatus cStatus;
public Navigation() {
actuators = new Actuators();
ultraSonic = new UltraSonic();
cStatus = new CarStatus();
}
public int[] moveForward() {
if (cStatus.whereIs(carStatus) < 500 && !isParked) { // Added so that it doesn't move past 500
if (!drivingForward) {
drivingForward = true;
if (carStatus[1] > 0) carStatus[1] = 1;
else carStatus[1] = 0;
}
carStatus[0] += 1; // Increments the position of the car
if (isEmpty() == 1) {
carStatus[1]++;
if (carStatus[1] == 5) {
parkingPlaces[cStatus.whereIs(carStatus)] = cStatus.whereIs(carStatus);
parkingPlaces[cStatus.whereIs(carStatus) - 1] = cStatus.whereIs(carStatus);
parkingPlaces[cStatus.whereIs(carStatus) - 2] = cStatus.whereIs(carStatus);
parkingPlaces[cStatus.whereIs(carStatus) - 3] = cStatus.whereIs(carStatus);
parkingPlaces[cStatus.whereIs(carStatus) - 4] = cStatus.whereIs(carStatus);
}
} else {
carStatus[1] = 0;
parkingPlaces[cStatus.whereIs(carStatus)] = 0;
}
}
return carStatus; // Return the status of the car
}
public int[] moveBackward() {
if (cStatus.whereIs(carStatus) > 1 && !isParked) { // Added so that it doesn't move past 0
if (drivingForward) {
drivingForward = false;
if (carStatus[1] > 0) carStatus[1] = 1;
else carStatus[1] = 0;
}
carStatus[0] -= 1; // Decrements the position of the car
if (isEmpty() == 1) {
carStatus[1]++;
if (carStatus[1] == 5) {
parkingPlaces[cStatus.whereIs(carStatus)] = cStatus.whereIs(carStatus);
parkingPlaces[cStatus.whereIs(carStatus) + 1] = cStatus.whereIs(carStatus);
parkingPlaces[cStatus.whereIs(carStatus) + 2] = cStatus.whereIs(carStatus);
parkingPlaces[cStatus.whereIs(carStatus) + 3] = cStatus.whereIs(carStatus);
parkingPlaces[cStatus.whereIs(carStatus) + 4] = cStatus.whereIs(carStatus);
}
} else {
carStatus[1] = 0;
parkingPlaces[cStatus.whereIs(carStatus)] = 0;
}
}
return carStatus; // Return the status of the car
}
public void park() {
int i = cStatus.whereIs(carStatus); // Initialize basic counter
if (!(parkingPlaces[cStatus.whereIs(carStatus)] == 0) && cStatus.whereIs(carStatus) != parkingPlaces[cStatus.whereIs(carStatus)]) {
if (cStatus.whereIs(carStatus) < parkingPlaces[cStatus.whereIs(carStatus)]) {
while (cStatus.whereIs(carStatus) != parkingPlaces[cStatus.whereIs(carStatus)] && !isParked) {
moveForward();
}
if (cStatus.whereIs(carStatus) == parkingPlaces[cStatus.whereIs(carStatus)]) isParked = true;
} else {
while (cStatus.whereIs(carStatus) != parkingPlaces[cStatus.whereIs(carStatus)] && !isParked) {
moveBackward();
}
if (cStatus.whereIs(carStatus) == parkingPlaces[cStatus.whereIs(carStatus)]) isParked = true;
}
} else if (cStatus.whereIs(carStatus) != 0 && cStatus.whereIs(carStatus) == parkingPlaces[cStatus.whereIs(carStatus)]) {
isParked = true; // Set the parking state of the car to parked (true)
} else {
do
{ // Do While loop for iterating 500 times or until 5 consecutive free spaces are registered
moveForward(); // Move the car 1 meter and returns the status of the car
if (carStatus[1] == 5) { // Check if there is enough spaces (5) to park the car or not
isParked = true; // Set the parking state of the car to parked (true)
carStatus[1] = 0; // Reset the IS_EMPTY_COUNTER of the car
}
i++;
} while (i < 500 && !isParked);
}
}
public void unPark() {
if (isParked) {
isParked = false;
if (cStatus.whereIs(carStatus) != 500) moveForward();
}
}
public int isEmpty() {
//simulate random sensor data
int k = 0;
int sensor1, badSensor, total1 = 0, total2 = 0, readingToReturn;
while (k < 5) {
sensor1 = ThreadLocalRandom.current().nextInt(0, 200);
badSensor = ThreadLocalRandom.current().nextInt(200, 300);
total1 += sensor1;
total2 += badSensor;
k++;
}
int i = cStatus.whereIs(carStatus);
if ((i > 495 && i < 501) || (i > 30 && i < 36)) { // Hard coded "empty" space 31 - 35 and 495 - 500
return 1; // 1 == empty
} else {
if ((total1 / 5) > 200) { //sensor1 providing unusable values
readingToReturn = total2 / 5;
return readingToReturn;
} else if ((total2 / 5) > 200) { //sensor2 providing unusable values
readingToReturn = total1 / 5;
return readingToReturn;
}
// Store the position of the car
}
return 0;
}
} |
package ifc.sheet;
import lib.MultiPropertyTest;
/**
* Testing <code>com.sun.star.sheet.CellAreaLink</code>
* service properties :
* <ul>
* <li><code> Url</code></li>
* <li><code> Filter</code></li>
* <li><code> FilterOptions</code></li>
* <li><code> RefreshDelay</code></li>
* </ul> <p>
* Properties testing is automated by <code>lib.MultiPropertyTest</code>.
* @see com.sun.star.sheet.CellAreaLink
*/
public class _CellAreaLink extends MultiPropertyTest {
} // finish class _CellAreaLink |
package raptor.swt.chess;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import raptor.Quadrant;
import raptor.Raptor;
import raptor.RaptorWindowItem;
import raptor.action.RaptorAction;
import raptor.action.SeparatorAction;
import raptor.action.RaptorAction.RaptorActionContainer;
import raptor.action.game.AutoBishopAction;
import raptor.action.game.AutoDrawAction;
import raptor.action.game.AutoKingAction;
import raptor.action.game.AutoKnightAction;
import raptor.action.game.AutoQueenAction;
import raptor.action.game.AutoRookAction;
import raptor.action.game.BackAction;
import raptor.action.game.CastleLongAction;
import raptor.action.game.CastleShortAction;
import raptor.action.game.ClearPremovesAction;
import raptor.action.game.CommitAction;
import raptor.action.game.FirstAction;
import raptor.action.game.ForceUpdateAction;
import raptor.action.game.ForwardAction;
import raptor.action.game.LastAction;
import raptor.action.game.MatchWinnerAction;
import raptor.action.game.MoveListAction;
import raptor.action.game.RematchAction;
import raptor.action.game.RevertAction;
import raptor.action.game.ToggleEngineAnalysisAction;
import raptor.chess.Game;
import raptor.chess.GameConstants;
import raptor.chess.Move;
import raptor.chess.Variant;
import raptor.chess.util.GameUtils;
import raptor.pref.PreferenceKeys;
import raptor.service.ActionScriptService;
import raptor.service.UCIEngineService;
import raptor.swt.chess.controller.BughouseSuggestController;
import raptor.swt.chess.controller.ExamineController;
import raptor.swt.chess.controller.InactiveController;
import raptor.swt.chess.controller.ObserveController;
import raptor.swt.chess.controller.ToolBarItemKey;
import raptor.util.RaptorRunnable;
public class ChessBoardUtils implements BoardConstants {
public static final String CHESS_SET_DIR = Raptor.RESOURCES_DIR + "set/";
public static final int DARK_IMAGE_INDEX = 1;
public static final int LIGHT_IMAGE_INDEX = 0;
private static final Log LOG = LogFactory.getLog(ChessBoardUtils.class);
public static final String PIECE_IMAGE_SUFFIX = ".png";
public static final String SQUARE_BACKGROUND_DIR = Raptor.RESOURCES_DIR
+ "square/";
public static final String SQUARE_BACKGROUND_IMAGE_SUFFIX = ".png";
public static final Object PGN_PREPEND_SYNCH = new Object();
public static void addActionsToToolbar(
final ChessBoardController controller,
RaptorActionContainer container, ToolBar toolbar,
boolean isUserWhite) {
RaptorAction[] toolbarActions = ActionScriptService.getInstance()
.getActions(container);
for (RaptorAction action : toolbarActions) {
ToolItem item = createToolItem(action, controller, toolbar,
isUserWhite);
if (LOG.isDebugEnabled()) {
LOG.debug("Added " + action + " to toolbar " + item);
}
}
if (!controller.getPreferences().getBoolean(
PreferenceKeys.BOARD_COOLBAR_MODE)) {
new ToolItem(toolbar, SWT.SEPARATOR);
}
}
public static void adjustCoolbar(ChessBoard board, ToolBar toolbar) {
clearCoolbar(board);
toolbar.pack();
Point size = toolbar.getSize();
board.getCoolbar().setVisible(true);
board.getCoolbar().setLocked(true);
CoolItem coolItem = new CoolItem(board.getCoolbar(), SWT.NONE);
coolItem.setControl(toolbar);
coolItem.setSize(size.x, size.y);
coolItem.setPreferredSize(size.x, size.y);
coolItem.setMinimumSize(size);
board.getControl().layout();
}
public static boolean arePiecesSameColor(int piece1, int piece2) {
return isWhitePiece(piece1) && isWhitePiece(piece2)
|| isBlackPiece(piece1) && isBlackPiece(piece2);
}
public static void clearCoolbar(ChessBoard board) {
CoolBar coolbar = board.getCoolbar();
CoolItem[] items = coolbar.getItems();
for (CoolItem item : items) {
if (item.getControl() != null && !item.getControl().isDisposed()) {
item.getControl().dispose();
}
item.dispose();
}
board.getCoolbar().setVisible(false);
}
public static Move createDropMove(int fromSquare, int toSquare) {
int coloredPiece = ChessBoardUtils.pieceJailSquareToPiece(fromSquare);
int colorlessPiece = ChessBoardUtils
.pieceFromColoredPiece(coloredPiece);
return new Move(toSquare, colorlessPiece, ChessBoardUtils
.isWhitePiece(coloredPiece) ? WHITE : BLACK);
}
public static Move createMove(Game game, int fromSquare, int toSquare) {
try {
Move result = game.makeMove(fromSquare, toSquare);
game.rollback();
return result;
} catch (IllegalArgumentException iae) {
if (LOG.isDebugEnabled()) {
LOG.debug("IllegalArgumentException in game.makeMove()", iae);
}
return null;
}
}
public static Move createMove(Game game, int fromSquare, int toSquare,
int nonColoredPromotionPiece) {
try {
Move result = game.makeMove(fromSquare, toSquare,
nonColoredPromotionPiece);
game.rollback();
return result;
} catch (IllegalArgumentException iae) {
if (LOG.isDebugEnabled()) {
LOG.debug("IllegalArgumentException in game.makeMove()", iae);
}
return null;
}
}
/**
* Returns the image from the users image cache matching the type,width, and
* height. If the image is in the localImageRegistry it is returned.
* Otherwise the users image cache is checked, if its not there then it is
* loaded form the svg file and cached in the users image cache.
*/
public static Image getChessPieceImage(int type, int size) {
if (type == EMPTY) {
return null;
} else {
return getChessPieceImage(getChessSetName(), type, size);
}
}
/**
* Returns the image with the specified of the specified name,type,width and
* height. If the image is in the localImageRegistry it is returned.
* Otherwise the users image cache is checked, if its not there then it is
* loaded form the svg file and cached in the users image cache.
*/
public static Image getChessPieceImage(String name, int type, int size) {
if (type == EMPTY) {
return null;
} else {
if (size < 8) {
size = 8;
}
if (size > 100) {
size = 100;
}
String key = name + "_" + type + "_" + size + "x" + size;
Image image = Raptor.getInstance().getImageRegistry().get(key);
if (image == null) {
Image result = new Image(Display.getCurrent(), CHESS_SET_DIR
+ name + "/" + size + "/" + getPieceName(type));
Raptor.getInstance().getImageRegistry().put(key, result);
return result;
} else {
return image;
}
}
}
/**
* Returns the users current chess set name.
*/
public static String getChessSetName() {
return Raptor.getInstance().getPreferences().getString(
BOARD_CHESS_SET_NAME);
}
/**
* Returns a list of all chess set names.
*/
public static String[] getChessSetNames() {
List<String> result = new LinkedList<String>();
File file = new File(CHESS_SET_DIR);
File[] files = file.listFiles(new FilenameFilter() {
public boolean accept(File arg0, String arg1) {
File file = new File(arg0.getAbsolutePath() + "/" + arg1);
return file.isDirectory() && !file.getName().startsWith(".");
}
});
for (File file2 : files) {
StringTokenizer tok = new StringTokenizer(file2.getName(), ".");
result.add(tok.nextToken());
}
Collections.sort(result);
return result.toArray(new String[0]);
}
public static int getColoredPiece(int piece, boolean isWhite) {
switch (piece) {
case PAWN:
return isWhite ? WP : BP;
case KNIGHT:
return isWhite ? WN : BN;
case BISHOP:
return isWhite ? WB : BB;
case ROOK:
return isWhite ? WR : BR;
case QUEEN:
return isWhite ? WQ : BQ;
case KING:
return isWhite ? WK : BK;
case EMPTY:
return EMPTY;
default:
throw new IllegalArgumentException("Invalid piece " + piece);
}
}
/**
* Returns the cursor for the specified piece type.
*
* @param type
* The piece type.
* @return
*/
public static Cursor getCursorForPiece(int type, int size) {
String key = getChessSetName() + "_" + type + "_" + size + "x" + size;
Cursor result = Raptor.getInstance().getCursorRegistry().get(key);
if (result == null) {
ImageData pieceImageData = getChessPieceImage(type, size)
.getImageData();
int hotx = pieceImageData.width / 2;
int hoty = pieceImageData.height / 2;
result = new Cursor(Raptor.getInstance().getCursorRegistry()
.getDisplay(), pieceImageData, hotx, hoty);
Raptor.getInstance().getCursorRegistry().put(key, result);
}
return result;
}
/**
* Returns the quadrant to use for the specified controller. This should not
* be used if its the "other" bughouse board. Use
* getQuadrantForController(controller,true) for that.
*/
public static Quadrant getQuadrantForController(
ChessBoardController controller) {
return getQuadrantForController(controller, false);
}
/**
* Returns an array of quadrants available for chess boards. This does not
* do any filtering on games currently being played or bughouse, it just
* returns a list of all possible quadrants boards can be placed at.
*/
public static Quadrant[] getQuadrantsAvailableForBoards() {
String[] boardQuadrants = Raptor.getInstance().getPreferences()
.getStringArray(PreferenceKeys.APP_CHESS_BOARD_QUADRANTS);
Quadrant[] result = new Quadrant[boardQuadrants.length];
for (int i = 0; i < boardQuadrants.length; i++) {
result[i] = Quadrant.valueOf(boardQuadrants[i]);
}
return result;
}
/**
* Returns the ideal quadrant for this controller. Criteria used for making
* this decision include: available quadrants for a chess board, if the game
* is bughouse, and if an item can be taken over.
*/
public static Quadrant getQuadrantForController(
ChessBoardController controller, boolean isBughouseOtherBoard) {
Quadrant[] availableQuadrants = getQuadrantsAvailableForBoards();
Quadrant result = null;
if (availableQuadrants.length == 1) {
result = availableQuadrants[0];
} else {
if (Variant.isBughouse(controller.getGame().getVariant())) {
result = isBughouseOtherBoard ? availableQuadrants[1]
: availableQuadrants[0];
} else {
quadrantLoop: for (Quadrant currentQuadrant : availableQuadrants) {
// If a board is already open in this quadrant, be nice and
// open it in another quadrant if possible.
RaptorWindowItem[] items = Raptor.getInstance().getWindow()
.getWindowItems(currentQuadrant);
if (items == null || items.length == 0) {
result = currentQuadrant;
break;
} else {
for (RaptorWindowItem currentItem : items) {
if (currentItem instanceof ChessBoardWindowItem) {
ChessBoardWindowItem chessBoardItem = (ChessBoardWindowItem) currentItem;
if (chessBoardItem.isTakeOverable()) {
result = currentQuadrant;
break quadrantLoop;
}
else {
continue quadrantLoop;
}
}
}
result = currentQuadrant;
break;
}
}
if (result == null) {
result = availableQuadrants[0];
}
}
}
return result;
}
/**
* Returns the Image for users current background name
*/
public static Image getSquareBackgroundImage(boolean isLight, int width,
int height) {
return getSquareBackgroundImage(getSquareBackgroundName(), isLight,
width, height);
}
/**
* Returns the Image for users current background name
*/
public static Image getSquareBackgroundImage(String name, boolean isLight,
int width, int height) {
if (width <= 0 || height <= 0) {
width = 10;
height = 10;
}
String key = name + "_" + isLight + "_" + width + "x" + height;
Image result = Raptor.getInstance().getImageRegistry().get(key);
if (result == null) {
result = new Image(Display.getCurrent(), getSquareBackgroundMold(
name, isLight).getImageData().scaledTo(width, height));
Raptor.getInstance().getImageRegistry().put(key, result);
return result;
} else {
return result;
}
}
/**
* Returns the path to the backgrund image name.
*/
public static String getSquareBackgroundImageName(
String squareBackgroundName, boolean isLight) {
return SQUARE_BACKGROUND_DIR + squareBackgroundName + "/"
+ (isLight ? "light" : "dark") + SQUARE_BACKGROUND_IMAGE_SUFFIX;
}
/**
* Returns an image in the default size of the specified background name and
* color.
*/
public static Image getSquareBackgroundMold(String name, boolean isLight) {
return Raptor.getInstance().getImage(
getSquareBackgroundImageName(name, isLight));
}
/**
* Returns the users current square background name.
*/
public static String getSquareBackgroundName() {
return Raptor.getInstance().getPreferences().getString(
BOARD_SQUARE_BACKGROUND_NAME);
}
/**
* Returns a list of all the square background names.
*/
public static String[] getSquareBackgroundNames() {
List<String> result = new LinkedList<String>();
File file = new File(SQUARE_BACKGROUND_DIR);
File[] files = file.listFiles(new FilenameFilter() {
public boolean accept(File arg0, String arg1) {
File file = new File(arg0.getAbsolutePath() + "/" + arg1);
return file.isDirectory() && !file.getName().startsWith(".");
}
});
for (File file2 : files) {
StringTokenizer tok = new StringTokenizer(file2.getName(), ".");
result.add(tok.nextToken());
}
Collections.sort(result);
return result.toArray(new String[0]);
}
/**
* Returns the path to the specified svg chess piece.
*/
public static String getPieceName(int piece) {
return PIECE_TO_NAME[piece] + PIECE_IMAGE_SUFFIX;
}
/**
* Returns a to move indicator indicating the side to move with the
* specified width/height this image will always be a square.
*/
public static Image getToMoveIndicatorImage(boolean isSideToMove, int width) {
if (width < 5) {
width = 5;
}
String key = "toMoveIndicator_" + isSideToMove + "_" + width;
Image result = Raptor.getInstance().getImageRegistry().get(key);
if (result == null) {
Image mold = getToMoveIndicatorImageMold(isSideToMove);
result = new Image(mold.getDevice(), mold.getImageData().scaledTo(
width, width));
Raptor.getInstance().getImageRegistry().put(key, result);
}
return result;
}
/**
* Returns a to move indicator indicating the side to move with the
* specified width/height this image will always be a square.
*/
public static Image getToMoveIndicatorImageMold(boolean isSideToMove) {
String key = "toMoveIndicator_" + isSideToMove;
Image result = Raptor.getInstance().getImageRegistry().get(key);
if (result == null) {
result = new Image(Raptor.getInstance().getWindow().getShell()
.getDisplay(), Raptor.IMAGES_DIR + "circle_"
+ (isSideToMove ? "green" : "gray") + "30x30.png");
Raptor.getInstance().getImageRegistry().put(key, result);
}
return result;
}
/**
* Returns the path to the specified chess piece in the users image cache.
*/
public static String getUserImageCachePieceName(String chessSetName,
int piece, int width, int height) {
return Raptor.USER_RAPTOR_HOME_PATH + "/imagecache/" + chessSetName
+ "_" + PIECE_TO_NAME[piece] + "_" + width + "_" + height
+ ".png";
}
public static String halfMoveIndexToDescription(int halfMoveIndex,
int colorToMove) {
int fullMoveIndex = halfMoveIndex / 2 + 1;
return colorToMove == WHITE ? fullMoveIndex + ") " : fullMoveIndex
+ ") ... ";
}
public static boolean isBlackPiece(int setPieceType) {
return setPieceType >= 7 && setPieceType < 13;
}
public static boolean isChessSetOptimized(String setName) {
File file = new File(getUserImageCachePieceName(setName,
GameConstants.WP, 6, 6));
File file2 = new File(getUserImageCachePieceName(setName,
GameConstants.BP, 100, 100));
return file.exists() && file2.exists();
}
public static boolean isJailSquareBlackPiece(int pieceJailSquare) {
return isBlackPiece(pieceJailSquareToPiece(pieceJailSquare));
}
public static boolean isJailSquareWhitePiece(int pieceJailSquare) {
return isWhitePiece(pieceJailSquareToPiece(pieceJailSquare));
}
public static boolean isPieceJailSquare(int pieceJailSquare) {
return GameUtils.isDropSquare(pieceJailSquare);
}
public static boolean isWhitePiece(int setPieceType) {
return setPieceType > 0 && setPieceType < 7;
}
public static String lagToString(long lag) {
if (lag < 0) {
lag = 0;
}
int seconds = (int) (lag / 1000L);
int tenths = (int) (lag % 1000) / 100;
return "Lag " + seconds + "." + tenths + " sec";
}
/**
* Opens a ChessBoardWindowItem for the specified controller. It is
* preferred that you use this method and not create a ChessBoardWindowItem
* and add it to RaptorWindow, as it contains code to take-over inactive
* window items if they are available. This can greatly increase
* performance.
*
* This method only handles controllers that are not the "other" bughosue
* board. Use openBoard(controller,true) to do that.
*/
public static void openBoard(ChessBoardController controller) {
openBoard(controller, false);
}
/**
* Opens a ChessBoardWindowItem for the specified controller. It is
* preferred that you use this method, as it contains code to take-over
* inactive window items if they are available. This can greatly increase
* performance.
*/
public static void openBoard(final ChessBoardController controller,
final boolean isBughouseOtherBoard) {
Raptor.getInstance().getDisplay().asyncExec(
new RaptorRunnable(controller.getConnector()) {
@Override
public void execute() {
Quadrant quadrant = getQuadrantForController(
controller, isBughouseOtherBoard);
ChessBoardWindowItem item = null;
if (Raptor.getInstance().getPreferences().getBoolean(
PreferenceKeys.BOARD_TAKEOVER_INACTIVE_GAMES)) {
item = Raptor
.getInstance()
.getWindow()
.getChessBoardWindowItemToTakeOver(quadrant);
if (item == null
&& controller.getGame().getVariant() != Variant.bughouse
&& controller.getGame().getVariant() != Variant.fischerRandomBughouse) {
item = Raptor.getInstance().getWindow()
.getChessBoardWindowItemToTakeOver(
quadrant);
}
}
if (item == null) {
// No item to take over so create one.
item = new ChessBoardWindowItem(controller,
isBughouseOtherBoard);
Raptor.getInstance().getWindow()
.addRaptorWindowItem(item);
} else {
// Take over the item.
item.getBoard().hideEngineAnalysisWidget();
item.getBoard().hideMoveList();
item.takeOver(controller, isBughouseOtherBoard);
Raptor.getInstance().getWindow().forceFocus(item);
}
}
});
}
public static String pieceCountToString(int count) {
if (count < 2) {
return "";
} else {
return "" + count;
}
}
public static int pieceFromColoredPiece(int coloredPiece) {
switch (coloredPiece) {
case EMPTY:
return GameConstants.EMPTY;
case WP:
case BP:
return GameConstants.PAWN;
case WN:
case BN:
return GameConstants.KNIGHT;
case WB:
case BB:
return GameConstants.BISHOP;
case WR:
case BR:
return GameConstants.ROOK;
case WQ:
case BQ:
return GameConstants.QUEEN;
case WK:
case BK:
return GameConstants.KING;
default:
throw new IllegalArgumentException("Invalid coloredPiece "
+ coloredPiece);
}
}
public static int pieceJailSquareToPiece(int pieceJailSquare) {
return pieceJailSquare - 100;
}
protected static ToolItem createToolItem(final RaptorAction action,
final ChessBoardController controller, ToolBar toolbar,
boolean isUserWhite) {
ToolItem result = null;
if (action instanceof SeparatorAction) {
result = new ToolItem(toolbar, SWT.SEPARATOR);
return result;
} else if (action instanceof RematchAction) {
if (controller.getConnector() == null) {
return null;
}
result = new ToolItem(toolbar, SWT.FLAT);
result.setText(action.getName());
} else if (action instanceof MatchWinnerAction) {
if (controller instanceof BughouseSuggestController) {
return null;
}
result = new ToolItem(toolbar, SWT.CHECK);
controller.addToolItem(ToolBarItemKey.MATCH_WINNER, result);
} else if (action instanceof ToggleEngineAnalysisAction) {
if (controller instanceof InactiveController
|| controller instanceof ExamineController
|| controller instanceof ObserveController) {
if (Variant.isClassic(controller.getGame().getVariant())
&& UCIEngineService.getInstance().getDefaultEngine() != null) {
result = new ToolItem(toolbar, SWT.CHECK);
controller.addToolItem(
ToolBarItemKey.TOGGLE_ANALYSIS_ENGINE, result);
if (controller.getBoard() != null
&& controller.getBoard().isShowingEngineAnaylsis()) {
result.setSelection(true);
}
}
}
if (result == null) {
return null;
}
} else if (action instanceof AutoDrawAction) {
result = new ToolItem(toolbar, SWT.CHECK);
controller.addToolItem(ToolBarItemKey.AUTO_DRAW, result);
} else if (action instanceof BackAction) {
result = new ToolItem(toolbar, SWT.FLAT);
controller.addToolItem(ToolBarItemKey.BACK_NAV, result);
} else if (action instanceof ForwardAction) {
result = new ToolItem(toolbar, SWT.FLAT);
controller.addToolItem(ToolBarItemKey.NEXT_NAV, result);
} else if (action instanceof FirstAction) {
result = new ToolItem(toolbar, SWT.FLAT);
controller.addToolItem(ToolBarItemKey.FIRST_NAV, result);
} else if (action instanceof LastAction) {
result = new ToolItem(toolbar, SWT.FLAT);
controller.addToolItem(ToolBarItemKey.LAST_NAV, result);
} else if (action instanceof RevertAction) {
result = new ToolItem(toolbar, SWT.FLAT);
controller.addToolItem(ToolBarItemKey.REVERT_NAV, result);
} else if (action instanceof CommitAction) {
result = new ToolItem(toolbar, SWT.FLAT);
controller.addToolItem(ToolBarItemKey.COMMIT_NAV, result);
} else if (action instanceof ClearPremovesAction) {
result = new ToolItem(toolbar, SWT.CHECK);
controller.addToolItem(ToolBarItemKey.CLEAR_PREMOVES, result);
} else if (action instanceof MoveListAction) {
result = new ToolItem(toolbar, SWT.CHECK);
controller.addToolItem(ToolBarItemKey.MOVE_LIST, result);
} else if (action instanceof ForceUpdateAction) {
result = new ToolItem(toolbar, SWT.CHECK);
controller.addToolItem(ToolBarItemKey.FORCE_UPDATE, result);
} else if (action instanceof AutoQueenAction) {
result = new ToolItem(toolbar, SWT.RADIO);
controller.addToolItem(ToolBarItemKey.AUTO_QUEEN, result);
int pieceSize = Raptor.getInstance().getPreferences().getInt(
PreferenceKeys.APP_TOOLBAR_PIECE_SIZE);
result.setImage(getChessPieceImage("Portable", isUserWhite ? WQ
: BQ, pieceSize));
} else if (action instanceof AutoKnightAction) {
result = new ToolItem(toolbar, SWT.RADIO);
controller.addToolItem(ToolBarItemKey.AUTO_KNIGHT, result);
int pieceSize = Raptor.getInstance().getPreferences().getInt(
PreferenceKeys.APP_TOOLBAR_PIECE_SIZE);
result.setImage(getChessPieceImage("Portable", isUserWhite ? WN
: BN, pieceSize));
} else if (action instanceof AutoBishopAction) {
result = new ToolItem(toolbar, SWT.RADIO);
controller.addToolItem(ToolBarItemKey.AUTO_BISHOP, result);
int pieceSize = Raptor.getInstance().getPreferences().getInt(
PreferenceKeys.APP_TOOLBAR_PIECE_SIZE);
result.setImage(getChessPieceImage("Portable", isUserWhite ? WB
: BB, pieceSize));
} else if (action instanceof AutoRookAction) {
result = new ToolItem(toolbar, SWT.RADIO);
controller.addToolItem(ToolBarItemKey.AUTO_ROOK, result);
int pieceSize = Raptor.getInstance().getPreferences().getInt(
PreferenceKeys.APP_TOOLBAR_PIECE_SIZE);
result.setImage(getChessPieceImage("Portable", isUserWhite ? WR
: BR, pieceSize));
} else if (action instanceof AutoKingAction
&& controller.getGame().getVariant() == Variant.suicide) {
result = new ToolItem(toolbar, SWT.RADIO);
controller.addToolItem(ToolBarItemKey.AUTO_KING, result);
int pieceSize = Raptor.getInstance().getPreferences().getInt(
PreferenceKeys.APP_TOOLBAR_PIECE_SIZE);
result.setImage(getChessPieceImage("Portable", isUserWhite ? WK
: BK, pieceSize));
} else if (action instanceof AutoKingAction) {
return null;
} else if (action instanceof CastleLongAction
&& controller.getGame().isInState(Game.FISCHER_RANDOM_STATE)) {
result = new ToolItem(toolbar, SWT.FLAT);
controller.addToolItem(ToolBarItemKey.CASTLE_LONG, result);
} else if (action instanceof CastleLongAction) {
return null;
} else if (action instanceof CastleShortAction
&& controller.getGame().isInState(Game.FISCHER_RANDOM_STATE)) {
result = new ToolItem(toolbar, SWT.FLAT);
controller.addToolItem(ToolBarItemKey.CASTLE_SHORT, result);
} else if (action instanceof CastleShortAction) {
return null;
} else {
result = new ToolItem(toolbar, SWT.FLAT);
}
if (StringUtils.isBlank(result.getText())
&& StringUtils.isBlank(action.getIcon())
&& result.getImage() == null) {
result.setText(action.getName());
} else if (StringUtils.isNotBlank(action.getIcon())
&& result.getImage() == null) {
result.setImage(Raptor.getInstance().getIcon(action.getIcon()));
}
if (StringUtils.isNotBlank(action.getDescription())) {
result.setToolTipText(action.getDescription());
}
result.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
RaptorAction loadedAction = ActionScriptService.getInstance()
.getAction(action.getName());
loadedAction.setChessBoardControllerSource(controller);
loadedAction.run();
}
});
return result;
}
} |
package jkind.engines.pdr;
import java.util.HashSet;
import java.util.Set;
import de.uni_freiburg.informatik.ultimate.logic.ApplicationTerm;
import de.uni_freiburg.informatik.ultimate.logic.Sort;
import de.uni_freiburg.informatik.ultimate.logic.Term;
public class PredicateCollector {
private final Set<Term> predicates = new HashSet<>();
public static Set<Term> collect(Term term) {
PredicateCollector collector = new PredicateCollector();
collector.walk(term);
return collector.predicates;
}
private void walk(Term term) {
if (term instanceof ApplicationTerm) {
ApplicationTerm at = (ApplicationTerm) term;
walk(at);
} else {
throw new IllegalArgumentException("Unhandled: " + term.getClass().getSimpleName());
}
}
private void walk(ApplicationTerm at) {
if (at.getParameters().length == 0) {
String name = at.getFunction().getName();
if (name.equals("true") || name.equals("false")) {
return;
}
} else if (booleanParamaters(at)) {
for (Term sub : at.getParameters()) {
walk(sub);
}
return;
}
predicates.add(at);
}
private boolean booleanParamaters(ApplicationTerm at) {
for (Sort sort : at.getFunction().getParameterSorts()) {
if (!sort.getName().equals("Bool")) {
return false;
}
}
return true;
}
} |
package org.jpos.q2.qbean;
import java.io.IOException;
import java.util.Iterator;
import org.jpos.iso.ISOMsg;
import org.jpos.iso.ISOUtil;
import org.jpos.util.SimpleLogSource;
import org.jpos.util.Logger;
import org.jpos.util.LogEvent;
import org.jpos.space.Space;
import org.jpos.space.TransientSpace;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.core.Configurable;
import org.jpos.iso.ISOChannel;
import org.jpos.iso.ISOPackager;
import org.jpos.iso.ISOException;
import org.jpos.iso.ISOFilter;
import org.jpos.iso.FilteredChannel;
import org.jpos.util.LogSource;
import org.jpos.q2.QBeanSupport;
import org.jpos.q2.QFactory;
import org.jpos.q2.Q2ConfigurationException;
import org.jdom.Element;
/**
* @author Alejandro Revilla
* @version $Revision$ $Date$
* @jmx:mbean description="ISOChannel wrapper"
* extends="org.jpos.q2.QBeanSupportMBean"
*/
public class ChannelAdaptor
extends QBeanSupport
implements ChannelAdaptorMBean
{
Space sp;
Configuration cfg;
ISOChannel channel;
String in, out, ready;
long delay;
public ChannelAdaptor () {
super ();
}
public void initChannel ()
throws Q2ConfigurationException, ConfigurationException
{
sp = TransientSpace.getSpace ();
Element persist = getPersist ();
Element e = persist.getChild ("channel");
if (e == null)
throw new Q2ConfigurationException ("channel element missing");
in = persist.getChildTextTrim ("in");
out = persist.getChildTextTrim ("out");
String s = persist.getChildTextTrim ("reconnect-delay");
delay = s != null ? Long.parseLong (s) : 10000; // reasonable default
channel = newChannel (e, getFactory());
ready = channel.toString() + ".ready";
}
public void startService () {
try {
initChannel ();
new Thread (new Sender ()).start ();
new Thread (new Receiver ()).start ();
} catch (Exception e) {
getLog().warn ("error starting service", e);
}
}
public void stopService () {
try {
disconnect();
sp.out (in, new Object());
} catch (Exception e) {
getLog().warn ("error disconnecting from remote host", e);
}
}
/**
* @jmx:managed-attribute description="set reconnect delay"
*/
public synchronized void setReconnectDelay (long delay) {
getPersist().getChild ("reconnect-delay")
.setText (Long.toString (delay));
this.delay = delay;
setModified (true);
}
/**
* @jmx:managed-attribute description="get reconnect delay"
*/
public long getReconnectDelay () {
return delay;
}
/**
* @jmx:managed-attribute description="input queue"
*/
public synchronized void setInQueue (String in) {
String old = this.in;
this.in = in;
if (old != null)
sp.out (old, new Object());
getPersist().getChild("in").setText (in);
setModified (true);
}
/**
* @jmx:managed-attribute description="input queue"
*/
public String getInQueue () {
return in;
}
/**
* @jmx:managed-attribute description="output queue"
*/
public synchronized void setOutQueue (String out) {
this.out = out;
getPersist().getChild("out").setText (out);
setModified (true);
}
/**
* @jmx:managed-attribute description="output queue"
*/
public String getOutQueue () {
return out;
}
public ISOChannel newChannel (Element e, QFactory f)
throws Q2ConfigurationException
{
String channelName = e.getAttributeValue ("class");
String packagerName = e.getAttributeValue ("packager");
ISOChannel channel = (ISOChannel) f.newInstance (channelName);
ISOPackager packager = null;
if (packagerName != null) {
packager = (ISOPackager) f.newInstance (packagerName);
channel.setPackager (packager);
f.setConfiguration (packager, e);
}
f.invoke (channel, "setHeader", e.getAttributeValue ("header"));
f.setLogger (channel, e);
f.setConfiguration (channel, e);
if (channel instanceof FilteredChannel) {
addFilters ((FilteredChannel) channel, e, f);
}
return channel;
}
private void addFilters (FilteredChannel channel, Element e, QFactory fact)
throws Q2ConfigurationException
{
Iterator iter = e.getChildren ("filter").iterator();
while (iter.hasNext()) {
Element f = (Element) iter.next();
String clazz = f.getAttributeValue ("class");
ISOFilter filter = (ISOFilter) fact.newInstance (clazz);
fact.setLogger (filter, f);
fact.setConfiguration (filter, f);
String direction = f.getAttributeValue ("direction");
if (direction == null)
channel.addFilter (filter);
else if ("incoming".equalsIgnoreCase (direction))
channel.addIncomingFilter (filter);
else if ("outgoing".equalsIgnoreCase (direction))
channel.addOutgoingFilter (filter);
}
}
public class Sender implements Runnable {
public Sender () {
super ();
}
public void run () {
Thread.currentThread().setName ("channel-sender-" + in);
while (running ()){
try {
checkConnection ();
Object o = sp.in (in);
if (o instanceof ISOMsg)
channel.send ((ISOMsg) o);
} catch (Exception e) {
getLog().warn ("channel-sender-"+in, e);
ISOUtil.sleep (1000);
}
}
}
}
public class Receiver implements Runnable {
public Receiver () {
super ();
}
public void run () {
Thread.currentThread().setName ("channel-receiver-"+out);
while (running()) {
try {
sp.rd (ready);
ISOMsg m = channel.receive ();
sp.out (out, m);
} catch (Exception e) {
if (running()) {
getLog().warn ("channel-receiver-"+out, e);
disconnect ();
sp.out (in, new Object()); // wake-up Sender
}
}
}
}
}
protected synchronized void checkConnection () {
try {
while (running() && !channel.isConnected ()) {
while (sp.inp (ready) != null)
;
channel.connect ();
if (!channel.isConnected ())
ISOUtil.sleep (delay);
}
if (running())
sp.out (ready, new Object ());
} catch (IOException e) {
getLog().warn ("check-connection", e);
ISOUtil.sleep (delay);
}
}
protected synchronized void disconnect () {
try {
while (sp.inp (ready) != null)
;
channel.disconnect ();
} catch (IOException e) {
getLog().warn ("disconnect", e);
}
}
/**
* @jmx:managed-attribute description="remote host address"
*/
public synchronized void setHost (String host) {
setProperty (getProperties ("channel"), "host", host);
setModified (true);
}
/**
* @jmx:managed-attribute description="remote host address"
*/
public String getHost () {
return getProperty (getProperties ("channel"), "host");
}
/**
* @jmx:managed-attribute description="remote port"
*/
public synchronized void setPort (int port) {
setProperty (
getProperties ("channel"), "port", Integer.toString (port)
);
setModified (true);
}
/**
* @jmx:managed-attribute description="remote port"
*/
public int getPort () {
int port = 0;
try {
port = Integer.parseInt (
getProperty (getProperties ("channel"), "port")
);
} catch (NumberFormatException e) { }
return port;
}
} |
package city;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.sql.Time;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.Semaphore;
import restaurant.CashierAgent;
import restaurant.HostAgent;
import restaurant.gui.CustomerGui;
import agent.Agent;
import city.gui.PersonGui;
import city.roles.*;
public class PersonAgent extends Agent {
private List<Role> roles = new ArrayList<Role>();
//hacked in upon creation
private List<MyRestaurant> restaurants = new ArrayList<MyRestaurant>();
private List<MyBank> banks = new ArrayList<MyBank>();
private List<MyMarket> markets = new ArrayList<MyMarket>();
private List<MyBusStop> busStops = new ArrayList<MyBusStop>();
private List<Task> taskList = new ArrayList<Task>();
private Semaphore waitingResponse = new Semaphore(0,true);
private PersonGui personGui;
enum Task {goToMarket, goEatFood, goToWork, goToBank, goToBankNow, doPayRent, doPayEmployees, offWorkBreak, onWorkBreak};
enum State { doingNothing, goingOutToEat, goingHomeToEat, eating, goingToWork, working, goingToMarket, shopping, goingToBank, banking, onWorkBreak, offWorkBreak };
enum Location { AtHome, AtWork, AtMarket, AtBank, InCity, AtRestaurant};
enum TransportState { none, GoingToBus, WaitingForBus, OnBus, GettingOffBus, GettingOnBus};
boolean isRenter;
boolean isManager;
private String name;
public BufferedImage car = null;
//Bus busLeft;
//Bus busRight;
MyJob job;
private State state = State.doingNothing;
private Location location = Location.InCity;
private TransportState transportState = TransportState.none;
private Point destination;
Map<String, Integer> toOrderFromMarket = new HashMap<String, Integer>();
//Time currentTime;
int currentHour;
String dayOfWeek;
public int hungerLevel = 51;
public double cashOnHand, businessFunds;
class MyRestaurant {
//Restaurant r;
HostAgent h;
CashierAgent c;
Point location;
String type;
String name;
CustomerRole cr;
MyRestaurant(HostAgent h, CashierAgent c, Point location, String type, String name) {
this.h = h;
this.c = c;
this.location = location;
this.type = type;
this.name = name;
}
}
class MyBank {
Point location;
String name;
//BankCustomerRole bcr;
}
class MyMarket {
Point location;
String type;
String name;
//List<item> inventory;
}
class MyBusStop {
Point location;
}
class MyJob{
Point location;
String type;
Shift shift;
Role role;
}
enum Shift {day, night}
public PersonAgent(String name, double cash) {
this.name = name;
this.cashOnHand = cash;
}
public void addRole(Role r) {
roles.add(r);
r.setPerson(this);
}
public void addRestaurant(HostAgent h, CashierAgent c, Point location, String type, String name) {
restaurants.add(new MyRestaurant(h, c, location, type, name));
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
// messages
public void msgTransferSuccessful(PersonAgent recipient, double amount, String purpose) {
}
public void msgTransferFailure(PersonAgent recipient, double amount, String purpose) {
// get a loan, attempt transfer again
}
public void msgTransferCompleted(PersonAgent sender, double amount, String purpose) {
}
public void msgHereIsBalance(double amount, String accountType) {
}
public void msgNextHour(int hour, String dayOfWeek) {
this.currentHour = hour;
this.dayOfWeek = dayOfWeek;
this.hungerLevel += 1;
/*
if((job.shift == Shift.day && location != Location.AtWork && (currentHour >= 20 || currentHour <= 11)) ||
(job.shift == Shift.night && location != Location.AtWork && (currentHour >= 12 || currentHour <= 3))){
boolean inList = false;
for(Task t: taskList){
if(t == Task.goToWork)
inList = true;
}
if(!inList){
taskList.add(Task.goToWork);
}
}*/
print("newhour");
if(hour == 23 && isRenter){
boolean inList = false;
for(Task t: taskList){
if(t == Task.doPayRent)
inList = true;
}
if(!inList){
taskList.add(Task.doPayRent);
}
}
if(hour == 23 && isManager){
boolean inList = false;
for(Task t: taskList){
if(t == Task.doPayEmployees)
inList = true;
}
if(!inList){
taskList.add(Task.doPayEmployees);
}
}
if(hungerLevel > 50 && state != State.goingOutToEat && state != State.eating && state != State.goingHomeToEat){
boolean inList = false;
for(Task t: taskList){
if(t == Task.goEatFood)
inList = true;
}
if(!inList){
print("\t\t\t\tAHHHHHHHHHHHHHHHHH");
taskList.add(Task.goEatFood);
}
}
stateChanged();
}
public void msgGoBackToWork(){
boolean inList = false;
for(Task t: taskList){
if(t == Task.offWorkBreak)
inList = true;
}
if(!inList){
taskList.add(Task.offWorkBreak);
}
}
public void msgTakingBreak(){
boolean inList = false;
for(Task t: taskList){
if(t == Task.onWorkBreak)
inList = true;
}
if(!inList){
taskList.add(Task.onWorkBreak);
}
stateChanged();
}
public void msgNoMoreFood(){
boolean inList = false;
for(Task t: taskList){
if(t == Task.goToMarket)
inList = true;
}
if(!inList){
taskList.add(Task.goToMarket);
}
stateChanged();
}
public void msgGetFoodFromMarket(Map<String,Integer> toOrderFromMarket){
if(this.toOrderFromMarket != null){
Iterator<Entry<String, Integer>> it = toOrderFromMarket.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Integer> pairs = it.next();
if(this.toOrderFromMarket.get(pairs.getKey()) == null){
this.toOrderFromMarket.put(pairs.getKey(), pairs.getValue());
}else{
Integer temp = this.toOrderFromMarket.get(pairs.getKey());
this.toOrderFromMarket.put(pairs.getKey(), (pairs.getValue() + temp));
}
it.remove(); // avoids a ConcurrentModificationException
}
}else{
this.toOrderFromMarket = toOrderFromMarket;
}
stateChanged();
}
public void msgDepositBusinessCash(){
boolean inList = false;
for(Task t: taskList){
if(t == Task.goToBankNow)
inList = true;
}
if(!inList){
taskList.add(Task.goToBankNow);
}
stateChanged();
}
public void msgReenablePerson(){
//gui.setPresent();
}
public void msgBusIshere(){
transportState = TransportState.GettingOnBus;
stateChanged();
}
public void msgAtYourStop(){
transportState = TransportState.GettingOffBus;
stateChanged();
}
public void msgDoneWorking(){
state = State.doingNothing;
/*Role temp = null;
for(Role r: roles){
if(r instanceof job.role){
}
}
*/
stateChanged();
}
public void msgDoneEatingAtRestaurant() {
print("msgDoneEatingAtRestaurant");
state = State.doingNothing;
for(Task t: taskList){
print(t.toString());
}
print(state.toString());
stateChanged();
}
public boolean pickAndExecuteAnAction() {
try {
Task temp = null;
/*
for(Task t:taskList){
if(t == Task.doPayRent){
temp = t;
}
}
if(temp != null){
doPayRent();
taskList.remove(temp);
return true;
}
for(Task t:taskList){
if(state == State.doingNothing && t == Task.goToWork){
temp = t;
}
}
if(temp != null){
goToWork();
taskList.remove(temp);
return true;
}
for(Task t:taskList){
if(state == State.doingNothing && t == Task.goToBankNow){
temp = t;
}
}
if(temp != null){
goToBank();
taskList.remove(temp);
return true;
}*/
for(Task t:taskList){
if(state == State.doingNothing && t == Task.goEatFood){
temp = t;
}
}
if(temp != null){
goEatFood();
taskList.remove(temp);
return true;
}
/*for(Task t:taskList){
if(state == State.doingNothing && t == Task.goToBank){
temp = t;
}
}
if(temp != null){
goToBank();
taskList.remove(temp);
return true;
}
for(Task t:taskList){
if(state == State.doingNothing && t == Task.goToMarket){
temp = t;
}
}
if(temp != null){
goToMarket();
taskList.remove(temp);
return true;
}
if(transportState == TransportState.GettingOnBus){
getOnBus();
return true;
}
if(transportState = TransportState.GettingOffBus){
getOffBus();
return true;
}
if(transportState == TransportState.none && state == State.goingToWork){
finishGoingToWork();
return true;
}*/
if(transportState == TransportState.none && state == State.goingOutToEat){
finishGoingToRestaurant();
return true;
}
/*if(transportState == TransportState.none && state == State.goingHomeToEat){
finishGoingToHome();
return true;
}
if(transportState == TransportState.none && state == State.goingToBank){
finishGoingToBank();
return true;
}*/
for(Role r : roles) {
if( r.isActive() ) {
boolean tempBool = r.pickAndExecuteAnAction();
if(tempBool){
return true;
}
}
}
if(state == State.doingNothing){
System.out.println("goingHome");
goHome();
}
return false;
} catch(ConcurrentModificationException e){ return false; }
}
private void goHome() {
personGui.DoWalkTo(new Point(75,103)); ///CHange to special go home method and remove semaphore
try {
waitingResponse.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//actions
private void doPayRent(){
//bank.msgTransferFunds(this, landlord, "personal","rent");
}
private void goToWork(){
state = State.goingToWork;
}
private void goEatFood() {
state = State.goingOutToEat;
goToRestaurant();
}
private void goToRestaurant() {
// DoGoToRestaurant animation
location = Location.AtRestaurant;
MyRestaurant mr = restaurants.get(0); // hack for first restaurant for now
destination = mr.location;
personGui.DoWalkTo(destination);
try {
waitingResponse.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
//RestaurantCustomerRole rcr = roles.get(0); // hack
//mr.h.msgIWantToEat(rcr);
}
private void finishGoingToRestaurant(){
print("finishGoingToRestaurant");
state = State.eating;
/*MyRestaurant mr = restaurants.get(0); // hack for first restaurant for now
CustomerRole role = new CustomerRole(this, name, cashOnHand);
role.setGui(new CustomerGui(role));
roles.add(role);
role.active = true;
role.setHost(mr.h);
role.setCashier(mr.c);
personGui.gui.restaurantAnimationPanel.addGui(role.getGui());
role.getGui().setPresent(true);
role.gotHungry();*/
}
public void msgAnimationFinshed() {
print("msgAnimationFinshed");
waitingResponse.release();
}
public PersonGui getGui() {
return personGui;
}
public void setHost(HostAgent host) {
// TODO Auto-generated method stub
}
public void setCashier(CashierAgent cashier) {
// TODO Auto-generated method stub
}
public void setGui(PersonGui g) {
personGui = g;
}
} |
package city.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import transportation.TransportationBusDispatch;
import base.Location;
public class CityBus extends CityComponent {
private TransportationBusDispatch mBusDispatch;
List<Location> mStopCoords;
private int mStopNumber,
mSize = 25;
private Location destination = new Location(0, 0);
private boolean mTraveling, firstRun = true;
BufferedImage front, right, left, back;
/**
* Creates new CityBus
* @param b Bus "driver"
* @param busNum Index of this instance of bus
*/
public CityBus(TransportationBusDispatch b, List<Location> stopCoords) {
mBusDispatch = b;
mTraveling = true;
mStopNumber = 0;
mStopCoords = stopCoords;
// Inherited from CityComponent
x = mStopCoords.get(mStopNumber).mX;
y = mStopCoords.get(mStopNumber).mY;
front = null;
right = null;
left = null;
back = null;
try {
java.net.URL frontURL = this.getClass().getClassLoader().getResource("city/gui/images/bus/front_sm.png");
front = ImageIO.read(frontURL);
java.net.URL rightURL = this.getClass().getClassLoader().getResource("city/gui/images/bus/rightside_sm.png");
right = ImageIO.read(rightURL);
java.net.URL backURL = this.getClass().getClassLoader().getResource("city/gui/images/bus/back_sm.png");
back = ImageIO.read(backURL);
java.net.URL leftURL = this.getClass().getClassLoader().getResource("city/gui/images/bus/leftside_sm.png");
left = ImageIO.read(leftURL);
}
catch(IOException e) {
e.printStackTrace();
}
isActive = true;
// Set initial destination
destination.mX = mStopCoords.get(mStopNumber + 1).mX;
destination.mY = mStopCoords.get(mStopNumber + 1).mY;
}
public void paint(Graphics g) {
draw((Graphics2D)g);
}
public void updatePosition() {
if (x < destination.mX) x++;
else if (x > destination.mX) x
if (y < destination.mY) y++;
else if (y > destination.mY) y
if (x == destination.mX && y == destination.mY && mTraveling) {
mStopNumber = (mStopNumber + 1) % 4;
mBusDispatch.msgGuiArrivedAtStop();
mTraveling = false;
firstRun = false;
}
setX(x); setY(y);
}
@Override
public void draw(Graphics2D g) {
if (mStopNumber == 0) g.drawImage(left, x, y, null);
// hack firstRun
if (mStopNumber == 1) g.drawImage(front, x, y, null);
if (mStopNumber == 2) g.drawImage(right, x, y, null);
if (mStopNumber == 3) g.drawImage(back, x, y, null);
if (firstRun) g.drawImage(front, x, y, null);
}
@Override
public boolean isPresent() { return true; }
@Override
public void setPresent(boolean state) { }
public void DoAdvanceToNextStop() {
mTraveling = true;
destination.setTo(mStopCoords.get(mStopNumber));
}
} |
package net.fortuna.ical4j.data;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.util.Arrays;
import net.fortuna.ical4j.util.CompatibilityHints;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* <pre>
* $Id$ [06-Apr-2004]
* </pre>
*
* A reader which performs iCalendar unfolding as it reads. Note that unfolding rules may be "relaxed" to allow
* unfolding of non-conformant *.ics files. By specifying the system property "ical4j.unfolding.relaxed=true" iCalendar
* files created with Mozilla Calendar/Sunbird may be correctly unfolded.
*
* To wrap this reader with a {@link java.io.BufferedReader} you must ensure you specify an identical buffer size
* to that used in the {@link java.io.BufferedReader}.
*
* @author Ben Fortuna
*/
public class UnfoldingReader extends PushbackReader {
private Log log = LogFactory.getLog(UnfoldingReader.class);
/**
* The pattern used to identify a fold in an iCalendar data stream.
*/
private static final char[] DEFAULT_FOLD_PATTERN_1 = { '\r', '\n', ' ' };
/**
* The pattern used to identify a fold in Microsoft Outlook 2007.
*/
private static final char[] DEFAULT_FOLD_PATTERN_2 = { '\r', '\n', '\t' };
/**
* The pattern used to identify a fold in Mozilla Calendar/Sunbird and KOrganizer.
*/
private static final char[] RELAXED_FOLD_PATTERN_1 = { '\n', ' ' };
/**
* The pattern used to identify a fold in Microsoft Outlook 2007.
*/
private static final char[] RELAXED_FOLD_PATTERN_2 = { '\n', '\t' };
private char[][] patterns;
private char[][] buffers;
private int linesUnfolded;
private int maxPatternLength = 0;
/**
* Creates a new unfolding reader instance. Relaxed unfolding flag is read from system property.
* @param in the reader to unfold from
*/
public UnfoldingReader(final Reader in) {
this(in, DEFAULT_FOLD_PATTERN_1.length, CompatibilityHints
.isHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING));
}
/**
* @param in reader source for data
* @param size the buffer size
*/
public UnfoldingReader(final Reader in, int size) {
this(in, size, CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING));
}
/**
* @param in reader source for data
* @param relaxed indicates whether relaxed unfolding is enabled
*/
public UnfoldingReader(final Reader in, boolean relaxed) {
this(in, DEFAULT_FOLD_PATTERN_1.length, relaxed);
}
/**
* Creates a new unfolding reader instance.
* @param in a reader to read from
* @param size the buffer size
* @param relaxed specifies whether unfolding is relaxed
*/
public UnfoldingReader(final Reader in, int size, final boolean relaxed) {
super(in, size);
if (relaxed) {
patterns = new char[4][];
patterns[0] = DEFAULT_FOLD_PATTERN_1;
patterns[1] = DEFAULT_FOLD_PATTERN_2;
patterns[2] = RELAXED_FOLD_PATTERN_1;
patterns[3] = RELAXED_FOLD_PATTERN_2;
}
else {
patterns = new char[2][];
patterns[0] = DEFAULT_FOLD_PATTERN_1;
patterns[1] = DEFAULT_FOLD_PATTERN_2;
}
buffers = new char[patterns.length][];
for (int i = 0; i < patterns.length; i++) {
buffers[i] = new char[patterns[i].length];
maxPatternLength = Math.max(maxPatternLength, patterns[i].length);
}
}
/**
* @return number of lines unfolded so far while reading
*/
public final int getLinesUnfolded() {
return linesUnfolded;
}
/**
* {@inheritDoc}
*/
public final int read() throws IOException {
final int c = super.read();
boolean doUnfold = false;
for (int i = 0; i < patterns.length; i++) {
if (c == patterns[i][0]) {
doUnfold = true;
break;
}
}
if (!doUnfold) {
return c;
}
else {
unread(c);
}
unfold();
return super.read();
}
/**
* {@inheritDoc}
*/
public int read(final char[] cbuf, final int off, final int len) throws IOException {
final int read = super.read(cbuf, off, len);
boolean doUnfold = false;
for (int i = 0; i < patterns.length; i++) {
if (read > 0 && cbuf[0] == patterns[i][0]) {
doUnfold = true;
break;
}
else {
for (int j = 0; j < read; j++) {
if (cbuf[j] == patterns[i][0]) {
unread(cbuf, j, read - j);
return j;
}
}
}
}
if (!doUnfold) {
return read;
}
else {
unread(cbuf, off, read);
}
unfold();
return super.read(cbuf, off, maxPatternLength);
}
private void unfold() throws IOException {
// need to loop since one line fold might be directly followed by another
boolean didUnfold;
do {
didUnfold = false;
for (int i = 0; i < buffers.length; i++) {
int read = 0;
while (read < buffers[i].length) {
final int partialRead = super.read(buffers[i], read, buffers[i].length - read);
if (partialRead < 0) {
break;
}
read += partialRead;
}
if (read > 0) {
if (!Arrays.equals(patterns[i], buffers[i])) {
unread(buffers[i], 0, read);
}
else {
if (log.isTraceEnabled()) {
log.trace("Unfolding...");
}
linesUnfolded++;
didUnfold = true;
}
}
// else {
// return read;
}
}
while (didUnfold);
}
} |
/**
* "Graph" is the actual Dijkstra map combined with the logic to calculate the path
* @author Akhier Dragonheart
* @version 1.0.1
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
public class Graph {
private Vector2D sourceNode;
private ArrayList<Vector2D> listOfNodes;
private ArrayList<Edge> listOfEdges;
public ArrayList<Vector2D> allNodes() {
return listOfNodes;
}
public Vector2D sourceVector() {
return sourceNode;
}
/**
* Sets the sourceNode which is were the map is calculated to travel to
* @param value is the Vector2D you want to calculate routes to
*/
public void sourceVector(Vector2D value) {
for(int i = 0; i < listOfNodes.size(); i++) {
if(listOfNodes.get(i) == value) {
sourceNode = value;
break;
}
}
}
public Graph() {
listOfEdges = new ArrayList<Edge>();
listOfNodes = new ArrayList<Vector2D>();
sourceNode = null;
}
/**
* Sets all .visited to false, .aggregateCost to Vector2D.INFINITY, and .edgeWithLowestCost to null
* Then sets Vector2D.totalVisited to 0
*/
private void reset() {
for(int i = 0; i < listOfNodes.size(); i++) {
listOfNodes.get(i).resetVisited();
listOfNodes.get(i).aggregateCost = Vector2D.INFINITY;
listOfNodes.get(i).edgeWithLowestCost = null;
}
Vector2D.totalVisited = 0;
}
/**
* Adds the provided Edge to the listOfEdges then does reset()
*/
public void addEdge(Edge edge) {
listOfEdges.add(edge);
reset();
}
/**
* Adds an Edge created from the provided Vector2Ds with cost and then does reset()
* @param pointa is the Vector2D that is meant to be the 'first' point of this Edge
* @param pointb is the Vector2D that is meant to be the 'second' point of this Edge
* @param cost is how much traversing this edge costs
*/
public void addEdge(Vector2D pointa, Vector2D pointb, int cost) {
listOfEdges.add(new Edge(pointa, pointb, cost));
reset();
}
/**
* Adds the provided Vector2D to the listOfNodes then does reset()
* @param node
*/
public void addVector(Vector2D node) {
listOfNodes.add(node);
reset();
}
/**
* Adds a Vector2D created from the provided x, y, and deadendedness then does reset()
* @param x an int that represents it's position on the x axis
* @param y an int that represents it's position on the y axis
* @param deadend is a boolean of whether this point is a deadend
*/
public void addVector(int x, int y, boolean deadend) {
listOfNodes.add(new Vector2D(x, y, deadend));
reset();
}
private ArrayList<Vector2D> getListOfVisitedNodes() {
ArrayList<Vector2D> listOfVisitedNodes = new ArrayList<Vector2D>();
for(Vector2D node : listOfNodes) {
if(node.visited()) {
listOfVisitedNodes.add(node);
}
}
return listOfVisitedNodes;
}
private boolean ifMoreUnvisitedNodes() {
return Vector2D.totalVisited < listOfNodes.size();
}
private PriorityQueue<Edge> getConnectedEdges(Vector2D startnode) {
PriorityQueue<Edge> connectedEdges = new PriorityQueue<Edge>();
for(int i = 0; i < listOfEdges.size(); i++) {
Vector2D otherNode = listOfEdges.get(i).getOtherVector(startnode);
if(otherNode != null && !otherNode.visited()) {
connectedEdges.add(listOfEdges.get(i));
}
}
return connectedEdges;
}
private void performCalculationForAllNodes() {
Vector2D currentNode = sourceNode;
currentNode.setVisited();
visitAllNodes(currentNode);
}
private void visitAllNodes(Vector2D currentNode) {
do {
currentNode = getNextBestNode();
currentNode.setVisited();
} while(ifMoreUnvisitedNodes());
}
private Vector2D getNextBestNode() {
Vector2D nextBestNode = null;
for(Vector2D visitedNode : getListOfVisitedNodes()) {
PriorityQueue<Edge> connectedEdges = getConnectedEdges(visitedNode);
while(connectedEdges.size() > 0) {
Edge connectedEdge = connectedEdges.remove();
Vector2D otherNode = connectedEdge.getOtherVector(visitedNode);
if(otherNode.aggregateCost == Vector2D.INFINITY ||
(visitedNode.aggregateCost + connectedEdge.cost) < otherNode.aggregateCost) {
otherNode.aggregateCost = visitedNode.aggregateCost + connectedEdge.cost;
otherNode.edgeWithLowestCost = connectedEdge;
}
if(nextBestNode == null || otherNode.aggregateCost < nextBestNode.aggregateCost) {
nextBestNode = otherNode;
}
}
}
return nextBestNode;
}
/**
* @return boolean of if the calculation succeeded
*/
public boolean calculateShortestPath() {
boolean unreachable = false;
if(sourceNode == null) {
return false;
}
reset();
sourceNode.aggregateCost = 0;
performCalculationForAllNodes();
if(unreachable) {
return false;
}
return true;
}
/**
* Gets the shortest path from targetnode to sourceNode
* @param targetnode is the Vector2D to calculate the route to the sourceNode from
* @return ArrayList<Vector2D> with the path to sourceNode from targetnode
*/
public ArrayList<Vector2D> retrieveShortestPath(Vector2D targetnode) {
ArrayList<Vector2D> shortestPath = new ArrayList<Vector2D>();
if(targetnode != null) {
Vector2D currentNode = targetnode;
shortestPath.add(currentNode);
while(currentNode.edgeWithLowestCost != null) {
currentNode = currentNode.edgeWithLowestCost.getOtherVector(currentNode);
shortestPath.add(currentNode);
}
}
Collections.reverse(shortestPath);
return shortestPath;
}
} |
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.DataOutputStream;
import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.semanticweb.yars.nx.Node;
import org.semanticweb.yars.nx.Resource;
import org.semanticweb.yars.nx.Variable;
// this must sent random transactions to the server
public class TransactionClient
{
private String input_filename;
private String server_http_address;
private String source_graph;
private String dest_graph;
private int reset_flag;
private int snapshot_flag;
private String read_cons;
private String write_cons;
private String trans_lock_gran;
private int repl_factor;
private String check_my_writes;
private int no_threads;
private int time_run_per_th;
// after this timeout the results are gathered
private int warmup_period;
private int operation_type;
private int no_operations_per_transaction;
private int no_retrials;
private String distr_flag;
private String operation_name;
private String working_dir;
private String client_id;
private Integer client_dec_id;
private String conflictFlag;
private int numDiffEnt;
private int numDiffPropPerEnt;
private int numDiffValuePerProp;
private String transactionalSupport;
private ArrayList<Node[]> input_triples;
private Thread[] client_threads;
public int total_successful;
final public static String SERVER_TRANSACTION_SERVLET="/ers/transaction";
final public static String SERVER_HANDLE_GRAPHS_SERVLET="/ers/graph";
final public static String SERVER_SETUP_SERVLET="/ers/setup";
final public static String SERVER_VERSIONS_STATS="/ers/query_versions_stats";
final public static String SERVER_CREATE_SERVLET="/ers/create";
final public static String SERVER_READ_SERVLET="/ers/query";
public static final String FILENAME_SUFFIX_READY_WARMUP = "-client-ready-for-warmup";
public static final String FILENAME_SUFFIX_START_SENDING_REQUESTS = "-start-sending-requests";
public static final String FILENAME_SUFFIX_FINISHED = "-finished";
class ClientThread extends Thread
{
private int operation_type;
private int no_op_per_t;
private int retrials;
private int thread_id;
// this flag will be set to true after the warmup period
private boolean collect_results;
private long start_collection_res_time;
private boolean finished;
private long stop_time;
private Random random_gen;
private int size;
private int total_run_trans;
private int successful_trans;
private int conflicted_trans;
private int aborted_trans;
private int total_trans;
private HttpURLConnection connection;
private final int PperE = 20;
private final int VperP = 5;
// used to create non conflicting data when conflict flag is set to 'no'
private int counter_e;
private int counter_p;
private int counter_v;
public ClientThread(int operation_type, int no_op_per_t, int retrials,
int thread_id) {
this.operation_type = operation_type;
this.no_op_per_t = no_op_per_t;
this.retrials = retrials;
this.thread_id = thread_id;
this.collect_results = false;
this.finished = false;
this.random_gen = new Random(client_dec_id*thread_id);
this.size = input_triples.size();
this.total_run_trans = 0;
this.successful_trans = 0;
this.conflicted_trans = 0;
this.aborted_trans = 0;
this.total_trans = 0;
this.counter_e = 0;
this.counter_p = 0;
this.counter_v = 0;
}
public int getSuccessfulTrans() {
return this.successful_trans;
}
public int getConflictedTrans() {
return this.conflicted_trans;
}
public int getAbortedTrans() {
return this.aborted_trans;
}
public int getTotalTrans() {
return this.total_trans;
}
public void stopSendingTrans() {
this.finished = true;
this.stop_time = System.currentTimeMillis();
}
public void startCollectingResults() {
this.collect_results = true;
this.start_collection_res_time = System.currentTimeMillis();
}
private Node[] getRandomNode(boolean fullEntity, boolean insert) {
String randomE, randomP, randomV;
Node[] n = new Node[3];
int carry = 0;
if( conflictFlag.equals("yes") ) {
if( insert ) {
// change entity id for each operation
//++counter_e;
counter_e = random_gen.nextInt(numDiffEnt);
/*if( counter_e >= numDiffEnt ) {
counter_e = 0;
}*/
if( ++counter_v >= numDiffPropPerEnt ) {
counter_v = 0;
if( ++counter_p >= numDiffValuePerProp ) {
counter_p = 0;
counter_e++;
}
}
if( counter_e >= numDiffEnt ) {
counter_e = 0;
}
randomE = String.valueOf(counter_e);
randomP = String.valueOf(counter_p);
randomV = String.valueOf(counter_v);
}
else {
randomE = String.valueOf(random_gen.nextInt(numDiffEnt));
randomP = String.valueOf(random_gen.nextInt(numDiffPropPerEnt));
randomV = String.valueOf(random_gen.nextInt(numDiffValuePerProp));
}
}
else {
//if( fullEntity )
if( fullEntity || insert )
++counter_e;
else {
if( ++counter_v >= numDiffPropPerEnt ) {
counter_v = 0;
if( ++counter_p >= numDiffValuePerProp ) {
counter_p = 0;
counter_e++;
}
}
}
if( counter_e >= numDiffEnt ) {
counter_e = 0;
/*// do not increment carry when sending 'fullEntity' transactions
// by doing so it may send transactions to non-existing records
if( !fullEntity )
++carry;*/
}
randomE = client_dec_id + "-" + thread_id + "-" + counter_e;// + "--" + carry;
randomP = client_dec_id + "-" + thread_id + "-" + counter_e
+ "-" + counter_p;// + "--" + carry;
randomV = client_dec_id + "-" + thread_id + "-" + counter_e
+ "-" + counter_p + "-" + counter_v;// + "--" + carry;
}
n[0] = new Resource("eeeeeeeeeeeeeeeeeeeeee"+randomE);
n[1] = new Variable("pppppppppppppppppppppp"+randomP);
n[2] = new Variable("vvvvvvvvvvvvvvvvvvvvvv"+randomV);
//return input_triples.get(randomInt);
return n;
}
private String createAnInsert(Integer linkFlag) {
//Node[] random_node = input_triples.get(randomInt);
Node[] random_node;
if( linkFlag == 0 )
random_node = getRandomNode(false, true);
else
random_node = getRandomNode(false, false);
// create one insert ere
StringBuilder sb = new StringBuilder();
if( linkFlag != 0 )
sb.append("insert_link(");
else
sb.append("insert(");
sb.append("<"+random_node[0]+">").append(",");
sb.append("<"+random_node[1]+">").append(",");
// new value
sb.append("<"+random_node[2]+">").append(",");
sb.append(source_graph).append(");");
return sb.toString();
}
private String createAnUpdate(Integer linkFlag) {
Node[] random_node = getRandomNode(false, false);
// create one update here
StringBuilder sb = new StringBuilder();
if( linkFlag != 0 )
sb.append("update_link(");
else
sb.append("update(");
sb.append("<"+random_node[0]+">").append(",");
sb.append("<"+random_node[1]+">").append(",");
// new value
//sb.append("<"+random_node[2]+">").append(",");
sb.append("<"+random_node[2]+">").append(",");
sb.append(source_graph);
sb.append(",");
// old value of the update
sb.append("<"+random_node[2]+">").append(");");
return sb.toString();
}
private String createADelete(Integer linkFlag) {
Node[] random_node = getRandomNode(false, false);
// create one insert ere
StringBuilder sb = new StringBuilder();
if( linkFlag != 0 )
sb.append("delete_link(");
else
sb.append("delete(");
sb.append("<"+random_node[0]+">").append(",");
sb.append("<"+random_node[1]+">").append(",");
sb.append("<"+random_node[2]+">").append(",");
sb.append(source_graph).append(");");
return sb.toString();
}
private String createAnCopyShallow() {
Node[] random_node = getRandomNode(true, false);
// create one shallow copy here
StringBuilder sb = new StringBuilder();
sb.append("shallow_clone(");
sb.append("<"+random_node[0]+">").append(",");
sb.append(source_graph).append(",");
// new entity
sb.append("<NEW_"+random_node[2]+">").append(",");
sb.append(dest_graph);
sb.append(");");
return sb.toString();
}
private String createAnCopyDeep() {
Node[] random_node = getRandomNode(true, false);
// create one deep copy
StringBuilder sb = new StringBuilder();
sb.append("deep_clone(");
sb.append("<"+random_node[0]+">").append(",");
sb.append(source_graph).append(",");
// new entity
sb.append("<NEW_"+random_node[2]+">").append(",");
sb.append(dest_graph);
sb.append(");");
return sb.toString();
}
private String createDeleteEntity() {
Node[] random_node = getRandomNode(true, false);
// create one deep copy
StringBuilder sb = new StringBuilder();
sb.append("delete_all(");
sb.append("<"+random_node[0]+">").append(",");
sb.append(source_graph);
sb.append(");");
return sb.toString();
}
private StringBuilder createTransaction() {
StringBuilder sb = new StringBuilder();
sb.append("BEGIN");
for( int i=0; i<no_op_per_t; ++i ) {
switch( operation_type ) {
case 0: //insert
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 )// && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/IP-tx_client");
sb.append(";");
sb.append(createAnInsert(0));
break;
case 1: // insert link
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 ) //&& transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/IL-tx_client");
sb.append(";");
sb.append(createAnInsert(1));
break;
case 2: // update
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 ) //&& transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/UP-tx_client");
sb.append(";");
sb.append(createAnUpdate(0));
break;
case 3: // update link
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 )//&& transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/UL-tx_client");
sb.append(";");
sb.append(createAnUpdate(1));
break;
case 4: // delete
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 )//&& transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/DP-tx_client");
sb.append(";");
sb.append(createADelete(0));
break;
case 5:
// delete link
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 )//&& transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/DL-tx_client");
sb.append(";");
sb.append(createADelete(1));
break;
case 6: // entity shallow copy
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 )//&& transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/SC-tx_client");
sb.append(";");
sb.append(createAnCopyShallow());
break;
case 7: // entity deep copy
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 )//&& transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/DC-tx_client");
sb.append(";");
sb.append(createAnCopyDeep());
break;
case 8: // entity full delete
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 )//&& transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/DE-tx_client");
sb.append(";");
sb.append(createDeleteEntity());
break;
default:
break;
}
}
sb.append("COMMIT;");
//System.out.println("TRANSACTION: ");
//System.out.println(sb.toString());
return sb;
}
private void sendTransaction() {
StringBuilder transaction = createTransaction();
String urlParameters = "g="+source_graph+"&retries="+this.retrials+"&t="+transaction.toString();
try {
URL url = new URL(server_http_address+SERVER_TRANSACTION_SERVLET);
this.connection = (HttpURLConnection) url.openConnection();
this.connection.setDoOutput(true);
this.connection.setDoInput(true);
this.connection.setInstanceFollowRedirects(false);
this.connection.setRequestMethod("POST");
this.connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
this.connection.setRequestProperty("Connection", "Keep-Alive");
this.connection.setRequestProperty("charset", "utf-8");
this.connection.setUseCaches(false);
this.connection.setRequestProperty("Content-Length", ""
+ Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
int responseCode = connection.getResponseCode();
//System.out.println(line);
if( collect_results ) {
if( line.equals("0") )
successful_trans++;
else if( line.equals("-1") )
aborted_trans++;
else {
conflicted_trans += Integer.valueOf(line);
// even if there were conflicts, this T was run successfully at the end
successful_trans++;
}
this.total_trans++;
}
reader.close();
this.connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
// NO transactional context here!!!
private void sendSimpleInsert() {
Node[] randomNode = getRandomNode(false, false);
String urlParameters = "g="+source_graph+"&e="+randomNode[0].toN3()+
"&p=\""+randomNode[1].toString()+"\"&v=\""+randomNode[2].toString()+"\"";
try {
URL url = new URL(server_http_address+SERVER_CREATE_SERVLET);
this.connection = (HttpURLConnection) url.openConnection();
this.connection.setDoOutput(true);
this.connection.setDoInput(true);
this.connection.setInstanceFollowRedirects(false);
this.connection.setRequestMethod("POST");
this.connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
this.connection.setRequestProperty("Connection", "Keep-Alive");
this.connection.setRequestProperty("charset", "utf-8");
this.connection.setUseCaches(false);
this.connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
reader.close();
int responseCode = connection.getResponseCode();
//System.out.println(responseCode);
if(collect_results ) {
this.successful_trans++;
this.total_trans++;
}
this.connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
// NO transactional context here!!!
private void sendSimpleRead() {
Node[] randomNode = getRandomNode(false, false);
String urlParameters = "g="+source_graph+"&e="+randomNode[0].toN3()+
"&p=\""+randomNode[1].toString()+"\"&v=\""+randomNode[2].toString()+"\"";
try {
URL url = new URL(server_http_address+SERVER_READ_SERVLET+"?"+urlParameters);
this.connection = (HttpURLConnection) url.openConnection();
this.connection.setDoOutput(true);
this.connection.setInstanceFollowRedirects(false);
this.connection.setRequestMethod("GET");
this.connection.setRequestProperty("Connection", "Keep-Alive");
this.connection.setRequestProperty("charset", "utf-8");
this.connection.setUseCaches(false);
int responseCode = connection.getResponseCode();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
//System.out.println(line);
if( collect_results ) {
this.successful_trans++;
this.total_trans++;
}
reader.close();
this.connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void run() {
while( ! this.finished ) {
// simple insert, without TX context !!
if( operation_type == 10 ) {
sendSimpleInsert();
}
// simple read, without TX context !!
else if( operation_type == 20 ) {
sendSimpleRead();
}
else {
//send here a transaction to server
sendTransaction();
}
}
}
}
public TransactionClient() {
this.input_triples = new ArrayList<Node[]>();
}
// read the input file and populate the input_triples structure
public void init() {
this.client_threads = new ClientThread[this.no_threads];
/*File input_f = new File(this.input_filename);
if( ! input_f.exists() ) {
System.err.println("Input file " + input_filename + " does not exist!");
System.exit(2);
}
// load the triples file in memory
try {
FileInputStream fis = new FileInputStream(input_f);
Iterator<Node[]> nxp = new NxParser(fis);
while (nxp.hasNext()) {
boolean skip = false;
Node[] nx = nxp.next();
// filter here the triples that contain 'white_spaces' in one of the param
// reason: our primitive transaction engine do not accept this
for( int j=0; j<nx.length; ++j ) {
String n = nx[j].toString();
if( n.contains(" ") ) {
skip = true;
break;
}
}
if( skip )
continue;
this.input_triples.add(nx);
}
} catch( FileNotFoundException ex) {
ex.printStackTrace();
System.exit(3);
}*/
}
public void dbinit() throws InterruptedException {
// change consistency
changeReadWriteConsistency(read_cons, write_cons);
// change transaction locking granularity
changeTransactionLockingGranularity(trans_lock_gran);
// also change replication facotr
changeReplicationFactor(repl_factor);
// change transaction support mode
changeTransactionalSupport(transactionalSupport);
// change check-my-writes cons mode (valid only for MVCC)
changeCheckMyWritesMode(check_my_writes);
// reset the graph if needed (only for insert)
if( (reset_flag == 1 || reset_flag == 2) &&
(operation_type == 0 || operation_type == 10) ) {
System.out.println("Truncate the graph " + source_graph);
deleteGraph(source_graph, false);
if( transactionalSupport.equalsIgnoreCase("mvcc") ) {
// truncate the ERS_versions keyspace also
deleteGraph("<ERS_versions>", false);
}
}
System.out.println("Create the source graph " + source_graph);
createNewGraph(source_graph);
// truncate and create the destination
deleteGraph(dest_graph, false);
System.out.println("Create the dest graph " + dest_graph);
createNewGraph(dest_graph);
}
public void dbclear() {
// if truncate and deletion was is meant
if( reset_flag == 2 && operation_type == 0) {
System.out.println("Delete the graph " + source_graph);
deleteGraph(source_graph, true);
System.out.println("Now sleep 5s to leave some time for deletion ... ");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(TransactionClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void startThreads() {
for(int i=0; i<this.no_threads; ++i)
client_threads[i] = new ClientThread(
operation_type, no_operations_per_transaction,
no_retrials, i);
for(int i=0; i<this.no_threads; ++i)
client_threads[i].start();
}
public int getTotalTransactionsSent() {
int counter = 0;
for(int i=0; i<this.no_threads; ++i) {
counter += ((ClientThread)client_threads[i]).getTotalTrans();
}
return counter;
}
public double getSuccessfulRate(int total_tx) {
for(int i=0; i<this.no_threads; ++i)
total_successful+=((ClientThread)client_threads[i]).getSuccessfulTrans();
return ((double)total_successful/total_tx)*100;
}
public int getTotalConflicts() {
int r = 0;
for(int i=0; i<this.no_threads; ++i)
r+=((ClientThread)client_threads[i]).getConflictedTrans();
return r;
}
public int getTotalAborted() {
int r = 0;
for(int i=0; i<this.no_threads; ++i)
r+=((ClientThread)client_threads[i]).getAbortedTrans();
return r;
}
public void joinThreads() {
for(int i=0; i<this.no_threads; ++i) {
((ClientThread)client_threads[i]).stopSendingTrans();
}
try {
for(int i=0; i<this.no_threads; ++i)
client_threads[i].join();
} catch( InterruptedException ex ) {
ex.printStackTrace();
}
}
public void startCollectingResults() {
for(int i=0; i<this.no_threads; ++i) {
((ClientThread)client_threads[i]).startCollectingResults();
}
}
// delete an existing graph
public void deleteGraph(String graph, boolean cleanup) {
HttpURLConnection connection;
try {
URL url;
if( cleanup )
url = new URL(server_http_address+SERVER_HANDLE_GRAPHS_SERVLET+"?g="+graph+"&f=y");
else
url = new URL(server_http_address+SERVER_HANDLE_GRAPHS_SERVLET+"?g="+graph+"&f=y&truncate=y");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("DELETE");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println(line);
reader.close();
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void createNewGraph(String graph) {
HttpURLConnection connection;
String urlParameters = "g_id="+graph+"&g_p=<createdBy>&g_v=\"transaction_client\"";
if( transactionalSupport.equalsIgnoreCase("mvcc"))
urlParameters +="&ver";
try {
URL url = new URL(server_http_address+SERVER_HANDLE_GRAPHS_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Create new graph: " + line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void changeTransactionLockingGranularity(String transLockGran) {
HttpURLConnection connection;
String urlParameters = "trans_lock_gran="+transLockGran;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change read and write consistency levels: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void changeReadWriteConsistency(String readCons, String writeCons) {
HttpURLConnection connection;
String urlParameters = "read_cons="+readCons+"&write_cons="+writeCons;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change read and write consistency levels: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void changeReplicationFactor(int replFactor) {
HttpURLConnection connection;
String urlParameters = "repl_factor="+replFactor;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change replication factor to: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void changeCheckMyWritesMode(String mode) {
HttpURLConnection connection;
String urlParameters = "check_my_writes="+mode;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change check my writes consistency mode: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public String getVersionsStats(String keyspace) {
HttpURLConnection connection;
String output="";
String urlParameters = "graph="+keyspace;
try {
URL url = new URL(server_http_address+SERVER_VERSIONS_STATS+"?"+urlParameters);
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setUseCaches (false);
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while(true) {
line = reader.readLine();
if( line == null )
break;
output += line +"\n";
}
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
return output;
}
public void changeTransactionalSupport(String txSupportMode) {
HttpURLConnection connection;
String urlParameters = "trans_support="+txSupportMode;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change read and write consistency levels: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
private static String getOperationName(Integer operation_type) {
String operation_name;
switch( operation_type ) {
case 0:
operation_name = "insert";
break;
case 1:
operation_name = "insert link";
break;
case 2:
operation_name = "update";
break;
case 3:
operation_name = "update link";
break;
case 4:
operation_name = "delete";
break;
case 5:
operation_name = "delete link";
break;
case 6:
operation_name = "entity shallow copy";
break;
case 7:
operation_name = "entity deep copy";
break;
case 8:
operation_name = "entity full delete";
break;
case 10:
operation_name = "insert without transactional context";
break;
case 20:
operation_name = "read without transactional context";
break;
default:
operation_name = null;
break;
}
return operation_name;
}
public static void main(String[] args) throws IOException, InterruptedException {
if( args.length < 22 ) {
System.err.println("Usage: \n" +
"1. server http address \n"+
"2. source graph/dest graph (both separated by /) \n" +
"3. reset graph (0:do nothing, 1:delete&create)\n" +
"4. snashot graph (0:do nothing, 1:delete&create)\n" +
"5. read consistency (one, two, three, quorum, all)\n" +
"6. write consistency (one, two, three, quorum, all, any)\n" +
"7. transactional locking granularity (e, ep, epv)\n" +
"8. replication factor \n"+
"9. no of threads \n" +
"10. time to run per thread (sec) \n" +
"11. warm-up period (sec) \n" +
"12. operation type (0:insert, 1:insert_link, 2:update, 3:update_link" +
", 4:delete, 5:delete_link, 6:entity_shallow_copy, 7:entity_deep_copy," +
" 8:entity_full_delete; 10:insert-NO-TX; 20:read-NO-TX) \n" +
"13. number of operations to run per transaction \n" +
"14. number of retrials (if transaction conficts)\n" +
"15. distributed mode flag (yes/no); NOTE: if yes, the following parameters are used\n" +
"16. working directory (needed to run remote ssh commands)\n" +
"17. client hexa ID (used by reomte ssh commands)\n" +
"18. client deci ID (used by data generator)\n" +
"19. conflicts flag (if no, the following params are not used)\n" +
"20. number different entities \n" +
"21. number different properties per entity \n" +
"22. number different values per property \n" +
"23. transactional support (zookeeper, default, MVCC);\n" +
"24. check my writes mode (on, off) -> valid only for MVCC\n" +
"25. INIT FLAG (at most 1client must use this flag; it resets consistency, graph and others)");
System.exit(1);
}
//IMPORTANT FOR TESTING TOOL; DO NOT DELETE!( Integer.valueOf(args[22]) < 1 ) ? 1 : Integer.valueOf
String PID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
System.out.println("PID: "+PID);
System.out.flush();
System.out.print("Arguments passed: ");
for( int i=0; i<args.length; ++i )
System.out.print(args[i] + " ");
System.out.println("");
TransactionClient tc = new TransactionClient();
tc.server_http_address = args[0];
tc.source_graph = args[1].substring(0, args[1].indexOf("/"));
tc.dest_graph = args[1].substring(args[1].indexOf("/")+1);
tc.reset_flag = Integer.valueOf(args[2]);
tc.snapshot_flag = Integer.valueOf(args[3]);
tc.read_cons = args[4];
tc.write_cons = args[5];
tc.trans_lock_gran = args[6];
tc.repl_factor = Integer.valueOf(args[7]);
tc.no_threads = ( Integer.valueOf(args[8]) < 1 ) ? 1 : Integer.valueOf(args[8]);
tc.time_run_per_th = ( Integer.valueOf(args[9]) < 1 ) ? 1 : Integer.valueOf(args[9]);
// after this timeout the results are gathered
tc.warmup_period = Integer.valueOf(args[10]);
tc.operation_type = Integer.valueOf(args[11]);
tc.no_operations_per_transaction = ( Integer.valueOf(args[12]) < 1 ) ? 1 : Integer.valueOf(args[12]);
tc.no_retrials = Integer.valueOf(args[13]);
tc.distr_flag = args[14];
tc.operation_name = getOperationName(tc.operation_type);
if( tc.operation_name == null ) {
System.out.println("[ERROR] Please pass a correct operation type. See the 'usage'!");
return;
}
System.out.println("Create transactions with " + tc.no_operations_per_transaction
+ " " + tc.operation_name + " per T");
tc.working_dir="";
tc.client_id="-1";
if( tc.distr_flag !=null && ! tc.distr_flag.isEmpty() && tc.distr_flag.equals("yes") ) {
System.out.println("Distributed mode is on, thus use synch mechanism ... ");
tc.working_dir = args[15];
tc.client_id = args[16];
tc.client_dec_id = Integer.valueOf(args[17]);
}
tc.conflictFlag = args[18];
tc.numDiffEnt = ( Integer.valueOf(args[19]) < 1 ) ? 1 : Integer.valueOf(args[19]);
tc.numDiffPropPerEnt = ( Integer.valueOf(args[20]) < 1 ) ? 1 : Integer.valueOf(args[20]);
tc.numDiffValuePerProp = ( Integer.valueOf(args[21]) < 1 ) ? 1 : Integer.valueOf(args[21]);
tc.transactionalSupport = args[22];
tc.check_my_writes = args[23];
tc.init();
// does this client initialize/setup the DB?
if( args[24] != null && args[24].equals("yes") ) {
tc.dbinit();
}
if( tc.distr_flag !=null && ! tc.distr_flag.isEmpty() && tc.distr_flag.equals("yes") ) {
// initializations are done, so create the local msg
String ready_warmup_filename = tc.working_dir+"/"+tc.client_id+FILENAME_SUFFIX_READY_WARMUP;
new File(ready_warmup_filename).createNewFile();
System.out.println("Client ready for warmup and sending requests ...");
// now, we wait until the coordinator creates another local file
String read_to_start_filename = tc.working_dir+"/"+tc.client_id+
FILENAME_SUFFIX_START_SENDING_REQUESTS;
while( ! new File(read_to_start_filename).exists() ) {
Thread.sleep(50);
}
System.out.println("Warmup begins now and in " + tc.warmup_period
+ "sec statistics will start to be gathered ...");
}
// start threads to send 'operation_type' transaction for no_op.. times
tc.startThreads();
long start_time = 0;
// wait to warmup before signaling the other threads to go ahead
try {
System.out.println("Threads have been started, but wait " + tc.warmup_period
+ " seconds to warmup ... ");
for( int i=0; i<tc.warmup_period; ++i ) {
Thread.sleep(1000);
System.out.print("warmup ");
}
// now its time to start collecting data
System.out.println("Signal threads that now they can record statistical data");
tc.startCollectingResults();
start_time = System.currentTimeMillis();
// now wait the given period for the threads to run transactions before joining them
System.out.println("Leave threads to send transactions for "
+ tc.time_run_per_th + " seconds ... ");
for( int i=0; i<tc.time_run_per_th; i=i+5) {
System.out.print((tc.time_run_per_th-i)+"s ");
if( i+5 > tc.time_run_per_th )
Thread.sleep(tc.time_run_per_th-i * 1000);
else
Thread.sleep(5000);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
// stop all the trans threads here
System.out.println("\nStop threads and gather statistics ");
tc.joinThreads();
if( args[22] != null && args[22].equals("yes") ) {
tc.dbclear();
}
long total_time = System.currentTimeMillis()-start_time;
int total_trans = tc.getTotalTransactionsSent();
double s_rate = tc.getSuccessfulRate(total_trans);
int conflicts = tc.getTotalConflicts();
int aborted = tc.getTotalAborted();
System.out.println("Time time needed for sending " + total_trans + " transactions " + total_time +"ms");
System.out.println(" ... " + tc.no_operations_per_transaction + " no of " + tc.operation_name + " ran per transaction ");
System.out.println(" ... with a successful rate of " + s_rate + "% => transaction rate of " + ((double)tc.total_successful/total_time*1000) + "tx/sec" );
System.out.println(" ... " + conflicts + " total number of conflicts; 1 unit means one certain transaction was restarted");
System.out.println(" ... " + aborted + " total number of aborted transactions");
System.out.println(" ... after " + tc.no_retrials + " of retrials a transaction was aborted!");
System.out.println();
System.out.println("No threads,Total time, total trans, conflicts, aborted, successful rate/sec, no retrials");
System.out.println(tc.no_threads + " " + total_time + " " + total_trans + " " + conflicts + " " + aborted + " " +
((double)tc.total_successful/total_time*1000) + " " + tc.no_retrials);
if( args[24] != null && args[24].equals("yes") ) {
System.out.println("Versions stats: ");
System.out.println(tc.getVersionsStats(tc.dest_graph));
}
if( tc.distr_flag !=null && ! tc.distr_flag.isEmpty() && tc.distr_flag.equals("yes") ) {
// as the threads are finished, signal it again with a new empty file
String ready_filename = tc.working_dir+"/"+tc.client_id+FILENAME_SUFFIX_FINISHED;
new File(ready_filename).createNewFile();
}
}
} |
package net.sf.cglib;
import java.io.Serializable;
import java.util.*;
import java.lang.reflect.*;
/**
* This class is meant to be used as a drop-in replacement for
* <code>java.lang.reflect.Proxy</code>. There are some known subtle differences:
* <ul>
* <li>The exceptions returned by invoking <code>getExceptionTypes</code>
* on the <code>Method</code> passed to the <code>invoke</code> method
* <b>are</b> the exact set that can be thrown without resulting in an
* <code>UndeclaredThrowableException</code> being thrown.
* <li>There is no protected constructor which accepts an
* <code>InvocationHandler</code>. Instead, use the more convenient
* <code>newProxyInstance</code> static method.
* <li><code>net.sf.cglib.UndeclaredThrowableException</code> is used instead
* of <code>java.lang.reflect.UndeclaredThrowableException</code>, because the latter
* is not availabe in JDK 1.2.
* </ul>
* @author Chris Nokleberg <a href="mailto:chris@nokleberg.com">chris@nokleberg.com</a>
* @version $Id: JdkCompatibleProxy.java,v 1.3 2002-12-06 19:03:02 herbyderby Exp $
*/
public class JdkCompatibleProxy implements Serializable {
private static final Class thisClass = JdkCompatibleProxy.class;
private static final HandlerAdapter nullInterceptor = new HandlerAdapter(null);
private static class HandlerAdapter implements MethodInterceptor {
private InvocationHandler handler;
public HandlerAdapter(InvocationHandler handler) {
this.handler = handler;
}
public Object aroundAdvice(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
return handler.invoke(obj, method, args);
}
}
protected InvocationHandler h;
protected JdkCompatibleProxy(MethodInterceptor mi) {
HandlerAdapter adapter = (HandlerAdapter)mi;
if (adapter != null)
h = adapter.handler;
}
public static InvocationHandler getInvocationHandler(Object proxy) {
return ((HandlerAdapter)((Factory)proxy).getInterceptor()).handler;
}
public static Class getProxyClass(ClassLoader loader, Class[] interfaces) {
return Enhancer.enhance(thisClass, interfaces, nullInterceptor, loader).getClass();
}
public static boolean isProxyClass(Class cl) {
return cl.getSuperclass().getName().equals(thisClass.getName());
}
public static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h) {
return Enhancer.enhance(thisClass, interfaces, new HandlerAdapter(h), loader);
}
} |
// Hash table with linked lists for collisions
// Supports add, get, update, remove, toString
public class HashTable {
private int tableSize;
private HashNode[] table;
//LinkedList<Integer>[] vertex = new LinkedList[5];
public HashTable(){
this.tableSize = 128;
initializeTable();
}
public HashTable(int tableSize){
this.tableSize = tableSize;
initializeTable();
}
public void add(String str, int value){
int key = stringToHashKey(str);
Object[] data = new Object[2];
data[0] = str;
data[1] = value;
table[key].add(data);
}
public int get(String str){
int key = stringToHashKey(str);
int value = table[key].get(str);
return value;
}
public int update(String str, int value){
// create the new object
int key = stringToHashKey(str);
Object[] data = new Object[2];
data[0] = str;
data[1] = value;
// get the previous value
int oldValue = table[key].get(str);
//update the value
table[key].update(data);
return oldValue;
}
public int remove(String str){
int key = stringToHashKey(str);
int value = table[key].get(str);
table[key].remove(str);
return value;
}
public String toString(){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < table.length; i++){
for(Object[] data : table[i].list){
sb.append("index: " + i + " | ");
sb.append(data[0] + " => ");
sb.append(data[1]);
sb.append("\n");
}
}
return sb.toString();
}
private int stringToHashKey(String string){
int key = string.hashCode();
key = Math.abs(key % tableSize);
return key;
}
// set default values to -999
private void initializeTable(){
this.table = new HashNode[this.tableSize];
for (int i = 0; i < table.length; i++){
table[i] = new HashNode();
}
}
} |
package jolie.net;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jolie.Interpreter;
import jolie.lang.NativeType;
import jolie.net.http.HttpMessage;
import jolie.net.http.HttpParser;
import jolie.net.http.HttpUtils;
import jolie.net.http.json.JsonUtils;
import joliex.gwt.server.JolieGWTConverter;
import jolie.net.http.Method;
import jolie.net.http.MultiPartFormDataParser;
import jolie.net.ports.Interface;
import jolie.net.protocols.CommProtocol;
import jolie.runtime.ByteArray;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
import jolie.runtime.typing.OneWayTypeDescription;
import jolie.runtime.typing.RequestResponseTypeDescription;
import jolie.runtime.typing.Type;
import jolie.runtime.typing.TypeCastingException;
import jolie.util.LocationParser;
import jolie.xml.XmlUtils;
import joliex.gwt.client.JolieService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* HTTP protocol implementation
* @author Fabrizio Montesi
* 14 Nov 2012 - Saverio Giallorenzo - Fabrizio Montesi: support for status codes
*/
public class HttpProtocol extends CommProtocol
{
private static final byte[] NOT_IMPLEMENTED_HEADER = "HTTP/1.1 501 Not Implemented".getBytes();
private static final int DEFAULT_STATUS_CODE = 200;
private static final int DEFAULT_REDIRECTION_STATUS_CODE = 303;
private static final Map< Integer, String > statusCodeDescriptions = new HashMap< Integer, String >();
private static final Set< Integer > locationRequiredStatusCodes = new HashSet< Integer >();
static {
locationRequiredStatusCodes.add( 301 );
locationRequiredStatusCodes.add( 302 );
locationRequiredStatusCodes.add( 303 );
locationRequiredStatusCodes.add( 307 );
locationRequiredStatusCodes.add( 308 );
}
static {
// Initialise the HTTP Status code map.
statusCodeDescriptions.put( 100,"Continue" );
statusCodeDescriptions.put( 101,"Switching Protocols" );
statusCodeDescriptions.put( 102,"Processing" );
statusCodeDescriptions.put( 200,"OK" );
statusCodeDescriptions.put( 201,"Created" );
statusCodeDescriptions.put( 202,"Accepted" );
statusCodeDescriptions.put( 203,"Non-Authoritative Information" );
statusCodeDescriptions.put( 204,"No Content" );
statusCodeDescriptions.put( 205,"Reset Content" );
statusCodeDescriptions.put( 206,"Partial Content" );
statusCodeDescriptions.put( 207,"Multi-Status" );
statusCodeDescriptions.put( 208,"Already Reported" );
statusCodeDescriptions.put( 226,"IM Used" );
statusCodeDescriptions.put( 300,"Multiple Choices" );
statusCodeDescriptions.put( 301,"Moved Permanently" );
statusCodeDescriptions.put( 302,"Found" );
statusCodeDescriptions.put( 303,"See Other" );
statusCodeDescriptions.put( 304,"Not Modified" );
statusCodeDescriptions.put( 305,"Use Proxy" );
statusCodeDescriptions.put( 306,"Reserved" );
statusCodeDescriptions.put( 307,"Temporary Redirect" );
statusCodeDescriptions.put( 308,"Permanent Redirect" );
statusCodeDescriptions.put( 400,"Bad Request" );
statusCodeDescriptions.put( 401,"Unauthorized" );
statusCodeDescriptions.put( 402,"Payment Required" );
statusCodeDescriptions.put( 403,"Forbidden" );
statusCodeDescriptions.put( 404,"Not Found" );
statusCodeDescriptions.put( 405,"Method Not Allowed" );
statusCodeDescriptions.put( 406,"Not Acceptable" );
statusCodeDescriptions.put( 407,"Proxy Authentication Required" );
statusCodeDescriptions.put( 408,"Request Timeout" );
statusCodeDescriptions.put( 409,"Conflict" );
statusCodeDescriptions.put( 410,"Gone" );
statusCodeDescriptions.put( 411,"Length Required" );
statusCodeDescriptions.put( 412,"Precondition Failed" );
statusCodeDescriptions.put( 413,"Request Entity Too Large" );
statusCodeDescriptions.put( 414,"Request-URI Too Long" );
statusCodeDescriptions.put( 415,"Unsupported Media Type" );
statusCodeDescriptions.put( 416,"Requested Range Not Satisfiable" );
statusCodeDescriptions.put( 417,"Expectation Failed" );
statusCodeDescriptions.put( 422,"Unprocessable Entity" );
statusCodeDescriptions.put( 423,"Locked" );
statusCodeDescriptions.put( 424,"Failed Dependency" );
statusCodeDescriptions.put( 426,"Upgrade Required" );
statusCodeDescriptions.put( 427,"Unassigned" );
statusCodeDescriptions.put( 428,"Precondition Required" );
statusCodeDescriptions.put( 429,"Too Many Requests" );
statusCodeDescriptions.put( 430,"Unassigned" );
statusCodeDescriptions.put( 431,"Request Header Fields Too Large" );
statusCodeDescriptions.put( 500,"Internal Server Error" );
statusCodeDescriptions.put( 501,"Not Implemented" );
statusCodeDescriptions.put( 502,"Bad Gateway" );
statusCodeDescriptions.put( 503,"Service Unavailable" );
statusCodeDescriptions.put( 504,"Gateway Timeout" );
statusCodeDescriptions.put( 505,"HTTP Version Not Supported" );
statusCodeDescriptions.put( 507,"Insufficient Storage" );
statusCodeDescriptions.put( 508,"Loop Detected" );
statusCodeDescriptions.put( 509,"Unassigned" );
statusCodeDescriptions.put( 510,"Not Extended" );
statusCodeDescriptions.put( 511,"Network Authentication Required" );
}
private static class Parameters {
private static final String DEBUG = "debug";
private static final String COOKIES = "cookies";
private static final String METHOD = "method";
private static final String ALIAS = "alias";
private static final String MULTIPART_HEADERS = "multipartHeaders";
private static final String CONCURRENT = "concurrent";
private static final String USER_AGENT = "userAgent";
private static final String HEADERS = "headers";
private static final String STATUS_CODE = "statusCode";
private static final String REDIRECT = "redirect";
private static class MultiPartHeaders {
private static final String FILENAME = "filename";
}
}
private static class Headers {
private static String JOLIE_MESSAGE_ID = "X-Jolie-MessageID";
}
private String inputId = null;
private final Transformer transformer;
private final DocumentBuilderFactory docBuilderFactory;
private final DocumentBuilder docBuilder;
private final URI uri;
private final boolean inInputPort;
private MultiPartFormDataParser multiPartFormDataParser = null;
public final static String CRLF = new String( new char[] { 13, 10 } );
public String name()
{
return "http";
}
public boolean isThreadSafe()
{
return checkBooleanParameter( Parameters.CONCURRENT );
}
public HttpProtocol(
VariablePath configurationPath,
URI uri,
boolean inInputPort,
TransformerFactory transformerFactory,
DocumentBuilderFactory docBuilderFactory,
DocumentBuilder docBuilder
)
throws TransformerConfigurationException
{
super( configurationPath );
this.uri = uri;
this.inInputPort = inInputPort;
this.transformer = transformerFactory.newTransformer();
this.docBuilderFactory = docBuilderFactory;
this.docBuilder = docBuilder;
transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
}
private void valueToDocument(
Value value,
Node node,
Document doc
)
{
node.appendChild( doc.createTextNode( value.strValue() ) );
Element currentElement;
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
for( Value val : entry.getValue() ) {
currentElement = doc.createElement( entry.getKey() );
node.appendChild( currentElement );
Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val );
if ( attrs != null ) {
for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) {
currentElement.setAttribute(
attrEntry.getKey(),
attrEntry.getValue().first().strValue()
);
}
}
valueToDocument( val, currentElement, doc );
}
}
}
}
public String getMultipartHeaderForPart( String operationName, String partName )
{
if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) {
Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS );
if ( v.hasChildren( partName ) ) {
v = v.getFirstChild( partName );
if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) {
v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME );
return v.strValue();
}
}
}
return null;
}
private final static String BOUNDARY = "----Jol13H77p$$Bound4r1$$";
private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder )
{
Value cookieParam = null;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) {
cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookieParam = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookieParam != null ) {
Value cookieConfig;
String domain;
StringBuilder cookieSB = new StringBuilder();
for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) {
cookieConfig = entry.getValue().first();
if ( message.value().hasChildren( cookieConfig.strValue() ) ) {
domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "";
if ( domain.isEmpty() || hostname.endsWith( domain ) ) {
cookieSB
.append( entry.getKey() )
.append( '=' )
.append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() )
.append( ";" );
}
}
}
if ( cookieSB.length() > 0 ) {
headerBuilder
.append( "Cookie: " )
.append( cookieSB )
.append( CRLF );
}
}
}
private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder )
{
Value cookieParam = null;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) {
cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookieParam = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookieParam != null ) {
Value cookieConfig;
for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) {
cookieConfig = entry.getValue().first();
if ( message.value().hasChildren( cookieConfig.strValue() ) ) {
headerBuilder
.append( "Set-Cookie: " )
.append( entry.getKey() ).append( '=' )
.append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() )
.append( "; expires=" )
.append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" )
.append( "; domain=" )
.append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" )
.append( "; path=" )
.append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" );
if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) {
headerBuilder.append( "; secure" );
}
headerBuilder.append( CRLF );
}
}
}
}
private String requestFormat = null;
private void send_appendQuerystring( Value value, String charset, StringBuilder headerBuilder )
throws IOException
{
if ( value.children().isEmpty() == false ) {
headerBuilder.append( '?' );
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
for( Value v : entry.getValue() ) {
headerBuilder
.append( entry.getKey() )
.append( '=' )
.append( URLEncoder.encode( v.strValue(), charset ) )
.append( '&' );
}
}
}
}
private void send_appendParsedAlias( String alias, Value value, String charset, StringBuilder headerBuilder )
throws IOException
{
int offset = 0;
String currStrValue;
String currKey;
StringBuilder result = new StringBuilder( alias );
Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias );
while( m.find() ) {
if ( m.group( 1 ) == null ) { // We have to use URLEncoder
currKey = alias.substring( m.start() + 2, m.end() - 1 );
if ( "$".equals( currKey ) ) {
currStrValue = URLEncoder.encode( value.strValue(), charset );
} else {
currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset );
}
} else { // We have to insert the string raw
currKey = alias.substring( m.start() + 3, m.end() - 1 );
if ( "$".equals( currKey ) ) {
currStrValue = value.strValue();
} else {
currStrValue = value.getFirstChild( currKey ).strValue();
}
}
result.replace(
m.start() + offset, m.end() + offset,
currStrValue
);
offset += currStrValue.length() - 3 - currKey.length();
}
headerBuilder.append( result );
}
private String getCharset()
{
String charset = "UTF-8";
if ( hasParameter( "charset" ) ) {
charset = getStringParameter( "charset" );
}
return charset;
}
private String send_getFormat()
{
String format = "xml";
if ( inInputPort && requestFormat != null ) {
format = requestFormat;
requestFormat = null;
} else if ( hasParameter( "format" ) ) {
format = getStringParameter( "format" );
}
return format;
}
private static class EncodedContent {
private ByteArray content = null;
private String contentType = "";
private String contentDisposition = "";
}
private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format )
throws IOException
{
EncodedContent ret = new EncodedContent();
if ( inInputPort == false && method == Method.GET ) {
// We are building a GET request
return ret;
}
if ( "xml".equals( format ) ) {
Document doc = docBuilder.newDocument();
Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") );
doc.appendChild( root );
if ( message.isFault() ) {
Element faultElement = doc.createElement( message.fault().faultName() );
root.appendChild( faultElement );
valueToDocument( message.fault().value(), faultElement, doc );
} else {
valueToDocument( message.value(), root, doc );
}
Source src = new DOMSource( doc );
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
Result dest = new StreamResult( tmpStream );
try {
transformer.transform( src, dest );
} catch( TransformerException e ) {
throw new IOException( e );
}
ret.content = new ByteArray( tmpStream.toByteArray() );
ret.contentType = "text/xml";
} else if ( "binary".equals( format ) ) {
if ( message.value().isByteArray() ) {
ret.content = (ByteArray) message.value().valueObject();
ret.contentType = "application/octet-stream";
}
} else if ( "html".equals( format ) ) {
ret.content = new ByteArray( message.value().strValue().getBytes( charset ) );
ret.contentType = "text/html";
} else if ( "multipart/form-data".equals( format ) ) {
ret.contentType = "multipart/form-data; boundary=" + BOUNDARY;
StringBuilder builder = new StringBuilder();
for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
builder.append( "--" ).append( BOUNDARY ).append( CRLF );
builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' ).append( CRLF ).append( CRLF );
builder.append( entry.getValue().first().strValue() ).append( CRLF );
}
}
builder.append( "--" + BOUNDARY + "--" );
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "x-www-form-urlencoded".equals( format ) ) {
ret.contentType = "application/x-www-form-urlencoded";
Iterator< Entry< String, ValueVector > > it =
message.value().children().entrySet().iterator();
Entry< String, ValueVector > entry;
StringBuilder builder = new StringBuilder();
while( it.hasNext() ) {
entry = it.next();
builder.append( entry.getKey() )
.append( "=" )
.append( URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) );
if ( it.hasNext() ) {
builder.append( '&' );
}
}
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "text/x-gwt-rpc".equals( format ) ) {
ret.contentType = "text/x-gwt-rpc";
try {
if ( message.isFault() ) {
ret.content = new ByteArray(
RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset )
);
} else {
joliex.gwt.client.Value v = new joliex.gwt.client.Value();
JolieGWTConverter.jolieToGwtValue( message.value(), v );
ret.content = new ByteArray(
RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset )
);
}
} catch( SerializationException e ) {
throw new IOException( e );
}
} else if ( "json".equals( format ) || "application/json".equals( format ) ) {
ret.contentType = "application/json";
StringBuilder jsonStringBuilder = new StringBuilder();
if ( message.isFault() ) {
Value jolieJSONFault = Value.create();
jolieJSONFault.getFirstChild("jolieFault").getFirstChild("faultName").setValue( message.fault().faultName() );
if ( !message.fault().value().hasChildren() && !message.fault().value().strValue().isEmpty() ) {
jolieJSONFault.getFirstChild("jolieFault").getFirstChild("data").deepCopy( message.fault().value() );
}
JsonUtils.valueToJsonString( jolieJSONFault, jsonStringBuilder );
} else {
JsonUtils.valueToJsonString( message.value(), jsonStringBuilder );
}
ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) );
}
return ret;
}
private boolean isLocationNeeded( int statusCode )
{
return locationRequiredStatusCodes.contains( statusCode );
}
private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder )
{
int statusCode = DEFAULT_STATUS_CODE;
String statusDescription = null;
if( hasParameter( Parameters.STATUS_CODE ) ) {
statusCode = getIntParameter( Parameters.STATUS_CODE );
if ( !statusCodeDescriptions.containsKey( statusCode ) ) {
Interpreter.getInstance().logWarning( "HTTP protocol for operation " +
message.operationName() +
" is sending a message with status code " +
statusCode +
", which is not in the HTTP specifications."
);
statusDescription = "Internal Server Error";
} else if ( isLocationNeeded( statusCode ) && !hasParameter( Parameters.REDIRECT ) ) {
// if statusCode is a redirection code, location parameter is needed
Interpreter.getInstance().logWarning( "HTTP protocol for operation " +
message.operationName() +
" is sending a message with status code " +
statusCode +
", which expects a redirect parameter but the latter is not set."
);
}
} else if ( hasParameter( Parameters.REDIRECT ) ) {
statusCode = DEFAULT_REDIRECTION_STATUS_CODE;
}
if ( statusDescription == null ) {
statusDescription = statusCodeDescriptions.get( statusCode );
}
headerBuilder.append( "HTTP/1.1 " + statusCode + " " + statusDescription + CRLF );
// if redirect has been set, the redirect location parameter is set
if ( hasParameter( Parameters.REDIRECT ) ) {
headerBuilder.append( "Location: " + getStringParameter( Parameters.REDIRECT ) + CRLF );
}
send_appendSetCookieHeader( message, headerBuilder );
headerBuilder.append( "Server: Jolie" ).append( CRLF );
StringBuilder cacheControlHeader = new StringBuilder();
if ( hasParameter( "cacheControl" ) ) {
Value cacheControl = getParameterFirstValue( "cacheControl" );
if ( cacheControl.hasChildren( "maxAge" ) ) {
cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() );
}
}
if ( cacheControlHeader.length() > 0 ) {
headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( CRLF );
}
}
private void send_appendRequestMethod( Method method, StringBuilder headerBuilder )
{
headerBuilder.append( method.id() );
}
private void send_appendRequestPath( CommMessage message, Method method, StringBuilder headerBuilder, String charset )
throws IOException
{
if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) {
headerBuilder.append( '/' );
}
headerBuilder.append( uri.getPath() );
String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS );
if ( alias.isEmpty() ) {
headerBuilder.append( message.operationName() );
} else {
send_appendParsedAlias( alias, message.value(), charset, headerBuilder );
}
if ( method == Method.GET ) {
send_appendQuerystring( message.value(), charset, headerBuilder );
}
}
private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder )
{
if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) {
Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() );
//String realm = v.getFirstChild( "realm" ).strValue();
String userpass =
v.getFirstChild( "userid" ).strValue() + ":" +
v.getFirstChild( "password" ).strValue();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
userpass = encoder.encode( userpass.getBytes() );
headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( CRLF );
}
}
private Method send_getRequestMethod( CommMessage message )
throws IOException
{
try {
Method method;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ) {
method = Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ).toUpperCase() );
} else if ( hasParameter( Parameters.METHOD ) ) {
method = Method.fromString( getStringParameter( Parameters.METHOD ).toUpperCase() );
} else {
method = Method.POST;
}
return method;
} catch( Method.UnsupportedMethodException e ) {
throw new IOException( e );
}
}
private void send_appendRequestHeaders( CommMessage message, Method method, StringBuilder headerBuilder, String charset )
throws IOException
{
send_appendRequestMethod( method, headerBuilder );
headerBuilder.append( ' ' );
send_appendRequestPath( message, method, headerBuilder, charset );
headerBuilder.append( " HTTP/1.1" + CRLF );
headerBuilder.append( "Host: " + uri.getHost() + CRLF );
send_appendCookies( message, uri.getHost(), headerBuilder );
send_appendAuthorizationHeader( message, headerBuilder );
}
private void send_appendGenericHeaders(
CommMessage message,
EncodedContent encodedContent,
String charset,
StringBuilder headerBuilder
)
{
String param;
if ( checkBooleanParameter( "keepAlive", true ) == false || channel().toBeClosed() ) {
channel().setToBeClosed( true );
headerBuilder.append( "Connection: close" + CRLF );
}
if ( checkBooleanParameter( Parameters.CONCURRENT, true ) ) {
headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( CRLF );
}
if ( encodedContent.content != null ) {
String contentType = getStringParameter( "contentType" );
if ( contentType.length() > 0 ) {
encodedContent.contentType = contentType;
}
headerBuilder.append( "Content-Type: " + encodedContent.contentType );
if ( charset != null ) {
headerBuilder.append( "; charset=" + charset.toLowerCase() );
}
headerBuilder.append( CRLF );
param = getStringParameter( "contentTransferEncoding" );
if ( !param.isEmpty() ) {
headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF );
}
String contentDisposition = getStringParameter( "contentDisposition" );
if ( contentDisposition.length() > 0 ) {
encodedContent.contentDisposition = contentDisposition;
headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition + CRLF );
}
headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF );
} else {
headerBuilder.append( "Content-Length: 0" + CRLF );
}
}
private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent )
{
if ( checkBooleanParameter( "debug" ) ) {
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Sending:\n" );
debugSB.append( header );
if (
getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0
&& encodedContent.content != null
) {
debugSB.append( encodedContent.content.toString() );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
}
public void send( OutputStream ostream, CommMessage message, InputStream istream )
throws IOException
{
Method method = send_getRequestMethod( message );
String charset = getCharset();
String format = send_getFormat();
EncodedContent encodedContent = send_encodeContent( message, method, charset, format );
StringBuilder headerBuilder = new StringBuilder();
if ( inInputPort ) {
// We're responding to a request
send_appendResponseHeaders( message, headerBuilder );
} else {
// We're sending a notification or a solicit
send_appendRequestHeaders( message, method, headerBuilder, charset );
}
send_appendGenericHeaders( message, encodedContent, charset, headerBuilder );
headerBuilder.append( CRLF );
send_logDebugInfo( headerBuilder, encodedContent );
inputId = message.operationName();
/*if ( charset == null ) {
charset = "UTF8";
}*/
ostream.write( headerBuilder.toString().getBytes( charset ) );
if ( encodedContent.content != null ) {
ostream.write( encodedContent.content.getBytes() );
ostream.write( CRLF.getBytes( charset ) );
}
}
private void parseXML( HttpMessage message, Value value )
throws IOException
{
try {
if ( message.size() > 0 ) {
DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) );
Document doc = builder.parse( src );
XmlUtils.documentToValue( doc, value );
}
} catch( ParserConfigurationException pce ) {
throw new IOException( pce );
} catch( SAXException saxe ) {
throw new IOException( saxe );
}
}
private static void parseJson( HttpMessage message, Value value )
throws IOException
{
JsonUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ) ), value );
}
private static void parseForm( HttpMessage message, Value value, String charset )
throws IOException
{
String line = new String( message.content(), "UTF8" );
String[] s, pair;
s = line.split( "&" );
for( int i = 0; i < s.length; i++ ) {
pair = s[i].split( "=", 2 );
value.getChildren( pair[0] ).first().setValue( URLDecoder.decode( pair[1], charset ) );
}
}
private void parseMultiPartFormData( HttpMessage message, Value value )
throws IOException
{
multiPartFormDataParser = new MultiPartFormDataParser( message, value );
multiPartFormDataParser.parse();
}
private static String parseGWTRPC( HttpMessage message, Value value )
throws IOException
{
RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) );
String operationName = (String)request.getParameters()[0];
joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1];
JolieGWTConverter.gwtToJolieValue( requestValue, value );
return operationName;
}
private void recv_checkForSetCookie( HttpMessage message, Value value )
throws IOException
{
if ( hasParameter( Parameters.COOKIES ) ) {
String type;
Value cookies = getParameterFirstValue( Parameters.COOKIES );
Value cookieConfig;
Value v;
for( HttpMessage.Cookie cookie : message.setCookies() ) {
if ( cookies.hasChildren( cookie.name() ) ) {
cookieConfig = cookies.getFirstChild( cookie.name() );
if ( cookieConfig.isString() ) {
v = value.getFirstChild( cookieConfig.strValue() );
if ( cookieConfig.hasChildren( "type" ) ) {
type = cookieConfig.getFirstChild( "type" ).strValue();
} else {
type = "string";
}
recv_assignCookieValue( cookie.value(), v, type );
}
}
/*currValue = Value.create();
currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() );
currValue.getNewChild( "path" ).setValue( cookie.path() );
currValue.getNewChild( "name" ).setValue( cookie.name() );
currValue.getNewChild( "value" ).setValue( cookie.value() );
currValue.getNewChild( "domain" ).setValue( cookie.domain() );
currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) );
cookieVec.add( currValue );*/
}
}
}
private void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword )
throws IOException
{
NativeType type = NativeType.fromString( typeKeyword );
if ( NativeType.INT == type ) {
try {
value.setValue( new Integer( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.LONG == type ) {
try {
value.setValue( new Long( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.STRING == type ) {
value.setValue( cookieValue );
} else if ( NativeType.DOUBLE == type ) {
try {
value.setValue( new Double( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.BOOL == type ) {
value.setValue( Boolean.valueOf( cookieValue ) );
} else {
value.setValue( cookieValue );
}
}
private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
Value cookies = null;
if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) {
cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookies = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookies != null ) {
Value v;
String type;
for( Entry< String, String > entry : message.cookies().entrySet() ) {
if ( cookies.hasChildren( entry.getKey() ) ) {
Value cookieConfig = cookies.getFirstChild( entry.getKey() );
if ( cookieConfig.isString() ) {
v = decodedMessage.value.getFirstChild( cookieConfig.strValue() );
if ( cookieConfig.hasChildren( "type" ) ) {
type = cookieConfig.getFirstChild( "type" ).strValue();
} else {
type = "string";
}
recv_assignCookieValue( entry.getValue(), v, type );
}
}
}
}
}
private void recv_checkForGenericHeader( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
Value header = null;
if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.HEADERS ) ) {
header = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.HEADERS );
} else if ( hasParameter( Parameters.HEADERS ) ) {
header = getParameterFirstValue( Parameters.HEADERS );
}
if ( header != null ) {
Iterator<String> iterator = header.children().keySet().iterator();
while( iterator.hasNext() ){
String name = iterator.next();
String val = header.getFirstChild( name ).strValue();
name = name.replace( "_", "-" );
decodedMessage.value.getFirstChild(val).setValue(message.getPropertyOrEmptyString(name));
}
}
}
private static void recv_parseQueryString( HttpMessage message, Value value )
{
Map< String, Integer > indexes = new HashMap< String, Integer >();
String queryString = message.requestPath() == null ? "" : message.requestPath();
String[] kv = queryString.split( "\\?" );
Integer index;
if ( kv.length > 1 ) {
queryString = kv[1];
String[] params = queryString.split( "&" );
for( String param : params ) {
kv = param.split( "=", 2 );
if ( kv.length > 1 ) {
index = indexes.get( kv[0] );
if ( index == null ) {
index = 0;
indexes.put( kv[0], index );
}
value.getChildren( kv[0] ).get( index ).setValue( kv[1] );
indexes.put( kv[0], index + 1 );
}
}
}
}
/*
* Prints debug information about a received message
*/
private void recv_logDebugInfo( HttpMessage message )
{
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Receiving:\n" );
debugSB.append( "HTTP Code: " + message.statusCode() + "\n" );
debugSB.append( "Resource: " + message.requestPath() + "\n" );
debugSB.append( "--> Header properties\n" );
for( Entry< String, String > entry : message.properties() ) {
debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' );
}
for( HttpMessage.Cookie cookie : message.setCookies() ) {
debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' );
}
for( Entry< String, String > entry : message.cookies().entrySet() ) {
debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' );
}
if (
getParameterFirstValue( "debug" ).getFirstChild( "showContent" ).intValue() > 0
&& message.content() != null
) {
debugSB.append( "--> Message content\n" );
debugSB.append( new String( message.content() ) );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
private void recv_parseRequestFormat( HttpMessage message )
throws IOException
{
requestFormat = null;
String type = message.getPropertyOrEmptyString( "content-type" ).split( ";" )[0];
if ( "text/x-gwt-rpc".equals( type ) ) {
requestFormat = "text/x-gwt-rpc";
} else if ( "application/json".equals( type ) ) {
requestFormat = "application/json";
}
}
private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String charset )
throws IOException
{
String format = "xml";
if ( hasParameter( "format" ) ) {
format = getStringParameter( "format" );
}
String type = message.getProperty( "content-type" ).split( ";" )[0];
if ( "text/html".equals( type ) ) {
decodedMessage.value.setValue( new String( message.content() ) );
} else if ( "application/x-www-form-urlencoded".equals( type ) ) {
parseForm( message, decodedMessage.value, charset );
} else if ( "text/xml".equals( type ) ) {
parseXML( message, decodedMessage.value );
} else if ( "text/x-gwt-rpc".equals( type ) ) {
decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value );
} else if ( "multipart/form-data".equals( type ) ) {
parseMultiPartFormData( message, decodedMessage.value );
} else if ( "application/octet-stream".equals( type ) || type.startsWith( "image/" ) ) {
decodedMessage.value.setValue( new ByteArray( message.content() ) );
} else if ( "application/json".equals( type ) ) {
parseJson( message, decodedMessage.value );
} else if ( "xml".equals( format ) || "rest".equals( format ) ) {
parseXML( message, decodedMessage.value );
} else if ( "json".equals( format ) ) {
parseJson( message, decodedMessage.value );
} else {
decodedMessage.value.setValue( new String( message.content() ) );
}
}
private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage )
{
if ( decodedMessage.operationName == null ) {
String requestPath = message.requestPath().split( "\\?" )[0];
decodedMessage.operationName = requestPath;
Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName );
if ( m.find() ) {
int resourceStart = m.end();
if ( m.find() ) {
decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() );
decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() );
}
}
}
if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) {
String defaultOpId = getStringParameter( "default" );
if ( defaultOpId.length() > 0 ) {
Value body = decodedMessage.value;
decodedMessage.value = Value.create();
decodedMessage.value.getChildren( "data" ).add( body );
decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName );
if ( message.userAgent() != null ) {
decodedMessage.value.getFirstChild( Parameters.USER_AGENT ).setValue( message.userAgent() );
}
Value cookies = decodedMessage.value.getFirstChild( "cookies" );
for( Entry< String, String > cookie : message.cookies().entrySet() ) {
cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() );
}
decodedMessage.operationName = defaultOpId;
}
}
}
private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage )
{
if ( multiPartFormDataParser != null ) {
String target;
for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) {
if ( entry.getValue().filename() != null ) {
target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() );
if ( target != null ) {
decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() );
}
}
}
multiPartFormDataParser = null;
}
}
private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
recv_checkForCookies( message, decodedMessage );
recv_checkForGenericHeader( message, decodedMessage );
recv_checkForMultiPartHeaders( decodedMessage );
if (
message.userAgent() != null &&
hasParameter( Parameters.USER_AGENT )
) {
getParameterFirstValue( Parameters.USER_AGENT ).setValue( message.userAgent() );
}
}
private static class DecodedMessage {
private String operationName = null;
private Value value = Value.create();
private String resourcePath = "/";
private long id = CommMessage.GENERIC_ID;
}
private void recv_checkForStatusCode( HttpMessage message )
{
if ( hasParameter( Parameters.STATUS_CODE ) ) {
getParameterFirstValue( Parameters.STATUS_CODE ).setValue( message.statusCode() );
}
}
public CommMessage recv( InputStream istream, OutputStream ostream )
throws IOException
{
CommMessage retVal = null;
DecodedMessage decodedMessage = new DecodedMessage();
HttpMessage message = new HttpParser( istream ).parse();
if ( message.isSupported() == false ) {
ostream.write( NOT_IMPLEMENTED_HEADER );
ostream.write( CRLF.getBytes() );
ostream.write( CRLF.getBytes() );
ostream.flush();
return null;
}
String charset = getCharset();
if ( message.getProperty( "connection" ) != null ) {
HttpUtils.recv_checkForChannelClosing( message, channel() );
} else {
channel().setToBeClosed( checkBooleanParameter( "keepAlive", true ) == false );
}
if ( checkBooleanParameter( Parameters.DEBUG ) ) {
recv_logDebugInfo( message );
}
recv_checkForStatusCode( message );
recv_parseRequestFormat( message );
if ( message.size() > 0 ) {
recv_parseMessage( message, decodedMessage, charset );
}
if ( checkBooleanParameter( Parameters.CONCURRENT ) ) {
String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID );
if ( messageId != null ) {
try {
decodedMessage.id = Long.parseLong( messageId );
} catch( NumberFormatException e ) {}
}
}
if ( message.isResponse() ) {
recv_checkForSetCookie( message, decodedMessage.value );
retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null );
} else if ( message.isError() == false ) {
if ( message.isGet() ) {
recv_parseQueryString( message, decodedMessage.value );
}
recv_checkReceivingOperation( message, decodedMessage );
recv_checkForMessageProperties( message, decodedMessage );
retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null );
}
if ( "/".equals( retVal.resourcePath() ) && channel().parentPort() != null
&& ( channel().parentPort().getInterface().containsOperation( retVal.operationName() )
||
channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) ) {
try {
// The message is for this service
OneWayTypeDescription oneWayTypeDescription;
if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) {
oneWayTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOneWayTypeDescription();
} else {
Interface iface = channel().parentPort().getInterface();
oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() );
}
if ( oneWayTypeDescription != null && message.isResponse() == false ) {
// We are receiving a One-Way message
oneWayTypeDescription.requestType().cast( retVal.value() );
} else {
RequestResponseTypeDescription rrTypeDescription;
if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) {
rrTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getRequestResponseTypeDescription();
} else {
Interface iface = channel().parentPort().getInterface();
rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() );
}
if ( retVal.isFault() ) {
Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() );
if ( faultType != null ) {
faultType.cast( retVal.value() );
}
} else {
if ( message.isResponse() ) {
rrTypeDescription.responseType().cast( retVal.value() );
} else {
rrTypeDescription.requestType().cast( retVal.value() );
}
}
}
} catch( TypeCastingException e ) {
// TODO: do something here?
}
}
return retVal;
}
} |
package jolie.net;
import com.ibm.wsdl.extensions.schema.SchemaImpl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.soap.Detail;
import javax.xml.soap.DetailEntry;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import jolie.lang.Constants;
import jolie.Interpreter;
import jolie.runtime.ByteArray;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.sun.xml.xsom.XSAttributeDecl;
import com.sun.xml.xsom.XSAttributeUse;
import com.sun.xml.xsom.XSComplexType;
import com.sun.xml.xsom.XSContentType;
import com.sun.xml.xsom.XSElementDecl;
import com.sun.xml.xsom.XSModelGroup;
import com.sun.xml.xsom.XSModelGroupDecl;
import com.sun.xml.xsom.XSParticle;
import com.sun.xml.xsom.XSSchema;
import com.sun.xml.xsom.XSSchemaSet;
import com.sun.xml.xsom.XSTerm;
import com.sun.xml.xsom.XSType;
import com.sun.xml.xsom.parser.XSOMParser;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.wsdl.BindingOperation;
import javax.wsdl.BindingOutput;
import javax.wsdl.Definition;
import javax.wsdl.Operation;
import javax.wsdl.Part;
import javax.wsdl.Port;
import javax.wsdl.Service;
import javax.wsdl.Types;
import javax.wsdl.WSDLException;
import javax.wsdl.extensions.ExtensibilityElement;
import javax.wsdl.extensions.soap.SOAPOperation;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import jolie.net.http.HttpMessage;
import jolie.net.http.HttpParser;
import jolie.net.http.HttpUtils;
import jolie.net.http.Method;
import jolie.net.http.UnsupportedMethodException;
import jolie.net.ports.Interface;
import jolie.net.protocols.SequentialCommProtocol;
import jolie.net.soap.WSDLCache;
import jolie.runtime.typing.OneWayTypeDescription;
import jolie.runtime.typing.RequestResponseTypeDescription;
import jolie.runtime.typing.Type;
import jolie.runtime.typing.TypeCastingException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
/**
* Implements the SOAP over HTTP protocol.
*
* @author Fabrizio Montesi
*
* 2006 - Fabrizio Montesi, Mauro Silvagni: first write. 2007 - Fabrizio
* Montesi: rewritten from scratch, exploiting new JOLIE capabilities. 2008 -
* Fabrizio Montesi: initial support for schemas. 2008 - Claudio Guidi: initial
* support for WS-Addressing. 2010 - Fabrizio Montesi: initial support for WSDL
* documents.
*
*/
public class SoapProtocol extends SequentialCommProtocol {
private String inputId = null;
private final Interpreter interpreter;
private final MessageFactory messageFactory;
private XSSchemaSet schemaSet = null;
private final URI uri;
private final boolean inInputPort;
private Definition wsdlDefinition = null;
private Port wsdlPort = null;
private final TransformerFactory transformerFactory;
private final Map< String, String> namespacePrefixMap = new HashMap< String, String>();
private boolean received = false;
private String encoding;
private static class Parameters {
private static final String WRAPPED = "wrapped";
private static final String INHERITED_TYPE = "__soap_inherited_type";
private static final String ADD_ATTRIBUTE = "add_attribute";
private static final String ENVELOPE = "envelope";
private static final String OPERATION = "operation";
private static final String STYLE = "style";
}
/*
* it forced the insertion of namespaces within the soap message
*
*
* type Attribute: void {
* .name: string
* .value: string
* }
*
* parameter add_attribute: void {
* .envelope: void {
* .attribute*: Attribute
* }
* .operation*: void {
* .operation_name: string
* .attribute: Attribute
* }
* }
*/
public String name() {
return "soap";
}
public SoapProtocol(
VariablePath configurationPath,
URI uri,
boolean inInputPort,
Interpreter interpreter)
throws SOAPException {
super(configurationPath);
this.uri = uri;
this.inInputPort = inInputPort;
this.transformerFactory = TransformerFactory.newInstance();
this.interpreter = interpreter;
this.messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
}
private void parseSchemaElement(Definition definition, Element element, XSOMParser schemaParser)
throws IOException {
try {
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(element);
transformer.transform(source, result);
InputSource schemaSource = new InputSource(new StringReader(sw.toString()));
schemaSource.setSystemId(definition.getDocumentBaseURI());
schemaParser.parse(schemaSource);
} catch (TransformerConfigurationException e) {
throw new IOException(e);
} catch (TransformerException e) {
throw new IOException(e);
} catch (SAXException e) {
throw new IOException(e);
}
}
private void parseWSDLTypes(XSOMParser schemaParser)
throws IOException {
Definition definition = getWSDLDefinition();
if (definition != null) {
Types types = definition.getTypes();
if (types != null) {
List<ExtensibilityElement> list = types.getExtensibilityElements();
for (ExtensibilityElement element : list) {
if (element instanceof SchemaImpl) {
Element schemaElement = ((SchemaImpl) element).getElement();
Map<String, String> namespaces = definition.getNamespaces();
for (Entry<String, String> entry : namespaces.entrySet()) {
if (entry.getKey().equals("xmlns") || entry.getKey().trim().isEmpty()) {
continue;
}
if (schemaElement.getAttribute("xmlns:" + entry.getKey()).isEmpty()) {
schemaElement.setAttribute("xmlns:" + entry.getKey(), entry.getValue());
}
}
parseSchemaElement(definition, schemaElement, schemaParser);
}
}
}
}
}
private XSSchemaSet getSchemaSet()
throws IOException, SAXException {
if (schemaSet == null) {
XSOMParser schemaParser = new XSOMParser();
ValueVector vec = getParameterVector("schema");
if (vec.size() > 0) {
for (Value v : vec) {
schemaParser.parse(new File(v.strValue()));
}
}
parseWSDLTypes(schemaParser);
schemaSet = schemaParser.getResult();
String nsPrefix = "jolie";
int i = 1;
for (XSSchema schema : schemaSet.getSchemas()) {
if (!schema.getTargetNamespace().equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
namespacePrefixMap.put(schema.getTargetNamespace(), nsPrefix + i++);
}
}
}
return schemaSet;
}
private boolean convertAttributes() {
boolean ret = false;
if (hasParameter("convertAttributes")) {
ret = checkBooleanParameter("convertAttributes");
}
return ret;
}
private void initNamespacePrefixes(SOAPElement element)
throws SOAPException {
for (Entry<String, String> entry : namespacePrefixMap.entrySet()) {
element.addNamespaceDeclaration(entry.getValue(), entry.getKey());
}
}
private void valueToSOAPElement(
Value value,
SOAPElement element,
SOAPEnvelope soapEnvelope)
throws SOAPException {
String type = "any";
if (value.isDefined()) {
if (value.isInt()) {
type = "int";
} else if (value.isLong()) {
type = "long";
} else if (value.isString()) {
type = "string";
} else if (value.isDouble()) {
type = "double";
} else if (value.isBool()) {
type = "boolean";
}
element.addAttribute(soapEnvelope.createName("type", "xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI), "xsd:" + type);
element.addTextNode(value.strValue());
}
if (convertAttributes()) {
Map<String, ValueVector> attrs = getAttributesOrNull(value);
if (attrs != null) {
for (Entry<String, ValueVector> attrEntry : attrs.entrySet()) {
element.addAttribute(
soapEnvelope.createName(attrEntry.getKey()),
attrEntry.getValue().first().strValue());
}
}
}
for (Entry<String, ValueVector> entry : value.children().entrySet()) {
if (!entry.getKey().startsWith("@")) {
for (Value val : entry.getValue()) {
valueToSOAPElement(
val,
element.addChildElement(entry.getKey()),
soapEnvelope);
}
}
}
}
private static Map<String, ValueVector> getAttributesOrNull(Value value) {
Map<String, ValueVector> ret = null;
ValueVector vec = value.children().get(Constants.Predefined.ATTRIBUTES.token().content());
if (vec != null && vec.size() > 0) {
ret = vec.first().children();
}
if (ret == null) {
ret = new HashMap<String, ValueVector>();
}
return ret;
}
private static Value getAttributeOrNull(Value value, String attrName) {
Value ret = null;
Map<String, ValueVector> attrs = getAttributesOrNull(value);
if (attrs != null) {
ValueVector vec = attrs.get(attrName);
if (vec != null && vec.size() > 0) {
ret = vec.first();
}
}
return ret;
}
private static Value getAttribute(Value value, String attrName) {
return value.getChildren(Constants.Predefined.ATTRIBUTES.token().content()).first().getChildren(attrName).first();
}
private String getPrefixOrNull(XSAttributeDecl decl) {
if (decl.getOwnerSchema().attributeFormDefault()) {
return namespacePrefixMap.get(decl.getOwnerSchema().getTargetNamespace());
}
return null;
}
private String getPrefixOrNull(XSElementDecl decl) {
if (decl.getOwnerSchema().elementFormDefault()) {
return namespacePrefixMap.get(decl.getOwnerSchema().getTargetNamespace());
}
return null;
}
private String getPrefix(XSElementDecl decl) {
return namespacePrefixMap.get(decl.getOwnerSchema().getTargetNamespace());
}
private String getPrefix(XSComplexType compType) {
return namespacePrefixMap.get(compType.getOwnerSchema().getTargetNamespace());
}
private void termProcessing(Value value, SOAPElement element, SOAPEnvelope envelope, boolean first,
XSTerm currTerm, int getMaxOccur,
XSSchemaSet sSet, String messageNamespace)
throws SOAPException {
if (currTerm.isElementDecl()) {
ValueVector vec;
XSElementDecl currElementDecl = currTerm.asElementDecl();
String name = currElementDecl.getName();
String prefix = (first) ? getPrefix(currElementDecl) : getPrefixOrNull(currElementDecl);
SOAPElement childElement = null;
if ((vec = value.children().get(name)) != null) {
int k = 0;
while (vec.size() > 0 && (getMaxOccur > k || getMaxOccur == XSParticle.UNBOUNDED)) {
if (prefix == null) {
childElement = element.addChildElement(name);
} else {
childElement = element.addChildElement(name, prefix);
}
Value v = vec.remove(0);
valueToTypedSOAP(
v,
currElementDecl,
childElement,
envelope,
false,
sSet,
messageNamespace);
k++;
}
}
}
}
private void groupProcessing(
Value value,
XSElementDecl xsDecl,
SOAPElement element,
SOAPEnvelope envelope,
boolean first,
XSModelGroup modelGroup,
XSSchemaSet sSet,
String messageNamespace)
throws SOAPException {
XSParticle[] children = modelGroup.getChildren();
XSTerm currTerm;
for (int i = 0; i < children.length; i++) {
currTerm = children[i].getTerm();
if (currTerm.isModelGroup()) {
groupProcessing(value, xsDecl, element, envelope, first, currTerm.asModelGroup(), sSet, messageNamespace);
} else {
termProcessing(value, element, envelope, first, currTerm, children[i].getMaxOccurs(), sSet, messageNamespace);
}
}
}
private void valueToTypedSOAP(
Value value,
XSElementDecl xsDecl,
SOAPElement element,
SOAPEnvelope envelope,
boolean first,// Ugly fix! This should be removed as soon as another option arises.
XSSchemaSet sSet,
String messageNamespace)
throws SOAPException {
XSType currType = xsDecl.getType();
if (currType.isSimpleType()) {
element.addTextNode(value.strValue());
} else if (currType.isComplexType()) {
XSType type = currType;
if (currType.asComplexType().isAbstract()) {
// if the complex type is abstract search for the inherited type defined into the jolie value
// under the node __soap_inherited_type
if (value.hasChildren(Parameters.INHERITED_TYPE)) {
String inheritedType = value.getFirstChild(Parameters.INHERITED_TYPE).strValue();
XSComplexType xsInheritedType = sSet.getComplexType(messageNamespace, inheritedType);
if (xsInheritedType == null) {
System.out.println("WARNING: Type " + inheritedType + " not found in the schema set");
} else {
type = xsInheritedType;
String nameType = "type";
String prefixType = "xsi";
QName attrName = envelope.createQName(nameType, prefixType);
element.addAttribute(attrName, getPrefix(xsInheritedType) + ":" + inheritedType);
}
}
}
String name;
Value currValue;
XSComplexType complexT = type.asComplexType();
XSParticle particle;
XSContentType contentT;
//end new stuff
// Iterate over attributes
Collection<? extends XSAttributeUse> attributeUses = complexT.getAttributeUses();
for (XSAttributeUse attrUse : attributeUses) {
name = attrUse.getDecl().getName();
if ((currValue = getAttributeOrNull(value, name)) != null) {
QName attrName = envelope.createQName(name, getPrefixOrNull(attrUse.getDecl()));
element.addAttribute(attrName, currValue.strValue());
}
}
// processing content (no base type parent )
contentT = complexT.getContentType();
if (contentT.asSimpleType() != null) {
element.addTextNode(value.strValue());
} else if ((particle = contentT.asParticle()) != null) {
XSTerm term = particle.getTerm();
XSModelGroupDecl modelGroupDecl;
XSModelGroup modelGroup = null;
if ((modelGroupDecl = term.asModelGroupDecl()) != null) {
modelGroup = modelGroupDecl.getModelGroup();
} else if (term.isModelGroup()) {
modelGroup = term.asModelGroup();
}
if (modelGroup != null) {
XSModelGroup.Compositor compositor = modelGroup.getCompositor();
if (compositor.equals(XSModelGroup.SEQUENCE)) {
groupProcessing(value, xsDecl, element, envelope, first, modelGroup, sSet, messageNamespace);
}
}
}
}
}
private Definition getWSDLDefinition()
throws IOException {
if (wsdlDefinition == null && hasParameter("wsdl")) {
String wsdlUrl = getStringParameter("wsdl");
try {
wsdlDefinition = WSDLCache.getInstance().get(wsdlUrl);
} catch (WSDLException e) {
throw new IOException(e);
}
}
return wsdlDefinition;
}
private String getSoapActionForOperation(String operationName)
throws IOException {
String soapAction = null;
Port port = getWSDLPort();
if (port != null) {
BindingOperation bindingOperation = port.getBinding().getBindingOperation(operationName, null, null);
for (ExtensibilityElement element : (List<ExtensibilityElement>) bindingOperation.getExtensibilityElements()) {
if (element instanceof SOAPOperation) {
soapAction = ((SOAPOperation) element).getSoapActionURI();
}
}
}
if (soapAction == null) {
soapAction = getStringParameter("namespace") + "/" + operationName;
}
return soapAction;
}
private Port getWSDLPort()
throws IOException {
Port port = wsdlPort;
if (port == null && hasParameter("wsdl") && getParameterFirstValue("wsdl").hasChildren("port")) {
String portName = getParameterFirstValue("wsdl").getFirstChild("port").strValue();
Definition definition = getWSDLDefinition();
if (definition != null) {
Map<QName, Service> services = definition.getServices();
Iterator<Entry<QName, Service>> it = services.entrySet().iterator();
while (port == null && it.hasNext()) {
port = it.next().getValue().getPort(portName);
}
}
if (port != null) {
wsdlPort = port;
}
}
return port;
}
private String getOutputMessageRootElementName(String operationName)
throws IOException {
String elementName = operationName + ((received) ? "Response" : "");
Port port = getWSDLPort();
if (port != null) {
try {
Operation operation = port.getBinding().getPortType().getOperation(operationName, null, null);
Part part = null;
if (received) {
// We are sending a response
part = ((Entry<String, Part>) operation.getOutput().getMessage().getParts().entrySet().iterator().next()).getValue();
} else {
// We are sending a request
part = ((Entry<String, Part>) operation.getInput().getMessage().getParts().entrySet().iterator().next()).getValue();
}
elementName = part.getElementName().getLocalPart();
} catch (Exception e) {
}
}
return elementName;
}
private String getOutputMessageNamespace(String operationName)
throws IOException {
String messageNamespace = "";
Port port = getWSDLPort();
if (port == null) {
if (hasParameter("namespace")) {
messageNamespace = getStringParameter("namespace");
}
} else {
Operation operation = port.getBinding().getPortType().getOperation(operationName, null, null);
if (operation != null) {
Map<String, Part> parts = operation.getOutput().getMessage().getParts();
if (parts.size() > 0) {
Part part = parts.entrySet().iterator().next().getValue();
if (part.getElementName() == null) {
messageNamespace = operation.getOutput().getMessage().getQName().getNamespaceURI();
} else {
messageNamespace = part.getElementName().getNamespaceURI();
}
}
}
}
return messageNamespace;
}
private String[] getParameterOrder(String operationName)
throws IOException {
List<String> parameters = null;
Port port = getWSDLPort();
if (port != null) {
Operation operation = port.getBinding().getPortType().getOperation(operationName, null, null);
if (operation != null) {
parameters = operation.getParameterOrdering();
}
}
return (parameters == null) ? null : parameters.toArray(new String[0]);
}
private void setOutputEncodingStyle(SOAPEnvelope soapEnvelope, String operationName)
throws IOException, SOAPException {
Port port = getWSDLPort();
if (port != null) {
BindingOperation bindingOperation = port.getBinding().getBindingOperation(operationName, null, null);
if (bindingOperation == null) {
return;
}
BindingOutput output = bindingOperation.getBindingOutput();
if (output == null) {
return;
}
for (ExtensibilityElement element : (List<ExtensibilityElement>) output.getExtensibilityElements()) {
if (element instanceof javax.wsdl.extensions.soap.SOAPBody) {
List<String> list = ((javax.wsdl.extensions.soap.SOAPBody) element).getEncodingStyles();
if (list != null && list.isEmpty() == false) {
soapEnvelope.setEncodingStyle(list.get(0));
soapEnvelope.addNamespaceDeclaration("enc", list.get(0));
}
}
}
}
}
private void send_internal(OutputStream ostream, CommMessage message, InputStream istream)
throws IOException {
try {
inputId = message.operationName();
String messageNamespace = getOutputMessageNamespace(message.operationName());
if (received) {
// We're responding to a request
inputId += "Response";
}
SOAPMessage soapMessage = messageFactory.createMessage();
soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
setOutputEncodingStyle(soapEnvelope, message.operationName());
SOAPBody soapBody = soapEnvelope.getBody();
if (checkBooleanParameter("wsAddressing")) {
SOAPHeader soapHeader = soapEnvelope.getHeader();
// WS-Addressing namespace
soapHeader.addNamespaceDeclaration("wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
// Message ID
Name messageIdName = soapEnvelope.createName("MessageID", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
SOAPHeaderElement messageIdElement = soapHeader.addHeaderElement(messageIdName);
if (received) {
// TODO: remove this after we implement a mechanism for being sure message.id() is the one received before.
messageIdElement.setValue("uuid:1");
} else {
messageIdElement.setValue("uuid:" + message.id());
}
// Action element
Name actionName = soapEnvelope.createName("Action", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
SOAPHeaderElement actionElement = soapHeader.addHeaderElement(actionName);
/*
* TODO: the action element could be specified within the
* parameter. Perhaps wsAddressing.action ? We could also allow
* for giving a prefix or a suffix to the operation name, like
* wsAddressing.action.prefix, wsAddressing.action.suffix
*/
actionElement.setValue(message.operationName());
// From element
Name fromName = soapEnvelope.createName("From", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
SOAPHeaderElement fromElement = soapHeader.addHeaderElement(fromName);
Name addressName = soapEnvelope.createName("Address", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
SOAPElement addressElement = fromElement.addChildElement(addressName);
addressElement.setValue("http://schemas.xmlsoap.org/ws/2004/03/addressing/role/anonymous");
// To element
}
if (message.isFault()) {
FaultException f = message.fault();
SOAPFault soapFault = soapBody.addFault();
soapFault.setFaultCode(soapEnvelope.createQName("Server", soapEnvelope.getPrefix()));
soapFault.setFaultString(f.getMessage());
Detail detail = soapFault.addDetail();
DetailEntry de = detail.addDetailEntry(soapEnvelope.createName(f.faultName(), null, messageNamespace));
valueToSOAPElement(f.value(), de, soapEnvelope);
} else {
XSSchemaSet sSet = getSchemaSet();
XSElementDecl elementDecl;
String messageRootElementName = getOutputMessageRootElementName(message.operationName());
if (sSet == null
|| (elementDecl = sSet.getElementDecl(messageNamespace, messageRootElementName)) == null) {
Name operationName = null;
soapEnvelope.addNamespaceDeclaration("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
soapEnvelope.addNamespaceDeclaration("xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI);
if (messageNamespace.isEmpty()) {
operationName = soapEnvelope.createName(messageRootElementName);
} else {
soapEnvelope.addNamespaceDeclaration("jolieMessage", messageNamespace);
operationName = soapEnvelope.createName(messageRootElementName, "jolieMessage", messageNamespace);
}
SOAPBodyElement opBody = soapBody.addBodyElement(operationName);
String[] parameters = getParameterOrder(message.operationName());
if (parameters == null) {
valueToSOAPElement(message.value(), opBody, soapEnvelope);
} else {
for (String parameterName : parameters) {
valueToSOAPElement(message.value().getFirstChild(parameterName), opBody.addChildElement(parameterName), soapEnvelope);
}
}
} else {
initNamespacePrefixes(soapEnvelope);
if (hasParameter(Parameters.ADD_ATTRIBUTE)) {
Value add_parameter = getParameterFirstValue(Parameters.ADD_ATTRIBUTE);
if (add_parameter.hasChildren(Parameters.ENVELOPE)) {
// attributes must be added to the envelope
ValueVector attributes = add_parameter.getFirstChild(Parameters.ENVELOPE).getChildren("attribute");
for (Value att : attributes) {
soapEnvelope.addNamespaceDeclaration(att.getFirstChild("name").strValue(), att.getFirstChild("value").strValue());
}
}
}
boolean wrapped = true;
Value vStyle = getParameterVector(Parameters.STYLE).first();
if ("document".equals(vStyle.strValue())) {
wrapped = vStyle.getFirstChild(Parameters.WRAPPED).boolValue();
}
SOAPElement opBody = soapBody;
if (wrapped) {
opBody = soapBody.addBodyElement(
soapEnvelope.createName(messageRootElementName, namespacePrefixMap.get(elementDecl.getOwnerSchema().getTargetNamespace()), null));
// adding forced attributes to operation
if (hasParameter(Parameters.ADD_ATTRIBUTE)) {
Value add_parameter = getParameterFirstValue(Parameters.ADD_ATTRIBUTE);
if (add_parameter.hasChildren(Parameters.OPERATION)) {
ValueVector operations = add_parameter.getChildren(Parameters.OPERATION);
for (Value op : operations) {
if (op.getFirstChild("operation_name").strValue().equals(message.operationName())) {
// attributes must be added to the envelope
Value attribute = op.getFirstChild("attribute");
QName attrName;
if (attribute.hasChildren("prefix")) {
attrName = opBody.createQName(attribute.getFirstChild("name").strValue(), attribute.getFirstChild("prefix").strValue());
} else {
attrName = opBody.createQName(attribute.getFirstChild("name").strValue(), null);
}
opBody.addAttribute(attrName, attribute.getFirstChild("value").strValue());
}
}
}
}
}
valueToTypedSOAP(message.value(), elementDecl, opBody, soapEnvelope, !wrapped, sSet, messageNamespace);
}
}
if (soapEnvelope.getHeader().hasChildNodes() == false) {
// Some service implementations do not like empty headers
soapEnvelope.getHeader().detachNode();
}
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
soapMessage.writeTo(tmpStream);
ByteArray content = new ByteArray( tmpStream.toByteArray() );
StringBuilder httpMessage = new StringBuilder();
String soapAction = null;
if (received) {
// We're responding to a request
if ( message.isFault() ) {
httpMessage.append("HTTP/1.1 500 Internal Server Error" + HttpUtils.CRLF);
} else {
httpMessage.append("HTTP/1.1 200 OK" + HttpUtils.CRLF);
}
httpMessage.append("Server: Jolie" + HttpUtils.CRLF);
received = false;
} else {
// We're sending a notification or a solicit
String path = uri.getRawPath(); // TODO: fix this to consider resourcePaths
if (path == null || path.length() == 0) {
path = "*";
}
httpMessage.append("POST " + path + " HTTP/1.1" + HttpUtils.CRLF);
httpMessage.append("Host: " + uri.getHost() + HttpUtils.CRLF);
/*
* soapAction = "SOAPAction: \"" + messageNamespace + "/" +
* message.operationName() + '\"' + HttpUtils.CRLF;
*/
soapAction = "SOAPAction: \"" + getSoapActionForOperation(message.operationName()) + '\"' + HttpUtils.CRLF;
if (checkBooleanParameter("compression", true)) {
String requestCompression = getStringParameter("requestCompression");
if (requestCompression.equals("gzip") || requestCompression.equals("deflate")) {
encoding = requestCompression;
httpMessage.append("Accept-Encoding: " + encoding + HttpUtils.CRLF);
} else {
httpMessage.append("Accept-Encoding: gzip, deflate" + HttpUtils.CRLF);
}
}
}
if (getParameterVector("keepAlive").first().intValue() != 1) {
channel().setToBeClosed(true);
httpMessage.append("Connection: close" + HttpUtils.CRLF);
}
if (encoding != null && checkBooleanParameter("compression", true)) {
content = HttpUtils.encode(encoding, content, httpMessage);
}
//httpMessage.append("Content-Type: application/soap+xml; charset=utf-8" + HttpUtils.CRLF);
httpMessage.append("Content-Type: text/xml; charset=utf-8" + HttpUtils.CRLF);
httpMessage.append("Content-Length: " + content.size() + HttpUtils.CRLF);
if (soapAction != null) {
httpMessage.append(soapAction);
}
httpMessage.append(HttpUtils.CRLF);
if (getParameterVector("debug").first().intValue() > 0) {
interpreter.logInfo("[SOAP debug] Sending:\n" + httpMessage.toString() + content.toString("utf-8"));
}
inputId = message.operationName();
ostream.write(httpMessage.toString().getBytes(HttpUtils.URL_DECODER_ENC));
ostream.write(content.getBytes());
} catch (SOAPException se) {
throw new IOException(se);
} catch (SAXException saxe) {
throw new IOException(saxe);
}
}
public void send(OutputStream ostream, CommMessage message, InputStream istream)
throws IOException {
try {
send_internal(ostream, message, istream);
} catch (IOException e) {
if (inInputPort && channel().isOpen()) {
HttpUtils.errorGenerator(ostream, e);
}
throw e;
}
}
private void xmlNodeToValue(Value value, Node node, boolean isRecRoot) {
String type = "xsd:string";
Node currNode;
// Set attributes
NamedNodeMap attributes = node.getAttributes();
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
currNode = attributes.item(i);
if ("type".equals(currNode.getNodeName()) == false && convertAttributes()) {
getAttribute(value, currNode.getNodeName()).setValue(currNode.getNodeValue());
} else {
type = currNode.getNodeValue();
}
}
}
// Set children
NodeList list = node.getChildNodes();
Value childValue;
for (int i = 0; i < list.getLength(); i++) {
currNode = list.item(i);
switch (currNode.getNodeType()) {
case Node.ELEMENT_NODE:
childValue = value.getNewChild(currNode.getLocalName());
xmlNodeToValue(childValue, currNode, false);
break;
case Node.TEXT_NODE:
if (!isRecRoot) {
value.setValue(currNode.getNodeValue());
}
break;
}
}
if ("xsd:int".equals(type)) {
value.setValue(value.intValue());
} else if ("xsd:long".equals(type)) {
value.setValue(value.longValue());
} else if ("xsd:double".equals(type)) {
value.setValue(value.doubleValue());
} else if ("xsd:boolean".equals(type)) {
value.setValue(value.boolValue());
}
}
private static Element getFirstElement(Node node) {
NodeList nodes = node.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
return (Element) nodes.item(i);
}
}
return null;
}
/*
* private Schema getRecvMessageValidationSchema() throws IOException {
* List< Source > sources = new ArrayList< Source >(); Definition definition
* = getWSDLDefinition(); if ( definition != null ) { Types types =
* definition.getTypes(); if ( types != null ) { List< ExtensibilityElement
* > list = types.getExtensibilityElements(); for( ExtensibilityElement
* element : list ) { if ( element instanceof SchemaImpl ) { sources.add(
* new DOMSource( ((SchemaImpl)element).getElement() ) ); } } } }
* SchemaFactory schemaFactory = SchemaFactory.newInstance(
* XMLConstants.W3C_XML_SCHEMA_NS_URI ); try { return
* schemaFactory.newSchema( sources.toArray( new Source[sources.size()] ) );
* } catch( SAXException e ) { throw new IOException( e ); } }
*/
private CommMessage recv_internal(InputStream istream, OutputStream ostream)
throws IOException {
HttpParser parser = new HttpParser(istream);
HttpMessage message = parser.parse();
String charset = HttpUtils.getCharset(null, message);
HttpUtils.recv_checkForChannelClosing(message, channel());
if (inInputPort && message.type() != HttpMessage.Type.POST) {
throw new UnsupportedMethodException("Only HTTP method POST allowed!", Method.POST);
}
encoding = message.getProperty("accept-encoding");
CommMessage retVal = null;
String messageId = message.getPropertyOrEmptyString("soapaction");
FaultException fault = null;
Value value = Value.create();
try {
if (message.size() > 0) {
if (checkBooleanParameter("debug")) {
interpreter.logInfo("[SOAP debug] Receiving:\n" + new String(message.content(), charset));
}
SOAPMessage soapMessage = messageFactory.createMessage();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
/*
* Schema messageSchema = getRecvMessageValidationSchema(); if (
* messageSchema != null ) {
* factory.setIgnoringElementContentWhitespace( true );
* factory.setSchema( messageSchema ); }
*/
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource src = new InputSource(new ByteArrayInputStream(message.content()));
src.setEncoding(charset);
Document doc = builder.parse(src);
DOMSource dom = new DOMSource(doc);
soapMessage.getSOAPPart().setContent(dom);
/*
* if ( checkBooleanParameter( "debugAfter" ) ) {
* ByteArrayOutputStream tmpStream = new
* ByteArrayOutputStream(); soapMessage.writeTo( tmpStream );
* interpreter.logInfo( "[SOAP debug] Receiving:\n" +
* tmpStream.toString() ); }
*/
SOAPFault soapFault = soapMessage.getSOAPBody().getFault();
if (soapFault == null) {
Element soapValueElement = getFirstElement(soapMessage.getSOAPBody());
messageId = soapValueElement.getLocalName();
xmlNodeToValue(value, soapValueElement, checkBooleanParameter("dropRootValue", false));
ValueVector schemaPaths = getParameterVector("schema");
if (schemaPaths.size() > 0) {
List<Source> sources = new LinkedList<Source>();
Value schemaPath;
for (int i = 0; i < schemaPaths.size(); i++) {
schemaPath = schemaPaths.get(i);
if (schemaPath.getChildren("validate").first().intValue() > 0) {
sources.add(new StreamSource(new File(schemaPaths.get(i).strValue())));
}
}
if (!sources.isEmpty()) {
Schema schema =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(sources.toArray(new Source[0]));
schema.newValidator().validate(new DOMSource(soapMessage.getSOAPBody().getFirstChild()));
}
}
} else {
String faultName = "UnknownFault";
Value faultValue = Value.create();
Detail d = soapFault.getDetail();
if (d != null) {
Node n = d.getFirstChild();
if (n != null) {
faultName = n.getLocalName();
xmlNodeToValue(
faultValue, n, true);
} else {
faultValue.setValue(soapFault.getFaultString());
}
}
fault = new FaultException(faultName, faultValue);
}
}
String resourcePath = recv_getResourcePath(message);
if (message.isResponse()) {
if (fault != null && message.statusCode() == 500) {
fault = new FaultException("InternalServerError", "");
}
retVal = new CommMessage(CommMessage.GENERIC_ID, inputId, resourcePath, value, fault);
} else if (!message.isError()) {
if (messageId.isEmpty()) {
throw new IOException("Received SOAP Message without a specified operation");
}
retVal = new CommMessage(CommMessage.GENERIC_ID, messageId, resourcePath, value, fault);
}
} catch (SOAPException e) {
throw new IOException(e);
} catch (ParserConfigurationException e) {
throw new IOException(e);
} catch (SAXException e) {
//TODO support resourcePath
retVal = new CommMessage(CommMessage.GENERIC_ID, messageId, "/", value, new FaultException("TypeMismatch", e));
}
received = true;
if ("/".equals(retVal.resourcePath()) && channel().parentPort() != null
&& channel().parentPort().getInterface().containsOperation(retVal.operationName())) {
try {
// The message is for this service
Interface iface = channel().parentPort().getInterface();
OneWayTypeDescription oneWayTypeDescription = iface.oneWayOperations().get(retVal.operationName());
if (oneWayTypeDescription != null && message.isResponse() == false) {
// We are receiving a One-Way message
oneWayTypeDescription.requestType().cast(retVal.value());
} else {
RequestResponseTypeDescription rrTypeDescription = iface.requestResponseOperations().get(retVal.operationName());
if (retVal.isFault()) {
Type faultType = rrTypeDescription.faults().get(retVal.fault().faultName());
if (faultType != null) {
faultType.cast(retVal.value());
}
} else {
if (message.isResponse()) {
rrTypeDescription.responseType().cast(retVal.value());
} else {
rrTypeDescription.requestType().cast(retVal.value());
}
}
}
} catch (TypeCastingException e) {
// TODO: do something here?
}
}
return retVal;
}
public CommMessage recv(InputStream istream, OutputStream ostream)
throws IOException
{
try {
return recv_internal(istream, ostream);
} catch (IOException e) {
if (inInputPort && channel().isOpen()) {
HttpUtils.errorGenerator(ostream, e);
}
throw e;
}
}
private String recv_getResourcePath(HttpMessage message) {
String ret = "/";
if (checkBooleanParameter("interpretResource")) {
ret = message.requestPath();
}
return ret;
}
} |
package jolie.net;
import com.ibm.wsdl.extensions.schema.SchemaImpl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.soap.Detail;
import javax.xml.soap.DetailEntry;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import jolie.lang.Constants;
import jolie.Interpreter;
import jolie.runtime.ByteArray;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.sun.xml.xsom.XSAttributeDecl;
import com.sun.xml.xsom.XSAttributeUse;
import com.sun.xml.xsom.XSComplexType;
import com.sun.xml.xsom.XSContentType;
import com.sun.xml.xsom.XSElementDecl;
import com.sun.xml.xsom.XSModelGroup;
import com.sun.xml.xsom.XSModelGroupDecl;
import com.sun.xml.xsom.XSParticle;
import com.sun.xml.xsom.XSSchema;
import com.sun.xml.xsom.XSSchemaSet;
import com.sun.xml.xsom.XSTerm;
import com.sun.xml.xsom.XSType;
import com.sun.xml.xsom.parser.XSOMParser;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.wsdl.BindingOperation;
import javax.wsdl.BindingOutput;
import javax.wsdl.Definition;
import javax.wsdl.Operation;
import javax.wsdl.Part;
import javax.wsdl.Port;
import javax.wsdl.Service;
import javax.wsdl.Types;
import javax.wsdl.WSDLException;
import javax.wsdl.extensions.ExtensibilityElement;
import javax.wsdl.extensions.soap.SOAPOperation;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import jolie.net.http.HttpMessage;
import jolie.net.http.HttpParser;
import jolie.net.http.HttpUtils;
import jolie.net.http.Method;
import jolie.net.http.UnsupportedMethodException;
import jolie.net.ports.Interface;
import jolie.net.protocols.SequentialCommProtocol;
import jolie.net.soap.WSDLCache;
import jolie.runtime.typing.OneWayTypeDescription;
import jolie.runtime.typing.RequestResponseTypeDescription;
import jolie.runtime.typing.Type;
import jolie.runtime.typing.TypeCastingException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
/**
* Implements the SOAP over HTTP protocol.
*
* @author Fabrizio Montesi
*
* 2006 - Fabrizio Montesi, Mauro Silvagni: first write. 2007 - Fabrizio
* Montesi: rewritten from scratch, exploiting new JOLIE capabilities. 2008 -
* Fabrizio Montesi: initial support for schemas. 2008 - Claudio Guidi: initial
* support for WS-Addressing. 2010 - Fabrizio Montesi: initial support for WSDL
* documents.
*
*/
public class SoapProtocol extends SequentialCommProtocol implements HttpUtils.HttpProtocol {
private String inputId = null;
private final Interpreter interpreter;
private final MessageFactory messageFactory;
private XSSchemaSet schemaSet = null;
private final URI uri;
private final boolean inInputPort;
private Definition wsdlDefinition = null;
private Port wsdlPort = null;
private final TransformerFactory transformerFactory;
private final Map< String, String> namespacePrefixMap = new HashMap< String, String>();
private boolean received = false;
private String encoding;
private static class Parameters {
private static final String WRAPPED = "wrapped";
private static final String INHERITED_TYPE = "__soap_inherited_type";
private static final String ADD_ATTRIBUTE = "add_attribute";
private static final String ENVELOPE = "envelope";
private static final String OPERATION = "operation";
private static final String STYLE = "style";
}
/*
* it forced the insertion of namespaces within the soap message
*
*
* type Attribute: void {
* .name: string
* .value: string
* }
*
* parameter add_attribute: void {
* .envelope: void {
* .attribute*: Attribute
* }
* .operation*: void {
* .operation_name: string
* .attribute: Attribute
* }
* }
*/
public String name() {
return "soap";
}
public SoapProtocol(
VariablePath configurationPath,
URI uri,
boolean inInputPort,
Interpreter interpreter)
throws SOAPException {
super(configurationPath);
this.uri = uri;
this.inInputPort = inInputPort;
this.transformerFactory = TransformerFactory.newInstance();
this.interpreter = interpreter;
this.messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
}
private void parseSchemaElement(Definition definition, Element element, XSOMParser schemaParser)
throws IOException {
try {
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(element);
transformer.transform(source, result);
InputSource schemaSource = new InputSource(new StringReader(sw.toString()));
schemaSource.setSystemId(definition.getDocumentBaseURI());
schemaParser.parse(schemaSource);
} catch (TransformerConfigurationException e) {
throw new IOException(e);
} catch (TransformerException e) {
throw new IOException(e);
} catch (SAXException e) {
throw new IOException(e);
}
}
private void parseWSDLTypes(XSOMParser schemaParser)
throws IOException {
Definition definition = getWSDLDefinition();
if (definition != null) {
Types types = definition.getTypes();
if (types != null) {
List<ExtensibilityElement> list = types.getExtensibilityElements();
for (ExtensibilityElement element : list) {
if (element instanceof SchemaImpl) {
Element schemaElement = ((SchemaImpl) element).getElement();
Map<String, String> namespaces = definition.getNamespaces();
for (Entry<String, String> entry : namespaces.entrySet()) {
if (entry.getKey().equals("xmlns") || entry.getKey().trim().isEmpty()) {
continue;
}
if (schemaElement.getAttribute("xmlns:" + entry.getKey()).isEmpty()) {
schemaElement.setAttribute("xmlns:" + entry.getKey(), entry.getValue());
}
}
parseSchemaElement(definition, schemaElement, schemaParser);
}
}
}
}
}
private XSSchemaSet getSchemaSet()
throws IOException, SAXException {
if (schemaSet == null) {
XSOMParser schemaParser = new XSOMParser();
ValueVector vec = getParameterVector("schema");
if (vec.size() > 0) {
for (Value v : vec) {
schemaParser.parse(new File(v.strValue()));
}
}
parseWSDLTypes(schemaParser);
schemaSet = schemaParser.getResult();
String nsPrefix = "jolie";
int i = 1;
for (XSSchema schema : schemaSet.getSchemas()) {
if (!schema.getTargetNamespace().equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
namespacePrefixMap.put(schema.getTargetNamespace(), nsPrefix + i++);
}
}
}
return schemaSet;
}
private boolean convertAttributes() {
boolean ret = false;
if (hasParameter("convertAttributes")) {
ret = checkBooleanParameter("convertAttributes");
}
return ret;
}
private void initNamespacePrefixes(SOAPElement element)
throws SOAPException {
for (Entry<String, String> entry : namespacePrefixMap.entrySet()) {
element.addNamespaceDeclaration(entry.getValue(), entry.getKey());
}
}
private void valueToSOAPElement(
Value value,
SOAPElement element,
SOAPEnvelope soapEnvelope)
throws SOAPException {
String type = "any";
if (value.isDefined()) {
if (value.isInt()) {
type = "int";
} else if (value.isLong()) {
type = "long";
} else if (value.isString()) {
type = "string";
} else if (value.isDouble()) {
type = "double";
} else if (value.isBool()) {
type = "boolean";
}
element.addAttribute(soapEnvelope.createName("type", "xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI), "xsd:" + type);
element.addTextNode(value.strValue());
}
if (convertAttributes()) {
Map<String, ValueVector> attrs = getAttributesOrNull(value);
if (attrs != null) {
for (Entry<String, ValueVector> attrEntry : attrs.entrySet()) {
element.addAttribute(
soapEnvelope.createName(attrEntry.getKey()),
attrEntry.getValue().first().strValue());
}
}
}
for (Entry<String, ValueVector> entry : value.children().entrySet()) {
if (!entry.getKey().startsWith("@")) {
for (Value val : entry.getValue()) {
valueToSOAPElement(
val,
element.addChildElement(entry.getKey()),
soapEnvelope);
}
}
}
}
private static Map<String, ValueVector> getAttributesOrNull(Value value) {
Map<String, ValueVector> ret = null;
ValueVector vec = value.children().get(Constants.Predefined.ATTRIBUTES.token().content());
if (vec != null && vec.size() > 0) {
ret = vec.first().children();
}
if (ret == null) {
ret = new HashMap<String, ValueVector>();
}
return ret;
}
private static Value getAttributeOrNull(Value value, String attrName) {
Value ret = null;
Map<String, ValueVector> attrs = getAttributesOrNull(value);
if (attrs != null) {
ValueVector vec = attrs.get(attrName);
if (vec != null && vec.size() > 0) {
ret = vec.first();
}
}
return ret;
}
private static Value getAttribute(Value value, String attrName) {
return value.getChildren(Constants.Predefined.ATTRIBUTES.token().content()).first().getChildren(attrName).first();
}
private String getPrefixOrNull(XSAttributeDecl decl) {
if (decl.getOwnerSchema().attributeFormDefault()) {
return namespacePrefixMap.get(decl.getOwnerSchema().getTargetNamespace());
}
return null;
}
private String getPrefixOrNull(XSElementDecl decl) {
if (decl.getOwnerSchema().elementFormDefault()) {
return namespacePrefixMap.get(decl.getOwnerSchema().getTargetNamespace());
}
return null;
}
private String getPrefix(XSElementDecl decl) {
return namespacePrefixMap.get(decl.getOwnerSchema().getTargetNamespace());
}
private String getPrefix(XSComplexType compType) {
return namespacePrefixMap.get(compType.getOwnerSchema().getTargetNamespace());
}
private void termProcessing(Value value, SOAPElement element, SOAPEnvelope envelope, boolean first,
XSTerm currTerm, int getMaxOccur,
XSSchemaSet sSet, String messageNamespace)
throws SOAPException {
if (currTerm.isElementDecl()) {
ValueVector vec;
XSElementDecl currElementDecl = currTerm.asElementDecl();
String name = currElementDecl.getName();
String prefix = (first) ? getPrefix(currElementDecl) : getPrefixOrNull(currElementDecl);
SOAPElement childElement = null;
if ((vec = value.children().get(name)) != null) {
int k = 0;
while (vec.size() > 0 && (getMaxOccur > k || getMaxOccur == XSParticle.UNBOUNDED)) {
if (prefix == null) {
childElement = element.addChildElement(name);
} else {
childElement = element.addChildElement(name, prefix);
}
Value v = vec.remove(0);
valueToTypedSOAP(
v,
currElementDecl,
childElement,
envelope,
false,
sSet,
messageNamespace);
k++;
}
}
}
}
private void groupProcessing(
Value value,
XSElementDecl xsDecl,
SOAPElement element,
SOAPEnvelope envelope,
boolean first,
XSModelGroup modelGroup,
XSSchemaSet sSet,
String messageNamespace)
throws SOAPException {
XSParticle[] children = modelGroup.getChildren();
XSTerm currTerm;
for (int i = 0; i < children.length; i++) {
currTerm = children[i].getTerm();
if (currTerm.isModelGroup()) {
groupProcessing(value, xsDecl, element, envelope, first, currTerm.asModelGroup(), sSet, messageNamespace);
} else {
termProcessing(value, element, envelope, first, currTerm, children[i].getMaxOccurs(), sSet, messageNamespace);
}
}
}
private void valueToTypedSOAP(
Value value,
XSElementDecl xsDecl,
SOAPElement element,
SOAPEnvelope envelope,
boolean first,// Ugly fix! This should be removed as soon as another option arises.
XSSchemaSet sSet,
String messageNamespace)
throws SOAPException {
XSType currType = xsDecl.getType();
if (currType.isSimpleType()) {
element.addTextNode(value.strValue());
} else if (currType.isComplexType()) {
XSType type = currType;
if (currType.asComplexType().isAbstract()) {
// if the complex type is abstract search for the inherited type defined into the jolie value
// under the node __soap_inherited_type
if (value.hasChildren(Parameters.INHERITED_TYPE)) {
String inheritedType = value.getFirstChild(Parameters.INHERITED_TYPE).strValue();
XSComplexType xsInheritedType = sSet.getComplexType(messageNamespace, inheritedType);
if (xsInheritedType == null) {
System.out.println("WARNING: Type " + inheritedType + " not found in the schema set");
} else {
type = xsInheritedType;
String nameType = "type";
String prefixType = "xsi";
QName attrName = envelope.createQName(nameType, prefixType);
element.addAttribute(attrName, getPrefix(xsInheritedType) + ":" + inheritedType);
}
}
}
String name;
Value currValue;
XSComplexType complexT = type.asComplexType();
XSParticle particle;
XSContentType contentT;
//end new stuff
// Iterate over attributes
Collection<? extends XSAttributeUse> attributeUses = complexT.getAttributeUses();
for (XSAttributeUse attrUse : attributeUses) {
name = attrUse.getDecl().getName();
if ((currValue = getAttributeOrNull(value, name)) != null) {
QName attrName = envelope.createQName(name, getPrefixOrNull(attrUse.getDecl()));
element.addAttribute(attrName, currValue.strValue());
}
}
// processing content (no base type parent )
contentT = complexT.getContentType();
if (contentT.asSimpleType() != null) {
element.addTextNode(value.strValue());
} else if ((particle = contentT.asParticle()) != null) {
XSTerm term = particle.getTerm();
XSModelGroupDecl modelGroupDecl;
XSModelGroup modelGroup = null;
if ((modelGroupDecl = term.asModelGroupDecl()) != null) {
modelGroup = modelGroupDecl.getModelGroup();
} else if (term.isModelGroup()) {
modelGroup = term.asModelGroup();
}
if (modelGroup != null) {
XSModelGroup.Compositor compositor = modelGroup.getCompositor();
if (compositor.equals(XSModelGroup.SEQUENCE)) {
groupProcessing(value, xsDecl, element, envelope, first, modelGroup, sSet, messageNamespace);
}
}
}
}
}
private Definition getWSDLDefinition()
throws IOException {
if (wsdlDefinition == null && hasParameter("wsdl")) {
String wsdlUrl = getStringParameter("wsdl");
try {
wsdlDefinition = WSDLCache.getInstance().get(wsdlUrl);
} catch (WSDLException e) {
throw new IOException(e);
}
}
return wsdlDefinition;
}
private String getSoapActionForOperation(String operationName)
throws IOException {
String soapAction = null;
Port port = getWSDLPort();
if (port != null) {
BindingOperation bindingOperation = port.getBinding().getBindingOperation(operationName, null, null);
for (ExtensibilityElement element : (List<ExtensibilityElement>) bindingOperation.getExtensibilityElements()) {
if (element instanceof SOAPOperation) {
soapAction = ((SOAPOperation) element).getSoapActionURI();
}
}
}
if (soapAction == null) {
soapAction = getStringParameter("namespace") + "/" + operationName;
}
return soapAction;
}
private Port getWSDLPort()
throws IOException {
Port port = wsdlPort;
if (port == null && hasParameter("wsdl") && getParameterFirstValue("wsdl").hasChildren("port")) {
String portName = getParameterFirstValue("wsdl").getFirstChild("port").strValue();
Definition definition = getWSDLDefinition();
if (definition != null) {
Map<QName, Service> services = definition.getServices();
Iterator<Entry<QName, Service>> it = services.entrySet().iterator();
while (port == null && it.hasNext()) {
port = it.next().getValue().getPort(portName);
}
}
if (port != null) {
wsdlPort = port;
}
}
return port;
}
private String getOutputMessageRootElementName(String operationName)
throws IOException {
String elementName = operationName + ((received) ? "Response" : "");
Port port = getWSDLPort();
if (port != null) {
try {
Operation operation = port.getBinding().getPortType().getOperation(operationName, null, null);
Part part = null;
if (received) {
// We are sending a response
part = ((Entry<String, Part>) operation.getOutput().getMessage().getParts().entrySet().iterator().next()).getValue();
} else {
// We are sending a request
part = ((Entry<String, Part>) operation.getInput().getMessage().getParts().entrySet().iterator().next()).getValue();
}
elementName = part.getElementName().getLocalPart();
} catch (Exception e) {
}
}
return elementName;
}
private String getOutputMessageNamespace(String operationName)
throws IOException {
String messageNamespace = "";
Port port = getWSDLPort();
if (port == null) {
if (hasParameter("namespace")) {
messageNamespace = getStringParameter("namespace");
}
} else {
Operation operation = port.getBinding().getPortType().getOperation(operationName, null, null);
if (operation != null) {
Map<String, Part> parts = operation.getOutput().getMessage().getParts();
if (parts.size() > 0) {
Part part = parts.entrySet().iterator().next().getValue();
if (part.getElementName() == null) {
messageNamespace = operation.getOutput().getMessage().getQName().getNamespaceURI();
} else {
messageNamespace = part.getElementName().getNamespaceURI();
}
}
}
}
return messageNamespace;
}
private String[] getParameterOrder(String operationName)
throws IOException {
List<String> parameters = null;
Port port = getWSDLPort();
if (port != null) {
Operation operation = port.getBinding().getPortType().getOperation(operationName, null, null);
if (operation != null) {
parameters = operation.getParameterOrdering();
}
}
return (parameters == null) ? null : parameters.toArray(new String[0]);
}
private void setOutputEncodingStyle(SOAPEnvelope soapEnvelope, String operationName)
throws IOException, SOAPException {
Port port = getWSDLPort();
if (port != null) {
BindingOperation bindingOperation = port.getBinding().getBindingOperation(operationName, null, null);
if (bindingOperation == null) {
return;
}
BindingOutput output = bindingOperation.getBindingOutput();
if (output == null) {
return;
}
for (ExtensibilityElement element : (List<ExtensibilityElement>) output.getExtensibilityElements()) {
if (element instanceof javax.wsdl.extensions.soap.SOAPBody) {
List<String> list = ((javax.wsdl.extensions.soap.SOAPBody) element).getEncodingStyles();
if (list != null && list.isEmpty() == false) {
soapEnvelope.setEncodingStyle(list.get(0));
soapEnvelope.addNamespaceDeclaration("enc", list.get(0));
}
}
}
}
}
public void send_internal(OutputStream ostream, CommMessage message, InputStream istream)
throws IOException {
try {
inputId = message.operationName();
String messageNamespace = getOutputMessageNamespace(message.operationName());
if (received) {
// We're responding to a request
inputId += "Response";
}
SOAPMessage soapMessage = messageFactory.createMessage();
soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
setOutputEncodingStyle(soapEnvelope, message.operationName());
SOAPBody soapBody = soapEnvelope.getBody();
if (checkBooleanParameter("wsAddressing")) {
SOAPHeader soapHeader = soapEnvelope.getHeader();
// WS-Addressing namespace
soapHeader.addNamespaceDeclaration("wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
// Message ID
Name messageIdName = soapEnvelope.createName("MessageID", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
SOAPHeaderElement messageIdElement = soapHeader.addHeaderElement(messageIdName);
if (received) {
// TODO: remove this after we implement a mechanism for being sure message.id() is the one received before.
messageIdElement.setValue("uuid:1");
} else {
messageIdElement.setValue("uuid:" + message.id());
}
// Action element
Name actionName = soapEnvelope.createName("Action", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
SOAPHeaderElement actionElement = soapHeader.addHeaderElement(actionName);
/*
* TODO: the action element could be specified within the
* parameter. Perhaps wsAddressing.action ? We could also allow
* for giving a prefix or a suffix to the operation name, like
* wsAddressing.action.prefix, wsAddressing.action.suffix
*/
actionElement.setValue(message.operationName());
// From element
Name fromName = soapEnvelope.createName("From", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
SOAPHeaderElement fromElement = soapHeader.addHeaderElement(fromName);
Name addressName = soapEnvelope.createName("Address", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing");
SOAPElement addressElement = fromElement.addChildElement(addressName);
addressElement.setValue("http://schemas.xmlsoap.org/ws/2004/03/addressing/role/anonymous");
// To element
}
if (message.isFault()) {
FaultException f = message.fault();
SOAPFault soapFault = soapBody.addFault();
soapFault.setFaultCode(soapEnvelope.createQName("Server", soapEnvelope.getPrefix()));
soapFault.setFaultString(f.getMessage());
Detail detail = soapFault.addDetail();
DetailEntry de = detail.addDetailEntry(soapEnvelope.createName(f.faultName(), null, messageNamespace));
valueToSOAPElement(f.value(), de, soapEnvelope);
} else {
XSSchemaSet sSet = getSchemaSet();
XSElementDecl elementDecl;
String messageRootElementName = getOutputMessageRootElementName(message.operationName());
if (sSet == null
|| (elementDecl = sSet.getElementDecl(messageNamespace, messageRootElementName)) == null) {
Name operationName = null;
soapEnvelope.addNamespaceDeclaration("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
soapEnvelope.addNamespaceDeclaration("xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI);
if (messageNamespace.isEmpty()) {
operationName = soapEnvelope.createName(messageRootElementName);
} else {
soapEnvelope.addNamespaceDeclaration("jolieMessage", messageNamespace);
operationName = soapEnvelope.createName(messageRootElementName, "jolieMessage", messageNamespace);
}
SOAPBodyElement opBody = soapBody.addBodyElement(operationName);
String[] parameters = getParameterOrder(message.operationName());
if (parameters == null) {
valueToSOAPElement(message.value(), opBody, soapEnvelope);
} else {
for (String parameterName : parameters) {
valueToSOAPElement(message.value().getFirstChild(parameterName), opBody.addChildElement(parameterName), soapEnvelope);
}
}
} else {
initNamespacePrefixes(soapEnvelope);
if (hasParameter(Parameters.ADD_ATTRIBUTE)) {
Value add_parameter = getParameterFirstValue(Parameters.ADD_ATTRIBUTE);
if (add_parameter.hasChildren(Parameters.ENVELOPE)) {
// attributes must be added to the envelope
ValueVector attributes = add_parameter.getFirstChild(Parameters.ENVELOPE).getChildren("attribute");
for (Value att : attributes) {
soapEnvelope.addNamespaceDeclaration(att.getFirstChild("name").strValue(), att.getFirstChild("value").strValue());
}
}
}
boolean wrapped = true;
Value vStyle = getParameterVector(Parameters.STYLE).first();
if ("document".equals(vStyle.strValue())) {
wrapped = vStyle.getFirstChild(Parameters.WRAPPED).boolValue();
}
SOAPElement opBody = soapBody;
if (wrapped) {
opBody = soapBody.addBodyElement(
soapEnvelope.createName(messageRootElementName, namespacePrefixMap.get(elementDecl.getOwnerSchema().getTargetNamespace()), null));
// adding forced attributes to operation
if (hasParameter(Parameters.ADD_ATTRIBUTE)) {
Value add_parameter = getParameterFirstValue(Parameters.ADD_ATTRIBUTE);
if (add_parameter.hasChildren(Parameters.OPERATION)) {
ValueVector operations = add_parameter.getChildren(Parameters.OPERATION);
for (Value op : operations) {
if (op.getFirstChild("operation_name").strValue().equals(message.operationName())) {
// attributes must be added to the envelope
Value attribute = op.getFirstChild("attribute");
QName attrName;
if (attribute.hasChildren("prefix")) {
attrName = opBody.createQName(attribute.getFirstChild("name").strValue(), attribute.getFirstChild("prefix").strValue());
} else {
attrName = opBody.createQName(attribute.getFirstChild("name").strValue(), null);
}
opBody.addAttribute(attrName, attribute.getFirstChild("value").strValue());
}
}
}
}
}
valueToTypedSOAP(message.value(), elementDecl, opBody, soapEnvelope, !wrapped, sSet, messageNamespace);
}
}
if (soapEnvelope.getHeader().hasChildNodes() == false) {
// Some service implementations do not like empty headers
soapEnvelope.getHeader().detachNode();
}
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
soapMessage.writeTo(tmpStream);
ByteArray content = new ByteArray( tmpStream.toByteArray() );
StringBuilder httpMessage = new StringBuilder();
String soapAction = null;
if (received) {
// We're responding to a request
if ( message.isFault() ) {
httpMessage.append("HTTP/1.1 500 Internal Server Error" + HttpUtils.CRLF);
} else {
httpMessage.append("HTTP/1.1 200 OK" + HttpUtils.CRLF);
}
httpMessage.append("Server: Jolie" + HttpUtils.CRLF);
received = false;
} else {
// We're sending a notification or a solicit
String path = uri.getRawPath(); // TODO: fix this to consider resourcePaths
if (path == null || path.length() == 0) {
path = "*";
}
httpMessage.append("POST " + path + " HTTP/1.1" + HttpUtils.CRLF);
httpMessage.append("Host: " + uri.getHost() + HttpUtils.CRLF);
/*
* soapAction = "SOAPAction: \"" + messageNamespace + "/" +
* message.operationName() + '\"' + HttpUtils.CRLF;
*/
soapAction = "SOAPAction: \"" + getSoapActionForOperation(message.operationName()) + '\"' + HttpUtils.CRLF;
if (checkBooleanParameter("compression", true)) {
String requestCompression = getStringParameter("requestCompression");
if (requestCompression.equals("gzip") || requestCompression.equals("deflate")) {
encoding = requestCompression;
httpMessage.append("Accept-Encoding: " + encoding + HttpUtils.CRLF);
} else {
httpMessage.append("Accept-Encoding: gzip, deflate" + HttpUtils.CRLF);
}
}
}
if (getParameterVector("keepAlive").first().intValue() != 1) {
channel().setToBeClosed(true);
httpMessage.append("Connection: close" + HttpUtils.CRLF);
}
if (encoding != null && checkBooleanParameter("compression", true)) {
content = HttpUtils.encode(encoding, content, httpMessage);
}
//httpMessage.append("Content-Type: application/soap+xml; charset=utf-8" + HttpUtils.CRLF);
httpMessage.append("Content-Type: text/xml; charset=utf-8" + HttpUtils.CRLF);
httpMessage.append("Content-Length: " + content.size() + HttpUtils.CRLF);
if (soapAction != null) {
httpMessage.append(soapAction);
}
httpMessage.append(HttpUtils.CRLF);
if (getParameterVector("debug").first().intValue() > 0) {
interpreter.logInfo("[SOAP debug] Sending:\n" + httpMessage.toString() + content.toString("utf-8"));
}
inputId = message.operationName();
ostream.write(httpMessage.toString().getBytes(HttpUtils.URL_DECODER_ENC));
ostream.write(content.getBytes());
} catch (SOAPException se) {
throw new IOException(se);
} catch (SAXException saxe) {
throw new IOException(saxe);
}
}
public void send(OutputStream ostream, CommMessage message, InputStream istream)
throws IOException {
HttpUtils.send(ostream, message, istream, inInputPort, channel(), this);
}
private void xmlNodeToValue(Value value, Node node, boolean isRecRoot) {
String type = "xsd:string";
Node currNode;
// Set attributes
NamedNodeMap attributes = node.getAttributes();
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
currNode = attributes.item(i);
if ("type".equals(currNode.getNodeName()) == false && convertAttributes()) {
getAttribute(value, currNode.getNodeName()).setValue(currNode.getNodeValue());
} else {
type = currNode.getNodeValue();
}
}
}
// Set children
NodeList list = node.getChildNodes();
Value childValue;
for (int i = 0; i < list.getLength(); i++) {
currNode = list.item(i);
switch (currNode.getNodeType()) {
case Node.ELEMENT_NODE:
childValue = value.getNewChild(currNode.getLocalName());
xmlNodeToValue(childValue, currNode, false);
break;
case Node.TEXT_NODE:
if (!isRecRoot) {
value.setValue(currNode.getNodeValue());
}
break;
}
}
if ("xsd:int".equals(type)) {
value.setValue(value.intValue());
} else if ("xsd:long".equals(type)) {
value.setValue(value.longValue());
} else if ("xsd:double".equals(type)) {
value.setValue(value.doubleValue());
} else if ("xsd:boolean".equals(type)) {
value.setValue(value.boolValue());
}
}
private static Element getFirstElement(Node node) {
NodeList nodes = node.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
return (Element) nodes.item(i);
}
}
return null;
}
/*
* private Schema getRecvMessageValidationSchema() throws IOException {
* List< Source > sources = new ArrayList< Source >(); Definition definition
* = getWSDLDefinition(); if ( definition != null ) { Types types =
* definition.getTypes(); if ( types != null ) { List< ExtensibilityElement
* > list = types.getExtensibilityElements(); for( ExtensibilityElement
* element : list ) { if ( element instanceof SchemaImpl ) { sources.add(
* new DOMSource( ((SchemaImpl)element).getElement() ) ); } } } }
* SchemaFactory schemaFactory = SchemaFactory.newInstance(
* XMLConstants.W3C_XML_SCHEMA_NS_URI ); try { return
* schemaFactory.newSchema( sources.toArray( new Source[sources.size()] ) );
* } catch( SAXException e ) { throw new IOException( e ); } }
*/
public CommMessage recv_internal(InputStream istream, OutputStream ostream)
throws IOException {
HttpParser parser = new HttpParser(istream);
HttpMessage message = parser.parse();
String charset = HttpUtils.getCharset(null, message);
HttpUtils.recv_checkForChannelClosing(message, channel());
if (inInputPort && message.type() != HttpMessage.Type.POST) {
throw new UnsupportedMethodException("Only HTTP method POST allowed!", Method.POST);
}
encoding = message.getProperty("accept-encoding");
CommMessage retVal = null;
String messageId = message.getPropertyOrEmptyString("soapaction");
FaultException fault = null;
Value value = Value.create();
try {
if (message.size() > 0) {
if (checkBooleanParameter("debug")) {
interpreter.logInfo("[SOAP debug] Receiving:\n" + new String(message.content(), charset));
}
SOAPMessage soapMessage = messageFactory.createMessage();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
/*
* Schema messageSchema = getRecvMessageValidationSchema(); if (
* messageSchema != null ) {
* factory.setIgnoringElementContentWhitespace( true );
* factory.setSchema( messageSchema ); }
*/
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource src = new InputSource(new ByteArrayInputStream(message.content()));
src.setEncoding(charset);
Document doc = builder.parse(src);
DOMSource dom = new DOMSource(doc);
soapMessage.getSOAPPart().setContent(dom);
/*
* if ( checkBooleanParameter( "debugAfter" ) ) {
* ByteArrayOutputStream tmpStream = new
* ByteArrayOutputStream(); soapMessage.writeTo( tmpStream );
* interpreter.logInfo( "[SOAP debug] Receiving:\n" +
* tmpStream.toString() ); }
*/
SOAPFault soapFault = soapMessage.getSOAPBody().getFault();
if (soapFault == null) {
Element soapValueElement = getFirstElement(soapMessage.getSOAPBody());
messageId = soapValueElement.getLocalName();
xmlNodeToValue(value, soapValueElement, checkBooleanParameter("dropRootValue", false));
ValueVector schemaPaths = getParameterVector("schema");
if (schemaPaths.size() > 0) {
List<Source> sources = new LinkedList<Source>();
Value schemaPath;
for (int i = 0; i < schemaPaths.size(); i++) {
schemaPath = schemaPaths.get(i);
if (schemaPath.getChildren("validate").first().intValue() > 0) {
sources.add(new StreamSource(new File(schemaPaths.get(i).strValue())));
}
}
if (!sources.isEmpty()) {
Schema schema =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(sources.toArray(new Source[0]));
schema.newValidator().validate(new DOMSource(soapMessage.getSOAPBody().getFirstChild()));
}
}
} else {
String faultName = "UnknownFault";
Value faultValue = Value.create();
Detail d = soapFault.getDetail();
if (d != null) {
Node n = d.getFirstChild();
if (n != null) {
faultName = n.getLocalName();
xmlNodeToValue(
faultValue, n, true);
} else {
faultValue.setValue(soapFault.getFaultString());
}
}
fault = new FaultException(faultName, faultValue);
}
}
String resourcePath = recv_getResourcePath(message);
if (message.isResponse()) {
if (fault != null && message.statusCode() == 500) {
fault = new FaultException("InternalServerError", "");
}
retVal = new CommMessage(CommMessage.GENERIC_ID, inputId, resourcePath, value, fault);
} else if (!message.isError()) {
if (messageId.isEmpty()) {
throw new IOException("Received SOAP Message without a specified operation");
}
retVal = new CommMessage(CommMessage.GENERIC_ID, messageId, resourcePath, value, fault);
}
} catch (SOAPException e) {
throw new IOException(e);
} catch (ParserConfigurationException e) {
throw new IOException(e);
} catch (SAXException e) {
//TODO support resourcePath
retVal = new CommMessage(CommMessage.GENERIC_ID, messageId, "/", value, new FaultException("TypeMismatch", e));
}
received = true;
if ("/".equals(retVal.resourcePath()) && channel().parentPort() != null
&& channel().parentPort().getInterface().containsOperation(retVal.operationName())) {
try {
// The message is for this service
Interface iface = channel().parentPort().getInterface();
OneWayTypeDescription oneWayTypeDescription = iface.oneWayOperations().get(retVal.operationName());
if (oneWayTypeDescription != null) {
// We are receiving a One-Way message
if (message.isResponse() == false) {
oneWayTypeDescription.requestType().cast(retVal.value());
}
} else {
RequestResponseTypeDescription rrTypeDescription = iface.requestResponseOperations().get(retVal.operationName());
if (retVal.isFault()) {
Type faultType = rrTypeDescription.faults().get(retVal.fault().faultName());
if (faultType != null) {
faultType.cast(retVal.value());
}
} else {
if (message.isResponse()) {
rrTypeDescription.responseType().cast(retVal.value());
} else {
rrTypeDescription.requestType().cast(retVal.value());
}
}
}
} catch (TypeCastingException e) {
// TODO: do something here?
}
}
return retVal;
}
public CommMessage recv(InputStream istream, OutputStream ostream)
throws IOException
{
return HttpUtils.recv(istream, ostream, inInputPort, channel(), this);
}
private String recv_getResourcePath(HttpMessage message) {
String ret = "/";
if (checkBooleanParameter("interpretResource")) {
ret = message.requestPath();
}
return ret;
}
} |
//There are things in this file that are prepared for the Android 3.0 port
//They are tagged by ANDROID3.0
package edu.vu.isis.ammo.core.ui;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.ToggleButton;
import edu.vu.isis.ammo.api.AmmoIntents;
import edu.vu.isis.ammo.core.R;
import edu.vu.isis.ammo.core.distributor.ui.DistributorTabActivity;
import edu.vu.isis.ammo.core.model.Channel;
import edu.vu.isis.ammo.core.model.Gateway;
import edu.vu.isis.ammo.core.model.Multicast;
import edu.vu.isis.ammo.core.model.Netlink;
import edu.vu.isis.ammo.core.network.INetworkService;
import edu.vu.isis.ammo.core.network.NetworkService;
import edu.vu.isis.ammo.core.receiver.StartUpReceiver;
import edu.vu.isis.ammo.core.ui.util.TabActivityEx;
/**
* The principle activity for the ammo core application.
* Provides a means for...
* ...changing the user preferences.
* ...checking delivery status of various messages.
* ...registering/unregistering content interest requests.
*
*/
public class AmmoActivity extends TabActivityEx implements OnItemClickListener
{
public static final Logger logger = LoggerFactory.getLogger( AmmoActivity.class );
private static final int VIEW_TABLES_MENU = Menu.NONE + 0;
private static final int CONFIG_MENU = Menu.NONE + 1;
private static final int DEBUG_MENU = Menu.NONE + 2;
private static final int ABOUT_MENU = Menu.NONE + 3;
// Fields
private List<Channel> channelModel = null;
private ChannelAdapter channelAdapter = null;
private List<Netlink> netlinkModel = null;
private NetlinkAdapter netlinkAdapter = null;
public boolean netlinkAdvancedView = false;
@SuppressWarnings("unused")
private Menu activity_menu;
SharedPreferences prefs = null;
// Views
private ChannelListView channelList = null;
private ListView netlinkList = null;
private INetworkService networkServiceBinder;
private ServiceConnection networkServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
logger.info("::onServiceConnected - Network Service");
networkServiceBinder = ((NetworkService.MyBinder) service).getService();
initializeGatewayAdapter();
initializeNetlinkAdapter();
}
public void onServiceDisconnected(ComponentName name) {
logger.info("::onServiceDisconnected - Network Service");
networkServiceBinder = null;
// FIXME: what to do here if the NS goes away?
// Change the model for the adapters to an empty list.
// This situation should probably never happen, but we should
// handle it properly anyway.
}
};
private void initializeGatewayAdapter()
{
channelModel = networkServiceBinder.getGatewayList();
// set gateway view references
channelList = (ChannelListView)findViewById(R.id.gateway_list);
channelAdapter = new ChannelAdapter(this, channelModel);
channelList.setAdapter(channelAdapter);
this.channelList.setOnItemClickListener(this);
//reset all rows
for (int ix=0; ix < channelList.getChildCount(); ix++)
{
View row = channelList.getChildAt(ix);
row.setBackgroundColor(Color.TRANSPARENT);
}
}
private void initializeNetlinkAdapter()
{
netlinkModel = networkServiceBinder.getNetlinkList();
// set netlink view references
netlinkList = (ListView)findViewById(R.id.netlink_list);
netlinkAdapter = new NetlinkAdapter(this, netlinkModel);
netlinkList.setAdapter(netlinkAdapter);
}
/**
* @Cateogry Lifecycle
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
logger.trace("::onCreate");
this.setContentView(R.layout.ammo_activity);
// Get a reference to the NetworkService.
Intent networkServiceIntent = new Intent(this, NetworkService.class);
boolean result = bindService( networkServiceIntent, networkServiceConnection, BIND_AUTO_CREATE );
if ( !result )
logger.error( "AmmoActivity failed to bind to the NetworkService!" );
Intent intent = new Intent();
// let others know we are running
intent.setAction(StartUpReceiver.RESET);
this.sendBroadcast(intent);
// setup tabs
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
spec = tabHost.newTabSpec("gateway");
spec.setIndicator("Channels", res.getDrawable(R.drawable.gateway_tab));
spec.setContent(R.id.gateway_layout);
getTabHost().addTab(spec);
spec = tabHost.newTabSpec("netlink");
spec.setIndicator("Link Status", res.getDrawable(R.drawable.netlink_32));
spec.setContent(R.id.netlink_layout);
getTabHost().addTab(spec);
/*
* Commented out for NTCNIE branch
*
spec = tabHost.newTabSpec("message_queue");
spec.setIndicator("Message Queue", res.getDrawable(R.drawable.mailbox_icon));
spec.setContent(new Intent("edu.vu.isis.ammo.core.ui.MessageQueueActivity.LAUNCH"));
getTabHost().addTab(spec);
*/
intent = new Intent().setClass(this, CorePreferenceActivity.class);
/*
spec = tabHost.newTabSpec("settings");
spec.setIndicator("Preferences", res.getDrawable(R.drawable.cog_32));
spec.setContent(intent);
tabHost.addTab(spec);
*/
tabHost.setCurrentTab(0);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
this.netlinkAdvancedView = prefs.getBoolean("debug_mode", this.netlinkAdvancedView);
}
@Override
public void onStart() {
super.onStart();
logger.trace("::onStart");
//reset all rows
if ( channelList != null )
{
for (int ix=0; ix < channelList.getChildCount(); ix++)
{
View row = channelList.getChildAt(ix);
row.setBackgroundColor(Color.TRANSPARENT);
}
this.channelList.setOnItemClickListener(this);
}
mReceiver = new StatusReceiver();
final IntentFilter statusFilter = new IntentFilter();
statusFilter.addAction( AmmoIntents.AMMO_ACTION_GATEWAY_STATUS_CHANGE );
statusFilter.addAction( AmmoIntents.AMMO_ACTION_NETLINK_STATUS_CHANGE );
registerReceiver( mReceiver, statusFilter );
if ( channelAdapter != null )
channelAdapter.notifyDataSetChanged();
if ( netlinkAdapter != null )
netlinkAdapter.notifyDataSetChanged();
}
@Override
public void onStop() {
super.onStop();
try {
unregisterReceiver( mReceiver );
} catch(IllegalArgumentException ex) {
logger.trace("tearing down the gateway status object");
}
}
private StatusReceiver mReceiver = null;
private class StatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent iIntent) {
final String action = iIntent.getAction();
if ( action.equals( AmmoIntents.AMMO_ACTION_GATEWAY_STATUS_CHANGE ))
{
if ( channelAdapter != null )
channelAdapter.notifyDataSetChanged();
}
else if ( action.equals( AmmoIntents.AMMO_ACTION_NETLINK_STATUS_CHANGE ))
{
if ( netlinkAdapter != null )
netlinkAdapter.notifyDataSetChanged();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
logger.trace("::onCreateOptionsMenu");
menu.add(Menu.NONE, VIEW_TABLES_MENU, Menu.NONE, getResources().getString(R.string.view_tables_label));
menu.add(Menu.NONE, CONFIG_MENU, Menu.NONE, getResources().getString(R.string.logging_label));
menu.add(Menu.NONE, DEBUG_MENU, Menu.NONE, getResources().getString((!this.netlinkAdvancedView)?(R.string.debug_label):(R.string.user_label)));
menu.add(Menu.NONE, ABOUT_MENU, Menu.NONE, getResources().getString(R.string.about_label));
//ANDROID3.0
//Store the reference to the menu so we can use it in the toggle
//function
//this.activity_menu = menu;
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
logger.trace("::onPrepareOptionsMenu");
menu.findItem(DEBUG_MENU).setTitle((!this.netlinkAdvancedView)?(R.string.debug_label):(R.string.user_label));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
logger.trace("::onOptionsItemSelected");
Intent intent = new Intent();
switch (item.getItemId()) {
case DEBUG_MENU:
toggleMode();
return true;
case VIEW_TABLES_MENU:
intent.setClass(this, DistributorTabActivity.class);
this.startActivity(intent);
return true;
case CONFIG_MENU:
intent.setClass(this, GeneralPreferences.class);
this.startActivity(intent);
return true;
case ABOUT_MENU:
intent.setClass(this, AboutActivity.class);
this.startActivity(intent);
return true;
}
return false;
}
@Override
public void onDestroy() {
super.onDestroy();
logger.trace("::onDestroy");
unbindService( networkServiceConnection );
}
// UI Management
public void onSettingsButtonClick(View view) {
logger.trace("::onClick");
Intent settingIntent = new Intent();
settingIntent.setClass(this, CorePreferenceActivity.class);
this.startActivity(settingIntent);
}
public void onGatewayElectionToggle(View view) {
int position = this.channelList.getPositionForView(view);
Gateway gw = (Gateway) this.channelAdapter.getItem(position);
// get the button's row
RelativeLayout row = (RelativeLayout)view.getParent();
ToggleButton button = (ToggleButton)view;
if (button.isChecked()) {
gw.enable();
}
else {
TextView t = (TextView)row.findViewById(R.id.gateway_status_text_one);
t.setText("Disabling...");
gw.disable();
}
row.refreshDrawableState();
}
public void onMulticastElectionToggle(View view)
{
int position = this.channelList.getPositionForView(view);
Multicast mc = (Multicast) this.channelAdapter.getItem(position);
RelativeLayout row = (RelativeLayout)view.getParent();
ToggleButton button = (ToggleButton)view;
if(button.isChecked())
mc.enable();
else
mc.disable();
row.refreshDrawableState();
}
/*
* Used to toggle the netlink view between simple and advanced.
*/
public void toggleMode()
{
this.netlinkAdvancedView = !this.netlinkAdvancedView;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean("debug_mode", this.netlinkAdvancedView).commit();
this.netlinkAdapter.notifyDataSetChanged();
this.channelAdapter.notifyDataSetChanged();
//ANDROID3.0
//Ideally, when this toggles, we need to
//refresh the menu. This line will invalidate it so that
//onPrepareOptionsMenu(...) will be called when the user
//opens it again.
//this.activity_menu.invalidateOptionsMenu();
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
/*Channel c = this.channelAdapter.getItem(arg2);
logger.trace("::onClick");
Intent gatewayIntent = new Intent();
if(c.getClass().equals(Gateway.class))
{
gatewayIntent.putExtra("IPKEY", INetPrefKeys.CORE_IP_ADDR);
gatewayIntent.putExtra("PORTKEY", INetPrefKeys.CORE_IP_PORT);
gatewayIntent.putExtra("NetConnTimeoutKey", INetPrefKeys.CORE_SOCKET_TIMEOUT);
gatewayIntent.putExtra("ConIdleTimeoutKey", "AMMO_NET_CONN_FLAT_LINE_TIME");
}
else
{
gatewayIntent.putExtra("IPKEY", INetPrefKeys.MULTICAST_IP_ADDRESS);
gatewayIntent.putExtra("PORTKEY", INetPrefKeys.MULTICAST_PORT);
gatewayIntent.putExtra("NetConnTimeoutKey", INetPrefKeys.MULTICAST_NET_CONN_TIMEOUT);
gatewayIntent.putExtra("ConIdleTimeoutKey", INetPrefKeys.MULTICAST_CONN_IDLE_TIMEOUT);
}
gatewayIntent.setClass(this, ChannelDetailActivity.class);
this.startActivity(gatewayIntent);
*/
}
public void editPreferences(View v)
{
ListView lv = (ListView) v.getParent().getParent();
int position = lv.getPositionForView((View) v.getParent());
Channel c = (Channel) lv.getAdapter().getItem(position);
Intent gatewayIntent = new Intent();
if(c.getClass().equals(Gateway.class))
{
gatewayIntent.putExtra(ChannelDetailActivity.PREF_TYPE, ChannelDetailActivity.GATEWAY_PREF);
}
else
{
gatewayIntent.putExtra(ChannelDetailActivity.PREF_TYPE, ChannelDetailActivity.MULTICAST_PREF);
}
gatewayIntent.setClass(this, ChannelDetailActivity.class);
this.startActivity(gatewayIntent);
}
} |
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class BaseXClient {
/** Output stream. */
final OutputStream out;
/** Socket. */
private final Socket socket;
/** Cache. */
private final BufferedInputStream in;
/** Process info. */
private String info;
/**
* Constructor.
* @param host server name
* @param port server port
* @param usern user name
* @param pw password
* @throws IOException Exception
*/
public BaseXClient(final String host, final int port, final String usern,
final String pw) throws IOException {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 5000);
in = new BufferedInputStream(socket.getInputStream());
// receive timestamp
final String ts = receive();
// send user name and hashed password/timestamp
out = socket.getOutputStream();
send(usern);
send(md5(md5(pw) + ts));
// receive success flag
if(!ok()) throw new IOException();
}
/**
* Executes a command and serializes the result to the specified stream.
* @param cmd command
* @param o output stream
* @return boolean success flag
* @throws IOException Exception
*/
public boolean execute(final String cmd, final OutputStream o)
throws IOException {
send(cmd);
receive(o);
info = receive();
return ok();
}
/**
* Executes a command and returns the result.
* @param cmd command
* @return result
* @throws IOException Exception
*/
public String execute(final String cmd) throws IOException {
send(cmd);
final String s = receive();
info = receive();
if(!ok()) throw new IOException(info);
return s;
}
/**
* Creates a query object.
* @param query query string
* @return query
* @throws IOException Exception
*/
public Query query(final String query) throws IOException {
return new Query(query);
}
/**
* Returns process information.
* @return string info
*/
public String info() {
return info;
}
/**
* Closes the session.
* @throws IOException Exception
*/
public void close() throws IOException {
send("exit");
socket.close();
}
/**
* Checks the next success flag.
* @return value of check
* @throws IOException Exception
*/
boolean ok() throws IOException {
int test = in.read();
return test == 0;
}
/**
* Returns the next received string.
* @return String result or info
* @throws IOException I/O exception
*/
String receive() throws IOException {
final OutputStream os = new ByteArrayOutputStream();
receive(os);
return os.toString();
}
/**
* Sends a string to the server.
* @param s string to be sent
* @throws IOException I/O exception
*/
void send(final String s) throws IOException {
for(final byte t : s.getBytes()) out.write(t);
out.write(0);
}
/**
* Receives a string and writes it to the specified output stream.
* @param o output stream
* @throws IOException I/O exception
*/
private void receive(final OutputStream o) throws IOException {
while(true) {
final int b = in.read();
if(b == 0) break;
if(b == 1) continue;
o.write(b);
}
}
/**
* Returns an MD5 hash.
* @param pw String
* @return String
*/
private static String md5(final String pw) {
final StringBuilder sb = new StringBuilder();
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
md.update(pw.getBytes());
for(final byte b : md.digest()) {
final String s = Integer.toHexString(b & 0xFF);
if(s.length() == 1) sb.append('0');
sb.append(s);
}
} catch(final NoSuchAlgorithmException ex) {
// should not occur
ex.printStackTrace();
}
return sb.toString();
}
/**
* Inner class for iterative query execution.
*/
class Query {
/** Query id. */
private final String id;
/** Next result item. */
private String next;
/**
* Standard constructor.
* @param query query string
* @throws IOException I/O exception
*/
public Query(final String query) throws IOException {
out.write(0);
send(query);
id = receive();
}
/**
* Checks for the next item.
* @return value of check
* @throws IOException I/O exception
*/
public boolean more() throws IOException {
out.write(1);
send(id);
next = receive();
if(!ok()) throw new IOException(receive());
return next.length() != 0;
}
/**
* Returns the next item.
* @return item string
*/
public String next() {
return next;
}
/**
* Closes the query.
* @throws IOException I/O exception
*/
public void close() throws IOException {
out.write(2);
send(id);
}
}
} |
package etomica.api;
import etomica.potential.PotentialMaster;
/**
* An ISpecies holds information about how to construct a molecule, and
* creates molecules on demand. In addition to actually creating molecules,
* ISpecies objects are often used as keys to pass and designate which
* species is of interest (for assigning potentials or setting the number of
* molecules in the box, for instance).
*
* @author David Kofke
* @author C. Daniel Barnes
* @author Andrew Schultz
* @see IBox
* @see PotentialMaster
*/
public interface ISpecies {
/**
* Informs the ISpecies what its index should be. This should only be
* called by the SpeciesManager.
*/
public void setIndex(int newIndex);
/**
* Returns the index for this ISpecies, within the context of an
* ISimulation. The index is the ISpecies' position in the array returned
* by SpeciesManager.getSpecies().
*/
public int getIndex();
/**
* Builds and returns the IMolecule of this ISpecies.
*/
public IMolecule makeMolecule();
/**
* Returns the number of child types of this group.
*/
public int getAtomTypeCount();
/**
* Returns the child types of this group for the specified index.
*/
public IAtomType getAtomType(int index);
/**
* Returns the conformation used to set the standard arrangement of
* the atoms/atom-groups produced by this factory.
*/
public IConformation getConformation();
/**
* The position definition held by the type provides an appropriate default
* to define the position of an atom of this type. This field is set in the
* definition of the parent species of the atom. It is null for SpeciesRoot,
* SpeciesMaster, and SpeciesAgent atoms.
*
* @return Returns the PositionDefinition for an atom of this type.
*/
public IAtomPositionDefinition getPositionDefinition();
} |
/**
* MIPSSim: This class emulates a MIPS system
*
* @author Chris Opperwall
* @version 1.0 May 29, 2013
*/
import java.util.ArrayList;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class ImpsTools {
// Instance Variables
private int[] dataMem;
private ArrayList<String> instMem;
private ArrayList<Register> regFile;
private int pc;
private Scanner scan;
/* Initialize dataMem
Initialize regFile: call initReg() to set up
Initialize instMem: Scan in all instructions?
*/
public ImpsTools(File instructions) throws FileNotFoundException {
dataMem = new int[8192];
instMem = new ArrayList<String>();
regFile = new ArrayList<Register>(32);
pc = 0;
initReg();
initInstMem(instructions);
}
public void step(int num) {
String opcode;
for (int i = 0; i != num && pc < instMem.size(); i++) {
scan = new Scanner(instMem.get(pc++));
scan.useDelimiter("[\\s,()]+");
while (scan.hasNext()) {
opcode = scan.next();
if (opcode.equals("add"))
add(false);
else if(opcode.equals("sub"))
add(true);
else if (opcode.equals("addi"))
addi();
else if (opcode.equals("and"))
logic(true);
else if (opcode.equals("or"))
logic(false);
else if (opcode.equals("slt"))
slt();
else if (opcode.equals("sw"))
memIO(true);
else if (opcode.equals("lw"))
memIO(false);
else if (opcode.equals("beq"))
branch(true);
else if (opcode.equals("bne"))
branch(false);
else if (opcode.equals("j"))
jump(0);
else if (opcode.equals("jal"))
jump(1);
else if (opcode.equals("jr"))
jump(2);
}
}
if (num > 0)
System.out.println(" " + num + " instruction(s) executed");
}
public void dumpRegState() {
System.out.println("\npc = " + pc);
for (int i = 0; i < regFile.size();) {
for (int j = 0; j < 4 && i < regFile.size(); j++) {
System.out.print(regFile.get(i).name + " = " +
regFile.get(i).value + " ");
if (i == 0)
System.out.print(" ");
++i;
}
System.out.println();
}
}
public void memDisplay(int start, int stop) {
while (start <= stop) {
System.out.println("[" + start + "] = " + dataMem[start]);
++start;
}
}
public void simReset() {
dataMem = new int[8192];
for (int i = 0; i < regFile.size(); i++)
regFile.get(i).value = 0;
System.out.println(" Simulator reset");
}
public void help() {
System.out.println("\nh = show help");
System.out.println("d = dump register state");
System.out.println("s = single step through the program (i.e. execute 1 instruction and stop)");
System.out.println("s num = step through num instructions of the program");
System.out.println("r = run until the program ends");
System.out.println("m num1 num2 = display data memory from location num1 to num2");
System.out.println("c = clear all registers, memory, and the program counter to 0");
System.out.println("q = exit the program");
}
private void initReg() {
regFile.add(new Register("$0"));
regFile.add(new Register("$v0"));
regFile.add(new Register("$v1"));
regFile.add(new Register("$a0"));
regFile.add(new Register("$a1"));
regFile.add(new Register("$a2"));
regFile.add(new Register("$a3"));
for (int i = 0; i < 8; i++)
regFile.add(new Register("$t" + i));
for (int i = 0; i < 8; i++)
regFile.add(new Register("$s" + i));
regFile.add(new Register("$t8"));
regFile.add(new Register("$t9"));
regFile.add(new Register("$sp"));
regFile.add(new Register("$ra"));
}
private void initInstMem(File instFile) throws FileNotFoundException {
String temp;
Scanner scan = new Scanner(instFile);
while (scan.hasNext()) {
temp = scan.nextLine().trim();
if (temp.indexOf("
temp = temp.substring(0, temp.indexOf("
if (temp.length() > 0)
instMem.add(temp);
}
}
// Begin private instruction methods
private void add(boolean sub) {
Register rd;
int rs, rt;
rd = getReg(scan.next());
rs = getValue(scan.next());
rt = getValue(scan.next());
rd.value = sub ? rs - rt : rs + rt;
}
private void addi() {
Register rd;
int rs, immed;
rd = getReg(scan.next());
rs = getValue(scan.next());
immed = scan.nextInt();
rd.value = rs + immed;
}
private void logic(boolean and) {
Register rd;
int rs, rt;
rd = getReg(scan.next());
rs = getValue(scan.next());
rt = getValue(scan.next());
rd.value = and ? rs & rt : rs | rt;
}
private void branch(boolean beq) {
int rs, rt;
String label;
rs = getValue(scan.next());
rt = getValue(scan.next());
label = scan.next();
if ( beq ? rs == rt : rs != rt)
pc = findLabel(label);
}
private void slt() {
Register rd = getReg(scan.next());
int rs, rt;
rs = getValue(scan.next());
rt = getValue(scan.next());
rd.value = rs < rt ? 1 : 0;
}
private void memIO(boolean store) {
Register rd = getReg(scan.next());
int offset = scan.nextInt(), memAddr = getValue(scan.next());
if (store)
dataMem[memAddr + offset] = rd.value;
else
rd.value = dataMem[memAddr + offset];
}
// type decides the type of jump
// 0 = j
// 1 = jal
// 2 = jr
private void jump(int type) {
if (type != 2) {
if (type == 1)
getReg("$ra").value = pc;
pc = findLabel(scan.next());
}
else
pc = getValue(scan.next());
}
private int findLabel(String label) {
for (int i = 0; i < instMem.size(); i++)
if (instMem.get(i).length() >= label.length())
if (instMem.get(i).substring(0, label.length()).equals(label))
return i;
return -1;
}
private int getValue(String regName) {
for (int i = 0; i < regFile.size(); i++)
if (regFile.get(i).name.equals(regName))
return regFile.get(i).value;
return -1;
}
private Register getReg(String regName) {
for (int i = 0; i < regFile.size(); i++)
if (regFile.get(i).name.equals(regName))
return regFile.get(i);
return null;
}
private class Register {
public String name;
public int value;
public Register(String name) {
this.name = name;
}
}
} |
package graphql_clj;
import clojure.lang.IMeta;
import clojure.lang.IObj;
import clojure.lang.IPersistentMap;
import clojure.lang.Keyword;
import clojure.lang.LazilyPersistentVector;
import clojure.lang.PersistentArrayMap;
import clojure.lang.PersistentVector;
import clojure.lang.Symbol;
import java.util.Arrays;
import java.util.function.Supplier;
public class Parser {
private static final int TOKEN_EOF = -1;
private static final int TOKEN_INTEGER = 1;
private static final int TOKEN_FLOAT = 2;
private static final int TOKEN_STRING = 3;
private static final int TOKEN_IDENT = 4;
private static final int TOKEN_ELLIPSIS = 5;
private static final char BYTE_ORDER_MARK = '\ufeff';
private static final int STATE_NEGATIVE = -1;
private static final int STATE_ZERO = 0;
private static final int STATE_INTEGER = 1;
private static final int STATE_DOT = 2;
private static final int STATE_E = 3;
private static final Keyword ALIAS = Keyword.intern("alias");
private static final Keyword ARGUMENT = Keyword.intern("argument");
private static final Keyword ARGUMENTS = Keyword.intern("arguments");
private static final Keyword ARGUMENT_DEFINITION = Keyword.intern("argument-definition");
private static final Keyword BASIC_TYPE = Keyword.intern("basic-type");
private static final Keyword BOOLEAN_VALUE = Keyword.intern("boolean-value");
private static final Keyword CONSTANTS = Keyword.intern("constants");
private static final Keyword DEFAULT_VALUE = Keyword.intern("default-value");
private static final Keyword DIRECTIVE = Keyword.intern("directive");
private static final Keyword DIRECTIVES = Keyword.intern("directives");
private static final Keyword DIRECTIVE_DEFINITION = Keyword.intern("directive-definition");
private static final Keyword DOC = Keyword.intern("doc");
private static final Keyword END = Keyword.intern("end");
private static final Keyword ENUM_VALUE = Keyword.intern("enum-value");
private static final Keyword ENUM_CONSTANT = Keyword.intern("enum-constant");
private static final Keyword ENUM_DEFINITION = Keyword.intern("enum-definition");
private static final Keyword EXTEND_TYPE_DEFINITION = Keyword.intern("extend-type-definition");
private static final Keyword FIELDS = Keyword.intern("fields");
private static final Keyword FLOAT_VALUE = Keyword.intern("float-value");
private static final Keyword FRAGMENT_DEFINITION = Keyword.intern("fragment-definition");
private static final Keyword FRAGMENT_SPREAD = Keyword.intern("fragment-spread");
private static final Keyword IMAGE = Keyword.intern("image");
private static final Keyword IMPLEMENTS = Keyword.intern("implements");
private static final Keyword INLINE_FRAGMENT = Keyword.intern("inline-fragment");
private static final Keyword INNER_TYPE = Keyword.intern("inner-type");
private static final Keyword INPUT_DEFINITION = Keyword.intern("input-definition");
private static final Keyword INTERFACE_DEFINITION = Keyword.intern("interface-definition");
private static final Keyword INT_VALUE = Keyword.intern("int-value");
private static final Keyword LIST_TYPE = Keyword.intern("list-type");
private static final Keyword LIST_VALUE = Keyword.intern("list-value");
private static final Keyword MEMBERS = Keyword.intern("members");
private static final Keyword MUTATION = Keyword.intern("mutation");
private static final Keyword NAME = Keyword.intern("name");
private static final Keyword NULL_VALUE = Keyword.intern("null-value");
private static final Keyword OBJECT_FIELD = Keyword.intern("object-field");
private static final Keyword OBJECT_VALUE = Keyword.intern("object-value");
private static final Keyword ON = Keyword.intern("on");
private static final Keyword QUERY = Keyword.intern("query");
private static final Keyword QUERY_DEFINITION = Keyword.intern("query-definition");
private static final Keyword REQUIRED = Keyword.intern("required");
private static final Keyword SCALAR_DEFINITION = Keyword.intern("scalar-definition");
private static final Keyword SCHEMA = Keyword.intern("schema");
private static final Keyword SCHEMA_DEFINITION = Keyword.intern("schema-definition");
private static final Keyword SELECTION_FIELD = Keyword.intern("selection-field");
private static final Keyword SELECTION_SET = Keyword.intern("selection-set");
private static final Keyword START = Keyword.intern("start");
private static final Keyword STRING_VALUE = Keyword.intern("string-value");
private static final Keyword SUBSCRIPTION = Keyword.intern("subscription");
private static final Keyword TAG = Keyword.intern("tag");
private static final Keyword TYPE = Keyword.intern("type");
private static final Keyword TYPE_DEFINITION = Keyword.intern("type-definition");
private static final Keyword TYPE_FIELD = Keyword.intern("type-field");
private static final Keyword TYPE_SYSTEM_DEFINITIONS = Keyword.intern("type-system-definitions");
private static final Keyword UNION_DEFINITION = Keyword.intern("union-definition");
private static final Keyword VALUE = Keyword.intern("value");
private static final Keyword VALUES = Keyword.intern("values");
private static final Keyword VARIABLE_DEFINITION = Keyword.intern("variable-definition");
private static final Keyword VARIABLE_DEFINITIONS = Keyword.intern("variable-definitions");
private static final Keyword VARIABLE_REFERENCE = Keyword.intern("variable-reference");
private final String _input;
private int _limit;
private int _index;
private int _line;
private int _lineStart;
private int _token;
private int _tokenStart;
private Location _startLocation;
private String _image;
private final StringBuilder _stringValue = new StringBuilder();
private int _docStart;
private int _docEnd;
private Object[] _stack = new Object[64];
private int _stackTop;
public Parser(String input) {
_line = 1;
_lineStart = -1;
_input = input;
_limit = input.length();
// populate the first token
next();
}
private void ensureCapacity() {
if (_stackTop >= _stack.length)
_stack = Arrays.copyOf(_stack, _stackTop*2);
}
private void push(Keyword key, Object value) {
ensureCapacity();
_stack[_stackTop++] = key;
_stack[_stackTop++] = value;
}
private void push(Object value) {
ensureCapacity();
_stack[_stackTop++] = value;
}
private Object[] pop(int topIndex) {
final int botIndex = _stackTop;
return Arrays.copyOfRange(_stack, _stackTop = topIndex, botIndex);
}
private PersistentVector popVec(int topIndex) {
final int botIndex = _stackTop;
return (PersistentVector)LazilyPersistentVector.createOwning(
Arrays.copyOfRange(_stack, _stackTop = topIndex, botIndex));
}
static PersistentArrayMap map(Object ... args) {
return new PersistentArrayMap(args);
}
private static IObj node(IPersistentMap meta, Object ... kvpairs) {
return new PersistentArrayMap(meta, kvpairs);
}
private static IObj nodeWithLoc(Object start, Object end, Object ... kvpairs) {
return node(map(START, start, END, end), kvpairs);
}
Location location(int index) {
return new Location(_line, index - _lineStart, index);
}
Location startLocation() {
if (_startLocation == null)
_startLocation = location(_tokenStart);
return _startLocation;
}
ParseException tokenError(int index, String msg) {
throw new ParseException(location(index), msg);
}
ParseException expectedError(String expected) {
throw new ParseException(
startLocation(),
"Expected "+expected+". Found "+tokenDescription());
}
static boolean isDigit(char ch) {
return '0' <= ch && ch <= '9';
}
private void next() {
_token = nextImpl();
}
void tabAdjust(int tabIndex) {
// TODO: update _lineStart to make subsequent column
// computation correct.
}
private void documentComment() {
if (_docStart >= 0)
push(DOC, _input.substring(_docStart, _docEnd));
}
private int nextImpl() {
char ch;
int i;
int state;
_tokenStart = _index;
_startLocation = null;
// clear out the document comment from the previous token.
// use -2 to indicate we have not seen a new line. We have a
// special case for the first charater in the input, that is
// assumed to follow a newline.
_docStart = _tokenStart == 0 ? -1 : -2;
outer:
for (;; _tokenStart++) {
if (_tokenStart >= _limit) {
_index = _tokenStart;
return TOKEN_EOF;
}
switch (ch = _input.charAt(_tokenStart)) {
case '\t':
tabAdjust(_tokenStart);
// fall through
case ' ':
case ',':
case BYTE_ORDER_MARK:
continue;
case '\r':
if (_tokenStart+1 < _limit && '\n' == _input.charAt(_tokenStart+1))
_tokenStart++;
// fall through
case '\n':
_line++;
_lineStart = _tokenStart;
// seen a newline, if there's a comment on the
// following line, it can start a document comment.
// This also clears out the previous document comment
// if there was one, since we want our document
// comments to be contiguous.
_docStart = -1;
continue;
case '
if (_docStart == -1)
_docStart = _tokenStart;
comment:
while (++_tokenStart < _limit) {
switch (_input.charAt(_docEnd = _tokenStart)) {
case '\r':
if (_tokenStart+1 < _limit && '\n' == _input.charAt(_tokenStart+1))
_tokenStart++;
// fall through
case '\n':
_line++;
_lineStart = _tokenStart;
if (_docStart < 0) {
// this is not a document comment, but the
// next comment could be.
_docStart = -1;
continue outer;
}
while (++_tokenStart < _limit) {
switch (ch = _input.charAt(_tokenStart)) {
case '\t':
tabAdjust(_tokenStart);
// fall through
case ' ':
case ',':
case BYTE_ORDER_MARK:
continue;
case '
continue comment;
default:
// process the character again
--_tokenStart;
continue outer;
}
}
continue outer;
}
}
_index = _tokenStart;
return TOKEN_EOF;
case '@':
case '{':
case '(':
case '[':
case '$':
case ']':
case '!':
case ':':
case '}':
case ')':
case '|':
case '=':
_index = _tokenStart + 1;
return ch;
case '.':
if (_tokenStart + 2 < _limit
&& '.' == _input.charAt(_tokenStart + 1)
&& '.' == _input.charAt(_tokenStart + 2)) {
_index = _tokenStart + 3;
return TOKEN_ELLIPSIS;
} else {
throw tokenError(
_tokenStart,
String.format(
"invalid character sequence '%s', did you mean '...'?",
_input.substring(_tokenStart, _tokenStart+2)));
}
case '"':
// need to track start location explicitly on strings,
// since their contents can make
// location(_startLocaiton) become invalid (once \t is
// handled)
_startLocation = location(_tokenStart);
_stringValue.setLength(0);
for (i=_tokenStart+1 ; i<_limit ; ) {
if ('"' == (ch = _input.charAt(i++))) {
// TODO: the image should probably include the quotes
_image = _input.substring(_tokenStart+1, (_index = i)-1);
return TOKEN_STRING;
} else if ('\\' == ch) {
if (i >= _limit)
throw tokenError(i, "unterminated string");
switch (ch = _input.charAt(i++)) {
case '\"': case '\\': case '/':
break;
case 'b': ch = '\b'; break;
case 'f': ch = '\f'; break;
case 'r': ch = '\r'; break;
case 't': ch = '\t'; break;
case 'n': ch = '\n'; break;
case 'u':
if (i+4 >= _limit)
throw tokenError(i, "unterminated string");
for (int n=i+4 ; i<n ; ) {
char x = _input.charAt(i++);
if ('0' <= x && x <= '9') {
ch = (char)((ch << 4) | (x - '0'));
} else if ('A' <= (x & ~0x20) && x <= 'F') {
// if x is a letter, then x & ~0x20 will convert
// lowercase to uppercase, and leave uppercase alone
ch = (char)((ch << 4) | (x - ('A' - 10)));
} else {
throw tokenError(i, "invalid hex escape");
}
}
break;
default:
throw tokenError(i, "invalid escape sequence");
}
} else if (ch < ' ') {
if (ch == '\t') {
tabAdjust(i-1);
} else {
throw tokenError(i, "invalid character in string");
}
}
_stringValue.append(ch);
}
throw tokenError(_limit, "unterminated string");
case '_':
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
for (i=_tokenStart ; ++i<_limit ; ) {
ch = _input.charAt(i);
if (!('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'0' <= ch && ch <= '9' || ch == '_'))
break;
}
_image = _input.substring(_tokenStart, _index = i);
return TOKEN_IDENT;
case '-':
state = STATE_NEGATIVE;
break;
case '0':
state = STATE_ZERO;
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
state = STATE_INTEGER;
break;
default:
throw tokenError(_tokenStart, String.format("invalid character '%c'", ch));
} // switch on char
stateLoop:
for (i=_tokenStart+1 ;; ++i) {
switch (state) {
case STATE_ZERO:
if (i < _limit) {
ch = _input.charAt(i);
if ('.' == ch) {
state = STATE_DOT;
continue;
} else if ('e' == ch || 'E' == ch) {
state = STATE_E;
continue;
} else if ('0' <= ch && ch <= '9') {
throw tokenError(i, "zero-prefixed numbers are not allowed");
}
}
_image = _input.substring(_tokenStart, _index = i);
return TOKEN_INTEGER;
case STATE_NEGATIVE:
if (i >= _limit)
throw tokenError(i, "expected digit after '-'");
ch = _input.charAt(i);
if ('1' <= ch && ch <= '9') {
state = STATE_INTEGER;
// fall through
} else if ('0' == ch) {
state = STATE_ZERO;
continue stateLoop;
} else {
throw tokenError(i, "expected digit after '-'");
}
case STATE_INTEGER:
for ( ; i < _limit ; ++i) {
ch = _input.charAt(i);
if ('0' <= ch && ch <= '9') {
continue;
} else if ('.' == ch) {
state = STATE_DOT;
} else if ('e' == ch || 'E' == ch) {
state = STATE_E;
} else {
break;
}
continue stateLoop;
}
_image = _input.substring(_tokenStart, _index = i);
return TOKEN_INTEGER;
case STATE_DOT:
if (!((i < _limit) && '0' <= (ch = _input.charAt(i)) && ch <= '9'))
throw tokenError(i, "expected digit after '.'");
while (++i < _limit) {
ch = _input.charAt(i);
if ('0' <= ch && ch <= '9')
continue;
if ('e' == ch || 'E' == ch) {
state = STATE_E;
continue stateLoop;
}
break;
}
_image = _input.substring(_tokenStart, _index = i);
return TOKEN_FLOAT;
case STATE_E:
if (i >= _limit)
throw tokenError(i, "expected '+', '-', or digit after 'e'");
if ('+' == (ch = _input.charAt(i)) || '-' == ch) {
if (++i >= _limit)
throw tokenError(i, "expected digit after 'e'");
ch = _input.charAt(i);
}
if (!('0' <= ch && ch <= '9'))
throw tokenError(i, "expected digit after 'e'");
while (++i < _limit) {
ch = _input.charAt(i);
if (!('0' <= ch && ch <= '9'))
break;
}
_image = _input.substring(_tokenStart, _index = i);
return TOKEN_FLOAT;
default:
throw new AssertionError("bad state: "+state);
}
} // stateLoop
} // outer: for
}
private String tokenDescription() {
return tokenDescription(_token);
}
private String tokenDescription(int kind) {
switch (kind) {
case TOKEN_EOF:
return "end of file";
case TOKEN_INTEGER:
case TOKEN_FLOAT:
case TOKEN_STRING:
return "'" + _image + "'";
case TOKEN_IDENT:
return _image;
case TOKEN_ELLIPSIS:
return "'...'";
default:
return new String(new char[] { '\'', (char)kind, '\'' });
}
}
private void expect(int kind) {
if (_token != kind)
throw expectedError(tokenDescription(kind));
}
private void consume(int kind) {
expect(kind);
next();
}
private Symbol parseName() {
if (TOKEN_IDENT != _token)
throw expectedError("name");
Symbol name = (Symbol)Symbol.intern(_image)
.withMeta(map(START, startLocation(), END, location(_index)));
next();
return name;
}
private IObj parseBasicType() {
Symbol name = parseName();
return node(name.meta(), TAG, BASIC_TYPE, NAME, name);
}
private IObj parseTypeRef() {
int topIndex = _stackTop;
Location start = startLocation();
Location end;
if ('[' == _token) {
next();
push(TAG, LIST_TYPE);
push(INNER_TYPE, parseTypeRef());
end = location(_index);
consume(']');
} else if (TOKEN_IDENT == _token) {
push(TAG, BASIC_TYPE);
Symbol name = parseName();
push(NAME, name);
end = (Location)name.meta().valAt(END);
} else {
throw expectedError("'[' or type name");
}
if ('!' == _token) {
end = location(_index);
next();
push(REQUIRED, true);
}
return nodeWithLoc(start, end, pop(topIndex));
}
private IObj parseVec(int startToken, int endToken, Supplier<Object> itemParser) {
Location start = startLocation();
consume(startToken);
int topIndex = _stackTop;
while (_token != endToken) {
push(itemParser.get());
}
Object end = location(_index);
next();
return popVec(topIndex).withMeta(map(START, start, END, end));
}
IObj parseArgumentDefinition() {
int topIndex = _stackTop;
push(TAG, ARGUMENT_DEFINITION);
Symbol name = parseName();
push(NAME, name);
consume(':');
IObj lastObj = parseTypeRef();
push(TYPE, lastObj);
if ('=' == _token) {
next();
push(DEFAULT_VALUE, lastObj = parseValue());
}
return nodeWithLoc(
name.meta().valAt(START),
lastObj.meta().valAt(END),
pop(topIndex));
}
// package private to avoid compiler-generated private accesor
// with lambda usage.
IObj parseTypeField() {
int topIndex = _stackTop;
push(TAG, TYPE_FIELD);
documentComment();
Symbol name = parseName();
push(NAME, name);
if ('(' == _token)
push(ARGUMENTS, parseVec('(', ')', this::parseArgumentDefinition).withMeta(null));
consume(':');
IObj type = parseTypeRef();
push(TYPE, type);
return nodeWithLoc(
name.meta().valAt(START),
type.meta().valAt(END),
pop(topIndex));
}
IObj parseTypeDefinition(IObj start, Keyword tag) {
int topIndex = _stackTop;
push(TAG, tag);
documentComment();
next(); // "type"
Symbol name = parseName();
push(NAME, name);
if (TOKEN_IDENT == _token && "implements".equals(_image)) {
next();
int vecStart = _stackTop;
do {
push(parseBasicType());
} while (TOKEN_IDENT == _token);
push(IMPLEMENTS, popVec(vecStart));
}
IObj fields = parseVec('{', '}', this::parseTypeField);
Object end = fields.meta().valAt(END);
push(FIELDS, fields.withMeta(null));
return nodeWithLoc(start, end, pop(topIndex));
}
IObj parseInterfaceDefinition() {
int topIndex = _stackTop;
Location start = startLocation();
push(TAG, INTERFACE_DEFINITION);
documentComment();
next();
push(NAME, parseName());
IObj fields = parseVec('{', '}', this::parseTypeField);
push(FIELDS, fields.withMeta(null));
return nodeWithLoc(
start, fields.meta().valAt(END),
pop(topIndex));
}
IObj parseInputDefinition() {
int topIndex = _stackTop;
Location start = startLocation();
push(TAG, INPUT_DEFINITION);
documentComment();
next(); // "input"
push(NAME, parseName());
IObj fields = parseVec('{', '}', this::parseTypeField);
push(FIELDS, fields.withMeta(null));
return nodeWithLoc(
start, fields.meta().valAt(END),
pop(topIndex));
}
IObj parseUnionDefinition() {
int topIndex = _stackTop;
Location start = startLocation();
push(TAG, UNION_DEFINITION);
documentComment();
next(); // "union"
push(NAME, parseName());
consume('=');
int vecStart = _stackTop;
IObj lastType = parseBasicType();
push(lastType);
while ('|' == _token) {
next();
push(lastType = parseBasicType());
}
push(MEMBERS, popVec(vecStart));
return nodeWithLoc(
start, lastType.meta().valAt(END),
pop(topIndex));
}
Keyword parseSchemaTag() {
if (TOKEN_IDENT == _token) {
switch (_image) {
case "query":
return QUERY;
case "mutation":
return MUTATION;
case "subscription":
return SUBSCRIPTION;
}
}
throw expectedError("'query', 'mutation', or 'subscription'");
}
IObj parseSchemaType() {
Location start = startLocation();
Keyword tag = parseSchemaTag();
next(); // consume the tag, the parseSchemaType does not
consume(':');
Symbol name = parseName();
return nodeWithLoc(
start, name.meta().valAt(END),
TAG, tag,
NAME, name);
}
IObj parseSchemaDefinition() {
Location start = startLocation();
next(); // "schema"
IObj members = parseVec('{', '}', this::parseSchemaType);
return nodeWithLoc(
start, members.meta().valAt(END),
TAG, SCHEMA_DEFINITION,
MEMBERS, members.withMeta(null)); // TODO: remove withMeta(null)
}
IObj parseEnumConstant() {
int topIndex = _stackTop;
push(TAG, ENUM_CONSTANT);
documentComment();
Symbol name = parseName();
push(NAME, name);
IObj directives = parseDirectives();
IPersistentMap meta = name.meta();
if (directives != null) {
push(DIRECTIVES, directives.withMeta(null));
meta = map(START, name.meta().valAt(START),
END, directives.meta().valAt(END));
}
return node(meta, pop(topIndex));
}
IObj parseEnumDefinition() {
int topIndex = _stackTop;
Location start = startLocation();
push(TAG, ENUM_DEFINITION);
documentComment();
next(); // "enum"
push(NAME, parseName());
IObj constants = parseVec('{', '}', this::parseEnumConstant);
push(CONSTANTS, constants.withMeta(null));
return nodeWithLoc(
start, constants.meta().valAt(END),
pop(topIndex));
}
IObj parseTypeConditionOpt() {
if (TOKEN_IDENT != _token || !"on".equals(_image))
return null;
Location start = startLocation();
next();
IObj type = parseBasicType();
// TODO: for backwards compatilbity with the AST, the
// type-condition's "on" is the start location.
return type.withMeta(type.meta().assoc(START, start));
}
IObj parseDirectiveDefinition() {
int topIndex = _stackTop;
Location start = startLocation();
next(); // "directive"
expect('@');
push(TAG, DIRECTIVE_DEFINITION);
Symbol name = parseName();
push(NAME, name);
IObj on = parseTypeConditionOpt();
if (on != null)
push(ON, on);
return nodeWithLoc(
start, (on == null ? name : on).meta().valAt(END),
pop(topIndex));
}
IObj parseExtendTypeDefinition() {
Location start = startLocation();
next(); // "extend"
return parseTypeDefinition(start, EXTEND_TYPE_DEFINITION);
}
IObj parseScalarDefinition() {
Location start = startLocation();
next(); // "scalar"
Symbol name = parseName();
return nodeWithLoc(
start, name.meta().valAt(END),
TAG, SCALAR_DEFINITION,
NAME, name);
}
IObj parseTypeSystemDefinition() {
if (TOKEN_IDENT == _token) {
switch (_image) {
case "type":
return parseTypeDefinition(startLocation(), TYPE_DEFINITION);
case "interface":
return parseInterfaceDefinition();
case "union":
return parseUnionDefinition();
case "schema":
return parseSchemaDefinition();
case "enum":
return parseEnumDefinition();
case "input":
return parseInputDefinition();
case "directive":
return parseDirectiveDefinition();
case "extend":
return parseExtendTypeDefinition();
case "scalar":
return parseScalarDefinition();
}
}
throw expectedError("'type', 'interface', 'union', 'schema', 'enum', 'input', "+
"'directive', 'extend', or 'scalar'");
}
private PersistentVector parseTypeSystemDefinitions() {
while (_token != TOKEN_EOF)
push(parseTypeSystemDefinition());
return popVec(0);
}
public IObj parseSchema() {
PersistentVector tsd = parseTypeSystemDefinitions();
Object start;
Object end;
return map(
TAG, SCHEMA,
TYPE_SYSTEM_DEFINITIONS, tsd);
}
private IObj parseSelection() {
if (TOKEN_IDENT == _token) {
int topIndex = _stackTop;
push(TAG, SELECTION_FIELD);
Symbol name = parseName();
Object start = name.meta().valAt(START);
Symbol alias = null;
if (':' == _token) {
next();
alias = name;
name = parseName();
push(ALIAS, alias);
}
push(NAME, name);
Object end = name.meta().valAt(END);
IObj arguments = null;
if ('(' == _token) {
arguments = parseVec('(', ')', this::parseArgument);
end = arguments.meta().valAt(END);
push(ARGUMENTS, arguments.withMeta(null));
}
IObj directives = parseDirectives();
if (directives != null) {
end = directives.meta().valAt(END);
push(DIRECTIVES, directives);
}
IObj sset = null;
if ('{' == _token) {
sset = parseSelectionSet();
end = sset.meta().valAt(END);
push(SELECTION_SET, sset.withMeta(null));
}
return nodeWithLoc(start, end, pop(topIndex));
} else if (TOKEN_ELLIPSIS == _token) {
int topIndex = _stackTop;
push(TAG, null); // null replaced later
Location start = startLocation();
next();
IObj on = null;
if (TOKEN_IDENT == _token) {
if ("on".equals(_image)) {
// TODO: convert this if block to parseTypeCondition
// note: that this is the correct way to populate `on`
on = parseTypeConditionOpt();
push(ON, on);
} else {
Symbol name = parseName();
push(NAME, name);
IObj directives = parseDirectives();
if (directives != null)
push(DIRECTIVES, directives);
_stack[topIndex+1] = FRAGMENT_SPREAD;
return nodeWithLoc(
start, (directives != null ? directives : name).meta().valAt(END),
pop(topIndex));
}
}
_stack[topIndex+1] = INLINE_FRAGMENT;
IObj directives = parseDirectives();
if (directives != null)
push(DIRECTIVES, directives);
IObj sset = parseSelectionSet();
push(SELECTION_SET, sset.withMeta(null));
return nodeWithLoc(start, sset.meta().valAt(END), pop(topIndex));
} else {
throw expectedError("field name or '...'");
}
}
private IObj parseSelectionSet() {
return parseVec('{', '}', this::parseSelection);
}
private IObj parseAnonymousQuery() {
IObj sset = parseSelectionSet();
return node(
sset.meta(),
TAG, SELECTION_SET,
SELECTION_SET, sset.withMeta(null)); // TODO: remove withMeta(null)
}
private IObj parseObjectField() {
Symbol name = parseName();
consume(':');
IObj value = parseValue();
return nodeWithLoc(
name.meta().valAt(START),
value.meta().valAt(END),
TAG, OBJECT_FIELD,
NAME, name,
VALUE, value);
}
private IObj parseVarRef() {
Location start = startLocation();
next();
Symbol name = parseName();
return nodeWithLoc(
start, name.meta().valAt(END),
TAG, VARIABLE_REFERENCE,
NAME, name);
}
private IObj parseObjectValue() {
IObj fields = parseVec('{', '}', this::parseObjectField);
return node(
fields.meta(),
TAG, OBJECT_VALUE,
FIELDS, fields.withMeta(null)); // TODO: remove withMeta(null)
}
private IObj parseListValue() {
IObj values = parseVec('[', ']', this::parseValue);
return node(
values.meta(),
TAG, LIST_VALUE,
VALUES, values.withMeta(null)); // TODO: remove withMeta(null)
}
private IObj parseValue() {
Keyword tag;
Object value;
switch (_token) {
case TOKEN_INTEGER:
tag = INT_VALUE;
value = Long.parseLong(_image, 10);
break;
case TOKEN_FLOAT:
tag = FLOAT_VALUE;
value = new Double(_image);
break;
case TOKEN_STRING:
tag = STRING_VALUE;
value = _stringValue.toString();
break;
case TOKEN_IDENT:
switch (_image) {
case "null":
tag = NULL_VALUE;
value = null;
break;
case "true":
tag = BOOLEAN_VALUE;
value = Boolean.TRUE;
break;
case "false":
tag = BOOLEAN_VALUE;
value = Boolean.FALSE;
break;
default:
tag = ENUM_VALUE;
value = Symbol.intern(_image);
break;
}
break;
case '$':
return parseVarRef();
case '[':
return parseListValue();
case '{':
return parseObjectValue();
default:
throw expectedError("value");
}
Location start = startLocation();
IObj end = location(_index);
String image = _image;
next();
return nodeWithLoc(
start, end,
TAG, tag,
IMAGE, image,
VALUE, value);
}
private IObj parseVariableDefinition() {
Location start = startLocation();
consume('$');
Symbol name = parseName();
consume(':');
IObj type = parseTypeRef();
if ('=' != _token) {
return nodeWithLoc(
start, type.meta().valAt(END),
TAG, VARIABLE_DEFINITION,
NAME, name,
TYPE, type);
} else {
next();
IObj defVal = parseValue();
return nodeWithLoc(
start, defVal.meta().valAt(END),
TAG, VARIABLE_DEFINITION,
NAME, name,
TYPE, type,
DEFAULT_VALUE, defVal);
}
}
private IObj parseArgument() {
Symbol name = parseName();
consume(':');
IObj value = parseValue();
return nodeWithLoc(
name.meta().valAt(START),
value.meta().valAt(END),
TAG, ARGUMENT,
NAME, name,
VALUE, value);
}
private IObj parseDirectives() {
if ('@' != _token)
return null;
Location firstStart = startLocation();
Object lastEnd;
int vecStart = _stackTop;
do {
int topIndex = _stackTop;
push(TAG, DIRECTIVE);
Location start = startLocation();
next();
Symbol name = parseName();
push(NAME, name);
Object end;
IObj arguments = null;
if ('(' == _token) {
arguments = parseVec('(', ')', this::parseArgument);
end = arguments.meta().valAt(END);
push(ARGUMENTS, arguments.withMeta(null));
} else {
end = name.meta().valAt(END);
}
push(nodeWithLoc(start, lastEnd = end, pop(topIndex)));
} while ('@' == _token);
return popVec(vecStart).withMeta(map(START, firstStart, END, lastEnd));
}
private IObj parseOperationDefinition(Keyword tag) {
int topIndex = _stackTop;
int i = 0;
push(TAG, tag);
Location start = startLocation();
next(); // "query" or "mutation"
Symbol name = null;
if (TOKEN_IDENT == _token) {
name = parseName();
push(NAME, name);
}
// optional
IObj varDefs = null;
if ('(' == _token) {
varDefs = parseVec('(', ')', this::parseVariableDefinition);
push(VARIABLE_DEFINITIONS, varDefs.withMeta(null));
}
IObj directives = parseDirectives();
if (directives != null)
push(DIRECTIVES, directives);
IObj sset = parseSelectionSet();
push(SELECTION_SET, sset.withMeta(null));
return nodeWithLoc(start, sset.meta().valAt(END), pop(topIndex));
}
private IObj parseFragmentDefinition() {
final int topIndex = _stackTop;
push(TAG, FRAGMENT_DEFINITION);
Location start = startLocation();
next(); // "fragment"
Symbol name = parseName();
push(NAME, name);
IObj on = parseTypeConditionOpt();
if (on != null)
push(ON, on);
IObj directives = parseDirectives();
if (directives != null)
push(DIRECTIVES, directives);
IObj sset = parseSelectionSet();
push(SELECTION_SET, sset.withMeta(null));
return nodeWithLoc(
start, sset.meta().valAt(END),
pop(topIndex));
}
private IObj parseQueryElement() {
if ('{' == _token) {
return parseAnonymousQuery();
} else if (TOKEN_IDENT == _token) {
switch (_image) {
case "query":
return parseOperationDefinition(QUERY_DEFINITION);
case "mutation":
return parseOperationDefinition(MUTATION);
case "fragment":
return parseFragmentDefinition();
}
}
throw expectedError("'{', 'query', 'mutation', or 'fragment'");
}
public IObj parseQueryDocument() {
while (_token != TOKEN_EOF)
push(parseQueryElement());
return popVec(0).withMeta(
map(START, new Location(1, 1, 0),
END, location(_index)));
}
} |
package be.raildelays.logger;
import be.raildelays.domain.dto.RouteLogDTO;
import be.raildelays.domain.dto.ServedStopDTO;
import be.raildelays.domain.entities.LineStop;
import be.raildelays.domain.entities.TimestampDelay;
import be.raildelays.domain.railtime.Direction;
import be.raildelays.domain.railtime.Step;
import be.raildelays.domain.railtime.Train;
import be.raildelays.domain.railtime.TwoDirections;
import be.raildelays.domain.xls.ExcelRow;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.joda.time.Duration;
import org.joda.time.LocalTime;
import org.slf4j.Marker;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class RaildelaysLogger implements Logger {
private static final int STATION_LENGTH = 12;
private static final int MESSAGE_LENGTH = 20;
private static final int PREFIX_LENGTH = 3;
private static final String ID_FORMAT = "000000";
private static final String TRAIN_FORMAT = "0000";
private static final String DELAY_FORMAT = "00";
private static final String DATE_FORMAT = "dd/MM/yyyy";
private static final String TIME_FORMAT = "HH:mm";
private static final int TOTAL_LENGTH = ID_FORMAT.length() + DATE_FORMAT.length() + 2 * TRAIN_FORMAT.length() +
2 * STATION_LENGTH + 4 * TIME_FORMAT.length() + 2 * ID_FORMAT.length() + 12;
private org.slf4j.Logger delegate;
private char separator = ' ';
private String type;
public RaildelaysLogger(String type, org.slf4j.Logger delegate) {
this.type = type;
this.delegate = delegate;
}
private enum Level {DEBUG, TRACE, INFO}
private class LogLineBuilder {
private String message;
private Long id;
private Date date;
private Long expectedTrain;
private Long effectiveTrain;
private String departureStation;
private String arrivalStation;
private Date expectedDepartureTime;
private Date expectedArrivalTime;
private Date effectiveDepartureTime;
private Date effectiveArrivalTime;
private Long idPrevious;
private Long idNext;
public LogLineBuilder message(String message) {
this.message = message;
return this;
}
public LogLineBuilder id(Long id) {
this.id = id;
return this;
}
public LogLineBuilder idPrevious(Long idPrevious) {
this.idPrevious = idPrevious;
return this;
}
public LogLineBuilder idNext(Long idNext) {
this.idNext = idNext;
return this;
}
public LogLineBuilder date(Date date) {
this.date = date;
return this;
}
public LogLineBuilder expectedTrain(Long expectedTrain) {
this.expectedTrain = expectedTrain;
return this;
}
public LogLineBuilder effectiveTrain(Long effectiveTrain) {
this.effectiveTrain = effectiveTrain;
return this;
}
public LogLineBuilder arrivalStation(String arrivalStation) {
this.arrivalStation = arrivalStation;
return this;
}
public LogLineBuilder departureStation(String departureStation) {
this.departureStation = departureStation;
return this;
}
public LogLineBuilder expectedDepartureTime(Date expectedDepartureTime) {
this.expectedDepartureTime = expectedDepartureTime;
return this;
}
public LogLineBuilder expectedArrivalTime(Date expectedArrivalTime) {
this.expectedArrivalTime = expectedArrivalTime;
return this;
}
public LogLineBuilder effectiveDepartureTime(Date effectiveDepartureTime) {
this.effectiveDepartureTime = effectiveDepartureTime;
return this;
}
public LogLineBuilder effectiveArrivalTime(Date effectiveArrivalTime) {
this.effectiveArrivalTime = effectiveArrivalTime;
return this;
}
public String build() {
final StringBuilder builder = new StringBuilder();
final NumberFormat idFormat = new DecimalFormat(ID_FORMAT);
final NumberFormat trainFormat = new DecimalFormat(TRAIN_FORMAT);
final NumberFormat delayFormat = new DecimalFormat(DELAY_FORMAT);
final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
final SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
if (expectedTrain != null ||
departureStation != null ||
expectedDepartureTime != null ||
effectiveDepartureTime != null) {
builder.append(StringUtils.rightPad(id != null ? idFormat.format(id) : "null", ID_FORMAT.length()));
builder.append(separator);
builder.append(StringUtils.rightPad(date != null ? dateFormat.format(date) : "", DATE_FORMAT.length()));
builder.append(separator);
builder.append(StringUtils.rightPad(expectedTrain != null ? trainFormat.format(expectedTrain) : "", TRAIN_FORMAT.length()));
builder.append(separator);
builder.append(StringUtils.rightPad(effectiveTrain != null ? trainFormat.format(effectiveTrain) : "", TRAIN_FORMAT.length()));
builder.append(separator);
builder.append(StringUtils.rightPad(departureStation != null ? substringCenter(departureStation, STATION_LENGTH, '~') : "", STATION_LENGTH));
builder.append(separator);
builder.append(StringUtils.rightPad(arrivalStation != null ? substringCenter(arrivalStation, STATION_LENGTH, '~') : "", STATION_LENGTH));
builder.append(separator);
builder.append(StringUtils.rightPad(expectedDepartureTime != null ? timeFormat.format(expectedDepartureTime) : "null", TIME_FORMAT.length()));
builder.append(separator);
builder.append(StringUtils.rightPad(expectedArrivalTime != null ? timeFormat.format(expectedArrivalTime) : "null", TIME_FORMAT.length()));
builder.append(separator);
builder.append(StringUtils.rightPad(effectiveDepartureTime != null ? timeFormat.format(effectiveDepartureTime) : "", TIME_FORMAT.length()));
builder.append(separator);
builder.append(StringUtils.rightPad(effectiveArrivalTime != null ? timeFormat.format(effectiveArrivalTime) : "", TIME_FORMAT.length()));
builder.append(separator);
builder.append(delayFormat.format(computeDelay()));
builder.append(separator);
builder.append(StringUtils.rightPad(idPrevious != null ? idFormat.format(idPrevious) : "", ID_FORMAT.length()));
builder.append(separator);
builder.append(StringUtils.rightPad(idNext != null ? idFormat.format(idNext) : "", ID_FORMAT.length()));
} else {
builder.append(StringUtils.rightPad("null", TOTAL_LENGTH));
}
builder.append(separator);
return builder.toString();
}
public String substringCenter(String characters, int length, char centerCharacter) {
String result = null;
if (characters != null) {
StringBuilder builder = new StringBuilder(length);
if (characters.length() <= length) {
result = characters;
} else {
builder.append(characters.substring(0, length - 4));
builder.append(centerCharacter);
builder.append(characters.substring(characters.length() - 3));
result = builder.toString();
}
}
return result;
}
private Long computeDelay() {
Long result = 0L;
if (expectedArrivalTime != null && effectiveArrivalTime != null) {
LocalTime expected = new LocalTime(expectedArrivalTime);
LocalTime effective = new LocalTime(effectiveArrivalTime);
Duration duration = new Duration(expected.toDateTimeToday(), effective.toDateTimeToday());
result = duration.getStandardMinutes();
}
return result;
}
}
private abstract class Delegator<T> {
public abstract String logLine(String message, T object);
public void log(String message, Level level, T object) {
final StringBuilder builder = new StringBuilder();
builder.append(separator);
builder.append(StringUtils.rightPad(type != null ? "[" + StringUtils.substring(type, 0, PREFIX_LENGTH) + "]" : "", PREFIX_LENGTH + 2));
builder.append(separator);
builder.append(StringUtils.rightPad(message != null ? StringUtils.substring(message, 0, MESSAGE_LENGTH) : "", MESSAGE_LENGTH));
builder.append(separator);
if (object != null) {
builder.append(logLine(message, object));
} else {
builder.append(StringUtils.rightPad("null", TOTAL_LENGTH));
}
switch (level) {
case DEBUG:
delegate.debug(builder.toString());
break;
case INFO:
delegate.info(builder.toString());
break;
case TRACE:
delegate.trace(builder.toString());
break;
}
}
public void log(String message, Level level, List<? extends T> objects) {
if (objects != null) {
for (int i = 0; i < objects.size(); i++) {
T object = objects.get(i);
log(message + "[" + i + "]", level, object);
}
}
}
}
private static Date computeEffectiveTime(TimestampDelay timestampDelay) {
Date result = null;
if (timestampDelay.getExpected() != null) {
result = DateUtils.addMinutes(timestampDelay.getExpected(),
timestampDelay.getDelay().intValue());
}
return result;
}
private Delegator<Direction> directionDelegator = new Delegator<Direction>() {
@Override
public String logLine(String message, Direction object) {
return new LogLineBuilder()
.message(object.getLibelle())
.expectedTrain(getTrainId(object.getTrain()))
.departureStation(object.getFrom() != null ? object.getFrom().getName() : null)
.arrivalStation(object.getTo() != null ? object.getTo().getName() : null)
.build();
}
};
private Delegator<Step> stepDelegator = new Delegator<Step>() {
@Override
public String logLine(String message, Step object) {
return new LogLineBuilder()
.message(message)
.departureStation(object.getStation() != null ? object.getStation().getName() : null)
.expectedDepartureTime(object.getTimestamp())
.effectiveDepartureTime(computeEffectiveTime(new TimestampDelay(object.getTimestamp(), object.getDelay())))
.build();
}
};
private Delegator<LineStop> lineStopDelegator = new Delegator<LineStop>() {
@Override
public String logLine(String message, LineStop object) {
return new LogLineBuilder()
.message(message)
.id(object.getId())
.date(object.getDate())
.expectedTrain(getTrainId(object.getTrain()))
.departureStation(object.getStation() != null ? object.getStation().getEnglishName() : null)
.expectedDepartureTime(object.getArrivalTime() != null ? object.getArrivalTime().getExpected() : null)
.expectedArrivalTime(object.getDepartureTime() != null ? object.getDepartureTime().getExpected() : null)
.effectiveDepartureTime(computeEffectiveTime(object.getArrivalTime()))
.effectiveArrivalTime(computeEffectiveTime(object.getDepartureTime()))
.idPrevious(object.getPrevious() != null ? object.getPrevious().getId() : null)
.idNext(object.getNext() != null ? object.getNext().getId() : null)
.build();
}
};
private Delegator<ExcelRow> excelRowDelegator = new Delegator<ExcelRow>() {
@Override
public String logLine(String message, ExcelRow object) {
return new LogLineBuilder()
.message(message)
.id(object.getId())
.date(object.getDate())
.expectedTrain(getTrainId(object.getExpectedTrain1()))
.effectiveTrain(getTrainId(object.getEffectiveTrain1()))
.departureStation(object.getDepartureStation() != null ? object.getDepartureStation().getEnglishName() : null)
.arrivalStation(object.getArrivalStation() != null ? object.getArrivalStation().getEnglishName() : null)
.expectedDepartureTime(object.getExpectedDepartureTime())
.expectedArrivalTime(object.getExpectedArrivalTime())
.effectiveDepartureTime(object.getEffectiveDepartureTime())
.effectiveArrivalTime(object.getEffectiveArrivalTime())
.build();
}
};
private static Long getTrainId(be.raildelays.domain.entities.Train train) {
Long result = null;
if (train != null && train.getEnglishName() != null) {
try {
result = Long.parseLong(train.getEnglishName());
} catch (NumberFormatException e) {
result = 0L;
}
}
return result;
}
private static Long getTrainId(Train train) {
Long result = null;
if (train != null && train.getIdRailtime() != null) {
try {
result = Long.parseLong(train.getIdRailtime());
} catch (NumberFormatException e) {
result = 0L;
}
}
return result;
}
private Delegator<RouteLogDTO> routeLogDTODelegator = new Delegator<RouteLogDTO>() {
@Override
public String logLine(String message, RouteLogDTO object) {
return new LogLineBuilder()
.message(message)
.date(object.getDate())
.expectedTrain(object.getTrainId() != null ? Long.parseLong(object.getTrainId()) : null)
.build();
}
};
private Delegator<ServedStopDTO> servedStopDTODelegator = new Delegator<ServedStopDTO>() {
@Override
public String logLine(String message, ServedStopDTO object) {
return new LogLineBuilder()
.message(message)
.departureStation(object.getStationName())
.expectedDepartureTime(object.getArrivalTime())
.expectedArrivalTime(object.getDepartureTime())
.effectiveDepartureTime(computeEffectiveTime(new TimestampDelay(object.getArrivalTime(), object.getArrivalDelay())))
.effectiveArrivalTime(computeEffectiveTime(new TimestampDelay(object.getDepartureTime(), object.getDepartureDelay())))
.build();
}
};
@Override
public void info(String message, LineStop lineStop) {
lineStopDelegator.log(message, Level.INFO, lineStop);
}
@Override
public void debug(String message, LineStop lineStop) {
lineStopDelegator.log(message, Level.DEBUG, lineStop);
}
@Override
public void trace(String message, LineStop lineStop) {
lineStopDelegator.log(message, Level.TRACE, lineStop);
}
@Override
public void info(String message, List<LineStop> lineStops) {
lineStopDelegator.log(message, Level.INFO, lineStops);
}
@Override
public void debug(String message, List<LineStop> lineStops) {
lineStopDelegator.log(message, Level.DEBUG, lineStops);
}
@Override
public void trace(String message, List<LineStop> lineStops) {
lineStopDelegator.log(message, Level.TRACE, lineStops);
}
@Override
public void info(String message, ExcelRow excelRow) {
excelRowDelegator.log(message, Level.INFO, excelRow);
}
@Override
public void debug(String message, ExcelRow excelRow) {
excelRowDelegator.log(message, Level.DEBUG, excelRow);
}
@Override
public void trace(String message, ExcelRow excelRow) {
excelRowDelegator.log(message, Level.TRACE, excelRow);
}
@Override
public void info(String message, RouteLogDTO routeLog) {
if (routeLog != null) {
routeLogDTODelegator.log(message, Level.INFO, routeLog);
servedStopDTODelegator.log("stops", Level.INFO, routeLog.getStops());
}
}
@Override
public void debug(String message, RouteLogDTO routeLog) {
if (routeLog != null) {
routeLogDTODelegator.log(message, Level.DEBUG, routeLog);
servedStopDTODelegator.log("stops", Level.DEBUG, routeLog.getStops());
}
}
@Override
public void trace(String message, RouteLogDTO routeLog) {
if (routeLog != null) {
routeLogDTODelegator.log(message, Level.TRACE, routeLog);
servedStopDTODelegator.log("stops", Level.TRACE, routeLog.getStops());
}
}
@Override
public void info(String message, TwoDirections twoDirections) {
if (twoDirections != null) {
if (twoDirections.getDeparture() != null) {
directionDelegator.log(message, Level.INFO, twoDirections.getDeparture());
stepDelegator.log(message, Level.INFO, twoDirections.getDeparture().getSteps());
}
if (twoDirections.getArrival() != null) {
directionDelegator.log(message, Level.INFO, twoDirections.getArrival());
stepDelegator.log(message, Level.INFO, twoDirections.getArrival().getSteps());
}
}
}
@Override
public void debug(String message, TwoDirections twoDirections) {
if (twoDirections != null) {
if (twoDirections.getDeparture() != null) {
directionDelegator.log(message, Level.DEBUG, twoDirections.getDeparture());
stepDelegator.log(message, Level.DEBUG, twoDirections.getDeparture().getSteps());
}
if (twoDirections.getArrival() != null) {
directionDelegator.log(message, Level.DEBUG, twoDirections.getArrival());
stepDelegator.log(message, Level.DEBUG, twoDirections.getArrival().getSteps());
}
}
}
@Override
public void trace(String message, TwoDirections twoDirections) {
if (twoDirections != null) {
if (twoDirections.getDeparture() != null) {
directionDelegator.log(message, Level.TRACE, twoDirections.getDeparture());
stepDelegator.log(message, Level.TRACE, twoDirections.getDeparture().getSteps());
}
if (twoDirections.getArrival() != null) {
directionDelegator.log(message, Level.TRACE, twoDirections.getArrival());
stepDelegator.log(message, Level.TRACE, twoDirections.getArrival().getSteps());
}
}
}
public void setDelegate(org.slf4j.Logger logger) {
this.delegate = logger;
}
public void setSeparator(char separator) {
this.separator = separator;
}
@Override
public String getName() {
return null;
}
@Override
public boolean isTraceEnabled() {
return false;
}
@Override
public void trace(String msg) {
}
@Override
public void trace(String format, Object arg) {
}
@Override
public void trace(String format, Object arg1, Object arg2) {
}
@Override
public void trace(String format, Object... arguments) {
}
@Override
public void trace(String msg, Throwable t) {
}
@Override
public boolean isTraceEnabled(Marker marker) {
return false;
}
@Override
public void trace(Marker marker, String msg) {
}
@Override
public void trace(Marker marker, String format, Object arg) {
}
@Override
public void trace(Marker marker, String format, Object arg1, Object arg2) {
}
@Override
public void trace(Marker marker, String format, Object... argArray) {
}
@Override
public void trace(Marker marker, String msg, Throwable t) {
}
@Override
public boolean isDebugEnabled() {
return false;
}
@Override
public void debug(String msg) {
}
@Override
public void debug(String format, Object arg) {
}
@Override
public void debug(String format, Object arg1, Object arg2) {
}
@Override
public void debug(String format, Object... arguments) {
}
@Override
public void debug(String msg, Throwable t) {
}
@Override
public boolean isDebugEnabled(Marker marker) {
return false;
}
@Override
public void debug(Marker marker, String msg) {
}
@Override
public void debug(Marker marker, String format, Object arg) {
}
@Override
public void debug(Marker marker, String format, Object arg1, Object arg2) {
}
@Override
public void debug(Marker marker, String format, Object... arguments) {
}
@Override
public void debug(Marker marker, String msg, Throwable t) {
}
@Override
public boolean isInfoEnabled() {
return delegate.isInfoEnabled();
}
@Override
public void info(String msg) {
delegate.info(msg);
}
@Override
public void info(String format, Object arg) {
delegate.info(format, arg);
}
@Override
public void info(String format, Object arg1, Object arg2) {
delegate.info(format, arg1, arg2);
}
@Override
public void info(String format, Object... arguments) {
delegate.info(format, arguments);
}
@Override
public void info(String msg, Throwable t) {
delegate.info(msg, t);
}
@Override
public boolean isInfoEnabled(Marker marker) {
return delegate.isInfoEnabled(marker);
}
@Override
public void info(Marker marker, String msg) {
delegate.info(marker, msg);
}
@Override
public void info(Marker marker, String format, Object arg) {
delegate.info(marker, format, arg);
}
@Override
public void info(Marker marker, String format, Object arg1, Object arg2) {
delegate.info(marker, format, arg1, arg2);
}
@Override
public void info(Marker marker, String format, Object... arguments) {
delegate.info(marker, format, arguments);
}
@Override
public void info(Marker marker, String msg, Throwable t) {
delegate.info(marker, msg, t);
}
@Override
public boolean isWarnEnabled() {
return delegate.isWarnEnabled();
}
@Override
public void warn(String msg) {
delegate.warn(msg);
}
@Override
public void warn(String format, Object arg) {
delegate.warn(format, arg);
}
@Override
public void warn(String format, Object... arguments) {
delegate.warn(format, arguments);
}
@Override
public void warn(String format, Object arg1, Object arg2) {
delegate.warn(format, arg1, arg2);
}
@Override
public void warn(String msg, Throwable t) {
delegate.warn(msg, t);
}
@Override
public boolean isWarnEnabled(Marker marker) {
return delegate.isWarnEnabled(marker);
}
@Override
public void warn(Marker marker, String msg) {
delegate.warn(marker, msg);
}
@Override
public void warn(Marker marker, String format, Object arg) {
delegate.warn(marker, format, arg);
}
@Override
public void warn(Marker marker, String format, Object arg1, Object arg2) {
delegate.warn(marker, format, arg1, arg2);
}
@Override
public void warn(Marker marker, String format, Object... arguments) {
delegate.warn(marker, format, arguments);
}
@Override
public void warn(Marker marker, String msg, Throwable t) {
delegate.warn(marker, msg, t);
}
@Override
public boolean isErrorEnabled() {
return delegate.isErrorEnabled();
}
@Override
public void error(String msg) {
delegate.error(msg);
}
@Override
public void error(String format, Object arg) {
delegate.error(format, arg);
}
@Override
public void error(String format, Object arg1, Object arg2) {
delegate.error(format, arg1, arg2);
}
@Override
public void error(String format, Object... arguments) {
delegate.error(format, arguments);
}
@Override
public void error(String msg, Throwable t) {
delegate.error(msg, t);
}
@Override
public boolean isErrorEnabled(Marker marker) {
return delegate.isErrorEnabled(marker);
}
@Override
public void error(Marker marker, String msg) {
delegate.error(marker, msg);
}
@Override
public void error(Marker marker, String format, Object arg) {
delegate.error(marker, format, arg);
}
@Override
public void error(Marker marker, String format, Object arg1, Object arg2) {
delegate.error(marker, format, arg1, arg2);
}
@Override
public void error(Marker marker, String format, Object... arguments) {
delegate.error(marker, format, arguments);
}
@Override
public void error(Marker marker, String msg, Throwable t) {
delegate.error(marker, msg, t);
}
} |
package ch.tutti.android.applover;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import java.util.Date;
import java.util.HashMap;
import ch.tutti.android.applover.criteria.AppLoverAllCustomEventsReached;
import ch.tutti.android.applover.criteria.AppLoverAppLaunchCriteria;
import ch.tutti.android.applover.criteria.AppLoverCriteria;
import ch.tutti.android.applover.criteria.AppLoverCriteriaBuilder;
import ch.tutti.android.applover.criteria.AppLoverFirstLaunchDaysCriteria;
/**
* Let users who like your app review it and those who don't write you an e-mail.
* That way you get positive reviews on Google Play and still hear about what users don't like.
*/
public class AppLover {
public static final int DIALOG_TYPE_FIRST = 0;
public static final int DIALOG_TYPE_RATE = 1;
public static final int DIALOG_TYPE_EMAIL = 2;
public static final String BUTTON_YES = "yes";
public static final String BUTTON_NO = "no";
public static final String BUTTON_LATER = "later";
private static final int DEFAULT_THRESHOLD = 10;
private static final int ONE_DAY = 24 * 60 * 60 * 1000;
private static AppLover INSTANCE;
private int mLaunchCountThreshold = DEFAULT_THRESHOLD;
private int mInstallDaysThreshold = DEFAULT_THRESHOLD;
private int mFirstLaunchDaysThreshold = DEFAULT_THRESHOLD;
private long mFirstLaunchDateTime;
private int mLaunchCount;
private int mAppNameResId;
private String mFeedbackEmail;
private AppLoverDialogStyle mStyle;
private HashMap<String, Integer> mCustomEventThresholdMap
= new HashMap<String, Integer>();
private OnTrackListener mOnTrackListener;
private AppLoverCriteria mShowDialogCriteria;
private AppLover() {
mShowDialogCriteria = new AppLoverCriteriaBuilder(
new AppLoverFirstLaunchDaysCriteria())
.and(new AppLoverAppLaunchCriteria())
.and(new AppLoverAllCustomEventsReached())
.build();
}
public static AppLover get(Context context) {
if (INSTANCE == null) {
INSTANCE = new AppLover();
AppLoverPreferences preferences = new AppLoverPreferences(context);
INSTANCE.mFirstLaunchDateTime = preferences.getFirstLaunchDate();
INSTANCE.mLaunchCount = preferences.getLaunchCount();
}
return INSTANCE;
}
public AppLover setAppName(int textResId) {
mAppNameResId = textResId;
return this;
}
public AppLoverDialogStyle getStyle() {
return mStyle == null ? new AppLoverDialogStyle() : mStyle;
}
public AppLover setStyle(AppLoverDialogStyle style) {
mStyle = style;
return this;
}
public String getFeedbackEmail() {
return mFeedbackEmail;
}
public AppLover setFeedbackEmail(String email) {
mFeedbackEmail = email;
return this;
}
/**
* Sets the listener for tracking/analytics purposes. This object will be kept around for a
* while. So do not register anything like an Activity/Fragment or similar.
*
* @param listener listener with tracking/analytics purpose callbacks
*/
public AppLover setOnTrackListener(OnTrackListener listener) {
mOnTrackListener = listener;
return this;
}
/**
* Set up a custom criteria for when the dialog should be shown.
* Default criteria is every criteria with AND. Setting criteria to null = no criteria. Which
* will show it at first opportunity.
*
* @param criteria criteria for the dialog to be shown
*/
public AppLover setShowDialogCriteria(AppLoverCriteria criteria) {
mShowDialogCriteria = criteria;
return this;
}
public AppLover setLaunchCountThreshold(final int launchTimesThreshold) {
mLaunchCountThreshold = launchTimesThreshold;
return this;
}
public int getLaunchCountThreshold() {
return mLaunchCountThreshold;
}
public AppLover setInstallDaysThreshold(int installDaysThreshold) {
mInstallDaysThreshold = installDaysThreshold;
return this;
}
public int getInstallDaysThreshold() {
return mInstallDaysThreshold;
}
public AppLover setFirstLaunchDaysThreshold(final int installDaysThreshold) {
mFirstLaunchDaysThreshold = installDaysThreshold;
return this;
}
public int getFirstLaunchDaysThreshold() {
return mFirstLaunchDaysThreshold;
}
public AppLover setCustomEventCountThreshold(String event, int eventCountThreshold) {
mCustomEventThresholdMap.put(event, eventCountThreshold);
return this;
}
public HashMap<String, Integer> getCustomEventCountThresholds() {
return mCustomEventThresholdMap;
}
public int getCustomEventCountThreshold(String event) {
Integer threshold = mCustomEventThresholdMap.get(event);
return threshold == null ? DEFAULT_THRESHOLD : threshold;
}
/**
* Increase launch count.<br/>
* Call this method in the MAIN Activity's onCreate() method.
*
* @param context context
*/
public void monitorLaunch(final Context context) {
AppLoverPreferences preferences = new AppLoverPreferences(context);
if (mFirstLaunchDateTime == 0) {
mFirstLaunchDateTime = new Date().getTime();
preferences.setFirstLaunchDate(mFirstLaunchDateTime);
}
mLaunchCount = preferences.incLaunchCount();
}
/**
* Increase count of occurrence of custom event. Call whenever custom event occurs.
*
* @param context context
* @param event name of the custom event
*/
public void monitorCustomEvent(Context context, String event) {
new AppLoverPreferences(context).incCustomEventCount(event);
}
/**
* Show feedback dialog if conditions are met.
*
* @param activity activity
*/
public void showDialogIfConditionsMet(final Activity activity) {
if (shouldShowRateDialog(activity) && !AppLoverDialogHelper.isDialogShown(activity)) {
AppLoverDialogHelper.showDialog(
activity, AppLover.DIALOG_TYPE_FIRST, getAppNameResId(activity));
}
}
private int getAppNameResId(Context context) {
return mAppNameResId == 0 ? context.getApplicationInfo().labelRes : mAppNameResId;
}
private boolean shouldShowRateDialog(Context context) {
AppLoverPreferences preferences = new AppLoverPreferences(context);
boolean stillShow = !(preferences.isDoNotShowAnymore());
return stillShow &&
(mShowDialogCriteria == null
|| mShowDialogCriteria.isCriteriaMet(context, this, preferences));
}
public int getLaunchCount() {
return mLaunchCount;
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public int getInstalledDays(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
try {
long installedTime = System.currentTimeMillis() -
context.getPackageManager().getPackageInfo(context.getPackageName(), 0)
.firstInstallTime;
return (int) (installedTime / ONE_DAY);
} catch (PackageManager.NameNotFoundException e) {
return getDaysSinceFirstLaunch();
}
} else {
return getDaysSinceFirstLaunch();
}
}
public int getDaysSinceFirstLaunch() {
if (mFirstLaunchDateTime == 0) {
return 0;
}
return (int) ((new Date().getTime() - mFirstLaunchDateTime) / ONE_DAY);
}
public int getCustomEventCount(Context context, String event) {
return new AppLoverPreferences(context).getCustomEventCount(event);
}
public boolean isDoNotShowAnymore(Context context) {
return new AppLoverPreferences(context).isDoNotShowAnymore();
}
public void trackDialogShown(int dialogType) {
if (mOnTrackListener != null) {
mOnTrackListener.onTrackDialogShown(dialogType);
}
}
public void trackDialogCanceled(int dialogType) {
if (mOnTrackListener != null) {
mOnTrackListener.onTrackDialogCanceled(dialogType);
}
}
public void trackDialogButtonPressed(int dialogType, String button) {
if (mOnTrackListener != null) {
mOnTrackListener.onTrackDialogButtonPressed(dialogType, button);
}
}
/**
* Reset the statistics and start at 0.
*/
public void reset(Context context) {
mFirstLaunchDateTime = 0;
mLaunchCount = 0;
new AppLoverPreferences(context).clear();
}
public static interface OnTrackListener {
/**
* Called when a dialog is shown.
*
* @param dialogType {@link ch.tutti.android.applover.AppLover#DIALOG_TYPE_FIRST},
* {@link ch.tutti.android.applover.AppLover#DIALOG_TYPE_RATE} or
* {@link ch.tutti.android.applover.AppLover#DIALOG_TYPE_EMAIL}
*/
void onTrackDialogShown(int dialogType);
/**
* Called when the dialog gets cancelled through the back button.
*
* @param dialogType {@link ch.tutti.android.applover.AppLover#DIALOG_TYPE_FIRST},
* {@link ch.tutti.android.applover.AppLover#DIALOG_TYPE_RATE} or
* {@link ch.tutti.android.applover.AppLover#DIALOG_TYPE_EMAIL}
*/
void onTrackDialogCanceled(int dialogType);
/**
* Called when user clicks on a button of the dialog.
*
* @param dialogType {@link ch.tutti.android.applover.AppLover#DIALOG_TYPE_FIRST},
* {@link ch.tutti.android.applover.AppLover#DIALOG_TYPE_RATE} or
* {@link ch.tutti.android.applover.AppLover#DIALOG_TYPE_EMAIL}
* @param button {@link ch.tutti.android.applover.AppLover#BUTTON_YES},
* {@link ch.tutti.android.applover.AppLover#BUTTON_NO} or
* {@link ch.tutti.android.applover.AppLover#BUTTON_LATER}
*/
void onTrackDialogButtonPressed(int dialogType, String button);
}
} |
package prefuse;
public interface Constants {
/** A left-to-right layout orientation */
public static final int ORIENT_LEFT_RIGHT = 0;
/** A right-to-left layout orientation */
public static final int ORIENT_RIGHT_LEFT = 1;
/** A top-to-bottom layout orientation */
public static final int ORIENT_TOP_BOTTOM = 2;
/** A bottom-to-top layout orientation */
public static final int ORIENT_BOTTOM_TOP = 3;
/** A centered layout orientation */
public static final int ORIENT_CENTER = 4;
/** The total number of orientation values */
public static final int ORIENTATION_COUNT = 5;
/** A left alignment */
public static final int LEFT = 0;
/** A right alignment */
public static final int RIGHT = 1;
/** A center alignment */
public static final int CENTER = 2;
/** A bottom alignment */
public static final int BOTTOM = 3;
/** A top alignment */
public static final int TOP = 4;
/** A left alignment, outside of bounds */
public static final int FAR_LEFT = 5;
/** A right alignment, outside of bounds */
public static final int FAR_RIGHT = 6;
/** A bottom alignment, outside of bounds */
public static final int FAR_BOTTOM = 7;
/** A top alignment, outside of bounds */
public static final int FAR_TOP = 8;
/** A straight-line edge type */
public static final int EDGE_TYPE_LINE = 0;
/** A curved-line edge type */
public static final int EDGE_TYPE_CURVE = 1;
/** The total number of edge type values */
public static final int EDGE_TYPE_COUNT = 2;
/** No arrows on edges */
public static final int EDGE_ARROW_NONE = 0;
/** Arrows on edges pointing from source to target */
public static final int EDGE_ARROW_FORWARD = 1;
/** Arrows on edges pointing from target to source */
public static final int EDGE_ARROW_REVERSE = 2;
/** The total number of edge arrow type values */
public static final int EDGE_ARROW_COUNT = 3;
/** Use straight-lines for polygon edges */
public static final int POLY_TYPE_LINE = EDGE_TYPE_LINE;
/** Use curved-lines for polygon edges */
public static final int POLY_TYPE_CURVE = EDGE_TYPE_CURVE;
/** Use curved-lines for polygon edges,
* but use straight lines for zero-slope edges */
public static final int POLY_TYPE_STACK = 2;
/** The total number of polygon type values */
public static final int POLY_TYPE_COUNT = 3;
/** A linear scale */
public static final int LINEAR_SCALE = 0;
/** A logarithmic (base 10) scale */
public static final int LOG_SCALE = 1;
/** A square root scale */
public static final int SQRT_SCALE = 2;
/** A quantile scale, based on the underlying distribution */
public static final int QUANTILE_SCALE = 3;
/** The total number of scale type values */
public static final int SCALE_COUNT = 4;
/** An unknown data type */
public static final int UNKNOWN = -1;
/** A nominal (categorical) data type */
public static final int NOMINAL = 0;
/** An ordinal (ordered) data type */
public static final int ORDINAL = 1;
/** A numerical (quantitative) data type */
public static final int NUMERICAL = 2;
/** The total number of data type values */
public static final int DATATYPE_COUNT = 3;
/** Indicates the horizontal (X) axis */
public static final int X_AXIS = 0;
/** Indicates the vertical (Y) axis */
public static final int Y_AXIS = 1;
/** The total number of axis type values */
public static final int AXIS_COUNT = 2;
public static final int NODE_TRAVERSAL = 0;
public static final int EDGE_TRAVERSAL = 1;
public static final int NODE_AND_EDGE_TRAVERSAL = 2;
/** The total number of traversal type values */
public static final int TRAVERSAL_COUNT = 3;
/** Indicates a continuous (non-discrete) spectrum */
public static final int CONTINUOUS = -1;
/** The absolute minimum degree-of-interest (DOI) value */
public static final double MINIMUM_DOI = -Double.MAX_VALUE;
/** No shape. Draw nothing. */
public static final int SHAPE_NONE = -1;
/** Rectangle/Square shape */
public static final int SHAPE_RECTANGLE = 0;
/** Ellipse/Circle shape */
public static final int SHAPE_ELLIPSE = 1;
/** Diamond shape */
public static final int SHAPE_DIAMOND = 2;
/** Cross shape */
public static final int SHAPE_CROSS = 3;
/** Star shape */
public static final int SHAPE_STAR = 4;
/** Up-pointing triangle shape */
public static final int SHAPE_TRIANGLE_UP = 5;
/** Down-pointing triangle shape */
public static final int SHAPE_TRIANGLE_DOWN = 6;
/** Left-pointing triangle shape */
public static final int SHAPE_TRIANGLE_LEFT = 7;
/** Right-pointing triangle shape */
public static final int SHAPE_TRIANGLE_RIGHT = 8;
/** Hexagon shape */
public static final int SHAPE_HEXAGON = 9;
/** The number of recognized shape types */
public static final int SHAPE_COUNT = 10;
} // end of interface Constants |
package com.haohaohu.cachemanage;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.LruCache;
import com.google.gson.Gson;
import com.haohaohu.cachemanage.observer.CacheObserver;
import com.haohaohu.cachemanage.util.Base64Util;
import com.haohaohu.cachemanage.util.LockUtil;
import com.haohaohu.cachemanage.util.Md5Utils;
import java.io.ByteArrayOutputStream;
import java.lang.ref.SoftReference;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
*
*
* @author haohao on 2017/6/9 14:56
* @version v1.1
*/
public class CacheUtil {
private CacheUtilConfig mConfig;
private SoftReference<LruCache<String, String>> mLuCache =
new SoftReference<>(new LruCache<String, String>(50));
private static CacheUtil getInstance() {
return CacheUtilHolder.mInstance;
}
/**
*
*
* @param config
*/
public static void init(CacheUtilConfig config) {
if (config == null) {
throw new NullPointerException("u should Builder first");
}
getInstance().mConfig = config;
}
protected static CacheUtilConfig getConfig() {
if (getInstance().mConfig == null) {
throw new NullPointerException("u should Builder first");
}
return getInstance().mConfig;
}
/**
* ApplicationContext
*
* @return ApplicationContext
*/
private static Context getContext() {
if (getConfig().getContext() != null) {
return getConfig().getContext();
}
throw new NullPointerException("u should init first");
}
/**
* LruCache,
*/
private static LruCache<String, String> getLruCache() {
LruCache<String, String> lruCache = getInstance().mLuCache.get();
if (lruCache == null) {
getInstance().mLuCache = new SoftReference<>(new LruCache<String, String>(50));
lruCache = getInstance().mLuCache.get();
}
return lruCache;
}
/**
* keyvalue
*
* @param key key
* @param value value
*/
public static void put(String key, @NonNull String value) {
put(key, value, getConfig().isEncrypt());
}
/**
* keyvalue
*
* @param key key
* @param value value
* @param isEncrypt
*/
public static void put(String key, @NonNull String value, boolean isEncrypt) {
if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) {
return;
}
LockUtil.getInstance().writeLock().lock();
if (getConfig().isKeyEncrypt()) {
key = translateSecretKey(key);
}
if (getConfig().isMemoryCache()) {
getLruCache().put(key, value);
}
getConfig().getACache().put(key, value, isEncrypt);
CacheObserver.getInstance().notifyDataChange(key, value);
LockUtil.getInstance().writeLock().unlock();
}
/**
* keyvalue
*
* @param key key
* @param value value
* @param time
*/
public static void put(String key, @NonNull String value, int time) {
put(key, value, time, getConfig().isEncrypt());
}
/**
* keyvalue
*
* @param key key
* @param value value
* @param time
* @param isEncrypt
*/
public static void put(String key, @NonNull String value, int time, boolean isEncrypt) {
if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) {
return;
}
LockUtil.getInstance().writeLock().lock();
if (getConfig().isKeyEncrypt()) {
key = translateSecretKey(key);
}
if (getConfig().isMemoryCache()) {
getLruCache().put(key, Utils.newStringWithDateInfo(time, value));
}
getConfig().getACache().put(key, value, time, isEncrypt);
CacheObserver.getInstance().notifyDataChange(key, value);
LockUtil.getInstance().writeLock().unlock();
}
/**
* keyvalue
*
* @param key key
* @param value value
* @param <T>
*/
public static <T> void put(String key, @NonNull T value) {
put(key, value, getConfig().isEncrypt());
}
/**
* keyvalue
*
* @param <T>
* @param key key
* @param value value
* @param isEncrypt
*/
public static <T> void put(String key, @NonNull T value, boolean isEncrypt) {
if (TextUtils.isEmpty(key)) {
return;
}
Gson gson = new Gson();
String date;
if (value instanceof JSONObject) {
date = value.toString();
} else if (value instanceof JSONArray) {
date = value.toString();
} else {
date = gson.toJson(value);
}
put(key, date, isEncrypt);
}
/**
* keyvalue
*
* @param <T>
* @param key key
* @param value value
* @param time
*/
public static <T> void put(String key, @NonNull T value, int time) {
put(key, value, time, getConfig().isEncrypt());
}
/**
* keyvalue
*
* @param <T>
* @param key key
* @param value value
* @param time
* @param isEncrypt
*/
public static <T> void put(String key, @NonNull T value, int time, boolean isEncrypt) {
if (TextUtils.isEmpty(key)) {
return;
}
Gson gson = new Gson();
String date;
if (value instanceof JSONObject) {
date = value.toString();
} else if (value instanceof JSONArray) {
date = value.toString();
} else {
date = gson.toJson(value);
}
put(key, date, time, isEncrypt);
}
/**
* keyvalue
*
*
* @param key key
* @return value
*/
@Nullable
public static String get(String key) {
return get(key, getConfig().isEncrypt());
}
/**
* keyvalue
*
*
* @param key key
* @param isEncrypt
* @return value
*/
@Nullable
public static String get(String key, boolean isEncrypt) {
if (TextUtils.isEmpty(key)) {
return "";
}
try {
LockUtil.getInstance().readLock().lock();
if (getConfig().isKeyEncrypt()) {
key = translateSecretKey(key);
}
String value;
if (getConfig().isMemoryCache()) {
value = getLruCache().get(key);
if (!TextUtils.isEmpty(value)) {
if (!Utils.isDue(value)) {
return Utils.clearDateInfo(value);
} else {
getLruCache().remove(key);
return "";
}
}
}
value = getConfig().getACache().getAsString(key, isEncrypt);
if (!TextUtils.isEmpty(value)) {
if (getConfig().isMemoryCache()) {
getLruCache().put(key,
getConfig().getACache().getAsStringHasDate(key, isEncrypt));
}
return value;
}
return "";
} catch (Exception e) {
return "";
} finally {
LockUtil.getInstance().readLock().unlock();
}
}
/**
* key
*
*
* @param key key
* @param classOfT
* @param <T>
* @return
*/
@Nullable
public static <T> T get(String key, Class<T> classOfT) {
return get(key, classOfT, getConfig().isEncrypt());
}
/**
* key
*
*
* @param <T>
* @param key key
* @param classOfT
* @param isEncrypt
* @return
*/
@Nullable
public static <T> T get(String key, Class<T> classOfT, boolean isEncrypt) {
if (TextUtils.isEmpty(key) || classOfT == null) {
return null;
}
try {
LockUtil.getInstance().readLock().lock();
if (getConfig().isKeyEncrypt()) {
key = translateSecretKey(key);
}
Gson gson = new Gson();
String value;
if (getConfig().isMemoryCache()) {
value = getLruCache().get(key);
if (!TextUtils.isEmpty(value)) {
if (!Utils.isDue(value)) {
return gson.fromJson(Utils.clearDateInfo(value), classOfT);
} else {
getLruCache().remove(key);
try {
return classOfT.newInstance();
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
}
}
value = getConfig().getACache().getAsString(key, isEncrypt);
if (!TextUtils.isEmpty(value)) {
if (getConfig().isMemoryCache()) {
getLruCache().put(key,
getConfig().getACache().getAsStringHasDate(key, isEncrypt));
}
return gson.fromJson(value, classOfT);
}
return classOfT.newInstance();
} catch (Exception e) {
return null;
} finally {
LockUtil.getInstance().readLock().unlock();
}
}
/**
* key
*
*
* @param <T>
* @param key key
* @param classOfT
* @param t
* @return
*/
public static <T> T get(String key, Class<T> classOfT, T t) {
return get(key, classOfT, t, getConfig().isEncrypt());
}
/**
* key
*
*
* @param <T>
* @param key key
* @param classOfT
* @param t
* @param isEncrypt
* @return
*/
public static <T> T get(String key, Class<T> classOfT, @NonNull T t, boolean isEncrypt) {
if (TextUtils.isEmpty(key) || classOfT == null) {
return t;
}
try {
LockUtil.getInstance().readLock().lock();
Gson gson = new Gson();
String value;
if (getConfig().isKeyEncrypt()) {
key = translateSecretKey(key);
}
if (getConfig().isMemoryCache()) {
value = getLruCache().get(key);
if (!TextUtils.isEmpty(value)) {
if (!Utils.isDue(value)) {
return gson.fromJson(Utils.clearDateInfo(value), classOfT);
} else {
getLruCache().remove(key);
return t;
}
}
}
value = getConfig().getACache().getAsString(key, isEncrypt);
if (!TextUtils.isEmpty(value)) {
if (getConfig().isMemoryCache()) {
getLruCache().put(key,
getConfig().getACache().getAsStringHasDate(key, isEncrypt));
}
return gson.fromJson(value, classOfT);
}
return t;
} catch (Exception e) {
return t;
} finally {
LockUtil.getInstance().readLock().unlock();
}
}
/**
* key
*
* @param key key
*/
public static void clear(String key) {
if (TextUtils.isEmpty(key)) {
return;
}
if (getConfig().isKeyEncrypt()) {
key = translateSecretKey(key);
}
LockUtil.getInstance().writeLock().lock();
getLruCache().remove(key);
getConfig().getACache().remove(key);
LockUtil.getInstance().writeLock().unlock();
}
/**
* key
*
* @param key key
*/
public static void clearMemory(@NonNull String key) {
if (TextUtils.isEmpty(key)) {
return;
}
if (getConfig().isKeyEncrypt()) {
key = translateSecretKey(key);
}
getLruCache().remove(key);
}
public static void clearAllMemory() {
getLruCache().evictAll();
}
public static void clearAll() {
getLruCache().evictAll();
getConfig().getACache().clear();
}
public static String translateKey(@NonNull String key) {
return "." + Base64Util.encode(key.getBytes());
}
/**
* keyMd5
*/
public static String translateSecretKey(@NonNull String key) {
return Md5Utils.md5(key);
}
private static class CacheUtilHolder {
private static CacheUtil mInstance = new CacheUtil();
}
/**
*
*
* @author michael
* @version 1.0
*/
private static class Utils {
private static final char SEPARATOR = ' ';
/**
* String
*
* @param str str
* @return true false
*/
private static boolean isDue(String str) {
return isDue(str.getBytes());
}
/**
* byte
*
* @param data data
* @return true false
*/
private static boolean isDue(byte[] data) {
String[] strs = getDateInfoFromDate(data);
if (strs != null && strs.length == 2) {
String saveTimeStr = strs[0];
while (saveTimeStr.startsWith("0")) {
saveTimeStr = saveTimeStr.substring(1, saveTimeStr.length());
}
long saveTime = Long.valueOf(saveTimeStr);
long deleteAfter = Long.valueOf(strs[1]);
if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) {
return true;
}
}
return false;
}
private static String newStringWithDateInfo(int second, String strInfo) {
return createDateInfo(second) + strInfo;
}
private static byte[] newByteArrayWithDateInfo(int second, byte[] data2) {
byte[] data1 = createDateInfo(second).getBytes();
byte[] retdata = new byte[data1.length + data2.length];
System.arraycopy(data1, 0, retdata, 0, data1.length);
System.arraycopy(data2, 0, retdata, data1.length, data2.length);
return retdata;
}
private static String clearDateInfo(String strInfo) {
if (strInfo != null && hasDateInfo(strInfo.getBytes())) {
strInfo = strInfo.substring(strInfo.indexOf(SEPARATOR) + 1, strInfo.length());
}
return strInfo;
}
private static byte[] clearDateInfo(byte[] data) {
if (hasDateInfo(data)) {
return copyOfRange(data, indexOf(data, SEPARATOR) + 1, data.length);
}
return data;
}
private static boolean hasDateInfo(byte[] data) {
return data != null
&& data.length > 15
&& data[13] == '-'
&& indexOf(data, SEPARATOR) > 14;
}
private static String[] getDateInfoFromDate(byte[] data) {
if (hasDateInfo(data)) {
String saveDate = new String(copyOfRange(data, 0, 13));
String deleteAfter = new String(copyOfRange(data, 14, indexOf(data, SEPARATOR)));
return new String[] { saveDate, deleteAfter };
}
return null;
}
private static int indexOf(byte[] data, char c) {
for (int i = 0; i < data.length; i++) {
if (data[i] == c) {
return i;
}
}
return -1;
}
private static byte[] copyOfRange(byte[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0) {
throw new IllegalArgumentException(from + " > " + to);
}
byte[] copy = new byte[newLength];
System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength));
return copy;
}
private static String createDateInfo(int second) {
StringBuilder currentTime = new StringBuilder(System.currentTimeMillis() + "");
while (currentTime.length() < 13) {
currentTime.insert(0, "0");
}
return currentTime + "-" + second + SEPARATOR;
}
private static byte[] bitmap2Bytes(Bitmap bm) {
if (bm == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
private static Bitmap bytes2Bimap(byte[] b) {
if (b.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
private static Bitmap drawable2Bitmap(Drawable drawable) {
if (drawable == null) {
return null;
}
// drawable
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
// drawable
Bitmap.Config config =
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
// bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// bitmap
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// drawable
drawable.draw(canvas);
return bitmap;
}
@SuppressWarnings("deprecation")
private static Drawable bitmap2Drawable(Bitmap bm) {
if (bm == null) {
return null;
}
return new BitmapDrawable(bm);
}
}
} |
package net.somethingdreadful.MAL;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.crashlytics.android.Crashlytics;
import net.somethingdreadful.MAL.adapters.DetailViewPagerAdapter;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.MALApi.ListType;
import net.somethingdreadful.MAL.api.response.Anime;
import net.somethingdreadful.MAL.api.response.GenericRecord;
import net.somethingdreadful.MAL.api.response.Manga;
import net.somethingdreadful.MAL.dialog.RemoveConfirmationDialogFragment;
import net.somethingdreadful.MAL.dialog.UpdatePasswordDialogFragment;
import net.somethingdreadful.MAL.sql.DatabaseManager;
import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener;
import net.somethingdreadful.MAL.tasks.NetworkTask;
import net.somethingdreadful.MAL.tasks.NetworkTaskCallbackListener;
import net.somethingdreadful.MAL.tasks.TaskJob;
import net.somethingdreadful.MAL.tasks.WriteDetailTask;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Locale;
public class DetailView extends ActionBarActivity implements Serializable, NetworkTaskCallbackListener, APIAuthenticationErrorListener, SwipeRefreshLayout.OnRefreshListener {
public ListType type;
public Anime animeRecord;
public Manga mangaRecord;
public String username;
public DetailViewGeneral general;
public DetailViewDetails details;
public DetailViewPersonal personal;
DetailViewPagerAdapter PageAdapter;
int recordID;
private ActionBar actionBar;
private ViewPager viewPager;
private ViewFlipper viewFlipper;
private Menu menu;
private Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailview);
actionBar = getSupportActionBar();
context = getApplicationContext();
username = getIntent().getStringExtra("username");
type = (ListType) getIntent().getSerializableExtra("recordType");
recordID = getIntent().getIntExtra("recordID", -1);
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
viewPager = (ViewPager) findViewById(R.id.pager);
viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
PageAdapter = new DetailViewPagerAdapter(getFragmentManager(), this);
viewPager.setAdapter(PageAdapter);
if (savedInstanceState != null) {
animeRecord = (Anime) savedInstanceState.getSerializable("anime");
mangaRecord = (Manga) savedInstanceState.getSerializable("manga");
}
}
/*
* Set text in all fragments
*/
public void setText() {
try {
actionBar.setTitle(type == ListType.ANIME ? animeRecord.getTitle() : mangaRecord.getTitle());
if (general != null) {
general.setText();
}
if (details != null && !isEmpty()) {
details.setText();
}
if (personal != null && !isEmpty()) {
personal.setText();
}
if (!isEmpty()) {
setupBeam();
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.setText(): " + e.getMessage());
if (!(e instanceof IllegalStateException))
Crashlytics.logException(e);
}
setMenu();
}
/*
* show or hide the personal card
*/
public void hidePersonal(boolean hide) {
PageAdapter.count = hide ? 2 : 3;
PageAdapter.notifyDataSetChanged();
}
/*
* Checks if the records are null to prevent nullpointerexceptions
*/
public boolean isEmpty() {
return animeRecord == null && mangaRecord == null;
}
/*
* Checks if this record is in our list
*/
public boolean isAdded() {
return !isEmpty() && (ListType.ANIME.equals(type) ? animeRecord.getWatchedStatus() != null : mangaRecord.getReadStatus() != null);
}
/*
* Set refreshing on all SwipeRefreshViews
*/
public void setRefreshing(Boolean show) {
if (general != null) {
general.swipeRefresh.setRefreshing(show);
general.swipeRefresh.setEnabled(!show);
}
if (details != null) {
details.swipeRefresh.setRefreshing(show);
details.swipeRefresh.setEnabled(!show);
}
if (personal != null) {
personal.swipeRefresh.setRefreshing(show);
personal.swipeRefresh.setEnabled(!show);
}
}
/*
* Show the dialog with the tag
*/
public void showDialog(String tag, DialogFragment dialog) {
FragmentManager fm = getFragmentManager();
dialog.show(fm, "fragment_" + tag);
}
/*
* Show the dialog with the tag
*/
public void showDialog(String tag, DialogFragment dialog, Bundle args) {
FragmentManager fm = getFragmentManager();
dialog.setArguments(args);
dialog.show(fm, "fragment_" + tag);
}
/*
* Episode picker dialog
*/
public void onDialogDismissed(int newValue) {
if (newValue != animeRecord.getWatchedEpisodes()) {
if (newValue == animeRecord.getEpisodes()) {
animeRecord.setWatchedStatus(GenericRecord.STATUS_COMPLETED);
}
if (newValue == 0) {
animeRecord.setWatchedStatus(Anime.STATUS_PLANTOWATCH);
}
animeRecord.setWatchedEpisodes(newValue);
animeRecord.setDirty(true);
setText();
}
}
/*
* Date picker dialog
*/
public void onDialogDismissed(boolean startDate, int year, int month, int day) {
String monthString = Integer.toString(month);
if (monthString.length() == 1)
monthString = "0" + monthString;
String dayString = Integer.toString(day);
if (dayString.length() == 1)
dayString = "0" + dayString;
if (type.equals(ListType.ANIME)) {
if (startDate)
animeRecord.setWatchingStart(Integer.toString(year) + "-" + monthString + "-" + dayString);
else
animeRecord.setWatchingEnd(Integer.toString(year) + "-" + monthString + "-" + dayString);
animeRecord.setDirty(true);
} else {
if (startDate)
mangaRecord.setReadingStart(Integer.toString(year) + "-" + monthString + "-" + dayString);
else
mangaRecord.setReadingEnd(Integer.toString(year) + "-" + monthString + "-" + dayString);
mangaRecord.setDirty(true);
}
setText();
}
/*
* Set the right menu items.
*/
public void setMenu() {
if (menu != null) {
if (isAdded()) {
menu.findItem(R.id.action_Remove).setVisible(!isEmpty() && MALApi.isNetworkAvailable(this));
menu.findItem(R.id.action_addToList).setVisible(false);
} else {
menu.findItem(R.id.action_Remove).setVisible(false);
menu.findItem(R.id.action_addToList).setVisible(!isEmpty());
}
menu.findItem(R.id.action_Share).setVisible(!isEmpty());
menu.findItem(R.id.action_ViewMALPage).setVisible(!isEmpty());
}
}
/*
* Add record to list
*/
public void addToList() {
if (!isEmpty()) {
if (type.equals(ListType.ANIME)) {
animeRecord.setCreateFlag(true);
animeRecord.setWatchedStatus(Anime.STATUS_WATCHING);
animeRecord.setDirty(true);
} else {
mangaRecord.setCreateFlag(true);
mangaRecord.setReadStatus(Manga.STATUS_READING);
mangaRecord.setDirty(true);
}
setText();
}
}
/*
* Open the share dialog
*/
public void Share() {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
sharingIntent.putExtra(Intent.EXTRA_TEXT, makeShareText());
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
/*
* Make the share text for the share dialog
*/
public String makeShareText() {
String shareText = PrefManager.getCustomShareText();
shareText = shareText.replace("$title;", actionBar.getTitle());
shareText = shareText.replace("$link;", "http://myanimelist.net/" + type.toString().toLowerCase(Locale.US) + "/" + Integer.toString(recordID));
shareText = shareText + getResources().getString(R.string.customShareText_fromAtarashii);
return shareText;
}
/*
* Check if the database contains the record.
*
* If it does contains the record it will set it.
*/
private boolean getRecordFromDB() {
DatabaseManager dbMan = new DatabaseManager(this);
if (type.equals(ListType.ANIME)) {
animeRecord = dbMan.getAnime(recordID, username);
return animeRecord != null;
} else {
mangaRecord = dbMan.getManga(recordID, username);
return mangaRecord != null;
}
}
/*
* Check if the record contains all the details.
*
* Without this function the fragments will call setText while it isn't loaded.
* This will cause a nullpointerexception.
*/
public boolean isDone() {
return (!isEmpty()) && (type.equals(ListType.ANIME) ? animeRecord.getSynopsis() != null : mangaRecord.getSynopsis() != null);
}
/*
* Get the translation from strings.xml
*/
private String getStringFromResourceArray(int resArrayId, int notFoundStringId, int index) {
Resources res = getResources();
try {
String[] types = res.getStringArray(resArrayId);
if (index < 0 || index >= types.length) // make sure to have a valid array index
return res.getString(notFoundStringId);
else
return types[index];
} catch (Resources.NotFoundException e) {
Crashlytics.logException(e);
return res.getString(notFoundStringId);
}
}
/*
* Get the anime or manga mediatype translations
*/
public String getTypeString(int typesInt) {
if (type.equals(ListType.ANIME))
return getStringFromResourceArray(R.array.mediaType_Anime, R.string.unknown, typesInt);
else
return getStringFromResourceArray(R.array.mediaType_Manga, R.string.unknown, typesInt);
}
/*
* Get the anime or manga status translations
*/
public String getStatusString(int statusInt) {
if (type.equals(ListType.ANIME))
return getStringFromResourceArray(R.array.mediaStatus_Anime, R.string.unknown, statusInt);
else
return getStringFromResourceArray(R.array.mediaStatus_Manga, R.string.unknown, statusInt);
}
/*
* Get the anime or manga genre translations
*/
public ArrayList<String> getGenresString(ArrayList<Integer> genresInt) {
ArrayList<String> genres = new ArrayList<String>();
for (Integer genreInt : genresInt) {
genres.add(getStringFromResourceArray(R.array.genresArray, R.string.unknown, genreInt));
}
return genres;
}
/*
* Get the anime or manga classification translations
*/
public String getClassificationString(Integer classificationInt) {
return getStringFromResourceArray(R.array.classificationArray, R.string.unknown, classificationInt);
}
public String getUserStatusString(int statusInt) {
return getStringFromResourceArray(R.array.mediaStatus_User, R.string.unknown, statusInt);
}
/*
* Get the records (Anime/Manga)
*
* Try to fetch them from the Database first to get reading/watching details.
* If the record doesn't contains a synopsis this method will get it.
*/
public void getRecord(boolean forceUpdate) {
setRefreshing(true);
toggleLoadingIndicator(isEmpty());
actionBar.setTitle(R.string.layout_card_loading);
boolean loaded = false;
if (!forceUpdate || !MALApi.isNetworkAvailable(this)) {
if (getRecordFromDB()) {
setText();
setRefreshing(false);
if (isDone()) {
loaded = true;
toggleLoadingIndicator(false);
}
}
}
if (MALApi.isNetworkAvailable(this)) {
if (!loaded || forceUpdate) {
Bundle data = new Bundle();
boolean saveDetails = username != null && !username.equals("") && isAdded();
if (saveDetails) {
data.putSerializable("record", type.equals(ListType.ANIME) ? animeRecord : mangaRecord);
} else {
data.putInt("recordID", recordID);
}
new NetworkTask(saveDetails ? TaskJob.GETDETAILS : TaskJob.GET, type, this, data, this, this).execute();
}
} else {
toggleLoadingIndicator(false);
setRefreshing(false);
if (isEmpty()) {
actionBar.setTitle("");
toggleNoNetworkCard(true);
}
}
}
public void onStatusDialogDismissed(String currentStatus) {
if (type.equals(ListType.ANIME)) {
animeRecord.setWatchedStatus(currentStatus);
if (GenericRecord.STATUS_COMPLETED.equals(currentStatus)) {
if (animeRecord.getEpisodes() != 0)
animeRecord.setWatchedEpisodes(animeRecord.getEpisodes());
}
animeRecord.setDirty(true);
} else {
mangaRecord.setReadStatus(currentStatus);
if (GenericRecord.STATUS_COMPLETED.equals(currentStatus)) {
if (mangaRecord.getChapters() != 0)
mangaRecord.setChaptersRead(mangaRecord.getChapters());
if (mangaRecord.getVolumes() != 0)
mangaRecord.setVolumesRead(mangaRecord.getVolumes());
}
mangaRecord.setDirty(true);
}
setText();
}
public void onMangaDialogDismissed(int value, int value2) {
if (value != mangaRecord.getChaptersRead()) {
if (value == mangaRecord.getChapters() && mangaRecord.getChapters() != 0) {
mangaRecord.setReadStatus(GenericRecord.STATUS_COMPLETED);
}
if (value == 0) {
mangaRecord.setReadStatus(Manga.STATUS_PLANTOREAD);
}
mangaRecord.setChaptersRead(value);
mangaRecord.setDirty(true);
}
if (value2 != mangaRecord.getVolumesRead()) {
if (value2 == mangaRecord.getVolumes()) {
mangaRecord.setReadStatus(GenericRecord.STATUS_COMPLETED);
}
if (value2 == 0) {
mangaRecord.setReadStatus(Manga.STATUS_PLANTOREAD);
}
mangaRecord.setVolumesRead(value2);
mangaRecord.setDirty(true);
}
setText();
setMenu();
}
public void onRemoveConfirmed() {
if (type.equals(ListType.ANIME)) {
animeRecord.setDirty(true);
animeRecord.setDeleteFlag(true);
} else {
mangaRecord.setDirty(true);
mangaRecord.setDeleteFlag(true);
}
finish();
}
@Override
protected void onSaveInstanceState(Bundle State) {
super.onSaveInstanceState(State);
State.putSerializable("anime", animeRecord);
State.putSerializable("manga", mangaRecord);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_detail_view, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
this.menu = menu;
setMenu();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.action_Share:
Share();
break;
case R.id.action_Remove:
showDialog("removeConfirmation", new RemoveConfirmationDialogFragment());
break;
case R.id.action_addToList:
addToList();
break;
case R.id.action_ViewMALPage:
Uri malurl = Uri.parse("http://myanimelist.net/" + type.toString().toLowerCase(Locale.US) + "/" + recordID + "/");
startActivity(new Intent(Intent.ACTION_VIEW, malurl));
break;
case R.id.action_copy:
if (animeRecord != null || mangaRecord != null) {
android.content.ClipboardManager clipBoard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clipData = android.content.ClipData.newPlainText("Atarashii", type == ListType.ANIME ? animeRecord.getTitle() : mangaRecord.getTitle());
clipBoard.setPrimaryClip(clipData);
} else {
Toast.makeText(context, R.string.toast_info_hold_on, Toast.LENGTH_SHORT).show();
}
break;
}
return true;
}
@Override
public void onPause() {
super.onPause();
if (animeRecord == null && mangaRecord == null)
return; // nothing to do
try {
if (type.equals(ListType.ANIME)) {
if (animeRecord.getDirty() && !animeRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.UPDATE, this, this).execute(animeRecord);
} else if (animeRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.FORCESYNC, this, this).execute(animeRecord);
}
} else if (type.equals(ListType.MANGA)) {
if (mangaRecord.getDirty() && !mangaRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.UPDATE, this, this).execute(mangaRecord);
} else if (mangaRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.FORCESYNC, this, this).execute(mangaRecord);
}
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.onPause(): " + e.getMessage());
Crashlytics.logException(e);
}
}
@Override
public void onResume() {
super.onResume();
// received Android Beam?
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()))
processIntent(getIntent());
}
private void processIntent(Intent intent) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
String message = new String(msg.getRecords()[0].getPayload());
String[] splitmessage = message.split(":", 2);
if (splitmessage.length == 2) {
try {
type = ListType.valueOf(splitmessage[0].toUpperCase(Locale.US));
recordID = Integer.parseInt(splitmessage[1]);
getRecord(false);
} catch (NumberFormatException e) {
Crashlytics.logException(e);
finish();
}
}
}
private void setupBeam() {
try {
// setup beam functionality (if NFC is available)
NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
Crashlytics.log(Log.INFO, "MALX", "DetailView.setupBeam(): NFC not available");
} else {
// Register NFC callback
String message_str = type.toString() + ":" + String.valueOf(recordID);
NdefMessage message = new NdefMessage(new NdefRecord[]{
new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
"application/net.somethingdreadful.MAL".getBytes(Charset.forName("US-ASCII")),
new byte[0], message_str.getBytes(Charset.forName("US-ASCII"))),
NdefRecord.createApplicationRecord(getPackageName())
});
mNfcAdapter.setNdefPushMessage(message, this);
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.setupBeam(): " + e.getMessage());
Crashlytics.logException(e);
}
}
@SuppressWarnings("unchecked") // Don't panic, we handle possible class cast exceptions
@Override
public void onNetworkTaskFinished(Object result, TaskJob job, ListType type, Bundle data, boolean cancelled) {
try {
if (type == ListType.ANIME) {
animeRecord = (Anime) result;
if (isAdded())
animeRecord.setDirty(true);
} else {
mangaRecord = (Manga) result;
if (isAdded())
mangaRecord.setDirty(true);
}
setRefreshing(false);
toggleLoadingIndicator(false);
setText();
} catch (ClassCastException e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.onNetworkTaskFinished(): " + result.getClass().toString());
Crashlytics.logException(e);
Toast.makeText(context, R.string.toast_error_DetailsError, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNetworkTaskError(TaskJob job, ListType type, Bundle data, boolean cancelled) {
Toast.makeText(context, R.string.toast_error_DetailsError, Toast.LENGTH_SHORT).show();
}
@Override
public void onAPIAuthenticationError(ListType type, TaskJob job) {
showDialog("updatePassword", new UpdatePasswordDialogFragment());
}
/*
* Set the fragment to future use
*/
public void setGeneral(DetailViewGeneral general) {
this.general = general;
if (isEmpty())
getRecord(false);
else
setText();
}
/*
* Set the fragment to future use
*/
public void setDetails(DetailViewDetails details) {
this.details = details;
}
public void setPersonal(DetailViewPersonal personal) {
this.personal = personal;
}
/*
* handle the loading indicator
*/
private void toggleLoadingIndicator(boolean show) {
if (viewFlipper != null) {
viewFlipper.setDisplayedChild(show ? 1 : 0);
}
}
/*
* handle the offline card
*/
private void toggleNoNetworkCard(boolean show) {
if (viewFlipper != null) {
viewFlipper.setDisplayedChild(show ? 2 : 0);
}
}
@Override
public void onRefresh() {
getRecord(true);
}
} |
package com.mikepenz.materialdrawer;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.mikepenz.iconics.typeface.IIcon;
import com.mikepenz.iconics.utils.Utils;
import com.mikepenz.materialdrawer.accountswitcher.AccountHeader;
import com.mikepenz.materialdrawer.adapter.BaseDrawerAdapter;
import com.mikepenz.materialdrawer.adapter.DrawerAdapter;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.Badgeable;
import com.mikepenz.materialdrawer.model.interfaces.Checkable;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.Iconable;
import com.mikepenz.materialdrawer.model.interfaces.Nameable;
import com.mikepenz.materialdrawer.util.UIUtils;
import com.mikepenz.materialdrawer.view.ScrimInsetsFrameLayout;
import java.util.ArrayList;
import java.util.Collections;
public class Drawer {
private static final String BUNDLE_SELECTION = "bundle_selection";
// some internal vars
// variable to check if a builder is only used once
protected boolean mUsed = false;
protected int mCurrentSelection = -1;
// the activity to use
protected Activity mActivity;
protected ViewGroup mRootView;
protected ScrimInsetsFrameLayout mDrawerContentRoot;
/**
* Pass the activity you use the drawer in ;)
* This is required if you want to set any values by resource
*
* @param activity
* @return
*/
public Drawer withActivity(Activity activity) {
this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content);
this.mActivity = activity;
return this;
}
// set actionbar Compatibility mode
protected boolean mTranslucentActionBarCompatibility = false;
/**
* Set this to true to use a translucent StatusBar in an activity with a good old
* ActionBar. Should be a rare scenario.
*
* @param translucentActionBarCompatibility
* @return
*/
public Drawer withTranslucentActionBarCompatibility(boolean translucentActionBarCompatibility) {
this.mTranslucentActionBarCompatibility = translucentActionBarCompatibility;
return this;
}
/**
* Set this to true if you want your drawer to be displayed below the toolbar.
* Note this will add a margin above the drawer
*
* @param displayBelowToolbar
* @return
*/
public Drawer withDisplayBelowToolbar(boolean displayBelowToolbar) {
this.mTranslucentActionBarCompatibility = displayBelowToolbar;
return this;
}
// set non translucent statusBar mode
protected boolean mTranslucentStatusBar = true;
/**
* Set to false to disable the use of a translucent statusBar
*
* @param translucentStatusBar
* @return
*/
public Drawer withTranslucentStatusBar(boolean translucentStatusBar) {
this.mTranslucentStatusBar = translucentStatusBar;
//if we disable the translucentStatusBar it should be disabled at all
if (!translucentStatusBar) {
this.mTranslucentStatusBarProgrammatically = false;
}
return this;
}
// set to disable the translucent statusBar Programmatically
protected boolean mTranslucentStatusBarProgrammatically = true;
/**
* set this to false if you want no translucent statusBar. or
* if you want to create this behavior only by theme.
*
* @param translucentStatusBarProgrammatically
* @return
*/
public Drawer withTranslucentStatusBarProgrammatically(boolean translucentStatusBarProgrammatically) {
this.mTranslucentStatusBarProgrammatically = translucentStatusBarProgrammatically;
//if we enable the programmatically translucent statusBar we want also the normal statusBar behavior
if (translucentStatusBarProgrammatically) {
this.mTranslucentStatusBar = true;
}
return this;
}
// the toolbar of the activity
protected Toolbar mToolbar;
/**
* Add the toolbar which is used in combination with this drawer.
* NOTE: if you use the drawer in a subActivity you don't need this, if you
* want to display the back arrow.
*
* @param toolbar
* @return
*/
public Drawer withToolbar(Toolbar toolbar) {
this.mToolbar = toolbar;
return this;
}
// set non translucent NavigationBar mode
protected boolean mTranslucentNavigationBar = false;
/**
* Set to true if you use a translucent NavigationBar
*
* @param translucentNavigationBar
* @return
*/
public Drawer withTranslucentNavigationBar(boolean translucentNavigationBar) {
this.mTranslucentNavigationBar = translucentNavigationBar;
return this;
}
// the drawerLayout to use
protected DrawerLayout mDrawerLayout;
protected RelativeLayout mSliderLayout;
/**
* Pass a custom DrawerLayout which will be used.
* NOTE: This requires the same structure as the drawer.xml
*
* @param drawerLayout
* @return
*/
public Drawer withDrawerLayout(DrawerLayout drawerLayout) {
this.mDrawerLayout = drawerLayout;
return this;
}
/**
* Pass a custom DrawerLayout Resource which will be used.
* NOTE: This requires the same structure as the drawer.xml
*
* @param resLayout
* @return
*/
public Drawer withDrawerLayout(int resLayout) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (resLayout != -1) {
this.mDrawerLayout = (DrawerLayout) mActivity.getLayoutInflater().inflate(resLayout, mRootView, false);
} else {
this.mDrawerLayout = (DrawerLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer, mRootView, false);
}
return this;
}
//the statusBar color
protected int mStatusBarColor = 0;
protected int mStatusBarColorRes = -1;
/**
* Set the statusBarColor color for this activity
*
* @param statusBarColor
* @return
*/
public Drawer withStatusBarColor(int statusBarColor) {
this.mStatusBarColor = statusBarColor;
return this;
}
/**
* Set the statusBarColor color for this activity from a resource
*
* @param statusBarColorRes
* @return
*/
public Drawer withStatusBarColorRes(int statusBarColorRes) {
this.mStatusBarColorRes = statusBarColorRes;
return this;
}
//the background color for the slider
protected int mSliderBackgroundColor = 0;
protected int mSliderBackgroundColorRes = -1;
protected Drawable mSliderBackgroundDrawable = null;
protected int mSliderBackgroundDrawableRes = -1;
/**
* Set the background color for the Slider.
* This is the view containing the list.
*
* @param sliderBackgroundColor
* @return
*/
public Drawer withSliderBackgroundColor(int sliderBackgroundColor) {
this.mSliderBackgroundColor = sliderBackgroundColor;
return this;
}
/**
* Set the background color for the Slider from a Resource.
* This is the view containing the list.
*
* @param sliderBackgroundColorRes
* @return
*/
public Drawer withSliderBackgroundColorRes(int sliderBackgroundColorRes) {
this.mSliderBackgroundColorRes = sliderBackgroundColorRes;
return this;
}
/**
* Set the background drawable for the Slider.
* This is the view containing the list.
*
* @param sliderBackgroundDrawable
* @return
*/
public Drawer withSliderBackgroundDrawable(Drawable sliderBackgroundDrawable) {
this.mSliderBackgroundDrawable = sliderBackgroundDrawable;
return this;
}
/**
* Set the background drawable for the Slider from a Resource.
* This is the view containing the list.
*
* @param sliderBackgroundDrawableRes
* @return
*/
public Drawer withSliderBackgroundDrawableRes(int sliderBackgroundDrawableRes) {
this.mSliderBackgroundDrawableRes = sliderBackgroundDrawableRes;
return this;
}
//the width of the drawer
protected int mDrawerWidth = -1;
/**
* Set the Drawer width with a pixel value
*
* @param drawerWidthPx
* @return
*/
public Drawer withDrawerWidthPx(int drawerWidthPx) {
this.mDrawerWidth = drawerWidthPx;
return this;
}
/**
* Set the Drawer width with a dp value
*
* @param drawerWidthDp
* @return
*/
public Drawer withDrawerWidthDp(int drawerWidthDp) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
this.mDrawerWidth = Utils.convertDpToPx(mActivity, drawerWidthDp);
return this;
}
/**
* Set the Drawer width with a dimension resource
*
* @param drawerWidthRes
* @return
*/
public Drawer withDrawerWidthRes(int drawerWidthRes) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
this.mDrawerWidth = mActivity.getResources().getDimensionPixelSize(drawerWidthRes);
return this;
}
//the gravity of the drawer
protected Integer mDrawerGravity = null;
/**
* Set the gravity for the drawer. START, LEFT | RIGHT, END
*
* @param gravity
* @return
*/
public Drawer withDrawerGravity(int gravity) {
this.mDrawerGravity = gravity;
return this;
}
//the account selection header to use
protected AccountHeader.Result mAccountHeader;
protected boolean mAccountHeaderSticky = false;
/**
* Add a AccountSwitcherHeader which will be used in this drawer instance.
* NOTE: This will overwrite any set headerView.
*
* @param accountHeader
* @return
*/
public Drawer withAccountHeader(AccountHeader.Result accountHeader) {
return withAccountHeader(accountHeader, false);
}
/**
* Add a AccountSwitcherHeader which will be used in this drawer instance. Pass true if it should be sticky
* NOTE: This will overwrite any set headerView or stickyHeaderView (depends on the boolean).
*
* @param accountHeader
* @param accountHeaderSticky
* @return
*/
public Drawer withAccountHeader(AccountHeader.Result accountHeader, boolean accountHeaderSticky) {
this.mAccountHeader = accountHeader;
this.mAccountHeaderSticky = accountHeaderSticky;
//set the header offset
if (!accountHeaderSticky) {
mHeaderOffset = 1;
}
return this;
}
// enable/disable the actionBarDrawerToggle animation
protected boolean mAnimateActionBarDrawerToggle = false;
/**
* Set this to true if you want the ActionBarDrawerToggle to be animated.
* NOTE: This will only work if the built in ActionBarDrawerToggle is used.
* Enable it by setting withActionBarDrawerToggle to true
*
* @param actionBarDrawerToggleAnimated
* @return
*/
public Drawer withActionBarDrawerToggleAnimated(boolean actionBarDrawerToggleAnimated) {
this.mAnimateActionBarDrawerToggle = actionBarDrawerToggleAnimated;
return this;
}
// enable the drawer toggle / if withActionBarDrawerToggle we will autoGenerate it
protected boolean mActionBarDrawerToggleEnabled = true;
/**
* Set this to false if you don't need the included ActionBarDrawerToggle
*
* @param actionBarDrawerToggleEnabled
* @return
*/
public Drawer withActionBarDrawerToggle(boolean actionBarDrawerToggleEnabled) {
this.mActionBarDrawerToggleEnabled = actionBarDrawerToggleEnabled;
return this;
}
// drawer toggle
protected ActionBarDrawerToggle mActionBarDrawerToggle;
/**
* Add a custom ActionBarDrawerToggle which will be used in combination with this drawer.
*
* @param actionBarDrawerToggle
* @return
*/
public Drawer withActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle) {
this.mActionBarDrawerToggleEnabled = true;
this.mActionBarDrawerToggle = actionBarDrawerToggle;
return this;
}
// header view
protected View mHeaderView;
protected int mHeaderOffset = 0;
protected boolean mHeaderDivider = true;
protected boolean mHeaderClickable = false;
/**
* Add a header to the Drawer ListView. This can be any view
*
* @param headerView
* @return
*/
public Drawer withHeader(View headerView) {
this.mHeaderView = headerView;
//set the header offset
mHeaderOffset = 1;
return this;
}
/**
* Add a header to the Drawer ListView defined by a resource.
*
* @param headerViewRes
* @return
*/
public Drawer withHeader(int headerViewRes) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (headerViewRes != -1) {
//i know there should be a root, bit i got none here
this.mHeaderView = mActivity.getLayoutInflater().inflate(headerViewRes, null, false);
//set the headerOffset :D
mHeaderOffset = 1;
}
return this;
}
/**
* Set this to true if you want the header to be clickable
*
* @param headerClickable
* @return
*/
public Drawer withHeaderClickable(boolean headerClickable) {
this.mHeaderClickable = headerClickable;
return this;
}
/**
* Set this to false if you don't need the divider below the header
*
* @param headerDivider
* @return
*/
public Drawer withHeaderDivider(boolean headerDivider) {
this.mHeaderDivider = headerDivider;
return this;
}
// sticky view
protected View mStickyHeaderView;
/**
* Add a sticky header below the Drawer ListView. This can be any view
*
* @param stickyHeader
* @return
*/
public Drawer withStickyHeader(View stickyHeader) {
this.mStickyHeaderView = stickyHeader;
return this;
}
/**
* Add a sticky header below the Drawer ListView defined by a resource.
*
* @param stickyHeaderRes
* @return
*/
public Drawer withStickyHeader(int stickyHeaderRes) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (stickyHeaderRes != -1) {
//i know there should be a root, bit i got none here
this.mStickyHeaderView = mActivity.getLayoutInflater().inflate(stickyHeaderRes, null, false);
}
return this;
}
// footer view
protected View mFooterView;
protected boolean mFooterDivider = true;
protected boolean mFooterClickable = false;
/**
* Add a footer to the Drawer ListView. This can be any view
*
* @param footerView
* @return
*/
public Drawer withFooter(View footerView) {
this.mFooterView = footerView;
return this;
}
/**
* Add a footer to the Drawer ListView defined by a resource.
*
* @param footerViewRes
* @return
*/
public Drawer withFooter(int footerViewRes) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (footerViewRes != -1) {
//i know there should be a root, bit i got none here
this.mFooterView = mActivity.getLayoutInflater().inflate(footerViewRes, null, false);
}
return this;
}
/**
* Set this to true if you want the footer to be clickable
*
* @param footerClickable
* @return
*/
public Drawer withFooterClickable(boolean footerClickable) {
this.mFooterClickable = footerClickable;
return this;
}
/**
* Set this to false if you don't need the divider above the footer
*
* @param footerDivider
* @return
*/
public Drawer withFooterDivider(boolean footerDivider) {
this.mFooterDivider = footerDivider;
return this;
}
// sticky view
protected View mStickyFooterView;
/**
* Add a sticky footer below the Drawer ListView. This can be any view
*
* @param stickyFooter
* @return
*/
public Drawer withStickyFooter(View stickyFooter) {
this.mStickyFooterView = stickyFooter;
return this;
}
/**
* Add a sticky footer below the Drawer ListView defined by a resource.
*
* @param stickyFooterRes
* @return
*/
public Drawer withStickyFooter(int stickyFooterRes) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (stickyFooterRes != -1) {
//i know there should be a root, bit i got none here
this.mStickyFooterView = mActivity.getLayoutInflater().inflate(stickyFooterRes, null, false);
}
return this;
}
// fire onClick after build
protected boolean mFireInitialOnClick = false;
/**
* Set this to true if you love to get an initial onClick event after the build method is called
*
* @param fireOnInitialOnClick
* @return
*/
public Drawer withFireOnInitialOnClick(boolean fireOnInitialOnClick) {
this.mFireInitialOnClick = fireOnInitialOnClick;
return this;
}
// item to select
protected int mSelectedItem = 0;
/**
* Set this to the index of the item, you would love to select upon start
*
* @param selectedItem
* @return
*/
public Drawer withSelectedItem(int selectedItem) {
this.mSelectedItem = selectedItem;
return this;
}
// an ListView to use within the drawer :D
protected ListView mListView;
/**
* Define a custom ListView which will be used in the drawer
* NOTE: this is not recommended
*
* @param listView
* @return
*/
public Drawer withListView(ListView listView) {
this.mListView = listView;
return this;
}
// an adapter to use for the list
protected BaseDrawerAdapter mAdapter;
/**
* Define a custom Adapter which will be used in the drawer
* NOTE: this is not recommended
*
* @param adapter
* @return
*/
public Drawer withAdapter(BaseDrawerAdapter adapter) {
this.mAdapter = adapter;
return this;
}
// list in drawer
protected ArrayList<IDrawerItem> mDrawerItems = new ArrayList<>();
/**
* Set the initial List of IDrawerItems for the Drawer
*
* @param drawerItems
* @return
*/
public Drawer withDrawerItems(ArrayList<IDrawerItem> drawerItems) {
this.mDrawerItems = drawerItems;
return this;
}
/**
* Add a initial DrawerItem or a DrawerItem Array for the Drawer
*
* @param drawerItems
* @return
*/
public Drawer addDrawerItems(IDrawerItem... drawerItems) {
if (this.mDrawerItems == null) {
this.mDrawerItems = new ArrayList<>();
}
if (drawerItems != null) {
Collections.addAll(this.mDrawerItems, drawerItems);
}
return this;
}
// always visible list in drawer
protected ArrayList<IDrawerItem> mStickyDrawerItems = new ArrayList<>();
/**
* Set the initial List of IDrawerItems for the StickyDrawerFooter
*
* @param stickyDrawerItems
* @return
*/
public Drawer withStickyDrawerItems(ArrayList<IDrawerItem> stickyDrawerItems) {
this.mStickyDrawerItems = stickyDrawerItems;
return this;
}
/**
* Add a initial DrawerItem or a DrawerItem Array for the StickyDrawerFooter
*
* @param stickyDrawerItems
* @return
*/
public Drawer addStickyDrawerItems(IDrawerItem... stickyDrawerItems) {
if (this.mStickyDrawerItems == null) {
this.mStickyDrawerItems = new ArrayList<>();
}
if (stickyDrawerItems != null) {
Collections.addAll(this.mStickyDrawerItems, stickyDrawerItems);
}
return this;
}
// close drawer on click
protected boolean mCloseOnClick = true;
/**
* Set this to false if the drawer should stay opened after an item was clicked
*
* @param closeOnClick
* @return this
*/
public Drawer withCloseOnClick(boolean closeOnClick) {
this.mCloseOnClick = closeOnClick;
return this;
}
// delay drawer close to prevent lag
protected int mDelayOnDrawerClose = 150;
/**
* Define the delay for the drawer close operation after a click.
* This is a small trick to improve the speed (and remove lag) if you open a new activity after a DrawerItem
* was selected.
* NOTE: Disable this by passing -1
*
* @param delayOnDrawerClose -1 to disable
* @return this
*/
public Drawer withDelayOnDrawerClose(int delayOnDrawerClose) {
this.mDelayOnDrawerClose = delayOnDrawerClose;
return this;
}
// onDrawerListener
protected OnDrawerListener mOnDrawerListener;
/**
* Define a OnDrawerListener for this Drawer
*
* @param onDrawerListener
* @return this
*/
public Drawer withOnDrawerListener(OnDrawerListener onDrawerListener) {
this.mOnDrawerListener = onDrawerListener;
return this;
}
// onDrawerItemClickListeners
protected OnDrawerItemClickListener mOnDrawerItemClickListener;
/**
* Define a OnDrawerItemClickListener for this Drawer
*
* @param onDrawerItemClickListener
* @return
*/
public Drawer withOnDrawerItemClickListener(OnDrawerItemClickListener onDrawerItemClickListener) {
this.mOnDrawerItemClickListener = onDrawerItemClickListener;
return this;
}
// onDrawerItemClickListeners
protected OnDrawerItemLongClickListener mOnDrawerItemLongClickListener;
/**
* Define a OnDrawerItemLongClickListener for this Drawer
*
* @param onDrawerItemLongClickListener
* @return
*/
public Drawer withOnDrawerItemLongClickListener(OnDrawerItemLongClickListener onDrawerItemLongClickListener) {
this.mOnDrawerItemLongClickListener = onDrawerItemLongClickListener;
return this;
}
// onDrawerItemClickListeners
protected OnDrawerItemSelectedListener mOnDrawerItemSelectedListener;
/**
* Define a OnDrawerItemSelectedListener for this Drawer
*
* @param onDrawerItemSelectedListener
* @return
*/
public Drawer withOnDrawerItemSelectedListener(OnDrawerItemSelectedListener onDrawerItemSelectedListener) {
this.mOnDrawerItemSelectedListener = onDrawerItemSelectedListener;
return this;
}
// onDrawerListener
protected OnDrawerNavigationListener mOnDrawerNavigationListener;
/**
* Define a OnDrawerNavigationListener for this Drawer
*
* @param onDrawerNavigationListener
* @return this
*/
public Drawer withOnDrawerNavigationListener(OnDrawerNavigationListener onDrawerNavigationListener) {
this.mOnDrawerNavigationListener = onDrawerNavigationListener;
return this;
}
// savedInstance to restore state
protected Bundle mSavedInstance;
/**
* Set the Bundle (savedInstance) which is passed by the activity.
* No need to null-check everything is handled automatically
*
* @param savedInstance
* @return
*/
public Drawer withSavedInstance(Bundle savedInstance) {
this.mSavedInstance = savedInstance;
return this;
}
/**
* helper method to set the TranslucenStatusFlag
*
* @param on
*/
private void setTranslucentStatusFlag(boolean on) {
if (Build.VERSION.SDK_INT >= 19) {
Window win = mActivity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
/**
* Build and add the Drawer to your activity
*
* @return
*/
public Result build() {
if (mUsed) {
throw new RuntimeException("you must not reuse a Drawer builder");
}
if (mActivity == null) {
throw new RuntimeException("please pass an activity");
}
//set that this builder was used. now you have to create a new one
mUsed = true;
// if the user has not set a drawerLayout use the default one :D
if (mDrawerLayout == null) {
withDrawerLayout(-1);
}
//get the content view
View contentView = mRootView.getChildAt(0);
boolean alreadyInflated = contentView instanceof DrawerLayout;
//get the drawer root
mDrawerContentRoot = (ScrimInsetsFrameLayout) mDrawerLayout.getChildAt(0);
if (!alreadyInflated && mTranslucentStatusBar) {
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setTranslucentStatusFlag(true);
}
if (Build.VERSION.SDK_INT >= 19) {
if (mTranslucentStatusBarProgrammatically) {
mActivity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
}
if (Build.VERSION.SDK_INT >= 21) {
setTranslucentStatusFlag(false);
if (mTranslucentStatusBarProgrammatically) {
mActivity.getWindow().setStatusBarColor(Color.TRANSPARENT);
}
}
mDrawerContentRoot.setPadding(0, mActivity.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding), 0, 0);
// define the statusBarColor
if (mStatusBarColor == 0 && mStatusBarColorRes != -1) {
mStatusBarColor = mActivity.getResources().getColor(mStatusBarColorRes);
} else if (mStatusBarColor == 0) {
mStatusBarColor = UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.colorPrimaryDark, R.color.material_drawer_primary_dark);
}
mDrawerContentRoot.setInsetForeground(mStatusBarColor);
}
//only add the new layout if it wasn't done before
if (!alreadyInflated) {
// remove the contentView
mRootView.removeView(contentView);
} else {
//if it was already inflated we have to clean up again
mRootView.removeAllViews();
}
//create the layoutParams to use for the contentView
FrameLayout.LayoutParams layoutParamsContentView = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
//if we have a translucent navigation bar set the bottom margin
if (mTranslucentNavigationBar) {
layoutParamsContentView.bottomMargin = UIUtils.getNavigationBarHeight(mActivity);
}
//add the contentView to the drawer content frameLayout
mDrawerContentRoot.addView(contentView, layoutParamsContentView);
//add the drawerLayout to the root
mRootView.addView(mDrawerLayout, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
//set the navigationOnClickListener
View.OnClickListener toolbarNavigationListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean handled = false;
if (mOnDrawerNavigationListener != null && (mActionBarDrawerToggle != null && !mActionBarDrawerToggle.isDrawerIndicatorEnabled())) {
handled = mOnDrawerNavigationListener.onNavigationClickListener(v);
}
if (!handled) {
if (mDrawerLayout.isDrawerOpen(mSliderLayout)) {
mDrawerLayout.closeDrawer(mSliderLayout);
} else {
mDrawerLayout.openDrawer(mSliderLayout);
}
}
}
};
//if we got a toolbar set a toolbarNavigationListener
if (mToolbar != null) {
this.mToolbar.setNavigationOnClickListener(toolbarNavigationListener);
}
// create the ActionBarDrawerToggle if not set and enabled and if we have a toolbar
if (mActionBarDrawerToggleEnabled && mActionBarDrawerToggle == null && mToolbar != null) {
this.mActionBarDrawerToggle = new ActionBarDrawerToggle(mActivity, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close) {
@Override
public void onDrawerOpened(View drawerView) {
if (mOnDrawerListener != null) {
mOnDrawerListener.onDrawerOpened(drawerView);
}
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerClosed(View drawerView) {
if (mOnDrawerListener != null) {
mOnDrawerListener.onDrawerClosed(drawerView);
}
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if (!mAnimateActionBarDrawerToggle) {
super.onDrawerSlide(drawerView, 0);
} else {
super.onDrawerSlide(drawerView, slideOffset);
}
}
};
this.mActionBarDrawerToggle.syncState();
}
//handle the ActionBarDrawerToggle
if (mActionBarDrawerToggle != null) {
mActionBarDrawerToggle.setToolbarNavigationClickListener(toolbarNavigationListener);
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
//build the view which will be set to the drawer
Result result = buildView();
// add the slider to the drawer
mDrawerLayout.addView(mSliderLayout, 1);
return result;
}
public Result buildView() {
// get the slider view
mSliderLayout = (RelativeLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_slider, mDrawerLayout, false);
mSliderLayout.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.material_drawer_background, R.color.material_drawer_background));
// get the layout params
DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mSliderLayout.getLayoutParams();
if (params != null) {
// if we've set a custom gravity set it
if (mDrawerGravity != null) {
params.gravity = mDrawerGravity;
}
// if this is a drawer from the right, change the margins :D
params = processDrawerLayoutParams(params);
// set the new layout params
mSliderLayout.setLayoutParams(params);
}
// set the background
if (mSliderBackgroundColor != 0) {
mSliderLayout.setBackgroundColor(mSliderBackgroundColor);
} else if (mSliderBackgroundColorRes != -1) {
mSliderLayout.setBackgroundColor(mActivity.getResources().getColor(mSliderBackgroundColorRes));
} else if (mSliderBackgroundDrawable != null) {
UIUtils.setBackground(mSliderLayout, mSliderBackgroundDrawable);
} else if (mSliderBackgroundDrawableRes != -1) {
UIUtils.setBackground(mSliderLayout, mSliderBackgroundColorRes);
}
//create the content
createContent();
//create the result object
Result result = new Result(this);
//set the drawer for the accountHeader if set
if (mAccountHeader != null) {
mAccountHeader.setDrawer(result);
}
//forget the reference to the activity
mActivity = null;
return result;
}
/**
* Call this method to append a new Drawer to a existing Drawer.
*
* @param result the Drawer.Result of an existing Drawer
* @return
*/
public Result append(Result result) {
if (mUsed) {
throw new RuntimeException("you must not reuse a Drawer builder");
}
if (mDrawerGravity == null) {
throw new RuntimeException("please set the gravity for the drawer");
}
//set that this builder was used. now you have to create a new one
mUsed = true;
//get the drawer layout from the previous drawer
mDrawerLayout = result.getDrawerLayout();
// get the slider view
mSliderLayout = (RelativeLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_slider, mDrawerLayout, false);
mSliderLayout.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.material_drawer_background, R.color.material_drawer_background));
// get the layout params
DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mSliderLayout.getLayoutParams();
// set the gravity of this drawerGravity
params.gravity = mDrawerGravity;
// if this is a drawer from the right, change the margins :D
params = processDrawerLayoutParams(params);
// set the new params
mSliderLayout.setLayoutParams(params);
// add the slider to the drawer
mDrawerLayout.addView(mSliderLayout, 1);
//create the content
createContent();
//forget the reference to the activity
mActivity = null;
return new Result(this);
}
/**
* the helper method to create the content for the drawer
*/
private void createContent() {
// if we have an adapter (either by defining a custom one or the included one add a list :D
if (mListView == null) {
mListView = new ListView(mActivity);
mListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
mListView.setDivider(null);
//only draw the selector on top if we are on a newer api than 10
if (Build.VERSION.SDK_INT > 10) {
mListView.setDrawSelectorOnTop(true);
}
mListView.setClipToPadding(false);
if (mTranslucentStatusBar && !mTranslucentActionBarCompatibility) {
mListView.setPadding(0, mActivity.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding), 0, 0);
}
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
params.weight = 1f;
mSliderLayout.addView(mListView, params);
//some extra stuff to beautify the whole thing ;)
if (!mTranslucentStatusBar || mTranslucentActionBarCompatibility) {
//disable the shadow if we don't use a translucent activity
mSliderLayout.getChildAt(0).setVisibility(View.GONE);
} else {
//bring shadow bar to front again
mSliderLayout.getChildAt(0).bringToFront();
}
// initialize list if there is an adapter or set items
if (mDrawerItems != null && mAdapter == null) {
mAdapter = new DrawerAdapter(mActivity, mDrawerItems);
}
//use the AccountHeader if set
if (mAccountHeader != null) {
if (mAccountHeaderSticky) {
mStickyHeaderView = mAccountHeader.getView();
} else {
mHeaderView = mAccountHeader.getView();
}
}
//sticky header view
if (mStickyHeaderView != null) {
//add the sticky footer view and align it to the bottom
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 1);
mStickyHeaderView.setId(R.id.sticky_header);
mSliderLayout.addView(mStickyHeaderView, 0, layoutParams);
//now align the listView above the stickyFooterView ;)
RelativeLayout.LayoutParams layoutParamsListView = (RelativeLayout.LayoutParams) mListView.getLayoutParams();
layoutParamsListView.addRule(RelativeLayout.BELOW, R.id.sticky_header);
mListView.setLayoutParams(layoutParamsListView);
//remove the padding of the listView again we have the header on top of it
mListView.setPadding(0, 0, 0, 0);
}
//use the StickyDrawerItems if set
if (mStickyDrawerItems != null && mStickyDrawerItems.size() > 0) {
mStickyFooterView = buildStickyDrawerItemFooter();
}
//sticky footer view
if (mStickyFooterView != null) {
//add the sticky footer view and align it to the bottom
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
mStickyFooterView.setId(R.id.sticky_footer);
mSliderLayout.addView(mStickyFooterView, layoutParams);
//now align the listView above the stickyFooterView ;)
RelativeLayout.LayoutParams layoutParamsListView = (RelativeLayout.LayoutParams) mListView.getLayoutParams();
layoutParamsListView.addRule(RelativeLayout.ABOVE, R.id.sticky_footer);
mListView.setLayoutParams(layoutParamsListView);
//remove the padding of the listView again we have the header on top of it
mListView.setPadding(mListView.getPaddingLeft(), mListView.getPaddingTop(), mListView.getPaddingRight(), mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_padding));
}
// set the header (do this before the setAdapter because some devices will crash else
if (mHeaderView != null) {
if (mListView == null) {
throw new RuntimeException("can't use a headerView without a listView");
}
if (mHeaderDivider) {
LinearLayout headerContainer = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_item_header, mListView, false);
headerContainer.addView(mHeaderView, 0);
//set the color for the divider
headerContainer.findViewById(R.id.divider).setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.material_drawer_divider, R.color.material_drawer_divider));
//add the headerContainer to the list
mListView.addHeaderView(headerContainer, null, mHeaderClickable);
//link the view including the container to the headerView field
mHeaderView = headerContainer;
} else {
mListView.addHeaderView(mHeaderView, null, mHeaderClickable);
}
//set the padding on the top to 0
mListView.setPadding(mListView.getPaddingLeft(), 0, mListView.getPaddingRight(), mListView.getPaddingBottom());
}
// set the footer (do this before the setAdapter because some devices will crash else
if (mFooterView != null) {
if (mListView == null) {
throw new RuntimeException("can't use a footerView without a listView");
}
if (mFooterDivider) {
LinearLayout footerContainer = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_item_footer, mListView, false);
footerContainer.addView(mFooterView, 1);
//set the color for the divider
footerContainer.findViewById(R.id.divider).setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.material_drawer_divider, R.color.material_drawer_divider));
//add the footerContainer to the list
mListView.addFooterView(footerContainer, null, mFooterClickable);
//link the view including the container to the footerView field
mFooterView = footerContainer;
} else {
mListView.addFooterView(mFooterView, null, mFooterClickable);
}
}
//after adding the header do the setAdapter and set the selection
if (mAdapter != null) {
//set the adapter on the listView
mListView.setAdapter(mAdapter);
//predefine selection (should be the first element
if (mListView != null && (mSelectedItem + mHeaderOffset) > -1) {
resetStickyFooterSelection();
mListView.setSelection(mSelectedItem + mHeaderOffset);
mListView.setItemChecked(mSelectedItem + mHeaderOffset, true);
mCurrentSelection = mSelectedItem;
}
}
// add the onDrawerItemClickListener if set
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
IDrawerItem i = getDrawerItem(position, true);
//close the drawer after click
closeDrawerDelayed();
if (i != null && i instanceof Checkable && !((Checkable) i).isCheckable()) {
mListView.setSelection(mCurrentSelection + mHeaderOffset);
mListView.setItemChecked(mCurrentSelection + mHeaderOffset, true);
} else {
resetStickyFooterSelection();
mCurrentSelection = position - mHeaderOffset;
}
if (mOnDrawerItemClickListener != null) {
mOnDrawerItemClickListener.onItemClick(parent, view, position - mHeaderOffset, id, i);
}
}
});
// add the onDrawerItemLongClickListener if set
if (mOnDrawerItemLongClickListener != null) {
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return mOnDrawerItemLongClickListener.onItemLongClick(parent, view, position - mHeaderOffset, id, getDrawerItem(position, true));
}
});
}
// add the onDrawerItemSelectedListener if set
if (mOnDrawerItemSelectedListener != null) {
mListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mOnDrawerItemSelectedListener.onItemSelected(parent, view, position - mHeaderOffset, id, getDrawerItem(position, true));
mCurrentSelection = position - mHeaderOffset;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mOnDrawerItemSelectedListener.onNothingSelected(parent);
}
});
}
if (mListView != null) {
mListView.smoothScrollToPosition(0);
}
// try to restore all saved values again
if (mSavedInstance != null) {
int selection = mSavedInstance.getInt(BUNDLE_SELECTION, -1);
if (selection != -1) {
//predefine selection (should be the first element
if (mListView != null && (selection + mHeaderOffset) > -1) {
resetStickyFooterSelection();
mListView.setSelection(selection + mHeaderOffset);
mListView.setItemChecked(selection + mHeaderOffset, true);
mCurrentSelection = selection;
}
}
}
// call initial onClick event to allow the dev to init the first view
if (mFireInitialOnClick && mOnDrawerItemClickListener != null) {
mOnDrawerItemClickListener.onItemClick(null, null, mCurrentSelection, mCurrentSelection, getDrawerItem(mCurrentSelection, false));
}
}
/**
* helper method to close the drawer delayed
*/
private void closeDrawerDelayed() {
if (mCloseOnClick && mDrawerLayout != null) {
if (mDelayOnDrawerClose > -1) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mDrawerLayout.closeDrawers();
}
}, mDelayOnDrawerClose);
} else {
mDrawerLayout.closeDrawers();
}
}
}
/**
* get the drawerItem at a specific position
*
* @param position
* @return
*/
private IDrawerItem getDrawerItem(int position, boolean includeOffset) {
if (includeOffset) {
if (mDrawerItems != null && mDrawerItems.size() > (position - mHeaderOffset) && (position - mHeaderOffset) > -1) {
return mDrawerItems.get(position - mHeaderOffset);
}
} else {
if (mDrawerItems != null && mDrawerItems.size() > position && position > -1) {
return mDrawerItems.get(position);
}
}
return null;
}
/**
* check if the item is within the bounds of the list
*
* @param position
* @param includeOffset
* @return
*/
private boolean checkDrawerItem(int position, boolean includeOffset) {
if (includeOffset) {
if (mDrawerItems != null && mDrawerItems.size() > (position - mHeaderOffset) && (position - mHeaderOffset) > -1) {
return true;
}
} else {
if (mDrawerItems != null && mDrawerItems.size() > position && position > -1) {
return true;
}
}
return false;
}
/**
* helper to extend the layoutParams of the drawer
*
* @param params
* @return
*/
private DrawerLayout.LayoutParams processDrawerLayoutParams(DrawerLayout.LayoutParams params) {
if (params != null) {
if (mDrawerGravity != null && (mDrawerGravity == Gravity.RIGHT || mDrawerGravity == Gravity.END)) {
params.rightMargin = 0;
if (Build.VERSION.SDK_INT >= 17) {
params.setMarginEnd(0);
}
params.leftMargin = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin);
if (Build.VERSION.SDK_INT >= 17) {
params.setMarginEnd(mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin));
}
}
if (mTranslucentActionBarCompatibility) {
TypedValue tv = new TypedValue();
if (mActivity.getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) {
int topMargin = TypedValue.complexToDimensionPixelSize(tv.data, mActivity.getResources().getDisplayMetrics());
if (mTranslucentStatusBar) {
topMargin = topMargin + mActivity.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding);
}
params.topMargin = topMargin;
}
}
if (mDrawerWidth > -1) {
params.width = mDrawerWidth;
} else {
params.width = UIUtils.getOptimalDrawerWidth(mActivity);
}
}
return params;
}
/**
* build the sticky footer item view
*
* @return
*/
private View buildStickyDrawerItemFooter() {
//create the container view
final LinearLayout linearLayout = new LinearLayout(mActivity);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
//create the divider
LinearLayout divider = new LinearLayout(mActivity);
LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dividerParams.bottomMargin = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_padding);
divider.setMinimumHeight((int) UIUtils.convertDpToPixel(1, mActivity));
divider.setOrientation(LinearLayout.VERTICAL);
divider.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.material_drawer_divider, R.color.material_drawer_divider));
linearLayout.addView(divider, dividerParams);
//get the inflater
LayoutInflater layoutInflater = LayoutInflater.from(mActivity);
int padding = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_vertical_padding);
//add all drawer items
for (IDrawerItem drawerItem : mStickyDrawerItems) {
//get the selected_color
int selected_color = UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.material_drawer_selected, R.color.material_drawer_selected);
if (drawerItem instanceof PrimaryDrawerItem) {
if (selected_color == 0 && ((PrimaryDrawerItem) drawerItem).getSelectedColorRes() != -1) {
selected_color = mActivity.getResources().getColor(((PrimaryDrawerItem) drawerItem).getSelectedColorRes());
} else if (((PrimaryDrawerItem) drawerItem).getSelectedColor() != 0) {
selected_color = ((PrimaryDrawerItem) drawerItem).getSelectedColor();
}
} else if (drawerItem instanceof SecondaryDrawerItem) {
if (selected_color == 0 && ((SecondaryDrawerItem) drawerItem).getSelectedColorRes() != -1) {
selected_color = mActivity.getResources().getColor(((SecondaryDrawerItem) drawerItem).getSelectedColorRes());
} else if (((SecondaryDrawerItem) drawerItem).getSelectedColor() != 0) {
selected_color = ((SecondaryDrawerItem) drawerItem).getSelectedColor();
}
}
View view = drawerItem.convertView(layoutInflater, null, linearLayout);
view.setTag(drawerItem);
if (drawerItem.isEnabled()) {
UIUtils.setBackground(view, UIUtils.getSelectableBackground(mActivity, selected_color));
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetStickyFooterSelection();
IDrawerItem drawerItem = (IDrawerItem) v.getTag();
boolean notCheckable = drawerItem != null && drawerItem instanceof Checkable && !((Checkable) drawerItem).isCheckable();
boolean checkable = !notCheckable;
if (checkable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
v.setActivated(true);
}
v.setSelected(true);
//remove the selection in the list
mListView.setSelection(-1);
mListView.setItemChecked(mCurrentSelection + mHeaderOffset, false);
}
//close the drawer after click
closeDrawerDelayed();
if (mOnDrawerItemClickListener != null) {
mOnDrawerItemClickListener.onItemClick(null, v, -1, -1, drawerItem);
}
}
});
}
//don't ask my why but it forgets the padding from the original layout
view.setPadding(padding, 0, padding, 0);
linearLayout.addView(view);
}
//and really. don't ask about this. it won't set the padding if i don't set the padding for the container
linearLayout.setPadding(0, 0, 0, 0);
return linearLayout;
}
/**
* simple helper method to reset the selection of the sticky footer
*/
private void resetStickyFooterSelection() {
if (mStickyFooterView instanceof LinearLayout) {
for (int i = 1; i < ((LinearLayout) mStickyFooterView).getChildCount(); i++) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
((LinearLayout) mStickyFooterView).getChildAt(i).setActivated(false);
}
((LinearLayout) mStickyFooterView).getChildAt(i).setSelected(false);
}
}
}
/**
* The result object used for the Drawer
*/
public static class Result {
private final Drawer mDrawer;
private FrameLayout mContentView;
/**
* the protected Constructor for the result
*
* @param drawer
*/
protected Result(Drawer drawer) {
this.mDrawer = drawer;
}
/**
* Get the DrawerLayout of the current drawer
*
* @return
*/
public DrawerLayout getDrawerLayout() {
return this.mDrawer.mDrawerLayout;
}
/**
* Open the drawer
*/
public void openDrawer() {
if (mDrawer.mDrawerLayout != null && mDrawer.mSliderLayout != null) {
mDrawer.mDrawerLayout.openDrawer(mDrawer.mSliderLayout);
}
}
/**
* close the drawer
*/
public void closeDrawer() {
if (mDrawer.mDrawerLayout != null) {
mDrawer.mDrawerLayout.closeDrawers();
}
}
/**
* Get the current state of the drawer.
* True if the drawer is currently open.
*
* @return
*/
public boolean isDrawerOpen() {
if (mDrawer.mDrawerLayout != null && mDrawer.mSliderLayout != null) {
return mDrawer.mDrawerLayout.isDrawerOpen(mDrawer.mSliderLayout);
}
return false;
}
/**
* Set the color for the statusBar
*
* @param statusBarColor
*/
public void setStatusBarColor(int statusBarColor) {
if (mDrawer.mDrawerContentRoot != null) {
mDrawer.mDrawerContentRoot.setInsetForeground(statusBarColor);
}
}
/**
* get the slider layout of the current drawer.
* This is the layout containing the ListView
*
* @return
*/
public RelativeLayout getSlider() {
return mDrawer.mSliderLayout;
}
/**
* get the container frameLayout of the current drawer
*
* @return
*/
public FrameLayout getContent() {
if (mContentView == null && this.mDrawer.mDrawerLayout != null) {
mContentView = (FrameLayout) this.mDrawer.mDrawerLayout.findViewById(R.id.content_layout);
}
return mContentView;
}
/**
* get the listView of the current drawer
*
* @return
*/
public ListView getListView() {
return mDrawer.mListView;
}
/**
* get the BaseDrawerAdapter of the current drawer
*
* @return
*/
public BaseDrawerAdapter getAdapter() {
return mDrawer.mAdapter;
}
/**
* get all drawerItems of the current drawer
*
* @return
*/
public ArrayList<IDrawerItem> getDrawerItems() {
return mDrawer.mDrawerItems;
}
/**
* get the Header View if set else NULL
*
* @return
*/
public View getHeader() {
return mDrawer.mHeaderView;
}
/**
* get the StickyHeader View if set else NULL
*
* @return
*/
public View getStickyHeader() {
return mDrawer.mStickyHeaderView;
}
/**
* method to replace a previous set header
*
* @param view
*/
public void setHeader(View view) {
if (getListView() != null) {
BaseDrawerAdapter adapter = getAdapter();
getListView().setAdapter(null);
if (getHeader() != null) {
getListView().removeHeaderView(getHeader());
}
getListView().addHeaderView(view);
getListView().setAdapter(adapter);
}
}
/**
* get the Footer View if set else NULL
*
* @return
*/
public View getFooter() {
return mDrawer.mFooterView;
}
/**
* get the StickyFooter View if set else NULL
*
* @return
*/
public View getStickyFooter() {
return mDrawer.mStickyFooterView;
}
/**
* get the ActionBarDrawerToggle
*
* @return
*/
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mDrawer.mActionBarDrawerToggle;
}
/**
* calculates the position of an drawerItem. searching by it's identifier
*
* @param drawerItem
* @return
*/
public int getPositionFromIdentifier(IDrawerItem drawerItem) {
return getPositionFromIdentifier(drawerItem.getIdentifier());
}
/**
* calculates the position of an drawerItem. searching by it's identifier
*
* @param identifier
* @return
*/
public int getPositionFromIdentifier(int identifier) {
if (identifier >= 0) {
if (mDrawer.mDrawerItems != null) {
int position = 0;
for (IDrawerItem i : mDrawer.mDrawerItems) {
if (i.getIdentifier() == identifier) {
return position;
}
position = position + 1;
}
}
}
return -1;
}
/**
* get the current selection
*
* @return
*/
public int getCurrentSelection() {
return mDrawer.mCurrentSelection;
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view!
*
* @param identifier
*/
public void setSelectionByIdentifier(int identifier) {
setSelection(getPositionFromIdentifier(identifier), true);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true;
*
* @param identifier
* @param fireOnClick
*/
public void setSelectionByIdentifier(int identifier, boolean fireOnClick) {
setSelection(getPositionFromIdentifier(identifier), fireOnClick);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view!
*
* @param drawerItem
*/
public void setSelection(IDrawerItem drawerItem) {
setSelection(getPositionFromIdentifier(drawerItem), true);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true;
*
* @param drawerItem
* @param fireOnClick
*/
public void setSelection(IDrawerItem drawerItem, boolean fireOnClick) {
setSelection(getPositionFromIdentifier(drawerItem), fireOnClick);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view!
*
* @param position the position to select
*/
public void setSelection(int position) {
setSelection(position, true);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true;
*
* @param position
* @param fireOnClick
*/
public void setSelection(int position, boolean fireOnClick) {
if (mDrawer.mListView != null) {
mDrawer.resetStickyFooterSelection();
mDrawer.mListView.setSelection(position + mDrawer.mHeaderOffset);
mDrawer.mListView.setItemChecked(position + mDrawer.mHeaderOffset, true);
if (fireOnClick && mDrawer.mOnDrawerItemClickListener != null) {
mDrawer.mOnDrawerItemClickListener.onItemClick(null, null, position, position, mDrawer.getDrawerItem(position, false));
}
mDrawer.mCurrentSelection = position;
}
}
/**
* update a specific drawer item :D
* automatically identified by its id
*
* @param drawerItem
*/
public void updateItem(IDrawerItem drawerItem) {
updateItem(drawerItem, getPositionFromIdentifier(drawerItem));
}
/**
* Update a drawerItem at a specific position
*
* @param drawerItem
* @param position
*/
public void updateItem(IDrawerItem drawerItem, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Add a drawerItem at the end
*
* @param drawerItem
*/
public void addItem(IDrawerItem drawerItem) {
if (mDrawer.mDrawerItems != null) {
mDrawer.mDrawerItems.add(drawerItem);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Add a drawerItem at a specific position
*
* @param drawerItem
* @param position
*/
public void addItem(IDrawerItem drawerItem, int position) {
if (mDrawer.mDrawerItems != null) {
mDrawer.mDrawerItems.add(position, drawerItem);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Set a drawerItem at a specific position
*
* @param drawerItem
* @param position
*/
public void setItem(IDrawerItem drawerItem, int position) {
if (mDrawer.mDrawerItems != null) {
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Remove a drawerItem at a specific position
*
* @param position
*/
public void removeItem(int position) {
if (mDrawer.checkDrawerItem(position, false)) {
mDrawer.mDrawerItems.remove(position);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Removes all items from drawer
*/
public void removeAllItems() {
mDrawer.mDrawerItems.clear();
mDrawer.mAdapter.dataUpdated();
}
/**
* add new Items to the current DrawerItem List
*
* @param drawerItems
*/
public void addItems(IDrawerItem... drawerItems) {
if (mDrawer.mDrawerItems != null) {
Collections.addAll(mDrawer.mDrawerItems, drawerItems);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Replace the current DrawerItems with a new ArrayList of items
*
* @param drawerItems
*/
public void setItems(ArrayList<IDrawerItem> drawerItems) {
setItems(drawerItems, false);
}
/**
* replace the current DrawerItems with the new ArrayList.
*
* @param drawerItems
* @param switchedItems
*/
private void setItems(ArrayList<IDrawerItem> drawerItems, boolean switchedItems) {
mDrawer.mDrawerItems = drawerItems;
//if we are currently at a switched list set the new reference
if (originalDrawerItems != null && !switchedItems) {
originalDrawerItems = drawerItems;
} else {
mDrawer.mAdapter.setDrawerItems(mDrawer.mDrawerItems);
}
mDrawer.mAdapter.dataUpdated();
}
/**
* Update the name of a drawer item if its an instance of nameable
*
* @param nameRes
* @param position
*/
public void updateName(int nameRes, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Nameable) {
((Nameable) drawerItem).setNameRes(nameRes);
((Nameable) drawerItem).setName(null);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the name of a drawer item if its an instance of nameable
*
* @param name
* @param position
*/
public void updateName(String name, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Nameable) {
((Nameable) drawerItem).setName(name);
((Nameable) drawerItem).setNameRes(-1);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the badge of a drawer item if its an instance of badgeable
*
* @param badge
* @param position
*/
public void updateBadge(String badge, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Badgeable) {
((Badgeable) drawerItem).setBadge(badge);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the icon of a drawer item if its an instance of iconable
*
* @param icon
* @param position
*/
public void updateIcon(Drawable icon, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Iconable) {
((Iconable) drawerItem).setIcon(icon);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the icon of a drawer item from an iconRes
*
* @param iconRes
* @param position
*/
public void updateIcon(int iconRes, int position) {
if (mDrawer.mRootView != null && mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Iconable) {
((Iconable) drawerItem).setIcon(UIUtils.getCompatDrawable(mDrawer.mRootView.getContext(), iconRes));
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the icon of a drawer item if its an instance of iconable
*
* @param icon
* @param position
*/
public void updateIcon(IIcon icon, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Iconable) {
((Iconable) drawerItem).setIIcon(icon);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* setter for the OnDrawerItemClickListener
*
* @param onDrawerItemClickListener
*/
public void setOnDrawerItemClickListener(OnDrawerItemClickListener onDrawerItemClickListener) {
mDrawer.mOnDrawerItemClickListener = onDrawerItemClickListener;
}
/**
* method to get the OnDrawerItemClickListener
*
* @return
*/
public OnDrawerItemClickListener getOnDrawerItemClickListener() {
return mDrawer.mOnDrawerItemClickListener;
}
/**
* setter for the OnDrawerItemLongClickListener
*
* @param onDrawerItemLongClickListener
*/
public void setOnDrawerItemLongClickListener(OnDrawerItemLongClickListener onDrawerItemLongClickListener) {
mDrawer.mOnDrawerItemLongClickListener = onDrawerItemLongClickListener;
}
/**
* method to get the OnDrawerItemLongClickListener
*
* @return
*/
public OnDrawerItemLongClickListener getOnDrawerItemLongClickListener() {
return mDrawer.mOnDrawerItemLongClickListener;
}
//variables to store and remember the original list of the drawer
private Drawer.OnDrawerItemClickListener originalOnDrawerItemClickListener;
private ArrayList<IDrawerItem> originalDrawerItems;
private int originalDrawerSelection = -1;
public boolean switchedDrawerContent() {
return !(originalOnDrawerItemClickListener == null && originalDrawerItems == null && originalDrawerSelection == -1);
}
/**
* method to switch the drawer content to new elements
*
* @param onDrawerItemClickListener
* @param drawerItems
* @param drawerSelection
*/
public void switchDrawerContent(OnDrawerItemClickListener onDrawerItemClickListener, ArrayList<IDrawerItem> drawerItems, int drawerSelection) {
//just allow a single switched drawer
if (!switchedDrawerContent()) {
//save out previous values
originalOnDrawerItemClickListener = getOnDrawerItemClickListener();
originalDrawerItems = getDrawerItems();
originalDrawerSelection = getCurrentSelection();
//set the new items
setOnDrawerItemClickListener(onDrawerItemClickListener);
setItems(drawerItems, true);
setSelection(drawerSelection, false);
}
}
/**
* helper method to reset to the original drawerContent
*/
public void resetDrawerContent() {
if (switchedDrawerContent()) {
//set the new items
setOnDrawerItemClickListener(originalOnDrawerItemClickListener);
setItems(originalDrawerItems, true);
setSelection(originalDrawerSelection, false);
//remove the references
originalOnDrawerItemClickListener = null;
originalDrawerItems = null;
originalDrawerSelection = -1;
}
}
/**
* add the values to the bundle for saveInstanceState
*
* @param savedInstanceState
* @return
*/
public Bundle saveInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (getListView() != null) {
savedInstanceState.putInt(BUNDLE_SELECTION, mDrawer.mCurrentSelection);
}
}
return savedInstanceState;
}
}
public interface OnDrawerNavigationListener {
public boolean onNavigationClickListener(View clickedView);
}
public interface OnDrawerItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem);
}
public interface OnDrawerItemLongClickListener {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem);
}
public interface OnDrawerListener {
public void onDrawerOpened(View drawerView);
public void onDrawerClosed(View drawerView);
}
public interface OnDrawerItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem);
public void onNothingSelected(AdapterView<?> parent);
}
} |
package net.somethingdreadful.MAL;
import android.content.Context;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import net.somethingdreadful.MAL.account.AccountService;
import net.somethingdreadful.MAL.api.ALApi;
import net.somethingdreadful.MAL.api.ALModels.ForumAL;
import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Anime;
import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.BrowseList;
import net.somethingdreadful.MAL.api.BaseModels.Forum;
import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Manga;
import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Reviews;
import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.UserList;
import net.somethingdreadful.MAL.api.BaseModels.History;
import net.somethingdreadful.MAL.api.BaseModels.Profile;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.MALModels.ForumMain;
import net.somethingdreadful.MAL.database.DatabaseManager;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
public class MALManager {
private MALApi malApi;
private ALApi alApi;
private final DatabaseManager dbMan;
public MALManager(Context context) {
if (AccountService.isMAL())
malApi = new MALApi();
else
alApi = new ALApi();
dbMan = new DatabaseManager(context);
}
public static String listSortFromInt(int i, MALApi.ListType type) {
switch (i) {
case 0:
return "";
case 1:
return type.equals(MALApi.ListType.ANIME) ? Anime.STATUS_WATCHING : Manga.STATUS_READING;
case 2:
return Anime.STATUS_COMPLETED;
case 3:
return Anime.STATUS_ONHOLD;
case 4:
return Anime.STATUS_DROPPED;
case 5:
return type.equals(MALApi.ListType.ANIME) ? Anime.STATUS_PLANTOWATCH : Manga.STATUS_PLANTOREAD;
case 6:
return type.equals(MALApi.ListType.ANIME) ? Anime.STATUS_REWATCHING : Manga.STATUS_REREADING;
default:
return type.equals(MALApi.ListType.ANIME) ? Anime.STATUS_WATCHING : Manga.STATUS_READING;
}
}
public Anime getAnime(int id) {
Crashlytics.log(Log.INFO, "MALX", "MALManager.getAnime() : Downloading " + id);
return dbMan.getAnime(id);
}
public Manga getManga(int id) {
Crashlytics.log(Log.INFO, "MALX", "MALManager.getManga() : Downloading " + id);
return dbMan.getManga(id);
}
public ArrayList<Anime> downloadAndStoreAnimeList(String username) {
Crashlytics.log(Log.INFO, "MALX", "MALManager.downloadAndStoreAnimeList() : Downloading " + username);
ArrayList<Anime> result = null;
UserList animeList = AccountService.isMAL() ? malApi.getAnimeList() : alApi.getAnimeList(username);
if (animeList != null) {
result = animeList.getAnimeList();
dbMan.saveAnimeList(result);
dbMan.cleanupAnimeTable();
}
return result;
}
public ArrayList<Manga> downloadAndStoreMangaList(String username) {
Crashlytics.log(Log.INFO, "MALX", "MALManager.downloadAndStoreMangaList() : Downloading " + username);
ArrayList<Manga> result = null;
UserList mangaList = AccountService.isMAL() ? malApi.getMangaList() : alApi.getMangaList(username);
if (mangaList != null) {
result = mangaList.getMangaList();
dbMan.saveMangaList(result);
dbMan.cleanupMangaTable();
}
return result;
}
public ArrayList<Anime> getAnimeListFromDB(String ListType) {
return dbMan.getAnimeList(ListType);
}
public ArrayList<Manga> getMangaListFromDB(String ListType) {
return dbMan.getMangaList(ListType);
}
public Manga updateWithDetails(int id, Manga manga) {
Crashlytics.log(Log.INFO, "MALX", "MALManager.updateWithDetails() : Downloading manga " + id);
Manga manga_api = AccountService.isMAL() ? malApi.getManga(id) : alApi.getManga(id);
if (manga_api != null) {
dbMan.saveManga(manga_api);
return AccountService.isMAL() ? manga_api : dbMan.getManga(id);
}
return manga;
}
public Anime updateWithDetails(int id, Anime anime) {
Crashlytics.log(Log.INFO, "MALX", "MALManager.updateWithDetails() : Downloading anime " + id);
Anime anime_api = AccountService.isMAL() ? malApi.getAnime(id) : alApi.getAnime(id);
if (anime_api != null) {
dbMan.saveAnime(anime_api);
return AccountService.isMAL() ? anime_api : dbMan.getAnime(id);
}
return anime;
}
public ArrayList<Profile> downloadAndStoreFriendList(String user) {
ArrayList<Profile> result = new ArrayList<>();
try {
Crashlytics.log(Log.DEBUG, "MALX", "MALManager.downloadAndStoreFriendList(): Downloading friendlist of " + user);
result = AccountService.isMAL() ? malApi.getFriends(user) : alApi.getFollowers(user);
if (result != null && result.size() > 0 && AccountService.getUsername().equals(user))
dbMan.saveFriendList(result);
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "MALManager.downloadAndStoreFriendList(): " + e.getMessage());
Crashlytics.logException(e);
}
return sortFriendlist(result);
}
private ArrayList<Profile> sortFriendlist(ArrayList<Profile> result){
//sort friendlist
Collections.sort(result != null ? result : new ArrayList<Profile>(), new Comparator<Profile>() {
@Override
public int compare(Profile profile1, Profile profile2)
{
return profile1.getUsername().toLowerCase().compareTo(profile2.getUsername().toLowerCase());
}
});
return result;
}
public ArrayList<Profile> getFriendListFromDB() {
return dbMan.getFriendList();
}
public Profile getProfile(String name) {
Profile profile = new Profile();
try {
Crashlytics.log(Log.DEBUG, "MALX", "MALManager.getProfile(): Downloading profile of " + name);
profile = AccountService.isMAL() ? malApi.getProfile(name) : alApi.getProfile(name);
if (profile != null) {
profile.setUsername(name);
if (name.equalsIgnoreCase(AccountService.getUsername()))
dbMan.saveProfile(profile);
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "MALManager.getProfile(): " + e.getMessage());
Crashlytics.logException(e);
}
return profile;
}
public Profile getProfileFromDB() {
return dbMan.getProfile();
}
public void saveAnimeToDatabase(Anime anime) {
dbMan.saveAnime(anime);
}
public void saveMangaToDatabase(Manga manga) {
dbMan.saveManga(manga);
}
public boolean cleanDirtyAnimeRecords() {
boolean totalSuccess = true;
ArrayList<Anime> dirtyAnimes = dbMan.getDirtyAnimeList();
if (dirtyAnimes != null) {
Crashlytics.log(Log.VERBOSE, "MALX", "MALManager.cleanDirtyAnimeRecords(): Got " + dirtyAnimes.size() + " dirty anime records. Cleaning..");
for (Anime anime : dirtyAnimes) {
totalSuccess = writeAnimeDetails(anime);
if (totalSuccess) {
anime.clearDirty();
saveAnimeToDatabase(anime);
}
if (!totalSuccess)
break;
}
Crashlytics.log(Log.VERBOSE, "MALX", "MALManager.cleanDirtyAnimeRecords(): Cleaned dirty anime records, status: " + totalSuccess);
}
return totalSuccess;
}
public boolean cleanDirtyMangaRecords() {
boolean totalSuccess = true;
ArrayList<Manga> dirtyMangas = dbMan.getDirtyMangaList();
if (dirtyMangas != null) {
Crashlytics.log(Log.VERBOSE, "MALX", "MALManager.cleanDirtyMangaRecords(): Got " + dirtyMangas.size() + " dirty manga records. Cleaning..");
for (Manga manga : dirtyMangas) {
totalSuccess = writeMangaDetails(manga);
if (totalSuccess) {
manga.clearDirty();
saveMangaToDatabase(manga);
}
if (!totalSuccess)
break;
}
Crashlytics.log(Log.VERBOSE, "MALX", "MALManager.cleanDirtyMangaRecords(): Cleaned dirty manga records, status: " + totalSuccess);
}
return totalSuccess;
}
public ArrayList<History> getActivity(String username) {
ArrayList<History> result = AccountService.isMAL() ? malApi.getActivity(username) : alApi.getActivity(username);
Crashlytics.log(Log.INFO, "MALX", "MALManager.getActivity(): got " + String.valueOf(result != null ? result.size() : 0) + " records");
return result;
}
/**
* Api Requests
* <p/>
* All the methods below this block is used to determine and make request to the API.
*/
public Anime getAnimeRecord(int id) {
Crashlytics.log(Log.DEBUG, "MALX", "MALManager.getAnimeRecord(): Downloading " + id);
return AccountService.isMAL() ? malApi.getAnime(id) : alApi.getAnime(id);
}
public Manga getMangaRecord(int id) {
Crashlytics.log(Log.DEBUG, "MALX", "MALManager.getMangaRecord(): Downloading " + id);
return AccountService.isMAL() ? malApi.getManga(id) : alApi.getManga(id);
}
public ForumMain getDiscussion(int id, int page, MALApi.ListType type) {
return type.equals(MALApi.ListType.ANIME) ? malApi.getAnime(id, page) : malApi.getManga(id, page);
}
public void verifyAuthentication() {
if (AccountService.isMAL())
malApi.verifyAuthentication();
else if (AccountService.getAccesToken() == null)
alApi.getAccesToken();
}
public boolean writeAnimeDetails(Anime anime) {
Crashlytics.log(Log.DEBUG, "MALX", "MALManager.writeAnimeDetails(): Updating " + anime.getId());
boolean result;
if (anime.getDeleteFlag())
result = AccountService.isMAL() ? malApi.deleteAnimeFromList(anime.getId()) : alApi.deleteAnimeFromList(anime.getId());
else
result = AccountService.isMAL() ? malApi.addOrUpdateAnime(anime) : alApi.addOrUpdateAnime(anime);
Crashlytics.log(Log.DEBUG, "MALX", "MALManager.writeAnimeDetails(): successfully updated: " + result);
return result;
}
public boolean writeMangaDetails(Manga manga) {
Crashlytics.log(Log.DEBUG, "MALX", "MALManager.writeMangaDetails(): Updating " + manga.getId());
boolean result;
if (manga.getDeleteFlag())
result = AccountService.isMAL() ? malApi.deleteMangaFromList(manga.getId()) : alApi.deleteMangaFromList(manga.getId());
else
result = AccountService.isMAL() ? malApi.addOrUpdateManga(manga) : alApi.addOrUpdateManga(manga);
return result;
}
public BrowseList getMostPopularAnime(int page) {
return AccountService.isMAL() ? malApi.getMostPopularAnime(page) : alApi.getAiringAnime(page);
}
public BrowseList getMostPopularManga(int page) {
return AccountService.isMAL() ? malApi.getMostPopularManga(page) : alApi.getPublishingManga(page);
}
public BrowseList getTopRatedAnime(int page) {
return AccountService.isMAL() ? malApi.getTopRatedAnime(page) : alApi.getYearAnime(Calendar.getInstance().get(Calendar.YEAR), page);
}
public BrowseList getTopRatedManga(int page) {
return AccountService.isMAL() ? malApi.getTopRatedManga(page) : alApi.getYearManga(Calendar.getInstance().get(Calendar.YEAR), page);
}
public BrowseList getJustAddedAnime(int page) {
return AccountService.isMAL() ? malApi.getJustAddedAnime(page) : alApi.getJustAddedAnime(page);
}
public BrowseList getJustAddedManga(int page) {
return AccountService.isMAL() ? malApi.getJustAddedManga(page) : alApi.getJustAddedManga(page);
}
public BrowseList getUpcomingAnime(int page) {
return AccountService.isMAL() ? malApi.getUpcomingAnime(page) : alApi.getUpcomingAnime(page);
}
public BrowseList getUpcomingManga(int page) {
return AccountService.isMAL() ? malApi.getUpcomingManga(page) : alApi.getUpcomingManga(page);
}
public ArrayList<Anime> searchAnime(String query, int page) {
return AccountService.isMAL() ? malApi.searchAnime(query, page) : alApi.searchAnime(query, page);
}
public ArrayList<Manga> searchManga(String query, int page) {
return AccountService.isMAL() ? malApi.searchManga(query, page) : alApi.searchManga(query, page);
}
public ArrayList<Reviews> getAnimeReviews(int id, int page) {
return AccountService.isMAL() ? malApi.getAnimeReviews(id, page) : alApi.getAnimeReviews(id, page);
}
public ArrayList<Reviews> getMangaReviews(int id, int page) {
return AccountService.isMAL() ? malApi.getMangaReviews(id, page) : alApi.getMangaReviews(id, page);
}
public ArrayList<Forum> getForumCategories() {
return AccountService.isMAL() ? malApi.getForum().createBaseModel() : ForumAL.getForum();
}
public ArrayList<Forum> getCategoryTopics(int id, int page) {
return AccountService.isMAL() ? malApi.getCategoryTopics(id, page).createBaseModel() : alApi.getTags(id, page).getForumListBase();
}
public ArrayList<Forum> getTopic(int id, int page) {
return AccountService.isMAL() ? malApi.getPosts(id, page).createBaseModel() : alApi.getPosts(id, page).convertBaseModel();
}
public boolean deleteAnime(Anime anime) {
return dbMan.deleteAnime(anime.getId());
}
public boolean deleteManga(Manga manga) {
return dbMan.deleteManga(manga.getId());
}
public ArrayList<Forum> search(String query) {
return AccountService.isMAL() ? malApi.search(query).createBaseModel() : alApi.search(query).getForumListBase();
}
public ArrayList<Forum> getSubCategory(int id, int page) {
return malApi.getSubBoards(id, page).createBaseModel();
}
public boolean addComment(int id, String message) {
return AccountService.isMAL() ? malApi.addComment(id, message) : alApi.addComment(id, message);
}
public boolean updateComment(int id, String message) {
return AccountService.isMAL() ? malApi.updateComment(id, message) : alApi.updateComment(id, message);
}
} |
package com.qiniu.android.http;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.qiniu.android.common.Constants;
import com.qiniu.android.utils.Dns;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import static java.lang.String.format;
/**
* HTTP
*/
public final class HttpManager {
private static final String userAgent = getUserAgent();
private AsyncHttpClient client;
private IReport reporter;
private String backUpIp;
private UrlConverter converter;
public HttpManager(Proxy proxy) {
this(proxy, null);
}
public HttpManager(Proxy proxy, IReport reporter) {
this(proxy, reporter, null, 10, 30, null);
}
public HttpManager(Proxy proxy, IReport reporter, String backUpIp,
int connectTimeout, int responseTimeout, UrlConverter converter) {
this.backUpIp = backUpIp;
client = new AsyncHttpClient();
client.setConnectTimeout(connectTimeout*1000);
client.setResponseTimeout(responseTimeout * 1000);
client.setUserAgent(userAgent);
client.setEnableRedirects(true);
client.setRedirectHandler(new UpRedirectHandler());
AsyncHttpClient.blockRetryExceptionClass(CancellationHandler.CancellationException.class);
if (proxy != null) {
client.setProxy(proxy.hostAddress, proxy.port, proxy.user, proxy.password);
}
this.reporter = reporter;
if (reporter == null) {
this.reporter = new IReport() {
@Override
public Header[] appendStatHeaders(Header[] headers) {
return headers;
}
@Override
public void updateErrorInfo(ResponseInfo info) {
}
@Override
public void updateSpeedInfo(ResponseInfo info) {
}
};
}
this.converter = converter;
}
public HttpManager() {
this(null);
}
private static String genId() {
Random r = new Random();
return System.currentTimeMillis() + "" + r.nextInt(999);
}
private static String getUserAgent() {
return format("QiniuAndroid/%s (%s; %s; %s)", Constants.VERSION,
android.os.Build.VERSION.RELEASE, android.os.Build.MODEL, genId());
}
/**
* POST
*
* @param url URL
* @param data
* @param offset
* @param size
* @param headers
* @param progressHandler
* @param completionHandler
*/
public void postData(String url, byte[] data, int offset, int size, Header[] headers,
ProgressHandler progressHandler, final CompletionHandler completionHandler, CancellationHandler c, boolean forceIp) {
ByteArrayEntity entity = new ByteArrayEntity(data, offset, size, progressHandler, c);
postEntity(url, entity, headers, progressHandler, completionHandler, forceIp);
}
public void postData(String url, byte[] data, Header[] headers, ProgressHandler progressHandler,
CompletionHandler completionHandler, CancellationHandler c, boolean forceIp) {
postData(url, data, 0, data.length, headers, progressHandler, completionHandler, c, forceIp);
}
private void postEntity(String url, final HttpEntity entity, Header[] headers,
final ProgressHandler progressHandler, final CompletionHandler completionHandler, final boolean forceIp) {
final CompletionHandler wrapper = wrap(completionHandler);
final Header[] h = reporter.appendStatHeaders(headers);
if (converter != null){
url = converter.convert(url);
}
ResponseHandler handler = new ResponseHandler(url, wrapper, progressHandler);
if(backUpIp == null || converter != null){
client.post(null, url, h, entity, null, handler);
return;
}
final String url2 = url;
ExecutorService t = client.getThreadPool();
t.execute(new Runnable() {
@Override
public void run() {
final URI uri = URI.create(url2);
String ip = null;
if (forceIp) {
ip = backUpIp;
}else {
ip = Dns.getAddress(uri.getHost());
if (ip == null || ip.equals("")){
ip = backUpIp;
}
}
final Header[] h2 = new Header[h.length + 1];
System.arraycopy(h, 0, h2, 0, h.length);
String newUrl = null;
try {
newUrl = new URI(uri.getScheme(), null, ip, uri.getPort(), uri.getPath(), uri.getQuery(), null).toString();
} catch (URISyntaxException e) {
throw new AssertionError(e);
}
h2[h.length] = new BasicHeader("Host", uri.getHost());
final String ip2 = ip;
ResponseHandler handler2 = new ResponseHandler(url2, wrap(new CompletionHandler() {
@Override
public void complete(ResponseInfo info, JSONObject response) {
if (uri.getPort() == 80 || info.statusCode != ResponseInfo.CannotConnectToHost){
completionHandler.complete(info, response);
return;
}
String newUrl80 = null;
try {
newUrl80 = new URI(uri.getScheme(), null, ip2, 80, uri.getPath(), uri.getQuery(), null).toString();
} catch (URISyntaxException e) {
throw new AssertionError(e);
}
ResponseHandler handler3 = new ResponseHandler(newUrl80, completionHandler, progressHandler);
client.post(null, newUrl80, h2, entity, null, handler3);
}
}), progressHandler);
client.post(null, newUrl, h2, entity, null, handler2);
}
});
}
/**
* POSTmultipart/form-data
*
* @param url URL
* @param args
* @param progressHandler
* @param completionHandler
*/
public void multipartPost(String url, PostArgs args, ProgressHandler progressHandler,
final CompletionHandler completionHandler, CancellationHandler c, boolean forceIp) {
MultipartBuilder mbuilder = new MultipartBuilder();
for (Map.Entry<String, String> entry : args.params.entrySet()) {
mbuilder.addPart(entry.getKey(), entry.getValue());
}
if (args.data != null) {
ByteArrayInputStream buff = new ByteArrayInputStream(args.data);
try {
mbuilder.addPart("file", args.fileName, buff, args.mimeType);
} catch (IOException e) {
completionHandler.complete(ResponseInfo.fileError(e), null);
return;
}
} else {
try {
mbuilder.addPart("file", args.file, args.mimeType, "filename");
} catch (IOException e) {
completionHandler.complete(ResponseInfo.fileError(e), null);
return;
}
}
ByteArrayEntity entity = mbuilder.build(progressHandler, c);
Header[] h = reporter.appendStatHeaders(new Header[0]);
postEntity(url, entity, h, progressHandler, completionHandler, forceIp);
}
private CompletionHandler wrap(final CompletionHandler completionHandler) {
return new CompletionHandler() {
@Override
public void complete(ResponseInfo info, JSONObject response) {
completionHandler.complete(info, response);
if (info.isOK()) {
reporter.updateSpeedInfo(info);
} else {
reporter.updateErrorInfo(info);
}
}
};
}
} |
package net.somethingdreadful.MAL.api;
import java.util.ArrayList;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpProtocolParams;
import net.somethingdreadful.MAL.PrefManager;
import net.somethingdreadful.MAL.api.response.Anime;
import net.somethingdreadful.MAL.api.response.AnimeList;
import net.somethingdreadful.MAL.api.response.Manga;
import net.somethingdreadful.MAL.api.response.MangaList;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.ApacheClient;
import retrofit.client.Response;
import android.content.Context;
import android.os.Build;
import android.util.Log;
public class MALApi {
private static final String API_HOST = "http://api.atarashiiapp.com";
private final static String USER_AGENT = "Atarashii! (Linux; Android " + Build.VERSION.RELEASE + "; " + Build.MODEL + " Build/" + Build.DISPLAY + ")";
private MALInterface service;
private String username;
public enum ListType {
ANIME, MANGA
}
public MALApi(Context context) {
PrefManager prefManager = new PrefManager(context);
username = prefManager.getUser();
setupRESTService(prefManager.getUser(), prefManager.getPass());
}
public MALApi(String username, String password) {
this.username = username;
setupRESTService(username, password);
}
private void setupRESTService(String username, String password) {
DefaultHttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUserAgent(client.getParams(), USER_AGENT);
client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(username,password));
RestAdapter restAdapter = new RestAdapter.Builder()
.setClient(new ApacheClient(client))
.setServer(API_HOST)
.build();
service = restAdapter.create(MALInterface.class);
}
public boolean isAuth() {
try {
Response response = service.verifyAuthentication();
return response.getStatus() == 200;
} catch (RetrofitError e) {
Log.e("MALX", "caught retrofit error: " + e.getResponse().getStatus());
return false;
}
}
public static ListType getListTypeByString(String name) {
return ListType.valueOf(name.toUpperCase());
}
public static String getListTypeString(ListType type) {
return type.name().toLowerCase();
}
public ArrayList<Anime> searchAnime(String query) {
return service.searchAnime(query);
}
public ArrayList<Manga> searchManga(String query) {
return service.searchManga(query);
}
public AnimeList getAnimeList() {
return service.getAnimeList(username);
}
public MangaList getMangaList() {
return service.getMangaList(username);
}
public Anime getAnime(int id) {
return service.getAnime(id);
}
public Manga getManga(int id) {
return service.getManga(id);
}
public boolean addOrUpdateAnime(Anime anime) {
boolean result = false;
if ( anime.getCreateFlag() )
result = service.addAnime(anime.getId(), anime.getWatchedStatus(), anime.getWatchedEpisodes(), anime.getScore()).getStatus() == 200;
else
result = service.updateAnime(anime.getId(), anime.getWatchedStatus(), anime.getWatchedEpisodes(), anime.getScore()).getStatus() == 200;
return result;
}
public boolean addOrUpdateManga(Manga manga) {
boolean result = false;
if ( manga.getCreateFlag() )
result = service.addManga(manga.getId(), manga.getStatus(), manga.getChaptersRead(), manga.getVolumesRead(), manga.getScore()).getStatus() == 200;
else
result = service.updateManga(manga.getId(), manga.getStatus(), manga.getChaptersRead(), manga.getVolumesRead(), manga.getScore()).getStatus() == 200;
return result;
}
public boolean deleteAnimeFromList(int id) {
return service.deleteAnime(id).getStatus() == 200;
}
public boolean deleteMangaFromList(int id) {
return service.deleteManga(id).getStatus() == 200;
}
public ArrayList<Anime> getMostPopularAnime(int page) {
return service.getPopularAnime(page);
}
public ArrayList<Manga> getMostPopularManga(int page) {
return service.getPopularManga(page);
}
public ArrayList<Anime> getTopRatedAnime(int page) {
return service.getTopRatedAnime(page);
}
public ArrayList<Manga> getTopRatedManga(int page) {
return service.getTopRatedManga(page);
}
public ArrayList<Anime> getJustAddedAnime(int page) {
return service.getJustAddedAnime(page);
}
public ArrayList<Manga> getJustAddedManga(int page) {
return service.getJustAddedManga(page);
}
public ArrayList<Anime> getUpcomingAnime(int page) {
return service.getUpcomingAnime(page);
}
public ArrayList<Manga> getUpcomingManga(int page) {
return service.getUpcomingManga(page);
}
} |
package com.willy.ratingbar;
import android.view.MotionEvent;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
class RatingBarUtils {
private static DecimalFormat mDecimalFormat;
private static final int MAX_CLICK_DISTANCE = 5;
private static final int MAX_CLICK_DURATION = 200;
static boolean isClickEvent(float startX, float startY, MotionEvent event) {
float duration = event.getEventTime() - event.getDownTime();
if (duration > MAX_CLICK_DURATION) {
return false;
}
float differenceX = Math.abs(startX - event.getX());
float differenceY = Math.abs(startY - event.getY());
return !(differenceX > MAX_CLICK_DISTANCE || differenceY > MAX_CLICK_DISTANCE);
}
static float calculateRating(PartialView partialView, float stepSize, float eventX) {
DecimalFormat decimalFormat = RatingBarUtils.getDecimalFormat();
float ratioOfView = Float.parseFloat(decimalFormat.format((eventX - partialView.getLeft()) / partialView.getWidth()));
float steps = Math.round(ratioOfView / stepSize) * stepSize;
return Float.parseFloat(decimalFormat.format((int) partialView.getTag() - (1 - steps)));
}
static float getValidMinimumStars(float minimumStars, int numStars, float stepSize) {
if (minimumStars < 0) {
minimumStars = 0;
}
if (minimumStars > numStars) {
minimumStars = numStars;
}
if (minimumStars % stepSize != 0) {
minimumStars = stepSize;
}
return minimumStars;
}
static DecimalFormat getDecimalFormat() {
if (mDecimalFormat == null) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
symbols.setDecimalSeparator('.');
mDecimalFormat = new DecimalFormat("#.##", symbols);
}
return mDecimalFormat;
}
} |
package jade.imtp.leap.JICP;
//#MIDP_EXCLUDE_FILE
import jade.core.BackEndContainer;
import jade.core.BEConnectionManager;
import jade.core.BackEnd;
import jade.core.FrontEnd;
import jade.core.IMTPException;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.ProfileException;
import jade.core.ContainerID;
import jade.imtp.leap.FrontEndStub;
import jade.imtp.leap.MicroSkeleton;
import jade.imtp.leap.BackEndSkel;
import jade.imtp.leap.Dispatcher;
import jade.imtp.leap.ICP;
import jade.imtp.leap.ICPException;
import jade.util.leap.Properties;
import jade.core.TimerDispatcher;
import jade.core.Timer;
import jade.core.TimerListener;
import jade.core.Runtime;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* Class declaration
* @author Giovanni Caire - TILAB
*/
public class BackEndDispatcher extends EndPoint implements BEConnectionManager, Dispatcher, JICPMediator {
private long maxDisconnectionTime;
private JICPServer myJICPServer;
private String myID;
// The permanent connection to the remote FrontEnd
private Connection conn;
private boolean newConnectionReady = false;
private MicroSkeleton mySkel = null;
private FrontEndStub myStub = null;
private BackEndContainer myContainer = null;
/**
* Constructor declaration
*/
public BackEndDispatcher() {
}
// JICPMediator interface implementation
/**
Initialize parameters and start the embedded thread
*/
public void init(JICPServer srv, String id, Properties props) throws ICPException {
myJICPServer = srv;
myID = id;
// Verbosity
try {
verbosity = Integer.parseInt(props.getProperty("verbosity"));
}
catch (NumberFormatException nfe) {
// Use default (1)
}
// Max disconnection time
maxDisconnectionTime = JICPProtocol.DEFAULT_MAX_DISCONNECTION_TIME;
try {
maxDisconnectionTime = Long.parseLong(props.getProperty(JICPProtocol.MAX_DISCONNECTION_TIME_KEY));
}
catch (Exception e) {
// Keep default
}
// Start the EndPoit embedded thread
start();
//initCnt();
log("Created BackEndDispatcher V1.0 ID = "+myID+" MaxDisconnectionTime = "+maxDisconnectionTime, 1);
try {
myStub = new FrontEndStub(this);
props.setProperty(Profile.MAIN, "false");
props.setProperty("mobility", "jade.core.DummyMobilityManager");
myContainer = new BackEndContainer(new ProfileImpl(props), this);
// Check that the BackEndContainer has successfully joined the platform
ContainerID cid = (ContainerID) myContainer.here();
if (cid == null || cid.getName().equals("No-Name")) {
throw new ICPException("BackEnd container failed to join the platform");
}
mySkel = new BackEndSkel(myContainer);
log("BackEndContainer successfully joined the platform: name is "+cid.getName(), 2);
}
catch (ProfileException pe) {
// should never happen
pe.printStackTrace();
throw new ICPException("Error creating profile");
}
}
/**
Shutdown forced by the JICPServer this BackEndContainer is attached
to
*/
public void kill() {
// Force the BackEndContainer to terminate. This will also
// cause this BackEndDispatcher to terminate and deregister
// from the JICPServer
try {
myContainer.exit();
}
catch (IMTPException imtpe) {
// Should never happen as this is a local call
imtpe.printStackTrace();
}
}
/**
This is called by the JICPServer. In the case of the BackEndDispatcher
it can happen when packets from the front end to the back end
are delivered through a separate channel.
@see AsymFrontEndDispatcher#deliver(JICPPacket)
*/
public JICPPacket handleJICPPacket(JICPPacket p) throws ICPException {
servePacket(p);
// No response is returned as the actual response will go back
// through the permanent connection
return null;
}
// BEConnectionManager interface implementation
/**
Return a stub of the remote FrontEnd that is connected to the
local BackEnd.
@param be The local BackEnd
@param props Additional (implementation dependent) connection
configuration properties.
@return A stub of the remote FrontEnd.
*/
public FrontEnd getFrontEnd(BackEnd be, Properties props) throws IMTPException {
return myStub;
}
/**
Make this BackEndDispatcher terminate.
*/
public void shutdown() {
log("Initiate BackEndDispatcher shutdown", 2);
// Deregister from the JICPServer
if (myID != null) {
myJICPServer.deregisterMediator(myID);
myID = null;
}
// Enable EndPoint shutdown
super.shutdown();
}
// Dispatcher interface implementation
public byte[] dispatch(byte[] payload) throws ICPException {
JICPPacket p = new JICPPacket(JICPProtocol.COMMAND_TYPE, JICPProtocol.COMPRESSED_INFO, payload);
JICPPacket r = deliverCommand(p);
updateTransmitted(p.getLength());
updateReceived(r.getLength());
return r.getData();
}
// EndPoint abstract class implementation
protected JICPPacket handleCommand(JICPPacket cmd) throws Exception {
updateReceived(cmd.getLength());
byte[] rspData = mySkel.handleCommand(cmd.getData());
JICPPacket rsp = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, rspData);
updateTransmitted(rsp.getLength());
return rsp;
}
protected synchronized void setup() throws ICPException {
while (!newConnectionReady) {
try {
wait(maxDisconnectionTime);
if (!newConnectionReady) {
throw new ICPException("The FrontEnd container is probably down!");
}
}
catch (InterruptedException ie) {
log("InterruptedException while waiting for the FrontEnd container to (re)connect", 1);
}
}
// If we get here there is a new connection ready --> Pass the connection to the EndPoint
try {
setConnection(conn);
newConnectionReady = false;
}
catch (IOException ioe) {
// The new connection is already down. Ignore it. The embedded thread
// will call setup() again.
log("New connection already down.", 1);
}
}
protected void handlePeerExited() {
// The FrontEnd has exited --> suicide!
kill();
}
protected void handleConnectionError() {
// The FrontEnd is probably dead --> suicide!
// FIXME: If there are pending messages that will never be delivered
// we should notify a FAILURE to the sender
kill();
}
/**
The connection is up --> flush bufferd commands.
*/
protected void handleConnectionReady() {
myStub.flush();
}
/**
* Sets the socket connected to the mediated container.
* This is called by the JICPServer this BackEndDispatcher is
* attached to as soon as the FrontEnd container (re)connects.
* @param s the socket connected to the FrontEnd container
*/
public synchronized void setConnection(Socket s) {
if (isConnected()) {
// If the connection seems to be still valid then reset it so that
// the embedded thread realizes it is no longer valid.
resetConnection();
}
conn = new Connection(s);
newConnectionReady = true;
notifyAll();
}
// This part is only related to counting transmitted/received bytes
private int transmittedCnt = 0;
private int receivedCnt = 0;
private Object cntLock = new Object();
private void updateTransmitted(int n) {
synchronized(cntLock) {
transmittedCnt += n;
}
}
private void updateReceived(int n) {
synchronized(cntLock) {
receivedCnt += n;
}
}
private void initCnt() {
if (myID != null) {
final String id = myID;
Timer t = new Timer(System.currentTimeMillis()+30000, new TimerListener() {
public void doTimeOut(Timer t) {
synchronized (cntLock) {
System.out.println("BackEndDispatcher "+id);
System.out.println("Transmitted cnt = "+transmittedCnt);
System.out.println("Received cnt = "+receivedCnt);
System.out.println("
transmittedCnt = 0;
receivedCnt = 0;
}
initCnt();
}
} );
TimerDispatcher td = Runtime.instance().getTimerDispatcher();
td.add(t);
}
}
} |
package org.client;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import org.common.Utils;
/**
* Hello world!
*
*/
public class App
{
private static final String serverAddress = "127.0.0.1";
private static final int serverPort = 3000;
private Socket sock;
private PrintWriter out;
private BufferedReader in;
/**
* Main entry point of the client application.
*
* @param args
*/
public static void main( String[] args )
{
App client = new App();
client.start();
// temporary, we will run this in a loop
Console console = System.console();
console.readLine("Any key to exit.");
}
/**
* Start the client logic.
*/
void start() {
try {
this.sock = new Socket(serverAddress, serverPort);
this.out = new PrintWriter(this.sock.getOutputStream(), true);
this.in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Host \"" + serverAddress + "\" is unknown.");
e.printStackTrace();
return;
} catch (IOException e) {
System.out.println("Failed to connect. Is server running at \"" + serverAddress + ":" + serverPort + "\"?");
e.printStackTrace();
return;
}
// Now we know the server is online.
// get their desired username. want to loop until they find an acceptable
// username.
boolean loginSuccessful = false;
Console console = System.console();
while(!loginSuccessful) {
String username = console.readLine("Enter your username: ");
String loginMsg = createLoginMessageForUser(username);
Utils.sendMessage(this.out, loginMsg);
if(statusOk()) {
System.out.println("Successful login as \"" + username + "\"");
// we shall stop trying
loginSuccessful = true;
}
else {
System.out.println("Failed to login as \"" + username + "\"");
}
}
}
/**
* Simple function to craft a message for logging in.
*
* @param username - desired username
* @return the login message
*/
public String createLoginMessageForUser(String username) {
return "login " + username;
}
/**
* Helper to check the status of return messages. Call when expecting
* a status response from the server.
*
* @return true if OK, false if not
*/
private boolean statusOk() {
// first need to get.
// NOTE we probably want to eventually add a timeout to this.
String msg = Utils.receiveMessage(this.in);
if(msg.equals(Utils.SUCCESS_STS)) {
return true;
} else {
System.out.println("Error: " + msg);
return false;
}
}
/**
* log off from the server
*
* @param
* username - the user log off from the server
* */
private void logoff(PrintWriter writer, String username) {
String logoffSignal = "logoff " + username;
Utils.sendMessage(writer, logoffSignal);
try {
finalize();
} catch (Throwable e) {
e.printStackTrace();
}
System.exit(0);
}
} |
package io.moquette.spi.impl;
import io.moquette.interception.InterceptHandler;
import io.moquette.server.netty.MessageBuilder;
import io.moquette.server.netty.NettyUtils;
import io.moquette.spi.IMatchingCondition;
import io.moquette.spi.IMessagesStore;
import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.ISessionsStore;
import io.moquette.spi.impl.security.PermitAllAuthorizator;
import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore;
import io.moquette.spi.security.IAuthorizator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.mqtt.*;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import static io.moquette.spi.impl.NettyChannelAssertions.assertConnAckAccepted;
import static io.moquette.spi.impl.ProtocolProcessor.lowerQosToTheSubscriptionDesired;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
*
* @author andrea
*/
public class ProtocolProcessorTest {
static final String FAKE_CLIENT_ID = "FAKE_123";
static final String FAKE_CLIENT_ID2 = "FAKE_456";
static final String FAKE_PUBLISHER_ID = "Publisher";
static final String FAKE_TOPIC = "/news";
static final String BAD_FORMATTED_TOPIC = "#MQTTClient";
static final String TEST_USER = "fakeuser";
static final String TEST_PWD = "fakepwd";
static final String EVIL_TEST_USER = "eviluser";
static final String EVIL_TEST_PWD = "unsecret";
static final List<InterceptHandler> EMPTY_OBSERVERS = Collections.emptyList();
static final BrokerInterceptor NO_OBSERVERS_INTERCEPTOR = new BrokerInterceptor(EMPTY_OBSERVERS);
EmbeddedChannel m_channel;
MqttConnectMessage connMsg;
ProtocolProcessor m_processor;
IMessagesStore m_messagesStore;
ISessionsStore m_sessionStore;
SubscriptionsStore subscriptions;
MockAuthenticator m_mockAuthenticator;
@Before
public void setUp() throws InterruptedException {
/*
* connMsg = new ConnectMessage(); connMsg.setProtocolVersion((byte) 0x03);
*
* connMsg = MessageBuilder.connect() .protocolVersion(MqttVersion.MQTT_3_1)
* .clientId(FAKE_CLIENT_ID) .cleanSession(true) .build();
*/
m_channel = new EmbeddedChannel();
NettyUtils.clientID(m_channel, FAKE_CLIENT_ID);
NettyUtils.cleanSession(m_channel, false);
// sleep to let the messaging batch processor to process the initEvent
Thread.sleep(300);
MemoryStorageService memStorage = new MemoryStorageService();
memStorage.initStore();
m_messagesStore = memStorage.messagesStore();
m_sessionStore = memStorage.sessionsStore();
// m_messagesStore.initStore();
Set<String> clientIds = new HashSet<>();
clientIds.add(FAKE_CLIENT_ID);
clientIds.add(FAKE_CLIENT_ID2);
Map<String, String> users = new HashMap<>();
users.put(TEST_USER, TEST_PWD);
m_mockAuthenticator = new MockAuthenticator(clientIds, users);
subscriptions = new SubscriptionsStore();
subscriptions.init(memStorage.sessionsStore());
m_processor = new ProtocolProcessor();
m_processor.init(
subscriptions,
m_messagesStore,
m_sessionStore,
m_mockAuthenticator,
true,
new PermitAllAuthorizator(),
NO_OBSERVERS_INTERCEPTOR);
}
@Test
public void testPublishToItself() throws InterruptedException {
final Subscription subscription = new Subscription(FAKE_CLIENT_ID, FAKE_TOPIC, MqttQoS.AT_MOST_ONCE);
// subscriptions.matches(topic) redefine the method to return true
SubscriptionsStore subs = new SubscriptionsStore() {
@Override
public List<Subscription> matches(String topic) {
if (topic.equals(FAKE_TOPIC)) {
return Collections.singletonList(subscription);
} else {
throw new IllegalArgumentException("Expected " + FAKE_TOPIC + " buf found " + topic);
}
}
};
// simulate a connect that register a clientID to an IoSession
MemoryStorageService storageService = new MemoryStorageService();
storageService.initStore();
subs.init(storageService.sessionsStore());
m_processor.init(
subs,
m_messagesStore,
m_sessionStore,
null,
true,
new PermitAllAuthorizator(),
NO_OBSERVERS_INTERCEPTOR);
MqttConnectMessage connectMessage = MessageBuilder.connect().protocolVersion(MqttVersion.MQTT_3_1)
.clientId(FAKE_CLIENT_ID).cleanSession(true).build();
m_processor.processConnect(m_channel, connectMessage);
// Exercise
MqttPublishMessage msg = MessageBuilder.publish().topicName(FAKE_TOPIC).qos(MqttQoS.AT_MOST_ONCE)
.retained(false).payload("Hello".getBytes()).build();
NettyUtils.userName(m_channel, "FakeCLI");
m_processor.processPublish(m_channel, msg);
// Verify
assertNotNull(m_channel.readOutbound());
// TODO check received message attributes
}
@Test
public void testPublishToMultipleSubscribers() throws InterruptedException {
final Subscription subscription = new Subscription(FAKE_CLIENT_ID, FAKE_TOPIC, MqttQoS.AT_MOST_ONCE);
final Subscription subscriptionClient2 = new Subscription(FAKE_CLIENT_ID2, FAKE_TOPIC, MqttQoS.AT_MOST_ONCE);
// subscriptions.matches(topic) redefine the method to return true
SubscriptionsStore subs = new SubscriptionsStore() {
@Override
public List<Subscription> matches(String topic) {
if (topic.equals(FAKE_TOPIC)) {
return Arrays.asList(subscription, subscriptionClient2);
} else {
throw new IllegalArgumentException("Expected " + FAKE_TOPIC + " buf found " + topic);
}
}
};
// simulate a connect that register a clientID to an IoSession
MemoryStorageService storageService = new MemoryStorageService();
storageService.initStore();
subs.init(storageService.sessionsStore());
m_processor.init(
subs,
m_messagesStore,
m_sessionStore,
null,
true,
new PermitAllAuthorizator(),
NO_OBSERVERS_INTERCEPTOR);
EmbeddedChannel firstReceiverChannel = new EmbeddedChannel();
MqttConnectMessage connectMessage = MessageBuilder.connect().protocolVersion(MqttVersion.MQTT_3_1)
.clientId(FAKE_CLIENT_ID).cleanSession(true).build();
m_processor.processConnect(firstReceiverChannel, connectMessage);
assertConnAckAccepted(firstReceiverChannel);
// connect the second fake subscriber
EmbeddedChannel secondReceiverChannel = new EmbeddedChannel();
MqttConnectMessage connectMessage2 = MessageBuilder.connect().protocolVersion(MqttVersion.MQTT_3_1)
.clientId(FAKE_CLIENT_ID2).cleanSession(true).build();
m_processor.processConnect(secondReceiverChannel, connectMessage2);
assertConnAckAccepted(secondReceiverChannel);
// Exercise
MqttPublishMessage msg = MessageBuilder.publish().topicName(FAKE_TOPIC).qos(MqttQoS.AT_MOST_ONCE)
.retained(false).payload("Hello".getBytes()).build();
NettyUtils.userName(m_channel, "FakeCLI");
m_processor.processPublish(m_channel, msg);
// Verify
firstReceiverChannel.flush();
MqttPublishMessage pub2FirstSubscriber = firstReceiverChannel.readOutbound();
assertNotNull(pub2FirstSubscriber);
String firstMessageContent = DebugUtils.payload2Str(pub2FirstSubscriber.payload());
assertEquals("Hello", firstMessageContent);
secondReceiverChannel.flush();
MqttPublishMessage pub2SecondSubscriber = secondReceiverChannel.readOutbound();
assertNotNull(pub2SecondSubscriber);
String secondMessageContent = DebugUtils.payload2Str(pub2SecondSubscriber.payload());
assertEquals("Hello", secondMessageContent);
}
@Test
public void testSubscribe() {
MqttSubscribeMessage msg = MessageBuilder.subscribe().addSubscription(MqttQoS.AT_MOST_ONCE, FAKE_TOPIC)
.messageId(10).build();
// Exercise
m_sessionStore.createNewSession(FAKE_CLIENT_ID, false);
m_processor.processSubscribe(m_channel, msg);
// Verify
assertTrue(m_channel.readOutbound() instanceof MqttSubAckMessage);
Subscription expectedSubscription = new Subscription(FAKE_CLIENT_ID, FAKE_TOPIC, MqttQoS.AT_MOST_ONCE);
assertTrue(subscriptions.contains(expectedSubscription));
}
@Test
public void testSubscribedToNotAuthorizedTopic() {
final String fakeUserName = "UnAuthUser";
NettyUtils.userName(m_channel, fakeUserName);
IAuthorizator mockAuthorizator = mock(IAuthorizator.class);
when(mockAuthorizator.canRead(eq(FAKE_TOPIC), eq(fakeUserName), eq(FAKE_CLIENT_ID))).thenReturn(false);
m_processor.init(
subscriptions,
m_messagesStore,
m_sessionStore,
m_mockAuthenticator,
true,
mockAuthorizator,
NO_OBSERVERS_INTERCEPTOR);
// Exercise
MqttSubscribeMessage msg = MessageBuilder.subscribe().addSubscription(MqttQoS.AT_MOST_ONCE, FAKE_TOPIC)
.messageId(10).build();
m_sessionStore.createNewSession(FAKE_CLIENT_ID, false);
m_processor.processSubscribe(m_channel, msg);
// Verify
Object ackMsg = m_channel.readOutbound();
assertTrue(ackMsg instanceof MqttSubAckMessage);
MqttSubAckMessage subAckMsg = (MqttSubAckMessage) ackMsg;
verifyFailureQos(subAckMsg);
}
private void verifyFailureQos(MqttSubAckMessage subAckMsg) {
List<Integer> grantedQoSes = subAckMsg.payload().grantedQoSLevels();
assertEquals(1, grantedQoSes.size());
assertTrue(grantedQoSes.contains(MqttQoS.FAILURE.value()));
}
@Test
public void testDoubleSubscribe() {
MqttSubscribeMessage msg = MessageBuilder.subscribe().addSubscription(MqttQoS.AT_MOST_ONCE, FAKE_TOPIC)
.messageId(10).build();
m_sessionStore.createNewSession(FAKE_CLIENT_ID, false);
assertEquals(0, subscriptions.size());
m_processor.processSubscribe(m_channel, msg);
// Exercise
m_processor.processSubscribe(m_channel, msg);
// Verify
assertEquals(1, subscriptions.size());
Subscription expectedSubscription = new Subscription(FAKE_CLIENT_ID, FAKE_TOPIC, MqttQoS.AT_MOST_ONCE);
assertTrue(subscriptions.contains(expectedSubscription));
}
@Test
public void testSubscribeWithBadFormattedTopic() {
MqttSubscribeMessage msg = MessageBuilder.subscribe().addSubscription(MqttQoS.AT_MOST_ONCE, BAD_FORMATTED_TOPIC)
.messageId(10).build();
m_sessionStore.createNewSession(FAKE_CLIENT_ID, false);
assertEquals(0, subscriptions.size());
// Exercise
m_processor.processSubscribe(m_channel, msg);
// Verify
assertEquals(0, subscriptions.size());
Object recvSubAckMessage = m_channel.readOutbound();
assertTrue(recvSubAckMessage instanceof MqttSubAckMessage);
verifyFailureQos((MqttSubAckMessage) recvSubAckMessage);
}
/*
* Check topicFilter is a valid MQTT topic filter (issue 68)
*/
@Test
public void testUnsubscribeWithBadFormattedTopic() {
MqttUnsubscribeMessage msg = MessageBuilder.unsubscribe().addTopicFilter(BAD_FORMATTED_TOPIC).messageId(1)
.build();
// Exercise
m_processor.processUnsubscribe(m_channel, msg);
// Verify
assertFalse("If client unsubscribe with bad topic than channel must be closed", m_channel.isOpen());
}
@Test
public void testPublishOfRetainedMessage_afterNewSubscription() throws Exception {
// simulate a connect that register a clientID to an IoSession
final Subscription subscription = new Subscription(FAKE_PUBLISHER_ID, FAKE_TOPIC, MqttQoS.AT_MOST_ONCE);
// subscriptions.matches(topic) redefine the method to return true
SubscriptionsStore subs = new SubscriptionsStore() {
@Override
public List<Subscription> matches(String topic) {
if (topic.equals(FAKE_TOPIC)) {
return Collections.singletonList(subscription);
} else {
throw new IllegalArgumentException("Expected " + FAKE_TOPIC + " buf found " + topic);
}
}
};
MemoryStorageService storageService = new MemoryStorageService();
storageService.initStore();
subs.init(storageService.sessionsStore());
// simulate a connect that register a clientID to an IoSession
m_processor.init(
subs,
m_messagesStore,
m_sessionStore,
null,
true,
new PermitAllAuthorizator(),
NO_OBSERVERS_INTERCEPTOR);
MqttConnectMessage connectMessage = MessageBuilder.connect().clientId(FAKE_PUBLISHER_ID)
.protocolVersion(MqttVersion.MQTT_3_1).cleanSession(true).build();
m_processor.processConnect(m_channel, connectMessage);
assertConnAckAccepted(m_channel);
MqttPublishMessage pubmsg = MessageBuilder.publish().topicName(FAKE_TOPIC).qos(MqttQoS.AT_MOST_ONCE)
.payload("Hello".getBytes()).retained(true).build();
NettyUtils.clientID(m_channel, FAKE_PUBLISHER_ID);
m_processor.processPublish(m_channel, pubmsg);
NettyUtils.cleanSession(m_channel, false);
// Exercise
MqttSubscribeMessage msg = MessageBuilder.subscribe().messageId(10).addSubscription(MqttQoS.AT_MOST_ONCE, "
.build();
m_processor.processSubscribe(m_channel, msg);
// Verify
// wait the latch
Object pubMessage = m_channel.readOutbound();
assertNotNull(pubMessage);
assertTrue(pubMessage instanceof MqttPublishMessage);
assertEquals(FAKE_TOPIC, ((MqttPublishMessage) pubMessage).variableHeader().topicName());
}
@Test
public void testRepublishAndConsumePersistedMessages_onReconnect() {
SubscriptionsStore subs = mock(SubscriptionsStore.class);
List<Subscription> emptySubs = Collections.emptyList();
when(subs.matches(anyString())).thenReturn(emptySubs);
StoredMessage retainedMessage = new StoredMessage("Hello".getBytes(), MqttQoS.EXACTLY_ONCE, "/topic");
retainedMessage.setRetained(true);
retainedMessage.setMessageID(120);
retainedMessage.setClientID(FAKE_PUBLISHER_ID);
m_messagesStore.storePublishForFuture(retainedMessage);
m_processor.init(
subs,
m_messagesStore,
m_sessionStore,
null,
true,
new PermitAllAuthorizator(),
NO_OBSERVERS_INTERCEPTOR);
MqttConnectMessage connectMessage = MessageBuilder.connect().clientId(FAKE_PUBLISHER_ID)
.protocolVersion(MqttVersion.MQTT_3_1).build();
m_processor.processConnect(m_channel, connectMessage);
// Verify no messages are still stored
BlockingQueue<StoredMessage> messages = m_sessionStore.queue(FAKE_PUBLISHER_ID);
assertTrue(messages.isEmpty());
}
@Test
public void publishNoPublishToInactiveSession() {
// create an inactive session for Subscriber
m_sessionStore.createNewSession("Subscriber", false);
SubscriptionsStore mockedSubscriptions = mock(SubscriptionsStore.class);
Subscription inactiveSub = new Subscription("Subscriber", "/topic", MqttQoS.AT_LEAST_ONCE);
List<Subscription> inactiveSubscriptions = Collections.singletonList(inactiveSub);
when(mockedSubscriptions.matches(eq("/topic"))).thenReturn(inactiveSubscriptions);
m_processor = new ProtocolProcessor();
m_processor.init(
mockedSubscriptions,
m_messagesStore,
m_sessionStore,
null,
true,
new PermitAllAuthorizator(),
NO_OBSERVERS_INTERCEPTOR);
// Exercise
MqttPublishMessage msg = MessageBuilder.publish().topicName("/topic").qos(MqttQoS.AT_MOST_ONCE)
.payload("Hello".getBytes()).retained(true).build();
NettyUtils.clientID(m_channel, "Publisher");
m_processor.processPublish(m_channel, msg);
// Verify no message is received
assertNull(m_channel.readOutbound());
}
/**
* Verify that receiving a publish with retained message and with Q0S = 0 clean the existing
* retained messages for that topic.
*/
@Test
public void testCleanRetainedStoreAfterAQoS0AndRetainedTrue() {
// force a connect
connMsg = MessageBuilder.connect().protocolVersion(MqttVersion.MQTT_3_1).clientId("Publisher")
.cleanSession(true).build();
m_processor.processConnect(m_channel, connMsg);
// prepare and existing retained store
NettyUtils.clientID(m_channel, "Publisher");
MqttPublishMessage msg = MessageBuilder.publish().topicName(FAKE_TOPIC).qos(MqttQoS.AT_LEAST_ONCE)
.payload("Hello".getBytes()).retained(true).messageId(100).build();
m_processor.processPublish(m_channel, msg);
Collection<IMessagesStore.StoredMessage> messages = m_messagesStore.searchMatching(new IMatchingCondition() {
public boolean match(String key) {
return SubscriptionsStore.matchTopics(key, FAKE_TOPIC);
}
});
assertFalse(messages.isEmpty());
// Exercise
MqttPublishMessage cleanPubMsg = MessageBuilder.publish().topicName(FAKE_TOPIC).qos(MqttQoS.AT_MOST_ONCE)
.payload("Hello".getBytes()).retained(true).build();
m_processor.processPublish(m_channel, cleanPubMsg);
// Verify
messages = m_messagesStore.searchMatching(new IMatchingCondition() {
public boolean match(String key) {
return SubscriptionsStore.matchTopics(key, FAKE_TOPIC);
}
});
assertTrue(messages.isEmpty());
}
@Test
public void testLowerTheQosToTheRequestedBySubscription() {
Subscription subQos1 = new Subscription("Sub A", "a/b", MqttQoS.AT_LEAST_ONCE);
assertEquals(MqttQoS.AT_LEAST_ONCE, lowerQosToTheSubscriptionDesired(subQos1, MqttQoS.EXACTLY_ONCE));
Subscription subQos2 = new Subscription("Sub B", "a/+", MqttQoS.EXACTLY_ONCE);
assertEquals(MqttQoS.EXACTLY_ONCE, lowerQosToTheSubscriptionDesired(subQos2, MqttQoS.EXACTLY_ONCE));
}
} |
package com.wonderkiln.camerakit;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Rect;
import android.support.media.ExifInterface;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import static com.wonderkiln.camerakit.CameraKit.Constants.FACING_FRONT;
public class PostProcessor {
private byte[] picture;
private int jpegQuality;
private int facing;
private AspectRatio cropAspectRatio;
public PostProcessor(byte[] picture) {
this.picture = picture;
}
public void setJpegQuality(int jpegQuality) {
this.jpegQuality = jpegQuality;
}
public void setFacing(int facing) {
this.facing = facing;
}
public void setCropOutput(AspectRatio aspectRatio) {
this.cropAspectRatio = aspectRatio;
}
public byte[] getJpeg() {
Bitmap bitmap;
try {
bitmap = getBitmap();
} catch (IOException e) {
return null;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
BitmapOperator bitmapOperator = new BitmapOperator(bitmap);
bitmap.recycle();
ExifPostProcessor exifPostProcessor = new ExifPostProcessor(picture);
exifPostProcessor.apply(bitmapOperator);
if (facing == FACING_FRONT) {
bitmapOperator.flipBitmapHorizontal();
}
if (cropAspectRatio != null) {
int cropWidth = width;
int cropHeight = height;
if (exifPostProcessor.areDimensionsFlipped()) {
cropWidth = height;
cropHeight = width;
}
new CenterCrop(cropWidth, cropHeight, cropAspectRatio).apply(bitmapOperator);
}
bitmap = bitmapOperator.getBitmapAndFree();
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, jpegQuality, out);
return out.toByteArray();
}
private Bitmap getBitmap() throws IOException {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(picture, 0, picture.length, options);
return BitmapRegionDecoder.newInstance(
picture,
0,
picture.length,
true
).decodeRegion(new Rect(0, 0, options.outWidth, options.outHeight), null);
}
private static class ExifPostProcessor {
private int orientation = ExifInterface.ORIENTATION_UNDEFINED;
public ExifPostProcessor(byte[] picture) {
try {
orientation = getExifOrientation(new ByteArrayInputStream(picture));
} catch (IOException e) {
e.printStackTrace();
}
}
public void apply(BitmapOperator bitmapOperator) {
switch (orientation) {
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
bitmapOperator.flipBitmapHorizontal();
break;
case ExifInterface.ORIENTATION_ROTATE_180:
bitmapOperator.rotateBitmap(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
bitmapOperator.flipBitmapVertical();
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
bitmapOperator.rotateBitmap(90);
bitmapOperator.flipBitmapHorizontal();
break;
case ExifInterface.ORIENTATION_ROTATE_90:
bitmapOperator.rotateBitmap(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
bitmapOperator.rotateBitmap(270);
bitmapOperator.flipBitmapHorizontal();
break;
case ExifInterface.ORIENTATION_ROTATE_270:
bitmapOperator.rotateBitmap(270);
break;
case ExifInterface.ORIENTATION_NORMAL:
case ExifInterface.ORIENTATION_UNDEFINED:
break;
}
}
public boolean areDimensionsFlipped() {
switch (orientation) {
case ExifInterface.ORIENTATION_TRANSPOSE:
case ExifInterface.ORIENTATION_ROTATE_90:
case ExifInterface.ORIENTATION_TRANSVERSE:
case ExifInterface.ORIENTATION_ROTATE_270:
return true;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
case ExifInterface.ORIENTATION_ROTATE_180:
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
case ExifInterface.ORIENTATION_NORMAL:
case ExifInterface.ORIENTATION_UNDEFINED:
return false;
}
return false;
}
private static int getExifOrientation(InputStream inputStream) throws IOException {
ExifInterface exif = new ExifInterface(inputStream);
return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}
}
private static class CenterCrop {
private int width;
private int height;
private AspectRatio aspectRatio;
public CenterCrop(int width, int height, AspectRatio aspectRatio) {
this.width = width;
this.height = height;
this.aspectRatio = aspectRatio;
}
public void apply(BitmapOperator bitmapOperator) {
Rect crop = getCrop(width, height, aspectRatio);
bitmapOperator.cropBitmap(crop.left, crop.top, crop.right, crop.bottom);
}
private static Rect getCrop(int currentWidth, int currentHeight, AspectRatio targetRatio) {
AspectRatio currentRatio = AspectRatio.of(currentWidth, currentHeight);
Rect crop;
if (currentRatio.toFloat() > targetRatio.toFloat()) {
int width = (int) (currentHeight * targetRatio.toFloat());
int widthOffset = (currentWidth - width) / 2;
crop = new Rect(widthOffset, 0, currentWidth - widthOffset, currentHeight);
} else {
int height = (int) (currentWidth * targetRatio.inverse().toFloat());
int heightOffset = (currentHeight - height) / 2;
crop = new Rect(0, heightOffset, currentWidth, currentHeight - heightOffset);
}
return crop;
}
}
} |
package checker;
import java.util.ArrayList;
import util.AST.*;
import util.AST.AST.Types;
import util.AST.Number;
import util.symbolsTable.IdentificationTable;
public class Checker implements Visitor{
private IdentificationTable idTable;
private int contadorParametros = 0;
public void check(Code code) throws SemanticException {
idTable = new IdentificationTable();
code.visit(this, null);
}
public Object visitAccept(Accept accept, Object args)
throws SemanticException {
//TODO
return null;
}
public Object visitArithmeticExpression(ArithmeticExpression expression,
Object args) throws SemanticException {
//TODO
return null;
}
public Object visitArithmeticFactor(ArithmeticFactor factor, Object args)
throws SemanticException {
//TODO
return null;
}
public Object visitArithmeticParcel(ArithmeticParcel parcel, Object args)
throws SemanticException {
//TODO
return null;
}
public Object visitArithmeticTerm(ArithmeticTerm term, Object args)
throws SemanticException {
//TODO
return null;
}
public Object visitBooleanExpression(BooleanExpression expression,
Object args) throws SemanticException {
//TODO
return null;
}
public Object visitBoolValue(BoolValue bool, Object args)
throws SemanticException {
return "PICBOOL";
}
public Object visitBreak(Break brk, Object args) throws SemanticException {
if (!(args instanceof Until)) {
throw new SemanticException("O comando BREAK só deve ser utilizado em loops");
}
return null;
}
public Object visitCode(Code code, Object args) throws SemanticException {
if (code.getGlobalDataDiv() != null) {
code.getGlobalDataDiv().visit(this, args);
}
code.getProgramDiv().visit(this, args);
return null;
}
public Object visitCommand(Command cmd, Object args)
throws SemanticException {
if (cmd instanceof IfStatement) {
return ((IfStatement) cmd).visit(this, args);
} else if (cmd instanceof Until) {
return ((Until) cmd).visit(this, args);
} else if (cmd instanceof Accept) {
return ((Accept) cmd).visit(this, args);
} else if (cmd instanceof Display) {
return ((Display) cmd).visit(this, args);
} else if (cmd instanceof FunctionCall) {
return ((FunctionCall) cmd).visit(this, args);
} else if (cmd instanceof Break) {
return ((Break) cmd).visit(this, args);
} else if (cmd instanceof Continue) {
return ((Continue) cmd).visit(this, args);
} else if (cmd instanceof Return) {
return ((Return) cmd).visit(this, args);
}
return null;
}
public Object visitContinue(Continue cont, Object args)
throws SemanticException {
if (!(args instanceof Until)) {
throw new SemanticException("O comando CONTINUE só deve ser utilizado em loops");
}
return null;
}
public Object visitDisplay(Display display, Object args)
throws SemanticException {
if (display.getIdentifier() != null) {
display.getIdentifier().visit(this, display);
} else {
display.getExpression().visit(this, display);
}
return null;
}
public Object visitExpression(Expression expression, Object args)
throws SemanticException {
//TODO
return null;
}
public Object visitFunction(Function function, Object args)
throws SemanticException {
function.getID().visit(this, function);
idTable.openScope();
for (Identifier param : function.getParams()) {
param.visit(this, args);
}
Object temp = null;
ArrayList<Command> cmds = new ArrayList<Command>();
for (Command cmd : function.getCommands()) {
if (cmd instanceof Return) {
temp = cmd;
cmds.add(cmd);
break;
} else
cmds.add(cmd);
}
if (cmds.size() != function.getCommands().size())
throw new SemanticException(
"Regra extra! Nao deve haver comandos apos o retorno do procedimentos ou funcoes!");
for (Command cmd : function.getCommands()) {
if (temp != null) {
if (temp instanceof Return)
cmd.visit(this, function);
else
temp = cmd.visit(this, function);
} else
temp = cmd.visit(this, function);
}
if (temp == null && ((!function.getTipoRetorno().equals("VOID")))) {
throw new SemanticException("A Funcao " + function.getID().spelling
+ " precisa retornar um valor do tipo "
+ function.getTipoRetorno());
}
idTable.closeScope();
return null;
}
public Object visitFunctionCall(FunctionCall fcall, Object args)
throws SemanticException {
if (idTable.retrieve(fcall.getId().spelling) == null) {
throw new SemanticException("A funcao "
+ fcall.getId().spelling
+ " nao foi declarada!");
} else {
AST temp = idTable.retrieve(fcall.getId().spelling);
if (!(temp instanceof Function)) {
throw new SemanticException("Identificador "
+ fcall.getId().spelling
+ " nao representa uma Funcao!");
} else {
if (((Function) temp).getParamsTypes().size() != fcall.getParams().size()) {
throw new SemanticException(
"Quantidade de parametros passada diferente da quantidade de parametros requeridas pela Funcao!");
} else {
ArrayList<String> params = ((Function) temp).getParamsTypes();
for (int i = 0; i < params.size(); i++) {
if (!params.get(i).equals(fcall.getParams().get(i).type)) {
throw new SemanticException(
"Tipo dos parametros informados não correspondem ao tipo esperado");
}
}
}
}
}
return null;
}
public Object visitGlobalDataDiv(GlobalDataDiv gdd, Object args)
throws SemanticException {
//TODO
return null;
}
public Object visitIdentifier(Identifier id, Object args)
throws SemanticException {
if (args instanceof VarDeclaration) {
id.kind = Types.VARIAVEL;
id.type = ((VarDeclaration) args).getType();
id.declaration = args;
idTable.enter(id.spelling, (AST)args);
} else if (args instanceof Function) {
id.kind = Types.FUNCAO;
id.type = ((Function) args).getTipoRetorno();
id.declaration = args;
this.contadorParametros++;
idTable.enter(id.spelling, (AST) args);
} else if (args instanceof ArithmeticFactor){
if (idTable.retrieve(((ArithmeticFactor) args).getId().spelling) == null
&& ((ArithmeticFactor) args).getId() != null) {
throw new SemanticException("A variavel "
+ ((ArithmeticFactor) args).getId().spelling
+ " nao foi declarada!");
} else {
return ((ArithmeticFactor) args).getId().type;
}
} else {
id.kind = Types.PARAMETRO;
id.declaration = args;
id.type = ((VarDeclaration) args).getType();
idTable.enter(id.spelling, (AST) args);
}
return null;
}
public Object visitIfStatement(IfStatement ifStatement, Object args)
throws SemanticException {
Object temp = null;
if(ifStatement.getBooleanExpression() instanceof BooleanExpression){
((BooleanExpression) ifStatement.getBooleanExpression()).visit(this, args);
idTable.openScope();
for (Command ifCmd : ifStatement.getCommandIF()) {
if (ifCmd instanceof Break) {
break;
} else
temp = ifCmd.visit(this, args);
}
idTable.closeScope();
for (Command elseCmd : ifStatement.getCommandElse()) {
if (elseCmd instanceof Break) {
break;
} else {
elseCmd.visit(this, args);
}
}
idTable.closeScope();
} else {
throw new SemanticException("Expressao da condicao do IF nao e booleana!");
}
return temp;
}
public Object visitMainProc(MainProc main, Object args)
throws SemanticException {
//TODO
return null;
}
public Object visitNumber(Number number, Object args)
throws SemanticException {
return "PIC9";
}
public Object visitOpAdd(OpAdd opAdd, Object args) throws SemanticException {
return null;
}
public Object visitOpMult(OpMult opMult, Object args)
throws SemanticException {
return null;
}
public Object visitOpRelational(OpRelational opRel, Object args)
throws SemanticException {
return null;
}
public Object visitProgramDiv(ProgramDiv pdiv, Object args)
throws SemanticException {
//TODO
return null;
}
public Object visitReturn(Return rtn, Object args) throws SemanticException {
if (args instanceof Function) {
if (((Function) args).getTipoRetorno().equals("VOID")) {
throw new SemanticException("Funcao VOID nao tem retorno");
} else if (args instanceof Function && ((ArithmeticExpression) args).getArithmeticParcel() == null) {
if (!(rtn.getExpression().visit(this, args).equals(((Function) args).getTipoRetorno()))) {
throw new SemanticException(
"Valor retornado incompativel com o tipo de retorno da funcao!");
} else {
Identifier id = ((ArithmeticParcel) args).getArithmeticTerm().getArithmeticFactor()
.getId();
AST temp = idTable.retrieve(id.spelling);
if (temp == null) {
throw new SemanticException("A variavel " + id.spelling
+ " nao foi declarada!");
}
}
} else if (!(rtn.getExpression().visit(this, args).equals(((Function) args).getTipoRetorno()))) {
throw new SemanticException(
"Valor retornado incompativel com o tipo de retorno da funcao!");
}
} else {
throw new SemanticException(
"Comando de retorno deve estar dentro de uma funcao!");
}
return null;
}
public Object visitTerminal(Terminal term, Object args)
throws SemanticException {
//TODO
return null;
}
public Object visitUntil(Until until, Object args) throws SemanticException {
until.getBooleanExpression().visit(this, args);
idTable.openScope();
for(Command cmd : until.getCommand()){
if (cmd instanceof Break) {
visitBreak((Break) cmd, args);
} else if (cmd instanceof Continue) {
visitContinue((Continue)cmd, args);
} else {
cmd.visit(this, until);
}
}
idTable.closeScope();
return null;
}
public Object visitVarDeclaration(VarDeclaration var, Object args)
throws SemanticException {
if (var instanceof VarPIC9Declaration) {
return ((VarPIC9Declaration) var).visit(this, args);
} else if (var instanceof VarPICBOOLDeclaration) {
return ((VarPICBOOLDeclaration) var).visit(this, args);
}
return null;
}
public Object visitVarPIC9Declaration(VarPIC9Declaration var9, Object args)
throws SemanticException {
if(idTable.retrieve(var9.getIdentifier().spelling) != null){
throw new SemanticException("Variavel " + var9.getIdentifier().spelling + " ja foi declarada");
} else {
var9.getIdentifier().visit(this, args);
}
return null;
}
public Object visitVarPICBOOLDeclaration(VarPICBOOLDeclaration varBool,
Object args) throws SemanticException {
if(idTable.retrieve(varBool.getIdentifier().spelling) != null){
throw new SemanticException("Variavel " + varBool.getIdentifier().spelling + " ja foi declarada");
} else {
varBool.getIdentifier().visit(this, args);
}
return null;
}
} |
package org.jeo.geogit;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.geogit.api.GeoGIT;
import org.geogit.api.GeogitTransaction;
import org.geogit.api.NodeRef;
import org.geogit.api.Ref;
import org.geogit.api.RevCommit;
import org.geogit.api.RevFeatureType;
import org.geogit.api.SymRef;
import org.geogit.api.data.FindFeatureTypeTrees;
import org.geogit.api.plumbing.RefParse;
import org.geogit.api.plumbing.RevObjectParse;
import org.geogit.api.plumbing.TransactionBegin;
import org.geogit.api.porcelain.AddOp;
import org.geogit.api.porcelain.BranchListOp;
import org.geogit.api.porcelain.CheckoutOp;
import org.geogit.api.porcelain.CommitOp;
import org.geogit.api.porcelain.LogOp;
import org.geogit.repository.Repository;
import org.geogit.repository.WorkingTree;
import org.jeo.data.Workspace;
import org.jeo.data.Workspaces;
import org.jeo.feature.Schema;
import org.jeo.geotools.GT;
import org.jeo.util.Pair;
import org.opengis.feature.simple.SimpleFeatureType;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
public class GeoGit implements Workspace {
static {
Workspaces.registerWorkspaceFactory(new GeoGitFactory());
}
/** underlying geogit repo */
GeoGIT gg;
public GeoGit(GeoGIT gg) {
this.gg = gg;
}
/**
* Underlying geogit repo.
*/
public GeoGIT getGeoGIT() {
return gg;
}
public Iterator<String> branches() {
ImmutableList<Ref> heads = gg.command(BranchListOp.class).call();
return Collections2.transform(heads, new Function<Ref,String>() {
@Override
public String apply(Ref ref) {
return ref.getName().substring(Ref.HEADS_PREFIX.length());
}
}).iterator();
}
@Override
public Iterator<String> layers() throws IOException {
return layers(branch());
}
public Iterator<String> layers(String rev) throws IOException {
List<NodeRef> trees = typeRefs(rev);
return Iterators.transform(trees.iterator(), new Function<NodeRef, String>() {
@Override
public String apply(NodeRef input) {
return NodeRef.nodeFromPath(input.path());
}
});
}
public Iterator<RevCommit> log(String branch, String... paths) throws IOException {
LogOp log = gg.command(LogOp.class);
for (String l : paths) {
log.addPath(l);
}
return log.call();
}
@Override
public GeoGitDataset get(String layer) throws IOException {
Pair<NodeRef,RevCommit> ref = parseName(layer);
if (ref == null) {
return null;
}
SimpleFeatureType featureType = featureType(ref.first());
if (featureType != null) {
return new GeoGitDataset(ref, GT.schema(featureType), this);
}
throw new IllegalStateException("No schema for tree: " + layer);
}
Pair<NodeRef,RevCommit> parseName(String name) {
String[] split = name.split("@");
final String type = split.length > 1 ? split[0] : name;
final String rev = split.length > 1 ? split[1] : branch();
//parse the revision
Optional<RevCommit> commit =
gg.command(RevObjectParse.class).setRefSpec(rev).call(RevCommit.class);
if (!commit.isPresent()) {
throw new IllegalArgumentException("No such commit: " + rev);
}
Collection<NodeRef> match = Collections2.filter(typeRefs(rev), new Predicate<NodeRef>() {
@Override
public boolean apply(NodeRef input) {
return NodeRef.nodeFromPath(input.path()).equals(type);
}
});
if (match.isEmpty()) {
return null;
}
if (match.size() == 1) {
return new Pair<NodeRef,RevCommit>(match.iterator().next(), commit.get());
}
throw new IllegalArgumentException("Multiple trees for " + type);
}
/**
* Returns the ref name <tt>ref</tt> if not null, otherwise falls back to name of current branch.
*/
String refOrBranch(String ref) {
return ref != null ? ref : branch();
}
/**
* Determines the "current" branch by parsing the HEAD reference.
*/
String branch() {
//grab the current branch
Repository repo = gg.getRepository();
//grab the head reference
Optional<Ref> head = repo.command(RefParse.class).setName(Ref.HEAD).call();
if (head.isPresent()) {
Ref ref = head.get();
if (ref instanceof SymRef) {
String target = ((SymRef) ref).getTarget();
if (target.startsWith(Ref.HEADS_PREFIX)) {
return target.substring(Ref.HEADS_PREFIX.length());
}
}
}
throw new IllegalStateException(
"Unable to determine current branch, repository in dettached head state");
}
/**
* Lists all the type references for the specified branch/revision.
*/
List<NodeRef> typeRefs(String rev) {
Repository repo = gg.getRepository();
return repo.command(FindFeatureTypeTrees.class).setRootTreeRef(refOrBranch(rev)).call();
}
SimpleFeatureType featureType(NodeRef ref) {
Optional<RevFeatureType> type = gg.command(RevObjectParse.class)
.setObjectId(ref.getMetadataId()).call(RevFeatureType.class);
return (SimpleFeatureType) (type.isPresent() ? type.get().type() : null);
}
@Override
public GeoGitDataset create(Schema schema) throws IOException {
GeogitTransaction tx = gg.command(TransactionBegin.class).call();
boolean abort = false;
try {
String treePath = schema.getName();
String branch = branch();
// check out the datastore branch on the transaction space
tx.command(CheckoutOp.class).setForce(true).setSource(branch).call();
// now we can use the transaction working tree with the correct branch checked out
WorkingTree workingTree = tx.getWorkingTree();
workingTree.createTypeTree(treePath, GT.featureType(schema));
tx.command(AddOp.class).addPattern(treePath).call();
tx.command(CommitOp.class).setMessage("Created type tree " + treePath).call();
tx.commit();
return get(schema.getName());
} catch (IllegalArgumentException alreadyExists) {
abort = true;
throw new IOException(alreadyExists.getMessage(), alreadyExists);
} catch (Exception e) {
abort = true;
throw Throwables.propagate(e);
} finally {
if (abort) {
tx.abort();
}
}
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
} |
package com.google.sps.objects;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EmbeddedEntity;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.ArrayList;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
import com.google.common.collect.ImmutableMap;
import com.google.sps.Objects.Coordinate;
import com.google.sps.Objects.GroupLocation;
import com.google.sps.Objects.User;
import com.google.sps.Objects.Badge;
import com.google.sps.Objects.Challenge;
/**
* Unit tests for GroupLocation.
*
*/
public class GroupLocationTest {
private static final String USER_ID = "123123123";
private static final String USER_EMAIL = "test@mctest.com";
private static final String OTHER_ID = "other";
private static final String OTHER_EMAIL = "other@test.com";
private static final String OTHER_ID2 = "other2";
private static final String OTHER_EMAIL2 = "other2@test.com";
private static final String OTHER_ID3 = "other3";
private static final String OTHER_EMAIL3 = "other3@test.com";
private static final double COORD1_LAT = 40.7721984;
private static final double COORD1_LNG = -73.97933858;
private static final double COORD2_LAT = 40.83389292;
private static final double COORD2_LNG = -73.95543518;
private static final double COORD3_LAT = 40.76680496;
private static final double COORD3_LNG = -73.96009353;
private static final double MID_LAT = 40.790965887749465;
private static final double MID_LNG = -73.96495858110758;
private static final String GROUP_1_ID = "1";
private static final String GROUP_NAME = "The 3 Musketeers";
private static final String HEADER_IMAGE = "";
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(
new LocalDatastoreServiceTestConfig()
.setDefaultHighRepJobPolicyUnappliedJobPercentage(0),
new LocalUserServiceTestConfig())
.setEnvEmail(USER_EMAIL)
.setEnvIsLoggedIn(true)
.setEnvAuthDomain("gmail.com")
.setEnvAttributes(
new HashMap(
ImmutableMap.of(
"com.google.appengine.api.users.UserService.user_id_key", USER_ID)));
private static final User USER_1 = new User(
USER_ID,
"Test",
"McTest",
USER_EMAIL,
/* phoneNumber= */ "123-456-7890",
/* profilePic= */ "",
/* address= */ "",
/* latitude= */ COORD1_LAT,
/* longitude= */ COORD1_LNG,
/* badges= */ new LinkedHashSet<Badge>(),
/* groups= */ new LinkedHashSet<Long>(),
/* interests= */ new ArrayList<String>());
private static final User OTHER_USER = new User(
OTHER_ID,
"Test Two",
"McTest",
OTHER_EMAIL,
/* phoneNumber= */ "123-456-1111",
/* profilePic= */ "",
/* address= */ "",
/* latitude= */ COORD2_LAT,
/* longitude= */ COORD2_LNG,
/* badges= */ new LinkedHashSet<Badge>(),
/* groups= */ new LinkedHashSet<Long>(),
/* interests= */ new ArrayList<String>());
private static final User OTHER_USER2 = new User(
OTHER_ID2,
"Test TwoTwo",
"McTest",
OTHER_EMAIL2,
/* phoneNumber= */ "123-456-2222",
/* profilePic= */ "",
/* address= */ "",
/* latitude= */ COORD3_LAT,
/* longitude= */ COORD3_LNG,
/* badges= */ new LinkedHashSet<Badge>(),
/* groups= */ new LinkedHashSet<Long>(),
/* interests= */ new ArrayList<String>());
private static final User OTHER_USER3 = new User(
OTHER_ID3,
"Test TwoTwo",
"McTest",
OTHER_EMAIL3,
/* phoneNumber= */ "123-456-2222",
/* profilePic= */ "",
/* address= */ "",
/* latitude= */ 0.0,
/* longitude= */ 0.0,
/* badges= */ new LinkedHashSet<Badge>(),
/* groups= */ new LinkedHashSet<Long>(),
/* interests= */ new ArrayList<String>());
Coordinate COORDINATE_1 = new Coordinate(COORD1_LAT, COORD1_LNG);
Coordinate COORDINATE_2 = new Coordinate(COORD2_LAT, COORD2_LNG);
Coordinate COORDINATE_3 = new Coordinate(COORD3_LAT, COORD3_LNG);
ArrayList<Coordinate> groupCoordinates = new ArrayList(Arrays.asList(COORDINATE_1, COORDINATE_2, COORDINATE_3));
private GroupLocation groupLocation;
private DatastoreService datastore;
@Before
public void setUp() {
helper.setUp();
datastore = DatastoreServiceFactory.getDatastoreService();
// Add test data
populateDatabase(datastore);
groupLocation = new GroupLocation(Long.parseLong(GROUP_1_ID));
}
@After
public void tearDown() {
helper.tearDown();
groupLocation = null;
}
private void populateDatabase(DatastoreService datastore) {
// Add test data.
Entity group1 = createGroupEntity();
datastore.put(group1);
datastore.put(USER_1.toEntity());
datastore.put(OTHER_USER.toEntity());
datastore.put(OTHER_USER2.toEntity());
}
/* Create a Group entity */
private Entity createGroupEntity() {
Entity groupEntity = new Entity("Group");
groupEntity.setProperty("groupName", GROUP_NAME);
groupEntity.setProperty("headerImg", HEADER_IMAGE);
groupEntity.setProperty("memberIds", new ArrayList<String>(Arrays.asList(USER_ID, OTHER_ID , OTHER_ID2)));
groupEntity.setProperty("posts", null);
groupEntity.setProperty("options", new ArrayList<Long>());
groupEntity.setProperty("challenges", new ArrayList<Challenge>());
groupEntity.setProperty("midLatitude", 0.0);
groupEntity.setProperty("midLongitude", 0.0);
return groupEntity;
}
@Test
public void findGroupMidPointTest() throws Exception {
Coordinate coordReturned = groupLocation.findGroupMidPoint(Long.parseLong(GROUP_1_ID));
assertTrue(coordReturned.getLat() == MID_LAT);
assertTrue(coordReturned.getLng() == MID_LNG);
}
@Test
public void findGroupMidPointTest_invalidGroup() throws Exception {
Coordinate coordReturned = groupLocation.findGroupMidPoint(34L);
assertTrue(coordReturned == null);
}
@Test
public void findGroupMidPointTest_userWithMissingCoordinates() throws Exception {
datastore.put(OTHER_USER3.toEntity());
Coordinate coordReturned = groupLocation.findGroupMidPoint(Long.parseLong(GROUP_1_ID));
assertTrue(coordReturned.getLat() == MID_LAT);
assertTrue(coordReturned.getLng() == MID_LNG);
}
} |
package domain;
import com.google.gson.GsonBuilder;
import com.microsoft.msr.malmo.AgentHost;
import com.microsoft.msr.malmo.TimestampedStringVector;
import domain.fluents.IsAt;
import main.Observations;
import java.util.Arrays;
import java.util.List;
public abstract class AbstractAction implements Action {
protected final AgentHost agentHost;
protected List<AtomicFluent> effects;
protected List<AtomicFluent> preconditions;
protected GsonBuilder builder = new GsonBuilder();
public AbstractAction(AgentHost agentHost) {
this.agentHost = agentHost;
this.effects = Arrays.asList();
this.preconditions = Arrays.asList();
}
@Override
public List<AtomicFluent> getPreconditions() {
return preconditions;
}
@Override
public List<AtomicFluent> getEffects() {
return effects;
}
private boolean effectsCompleted(Observations observations) {
return observations != null && effects.stream().allMatch(predicate -> predicate.test(observations));
}
@Override
public void perform() {
Observations observations = null;
do {
TimestampedStringVector obs = agentHost.getWorldState().getObservations();
if (obs.size() > 0) {
observations = builder.create().fromJson(obs.get(0).getText(), Observations.class);
doAction(observations);
}
} while (!effectsCompleted(observations));
}
protected abstract void doAction(Observations observations);
} |
package de.learnlib.alex.core.learner;
import de.learnlib.alex.core.entities.LearnerConfiguration;
import de.learnlib.alex.core.entities.LearnerResult;
import de.learnlib.alex.core.entities.LearnerResumeConfiguration;
import de.learnlib.alex.core.entities.Project;
import de.learnlib.alex.core.entities.Symbol;
import de.learnlib.alex.core.entities.learnlibproxies.eqproxies.SampleEQOracleProxy;
import de.learnlib.alex.core.learner.connectors.ConnectorContextHandler;
import de.learnlib.alex.core.learner.connectors.ConnectorContextHandlerFactory;
import de.learnlib.alex.core.learner.connectors.ConnectorManager;
import de.learnlib.alex.exceptions.LearnerException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
/**
* Basic class to control and monitor a learn process.
* This class is a high level abstraction of the LearnLib.
*/
public class Learner {
/** Factory to create a new ContextHandler. */
private ConnectorContextHandlerFactory contextHandlerFactory;
/** The current ContextHandler. */
private ConnectorContextHandler contextHandler;
/** Factory to create the {@link LearnerThread LearnerThreads}. */
private LearnerThreadFactory learnThreadFactory;
/** The current learning thread. Could be null. */
private LearnerThread learnThread;
/**
* Constructor which only set the thread factory.
* This constructor creates a new ConnectorContextHandlerFactory for internal use.
*
* @param threadFactory
* The thread factory to use.
*/
public Learner(LearnerThreadFactory threadFactory) {
this(threadFactory, new ConnectorContextHandlerFactory());
}
/**
* Constructor that initialises only the LearnerThreadFactory.
*
* @param learnThreadFactory
* The thread factory to use.
* @param contextHandlerFactory
* The factory that will be used to create new context handler.
*/
public Learner(LearnerThreadFactory learnThreadFactory, ConnectorContextHandlerFactory contextHandlerFactory) {
this.learnThreadFactory = learnThreadFactory;
this.contextHandlerFactory = contextHandlerFactory;
}
public void start(Project project, LearnerConfiguration configuration)
throws IllegalArgumentException, IllegalStateException {
if (isActive()) {
throw new IllegalStateException("You can only start the learning if no other learning is active");
}
// TODO: make it nicer than this instanceof stuff, because you have to somehow tell the eq oracle that the
// learner started and not resumed
if (configuration.getEqOracle() instanceof SampleEQOracleProxy) {
SampleEQOracleProxy oracle = (SampleEQOracleProxy) configuration.getEqOracle();
if (!oracle.getCounterExamples().isEmpty()) {
throw new IllegalStateException("You cannot start with predefined counterexamples");
}
} else {
configuration.checkConfiguration();
}
contextHandler = contextHandlerFactory.createContext(project);
learnThread = learnThreadFactory.createThread(contextHandler, project, configuration);
Thread thread = Executors.defaultThreadFactory().newThread(learnThread);
thread.start();
}
public void resume(LearnerResumeConfiguration newConfiguration) throws IllegalStateException {
if (isActive()) {
throw new IllegalStateException("You can only restart the learning if no other learning is active");
}
newConfiguration.checkConfiguration();
learnThread = learnThreadFactory.updateThread(learnThread, newConfiguration);
Thread thread = Executors.defaultThreadFactory().newThread(learnThread);
thread.start();
}
/**
* Ends the learning process after the current step.
*/
public void stop() {
learnThread.interrupt();
}
/**
* Method to check if a learning process is still active or if it has finished.
*
* @return true if the learning process is active, false otherwise.
*/
public boolean isActive() {
return learnThread != null && learnThread.isActive();
}
/**
* Get the current result of the learning process.
* This must not be a valid step of a test run!
*
* @return The current result of the LearnerThread.
*/
public LearnerResult getResult() {
if (learnThread != null) {
return learnThread.getResult();
} else {
return null;
}
}
/**
* Determine the output of the SUL by testing a sequence of input symbols.
*
* @param project
* The project in which context the test should happen.
* @param resetSymbol
* The reset symbol to use.
* @param symbols
* The symbol sequence to execute in order to generate the output sequence.
* @return The following output sequence.
*/
public List<String> readOutputs(Project project, Symbol resetSymbol, List<Symbol> symbols) throws LearnerException {
if (contextHandler == null) {
contextHandler = contextHandlerFactory.createContext(project);
}
contextHandler.setResetSymbol(resetSymbol);
ConnectorManager connectors = contextHandler.createContext();
try {
return symbols.stream().map(s -> s.execute(connectors).toString()).collect(Collectors.toList());
} catch (Exception e) {
throw new LearnerException("Could not read the outputs", e);
}
}
} |
package ch.elexis.data;
import java.util.List;
import ch.rgw.tools.JdbcLink;
import ch.rgw.tools.VersionInfo;
public class TarmedExtension extends PersistentObject {
private static final String TABLENAME = "TARMED_EXTENSION"; //$NON-NLS-1$
private static final String VERSION = "1.0.0";
public static final String FLD_CODE = "Code";
public static final String FLD_LIMITS = "limits";
public static final String FLD_MED_INTERPRET = "med_interpret";
public static final String FLD_TECH_INTERPRET = "tech_interpret";
// @formatter:off
private static final String upd100_h2 =
"ALTER TABLE " + TABLENAME + " ADD " + FLD_ID + " VARCHAR(25);"
+ "ALTER TABLE " + TABLENAME + " ADD " + FLD_LASTUPDATE + " BIGINT;"
+ "ALTER TABLE " + TABLENAME + " ADD " + FLD_DELETED + " CHAR(1) default '0';"
+ "UPDATE " + TABLENAME + " SET " + FLD_ID + "=(SELECT LPAD(random_uuid(), 25));"
+ "ALTER TABLE " + TABLENAME + " ADD " + FLD_ID + " VARCHAR(25);"
+ "ALTER TABLE " + TABLENAME + " ADD PRIMARY KEY (" + FLD_ID + ");"
+ "ALTER TABLE " + TABLENAME + " MODIFY Code VARCHAR(32);"
+ "INSERT INTO " + TABLENAME + " (ID, " + FLD_CODE + ") VALUES (" + JdbcLink.wrap(TarmedLeistung.ROW_VERSION) + ", " + JdbcLink.wrap(VERSION) + ");";
private static final String upd100_mysql =
"ALTER TABLE " + TABLENAME + " ADD " + FLD_ID + " VARCHAR(25);"
+ "ALTER TABLE " + TABLENAME + " ADD " + FLD_LASTUPDATE + " BIGINT;"
+ "ALTER TABLE " + TABLENAME + " ADD " + FLD_DELETED + " CHAR(1) default '0';"
+ "UPDATE " + TABLENAME + " SET " + FLD_ID + "=(SELECT LEFT(UUID(), 25));"
+ "ALTER TABLE " + TABLENAME + " ADD " + FLD_ID + " VARCHAR(25);"
+ "ALTER TABLE " + TABLENAME + " ADD PRIMARY KEY (" + FLD_ID + ");"
+ "ALTER TABLE " + TABLENAME + " MODIFY Code VARCHAR(32);"
+ "INSERT INTO " + TABLENAME + " (ID, " + FLD_CODE + ") VALUES (" + JdbcLink.wrap(TarmedLeistung.ROW_VERSION) + ", " + JdbcLink.wrap(VERSION) + ");";
private static final String upd100_postgresql =
"ALTER TABLE " + TABLENAME + " ADD " + FLD_ID + " VARCHAR(25);"
+ "ALTER TABLE " + TABLENAME + " ADD " + FLD_LASTUPDATE + " BIGINT;"
+ "ALTER TABLE " + TABLENAME + " ADD " + FLD_DELETED + " CHAR(1) default '0';"
+ "UPDATE " + TABLENAME + " SET " + FLD_ID + "=(SELECT lpad(random()::text, 25));"
+ "ALTER TABLE " + TABLENAME + " ADD " + FLD_ID + " VARCHAR(25);"
+ "ALTER TABLE " + TABLENAME + " ADD PRIMARY KEY (" + FLD_ID + ");"
+ "ALTER TABLE " + TABLENAME + " MODIFY Code VARCHAR(32);"
+ "INSERT INTO " + TABLENAME + " (ID, " + FLD_CODE + ") VALUES (" + JdbcLink.wrap(TarmedLeistung.ROW_VERSION) + ", " + JdbcLink.wrap(VERSION) + ");";
public static final String createDB = "CREATE TABLE " + TABLENAME + " ("
+"ID VARCHAR(25) primary key, "
+"lastupdate BIGINT,"
+"deleted CHAR(1) default '0',"
+ "Code VARCHAR(32),"
+ "limits BLOB,"
+ "med_interpret TEXT,"
+ "tech_interpret TEXT"
+ ");"
+ "CREATE INDEX tarmed4 on " + TABLENAME + " (" + FLD_CODE + ");"
+ "INSERT INTO " + TABLENAME + " (ID, " + FLD_CODE + ") VALUES (" + JdbcLink.wrap(TarmedLeistung.ROW_VERSION) + ", " + JdbcLink.wrap(VERSION) + ");";
//@formatter:on
static {
addMapping(TABLENAME, FLD_CODE, FLD_LIMITS, FLD_MED_INTERPRET, FLD_TECH_INTERPRET);
if (!tableExists(TABLENAME)) {
createOrModifyTable(createDB);
} else {
TarmedExtension version = load(TarmedLeistung.ROW_VERSION);
if (!version.exists()) {
String dbFlavor = getDefaultConnection().getDBFlavor();
if ("h2".equals(dbFlavor)) {
createOrModifyTable(upd100_h2);
} else if ("mysql".equals(dbFlavor)) {
createOrModifyTable(upd100_mysql);
} else if ("postgresql".equals(dbFlavor)) {
createOrModifyTable(upd100_postgresql);
}
}
VersionInfo vi = new VersionInfo(version.get(FLD_CODE));
if (vi.isOlder(VERSION)) {
// add update code here ...
version.set(FLD_CODE, VERSION);
}
}
}
protected TarmedExtension(){
// leer
}
public TarmedExtension(TarmedLeistung tarmedLeistung){
create(null, new String[] {
FLD_CODE
}, new String[] {
tarmedLeistung.getId()
});
}
public TarmedExtension(TarmedGroup tarmedGruppe){
create(null, new String[] {
FLD_CODE
}, new String[] {
tarmedGruppe.getId()
});
}
public static TarmedExtension load(String id){
return new TarmedExtension(id);
}
protected TarmedExtension(String id){
super(id);
}
public static TarmedExtension getExtension(TarmedLeistung tarmedLeistung){
Query<TarmedExtension> query = new Query<>(TarmedExtension.class);
query.add(FLD_CODE, Query.EQUALS, tarmedLeistung.getId());
List<TarmedExtension> result = query.execute();
if (!result.isEmpty()) {
return result.get(0);
}
return null;
}
public static TarmedExtension getExtension(TarmedGroup tarmedGroup){
Query<TarmedExtension> query = new Query<>(TarmedExtension.class);
query.add(FLD_CODE, Query.EQUALS, tarmedGroup.getId());
List<TarmedExtension> result = query.execute();
if (!result.isEmpty()) {
return result.get(0);
}
return null;
}
@Override
public String getLabel(){
return toString();
}
@Override
protected String getTableName(){
return TABLENAME;
}
} |
package com.bradmcevoy.http;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpManager {
private static final Logger log = LoggerFactory.getLogger(HttpManager.class);
private static final ThreadLocal<Request> tlRequest = new ThreadLocal<Request>();
private static final ThreadLocal<Response> tlResponse = new ThreadLocal<Response>();
public static Request request() {
return tlRequest.get();
}
public static Response response() {
return tlResponse.get();
}
final OptionsHandler optionsHandler;
final GetHandler getHandler;
final PostHandler postHandler;
final PropFindHandler propFindHandler;
final MkColHandler mkColHandler;
final MoveHandler moveHandler;
final PutHandler putHandler;
final DeleteHandler deleteHandler;
final PropPatchHandler propPatchHandler;
final CopyHandler copyHandler;
final HeadHandler headHandler;
final LockHandler lockHandler;
final UnlockHandler unlockHandler;
public final Handler[] allHandlers;
Map<Request.Method, Handler> methodFactoryMap = new ConcurrentHashMap<Request.Method, Handler>();
List<Filter> filters = new ArrayList<Filter>();
List<EventListener> eventListeners = new ArrayList<EventListener>();
final ResourceFactory resourceFactory;
final ResponseHandler responseHandler;
final String notFoundPath;
private SessionAuthenticationHandler sessionAuthenticationHandler;
/**
* @deprecated
*
* Creates the manager with a DefaultResponseHandler. Method handlers are
* instantiated with createXXXHandler methods
*
* The notFoundPath property is deprecated. Instead, you should use an appropriate
* ResponseHandler
*
* @param resourceFactory
* @param notFoundPath
*/
public HttpManager(ResourceFactory resourceFactory, String notFoundPath) {
this(resourceFactory, notFoundPath, new DefaultResponseHandler());
}
/**
* Creates the manager with a DefaultResponseHandler
*
* @param resourceFactory
*/
public HttpManager(ResourceFactory resourceFactory) {
this(resourceFactory, null, null);
}
public HttpManager(ResourceFactory resourceFactory, ResponseHandler responseHandler) {
this(resourceFactory, null, responseHandler);
}
/**
* @deprecated - instead of notFoundPath, use an appropriate ResponseHandler
*
* @param resourceFactory
* @param notFoundPath
* @param responseHandler
*/
public HttpManager(ResourceFactory resourceFactory, String notFoundPath, ResponseHandler responseHandler) {
if( resourceFactory == null ) throw new NullPointerException("resourceFactory cannot be null");
this.resourceFactory = resourceFactory;
this.responseHandler = responseHandler;
this.notFoundPath = notFoundPath;
optionsHandler = add( createOptionsHandler() );
getHandler = add( createGetHandler() );
postHandler = add( createPostHandler() );
propFindHandler = add( createPropFindHandler() );
mkColHandler = add( createMkColHandler() );
moveHandler = add( createMoveFactory() );
putHandler = add( createPutFactory() );
deleteHandler = add( createDeleteHandler() );
copyHandler = add( createCopyHandler() );
headHandler = add( createHeadHandler() );
propPatchHandler = add( createPropPatchHandler() );
lockHandler = add(createLockHandler());
unlockHandler = add(createUnlockHandler());
allHandlers = new Handler[]{optionsHandler,getHandler,postHandler,propFindHandler,mkColHandler,moveHandler,putHandler,deleteHandler,propPatchHandler, lockHandler, unlockHandler};
filters.add(createStandardFilter());
}
/**
* @deprecated - instead, use an appropriate ResponseHandler
* @return
*/
public String getNotFoundPath() {
return notFoundPath;
}
public ResourceFactory getResourceFactory() {
return resourceFactory;
}
public SessionAuthenticationHandler getSessionAuthenticationHandler() {
return sessionAuthenticationHandler;
}
public void setSessionAuthenticationHandler(SessionAuthenticationHandler sessionAuthenticationHandler) {
this.sessionAuthenticationHandler = sessionAuthenticationHandler;
}
/**
*
* @param request
* @return - if no SessionAuthenticationHandler has been set returns null. Otherwise,
* calls getSessionAuthentication on it and returns the result
*
*
*/
public Auth getSessionAuthentication(Request request) {
if( this.sessionAuthenticationHandler == null ) return null;
return this.sessionAuthenticationHandler.getSessionAuthentication(request);
}
public ResponseHandler getResponseHandler() {
return responseHandler;
}
private <T extends Handler> T add(T h) {
methodFactoryMap.put(h.method(),h);
return h;
}
public void process(Request request, Response response) {
log.debug(request.getMethod() + " :: " + request.getAbsoluteUrl() + " - " + request.getAbsoluteUrl());
tlRequest.set( request );
tlResponse.set( response );
try {
FilterChain chain = new FilterChain( this );
chain.process( request, response );
} finally {
tlRequest.remove();
tlResponse.remove();
}
}
protected Filter createStandardFilter() {
return new StandardFilter();
}
protected OptionsHandler createOptionsHandler() {
return new OptionsHandler(this);
}
protected GetHandler createGetHandler() {
return new GetHandler(this);
}
protected PostHandler createPostHandler() {
return new PostHandler(this);
}
protected DeleteHandler createDeleteHandler() {
return new DeleteHandler(this);
}
protected PutHandler createPutFactory() {
return new PutHandler(this);
}
protected MoveHandler createMoveFactory() {
return new MoveHandler(this);
}
protected MkColHandler createMkColHandler() {
return new MkColHandler(this);
}
protected PropFindHandler createPropFindHandler() {
return new PropFindHandler(this);
}
protected CopyHandler createCopyHandler() {
return new CopyHandler(this);
}
protected HeadHandler createHeadHandler() {
return new HeadHandler(this);
}
protected PropPatchHandler createPropPatchHandler() {
return new PropPatchHandler(this);
}
protected LockHandler createLockHandler() {
return new LockHandler(this);
}
protected UnlockHandler createUnlockHandler() {
return new UnlockHandler(this);
}
public static String decodeUrl(String s) {
return Utils.decodePath(s);
}
public void addFilter(int pos, Filter filter) {
filters.add(pos,filter);
}
public void addEventListener(EventListener l) {
eventListeners.add(l);
}
public void removeEventListener(EventListener l) {
eventListeners.remove(l);
}
void onProcessResourceFinish(Request request, Response response, Resource resource, long duration) {
for( EventListener l : eventListeners ) {
l.onProcessResourceFinish(request, response, resource,duration);
}
}
void onProcessResourceStart(Request request, Response response, Resource resource) {
for( EventListener l : eventListeners ) {
l.onProcessResourceStart(request, response, resource);
}
}
void onPost(Request request, Response response, Resource resource, Map<String, String> params, Map<String, FileItem> files) {
for( EventListener l : eventListeners ) {
l.onPost(request, response, resource, params, files);
}
}
void onGet(Request request, Response response, Resource resource, Map<String, String> params) {
for( EventListener l : eventListeners ) {
l.onGet(request, response, resource, params);
}
}
public List<Filter> getFilters() {
ArrayList<Filter> col = new ArrayList<Filter>(filters);
return col;
}
public void setFilters(List<Filter> filters) {
this.filters = filters;
filters.add(new StandardFilter());
}
public void setEventListeners(List<EventListener> eventListeners) {
this.eventListeners = eventListeners;
}
public CopyHandler getCopyHandler() {
return copyHandler;
}
public DeleteHandler getDeleteHandler() {
return deleteHandler;
}
public GetHandler getGetHandler() {
return getHandler;
}
public HeadHandler getHeadHandler() {
return headHandler;
}
public LockHandler getLockHandler() {
return lockHandler;
}
public MkColHandler getMkColHandler() {
return mkColHandler;
}
public MoveHandler getMoveHandler() {
return moveHandler;
}
public OptionsHandler getOptionsHandler() {
return optionsHandler;
}
public PostHandler getPostHandler() {
return postHandler;
}
public PropFindHandler getPropFindHandler() {
return propFindHandler;
}
public PropPatchHandler getPropPatchHandler() {
return propPatchHandler;
}
public UnlockHandler getUnlockHandler() {
return unlockHandler;
}
public PutHandler getPutHandler() {
return putHandler;
}
} |
package org.postgresql.jdbc2;
import java.math.BigDecimal;
import java.io.*;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import org.postgresql.Driver;
import org.postgresql.Field;
import org.postgresql.core.Encoding;
import org.postgresql.largeobject.*;
import org.postgresql.util.PGbytea;
import org.postgresql.util.PSQLException;
/* $Header: /home/davec/jdbc/CVSROOT/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java,v 1.11 2002/12/23 16:12:36 davec Exp $
* This class defines methods of the jdbc2 specification. This class extends
* org.postgresql.jdbc1.AbstractJdbc1ResultSet which provides the jdbc1
* methods. The real Statement class (for jdbc2) is org.postgresql.jdbc2.Jdbc2ResultSet
*/
public abstract class AbstractJdbc2ResultSet extends org.postgresql.jdbc1.AbstractJdbc1ResultSet
{
//needed for updateable result set support
protected boolean updateable = false;
protected boolean doingUpdates = false;
protected boolean onInsertRow = false;
protected Hashtable updateValues = new Hashtable();
private boolean usingOID = false; // are we using the OID for the primary key?
private Vector primaryKeys; // list of primary keys
private int numKeys = 0;
private boolean singleTable = false;
protected String tableName = null;
protected PreparedStatement updateStatement = null;
protected PreparedStatement insertStatement = null;
protected PreparedStatement deleteStatement = null;
private PreparedStatement selectStatement = null;
public AbstractJdbc2ResultSet(org.postgresql.PGConnection conn, Statement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
{
super (conn, statement, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public java.net.URL getURL(int columnIndex) throws SQLException
{
return null;
}
public java.net.URL getURL(String columnName) throws SQLException
{
return null;
}
/*
* Get the value of a column in the current row as a Java object
*
* <p>This method will return the value of the given column as a
* Java object. The type of the Java object will be the default
* Java Object type corresponding to the column's SQL type, following
* the mapping specified in the JDBC specification.
*
* <p>This method may also be used to read database specific abstract
* data types.
*
* @param columnIndex the first column is 1, the second is 2...
* @return a Object holding the column value
* @exception SQLException if a database access error occurs
*/
public Object getObject(int columnIndex) throws SQLException
{
Field field;
checkResultSet( columnIndex );
wasNullFlag = (this_row[columnIndex - 1] == null);
if (wasNullFlag)
return null;
field = fields[columnIndex - 1];
// some fields can be null, mainly from those returned by MetaData methods
if (field == null)
{
wasNullFlag = true;
return null;
}
switch (field.getSQLType())
{
case Types.BIT:
return getBoolean(columnIndex) ? Boolean.TRUE : Boolean.FALSE;
case Types.SMALLINT:
return new Short(getShort(columnIndex));
case Types.INTEGER:
return new Integer(getInt(columnIndex));
case Types.BIGINT:
return new Long(getLong(columnIndex));
case Types.NUMERIC:
return getBigDecimal
(columnIndex, (field.getMod() == -1) ? -1 : ((field.getMod() - 4) & 0xffff));
case Types.REAL:
return new Float(getFloat(columnIndex));
case Types.DOUBLE:
return new Double(getDouble(columnIndex));
case Types.CHAR:
case Types.VARCHAR:
return getString(columnIndex);
case Types.DATE:
return getDate(columnIndex);
case Types.TIME:
return getTime(columnIndex);
case Types.TIMESTAMP:
return getTimestamp(columnIndex);
case Types.BINARY:
case Types.VARBINARY:
return getBytes(columnIndex);
case Types.ARRAY:
return getArray(columnIndex);
default:
String type = field.getPGType();
// if the backend doesn't know the type then coerce to String
if (type.equals("unknown"))
{
return getString(columnIndex);
}
else
{
return connection.getObject(field.getPGType(), getString(columnIndex));
}
}
}
public boolean absolute(int index) throws SQLException
{
// index is 1-based, but internally we use 0-based indices
int internalIndex;
if (index == 0)
throw new SQLException("Cannot move to index of 0");
final int rows_size = rows.size();
//if index<0, count from the end of the result set, but check
//to be sure that it is not beyond the first index
if (index < 0)
{
if (index >= -rows_size)
internalIndex = rows_size + index;
else
{
beforeFirst();
return false;
}
}
else
{
//must be the case that index>0,
//find the correct place, assuming that
//the index is not too large
if (index <= rows_size)
internalIndex = index - 1;
else
{
afterLast();
return false;
}
}
current_row = internalIndex;
this_row = (byte[][]) rows.elementAt(internalIndex);
return true;
}
public void afterLast() throws SQLException
{
final int rows_size = rows.size();
if (rows_size > 0)
current_row = rows_size;
}
public void beforeFirst() throws SQLException
{
if (rows.size() > 0)
current_row = -1;
}
public boolean first() throws SQLException
{
if (rows.size() <= 0)
return false;
onInsertRow = false;
current_row = 0;
this_row = (byte[][]) rows.elementAt(current_row);
rowBuffer = new byte[this_row.length][];
System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
return true;
}
public java.sql.Array getArray(String colName) throws SQLException
{
return getArray(findColumn(colName));
}
public java.sql.Array getArray(int i) throws SQLException
{
wasNullFlag = (this_row[i - 1] == null);
if (wasNullFlag)
return null;
if (i < 1 || i > fields.length)
throw new PSQLException("postgresql.res.colrange");
return (java.sql.Array) new org.postgresql.jdbc2.Array( connection, i, fields[i - 1], (java.sql.ResultSet) this );
}
public java.math.BigDecimal getBigDecimal(int columnIndex) throws SQLException
{
return getBigDecimal(columnIndex, -1);
}
public java.math.BigDecimal getBigDecimal(String columnName) throws SQLException
{
return getBigDecimal(findColumn(columnName));
}
public Blob getBlob(String columnName) throws SQLException
{
return getBlob(findColumn(columnName));
}
public abstract Blob getBlob(int i) throws SQLException;
public java.io.Reader getCharacterStream(String columnName) throws SQLException
{
return getCharacterStream(findColumn(columnName));
}
public java.io.Reader getCharacterStream(int i) throws SQLException
{
checkResultSet( i );
wasNullFlag = (this_row[i - 1] == null);
if (wasNullFlag)
return null;
if (((AbstractJdbc2Connection) connection).haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all the PG text types
//As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate
//long string datatype, but with toast the text datatype is capable of
//handling very large values. Thus the implementation ends up calling
//getString() since there is no current way to stream the value from the server
return new CharArrayReader(getString(i).toCharArray());
}
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream
Encoding encoding = connection.getEncoding();
InputStream input = getBinaryStream(i);
return encoding.getDecodingReader(input);
}
}
public Clob getClob(String columnName) throws SQLException
{
return getClob(findColumn(columnName));
}
public abstract Clob getClob(int i) throws SQLException;
public int getConcurrency() throws SQLException
{
if (statement == null)
return java.sql.ResultSet.CONCUR_READ_ONLY;
return statement.getResultSetConcurrency();
}
public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException
{
// If I read the specs, this should use cal only if we don't
// store the timezone, and if we do, then act just like getDate()?
// for now...
return getDate(i);
}
public Time getTime(int i, java.util.Calendar cal) throws SQLException
{
// If I read the specs, this should use cal only if we don't
// store the timezone, and if we do, then act just like getTime()?
// for now...
return getTime(i);
}
public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException
{
// If I read the specs, this should use cal only if we don't
// store the timezone, and if we do, then act just like getDate()?
// for now...
return getTimestamp(i);
}
public java.sql.Date getDate(String c, java.util.Calendar cal) throws SQLException
{
return getDate(findColumn(c), cal);
}
public Time getTime(String c, java.util.Calendar cal) throws SQLException
{
return getTime(findColumn(c), cal);
}
public Timestamp getTimestamp(String c, java.util.Calendar cal) throws SQLException
{
return getTimestamp(findColumn(c), cal);
}
public int getFetchDirection() throws SQLException
{
//PostgreSQL normally sends rows first->last
return java.sql.ResultSet.FETCH_FORWARD;
}
public int getFetchSize() throws SQLException
{
// In this implementation we return the entire result set, so
// here return the number of rows we have. Sub-classes can return a proper
// value
return rows.size();
}
public Object getObject(String columnName, java.util.Map map) throws SQLException
{
return getObject(findColumn(columnName), map);
}
/*
* This checks against map for the type of column i, and if found returns
* an object based on that mapping. The class must implement the SQLData
* interface.
*/
public Object getObject(int i, java.util.Map map) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
public Ref getRef(String columnName) throws SQLException
{
return getRef(findColumn(columnName));
}
public Ref getRef(int i) throws SQLException
{
//The backend doesn't yet have SQL3 REF types
throw new PSQLException("postgresql.psqlnotimp");
}
public int getRow() throws SQLException
{
final int rows_size = rows.size();
if (current_row < 0 || current_row >= rows_size)
return 0;
return current_row + 1;
}
// This one needs some thought, as not all ResultSets come from a statement
public Statement getStatement() throws SQLException
{
return statement;
}
public int getType() throws SQLException
{
// This implementation allows scrolling but is not able to
// see any changes. Sub-classes may overide this to return a more
// meaningful result.
return java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE;
}
public boolean isAfterLast() throws SQLException
{
final int rows_size = rows.size();
return (current_row >= rows_size && rows_size > 0);
}
public boolean isBeforeFirst() throws SQLException
{
return (current_row < 0 && rows.size() > 0);
}
public boolean isFirst() throws SQLException
{
return (current_row == 0 && rows.size() >= 0);
}
public boolean isLast() throws SQLException
{
final int rows_size = rows.size();
return (current_row == rows_size - 1 && rows_size > 0);
}
public boolean last() throws SQLException
{
final int rows_size = rows.size();
if (rows_size <= 0)
return false;
current_row = rows_size - 1;
this_row = (byte[][]) rows.elementAt(current_row);
rowBuffer = new byte[this_row.length][];
System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
return true;
}
public boolean previous() throws SQLException
{
if (--current_row < 0)
return false;
this_row = (byte[][]) rows.elementAt(current_row);
System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
return true;
}
public boolean relative(int rows) throws SQLException
{
//have to add 1 since absolute expects a 1-based index
return absolute(current_row + 1 + rows);
}
public void setFetchDirection(int direction) throws SQLException
{
throw new PSQLException("postgresql.psqlnotimp");
}
public void setFetchSize(int rows) throws SQLException
{
// Sub-classes should implement this as part of their cursor support
throw org.postgresql.Driver.notImplemented();
}
public synchronized void cancelRowUpdates()
throws SQLException
{
if (doingUpdates)
{
doingUpdates = false;
clearRowBuffer();
}
}
public synchronized void deleteRow()
throws SQLException
{
if ( !isUpdateable() )
{
throw new PSQLException( "postgresql.updateable.notupdateable" );
}
if (onInsertRow)
{
throw new PSQLException( "postgresql.updateable.oninsertrow" );
}
if (rows.size() == 0)
{
throw new PSQLException( "postgresql.updateable.emptydelete" );
}
if (isBeforeFirst())
{
throw new PSQLException( "postgresql.updateable.beforestartdelete" );
}
if (isAfterLast())
{
throw new PSQLException( "postgresql.updateable.afterlastdelete" );
}
int numKeys = primaryKeys.size();
if ( deleteStatement == null )
{
StringBuffer deleteSQL = new StringBuffer("DELETE FROM " ).append(tableName).append(" where " );
for ( int i = 0; i < numKeys; i++ )
{
deleteSQL.append( ((PrimaryKey) primaryKeys.get(i)).name ).append( " = ? " );
if ( i < numKeys - 1 )
{
deleteSQL.append( " and " );
}
}
deleteStatement = ((java.sql.Connection) connection).prepareStatement(deleteSQL.toString());
}
deleteStatement.clearParameters();
for ( int i = 0; i < numKeys; i++ )
{
deleteStatement.setObject(i + 1, ((PrimaryKey) primaryKeys.get(i)).getValue());
}
deleteStatement.executeUpdate();
rows.removeElementAt(current_row);
}
public synchronized void insertRow()
throws SQLException
{
if ( !isUpdateable() )
{
throw new PSQLException( "postgresql.updateable.notupdateable" );
}
if (!onInsertRow)
{
throw new PSQLException( "postgresql.updateable.notoninsertrow" );
}
else
{
// loop through the keys in the insertTable and create the sql statement
// we have to create the sql every time since the user could insert different
// columns each time
StringBuffer insertSQL = new StringBuffer("INSERT INTO ").append(tableName).append(" (");
StringBuffer paramSQL = new StringBuffer(") values (" );
Enumeration columnNames = updateValues.keys();
int numColumns = updateValues.size();
for ( int i = 0; columnNames.hasMoreElements(); i++ )
{
String columnName = (String) columnNames.nextElement();
insertSQL.append( columnName );
if ( i < numColumns - 1 )
{
insertSQL.append(", ");
paramSQL.append("?,");
}
else
{
paramSQL.append("?)");
}
}
insertSQL.append(paramSQL.toString());
insertStatement = ((java.sql.Connection) connection).prepareStatement(insertSQL.toString());
Enumeration keys = updateValues.keys();
for ( int i = 1; keys.hasMoreElements(); i++)
{
String key = (String) keys.nextElement();
Object o = updateValues.get(key);
if (o instanceof NullObject)
insertStatement.setNull(i,java.sql.Types.NULL);
else
insertStatement.setObject(i, o);
}
insertStatement.executeUpdate();
if ( usingOID )
{
// we have to get the last inserted OID and put it in the resultset
long insertedOID = ((AbstractJdbc2Statement) insertStatement).getLastOID();
updateValues.put("oid", new Long(insertedOID) );
}
// update the underlying row to the new inserted data
updateRowBuffer();
rows.addElement(rowBuffer);
// we should now reflect the current data in this_row
// that way getXXX will get the newly inserted data
this_row = rowBuffer;
// need to clear this in case of another insert
clearRowBuffer();
}
}
public synchronized void moveToCurrentRow()
throws SQLException
{
if (!updateable)
{
throw new PSQLException( "postgresql.updateable.notupdateable" );
}
this_row = (byte[][]) rows.elementAt(current_row);
rowBuffer = new byte[this_row.length][];
System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
onInsertRow = false;
doingUpdates = false;
}
public synchronized void moveToInsertRow()
throws SQLException
{
if ( !isUpdateable() )
{
throw new PSQLException( "postgresql.updateable.notupdateable" );
}
if (insertStatement != null)
{
insertStatement = null;
}
// make sure the underlying data is null
clearRowBuffer();
onInsertRow = true;
doingUpdates = false;
}
private synchronized void clearRowBuffer()
throws SQLException
{
// rowBuffer is the temporary storage for the row
rowBuffer = new byte[fields.length][];
// clear the updateValues hashTable for the next set of updates
updateValues.clear();
}
public boolean rowDeleted() throws SQLException
{
// only sub-classes implement CONCURuPDATEABLE
throw Driver.notImplemented();
}
public boolean rowInserted() throws SQLException
{
// only sub-classes implement CONCURuPDATEABLE
throw Driver.notImplemented();
}
public boolean rowUpdated() throws SQLException
{
// only sub-classes implement CONCURuPDATEABLE
throw Driver.notImplemented();
}
public synchronized void updateAsciiStream(int columnIndex,
java.io.InputStream x,
int length
)
throws SQLException
{
byte[] theData = null;
try
{
x.read(theData, 0, length);
}
catch (NullPointerException ex )
{
throw new PSQLException("postgresql.updateable.inputstream");
}
catch (IOException ie)
{
throw new PSQLException("postgresql.updateable.ioerror" + ie);
}
updateValue(columnIndex, theData);
}
public synchronized void updateBigDecimal(int columnIndex,
java.math.BigDecimal x )
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateBinaryStream(int columnIndex,
java.io.InputStream x,
int length
)
throws SQLException
{
byte[] theData = null;
try
{
x.read(theData, 0, length);
}
catch ( NullPointerException ex )
{
throw new PSQLException("postgresql.updateable.inputstream");
}
catch (IOException ie)
{
throw new PSQLException("postgresql.updateable.ioerror" + ie);
}
updateValue(columnIndex, theData);
}
public synchronized void updateBoolean(int columnIndex, boolean x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("updating boolean " + fields[columnIndex - 1].getName() + "=" + x);
updateValue(columnIndex, new Boolean(x));
}
public synchronized void updateByte(int columnIndex, byte x)
throws SQLException
{
updateValue(columnIndex, String.valueOf(x));
}
public synchronized void updateBytes(int columnIndex, byte[] x)
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateCharacterStream(int columnIndex,
java.io.Reader x,
int length
)
throws SQLException
{
char[] theData = null;
try
{
x.read(theData, 0, length);
}
catch (NullPointerException ex)
{
throw new PSQLException("postgresql.updateable.inputstream");
}
catch (IOException ie)
{
throw new PSQLException("postgresql.updateable.ioerror" + ie);
}
updateValue(columnIndex, theData);
}
public synchronized void updateDate(int columnIndex, java.sql.Date x)
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateDouble(int columnIndex, double x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("updating double " + fields[columnIndex - 1].getName() + "=" + x);
updateValue(columnIndex, new Double(x));
}
public synchronized void updateFloat(int columnIndex, float x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("updating float " + fields[columnIndex - 1].getName() + "=" + x);
updateValue(columnIndex, new Float(x));
}
public synchronized void updateInt(int columnIndex, int x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("updating int " + fields[columnIndex - 1].getName() + "=" + x);
updateValue(columnIndex, new Integer(x));
}
public synchronized void updateLong(int columnIndex, long x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("updating long " + fields[columnIndex - 1].getName() + "=" + x);
updateValue(columnIndex, new Long(x));
}
public synchronized void updateNull(int columnIndex)
throws SQLException
{
updateValue(columnIndex, new NullObject());
}
public synchronized void updateObject(int columnIndex, Object x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("updating object " + fields[columnIndex - 1].getName() + " = " + x);
updateValue(columnIndex, x);
}
public synchronized void updateObject(int columnIndex, Object x, int scale)
throws SQLException
{
if ( !isUpdateable() )
{
throw new PSQLException( "postgresql.updateable.notupdateable" );
}
this.updateObject(columnIndex, x);
}
public void refreshRow() throws SQLException
{
if ( !isUpdateable() )
{
throw new PSQLException( "postgresql.updateable.notupdateable" );
}
try
{
StringBuffer selectSQL = new StringBuffer( "select ");
final int numColumns = java.lang.reflect.Array.getLength(fields);
for (int i = 0; i < numColumns; i++ )
{
selectSQL.append( fields[i].getName() );
if ( i < numColumns - 1 )
{
selectSQL.append(", ");
}
}
selectSQL.append(" from " ).append(tableName).append(" where ");
int numKeys = primaryKeys.size();
for ( int i = 0; i < numKeys; i++ )
{
PrimaryKey primaryKey = ((PrimaryKey) primaryKeys.get(i));
selectSQL.append(primaryKey.name).append("= ?");
if ( i < numKeys - 1 )
{
selectSQL.append(" and ");
}
}
if ( Driver.logDebug )
Driver.debug("selecting " + selectSQL.toString());
selectStatement = ((java.sql.Connection) connection).prepareStatement(selectSQL.toString());
for ( int j = 0, i = 1; j < numKeys; j++, i++)
{
selectStatement.setObject( i, ((PrimaryKey) primaryKeys.get(j)).getValue() );
}
AbstractJdbc2ResultSet rs = (AbstractJdbc2ResultSet) selectStatement.executeQuery();
if ( rs.first() )
{
rowBuffer = rs.rowBuffer;
}
rows.setElementAt( rowBuffer, current_row );
if ( Driver.logDebug )
Driver.debug("done updates");
rs.close();
selectStatement.close();
selectStatement = null;
}
catch (Exception e)
{
if ( Driver.logDebug )
Driver.debug(e.getClass().getName() + e);
throw new SQLException( e.getMessage() );
}
}
public synchronized void updateRow()
throws SQLException
{
if ( !isUpdateable() )
{
throw new PSQLException( "postgresql.updateable.notupdateable" );
}
if (doingUpdates)
{
try
{
StringBuffer updateSQL = new StringBuffer("UPDATE " + tableName + " SET ");
int numColumns = updateValues.size();
Enumeration columns = updateValues.keys();
for (int i = 0; columns.hasMoreElements(); i++ )
{
String column = (String) columns.nextElement();
updateSQL.append("\"");
updateSQL.append( column );
updateSQL.append("\" = ?");
if ( i < numColumns - 1 )
{
updateSQL.append(", ");
}
}
updateSQL.append( " WHERE " );
int numKeys = primaryKeys.size();
for ( int i = 0; i < numKeys; i++ )
{
PrimaryKey primaryKey = ((PrimaryKey) primaryKeys.get(i));
updateSQL.append("\"");
updateSQL.append(primaryKey.name);
updateSQL.append("\" = ?");
if ( i < numKeys - 1 )
{
updateSQL.append(" and ");
}
}
if ( Driver.logDebug )
Driver.debug("updating " + updateSQL.toString());
updateStatement = ((java.sql.Connection) connection).prepareStatement(updateSQL.toString());
int i = 0;
Iterator iterator = updateValues.values().iterator();
for (; iterator.hasNext(); i++)
{
Object o = iterator.next();
if (o instanceof NullObject)
updateStatement.setNull(i+1,java.sql.Types.NULL);
else
updateStatement.setObject( i + 1, o );
}
for ( int j = 0; j < numKeys; j++, i++)
{
updateStatement.setObject( i + 1, ((PrimaryKey) primaryKeys.get(j)).getValue() );
}
updateStatement.executeUpdate();
updateStatement.close();
updateStatement = null;
updateRowBuffer();
if ( Driver.logDebug )
Driver.debug("copying data");
System.arraycopy(rowBuffer, 0, this_row, 0, rowBuffer.length);
rows.setElementAt( rowBuffer, current_row );
if ( Driver.logDebug )
Driver.debug("done updates");
doingUpdates = false;
}
catch (Exception e)
{
if ( Driver.logDebug )
Driver.debug(e.getClass().getName() + e);
throw new SQLException( e.getMessage() );
}
}
}
public synchronized void updateShort(int columnIndex, short x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("in update Short " + fields[columnIndex - 1].getName() + " = " + x);
updateValue(columnIndex, new Short(x));
}
public synchronized void updateString(int columnIndex, String x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("in update String " + fields[columnIndex - 1].getName() + " = " + x);
updateValue(columnIndex, x);
}
public synchronized void updateTime(int columnIndex, Time x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("in update Time " + fields[columnIndex - 1].getName() + " = " + x);
updateValue(columnIndex, x);
}
public synchronized void updateTimestamp(int columnIndex, Timestamp x)
throws SQLException
{
if ( Driver.logDebug )
Driver.debug("updating Timestamp " + fields[columnIndex - 1].getName() + " = " + x);
updateValue(columnIndex, x);
}
public synchronized void updateNull(String columnName)
throws SQLException
{
updateNull(findColumn(columnName));
}
public synchronized void updateBoolean(String columnName, boolean x)
throws SQLException
{
updateBoolean(findColumn(columnName), x);
}
public synchronized void updateByte(String columnName, byte x)
throws SQLException
{
updateByte(findColumn(columnName), x);
}
public synchronized void updateShort(String columnName, short x)
throws SQLException
{
updateShort(findColumn(columnName), x);
}
public synchronized void updateInt(String columnName, int x)
throws SQLException
{
updateInt(findColumn(columnName), x);
}
public synchronized void updateLong(String columnName, long x)
throws SQLException
{
updateLong(findColumn(columnName), x);
}
public synchronized void updateFloat(String columnName, float x)
throws SQLException
{
updateFloat(findColumn(columnName), x);
}
public synchronized void updateDouble(String columnName, double x)
throws SQLException
{
updateDouble(findColumn(columnName), x);
}
public synchronized void updateBigDecimal(String columnName, BigDecimal x)
throws SQLException
{
updateBigDecimal(findColumn(columnName), x);
}
public synchronized void updateString(String columnName, String x)
throws SQLException
{
updateString(findColumn(columnName), x);
}
public synchronized void updateBytes(String columnName, byte x[])
throws SQLException
{
updateBytes(findColumn(columnName), x);
}
public synchronized void updateDate(String columnName, java.sql.Date x)
throws SQLException
{
updateDate(findColumn(columnName), x);
}
public synchronized void updateTime(String columnName, java.sql.Time x)
throws SQLException
{
updateTime(findColumn(columnName), x);
}
public synchronized void updateTimestamp(String columnName, java.sql.Timestamp x)
throws SQLException
{
updateTimestamp(findColumn(columnName), x);
}
public synchronized void updateAsciiStream(
String columnName,
java.io.InputStream x,
int length)
throws SQLException
{
updateAsciiStream(findColumn(columnName), x, length);
}
public synchronized void updateBinaryStream(
String columnName,
java.io.InputStream x,
int length)
throws SQLException
{
updateBinaryStream(findColumn(columnName), x, length);
}
public synchronized void updateCharacterStream(
String columnName,
java.io.Reader reader,
int length)
throws SQLException
{
updateCharacterStream(findColumn(columnName), reader, length);
}
public synchronized void updateObject(String columnName, Object x, int scale)
throws SQLException
{
updateObject(findColumn(columnName), x);
}
public synchronized void updateObject(String columnName, Object x)
throws SQLException
{
updateObject(findColumn(columnName), x);
}
private int _findColumn( String columnName )
{
int i;
final int flen = fields.length;
for (i = 0; i < flen; ++i)
{
if (fields[i].getName().equalsIgnoreCase(columnName))
{
return (i + 1);
}
}
return -1;
}
/**
* Is this ResultSet updateable?
*/
boolean isUpdateable() throws SQLException
{
if (updateable)
return true;
if ( Driver.logDebug )
Driver.debug("checking if rs is updateable");
parseQuery();
if ( singleTable == false )
{
if ( Driver.logDebug )
Driver.debug("not a single table");
return false;
}
if ( Driver.logDebug )
Driver.debug("getting primary keys");
// Contains the primary key?
primaryKeys = new Vector();
// this is not stricty jdbc spec, but it will make things much faster if used
// the user has to select oid, * from table and then we will just use oid
usingOID = false;
int oidIndex = _findColumn( "oid" );
int i = 0;
// if we find the oid then just use it
if ( oidIndex > 0 )
{
i++;
primaryKeys.add( new PrimaryKey( oidIndex, "oid" ) );
usingOID = true;
}
else
{
// otherwise go and get the primary keys and create a hashtable of keys
// if the user has supplied a quoted table name
// remove the quotes, but preserve the case.
// otherwise fold to lower case.
String quotelessTableName;
if (tableName.startsWith("\"") && tableName.endsWith("\"")) {
quotelessTableName = tableName.substring(1,tableName.length()-1);
} else {
quotelessTableName = tableName.toLowerCase();
}
java.sql.ResultSet rs = ((java.sql.Connection) connection).getMetaData().getPrimaryKeys("", "", quotelessTableName);
for (; rs.next(); i++ )
{
String columnName = rs.getString(4); // get the columnName
int index = findColumn( columnName );
if ( index > 0 )
{
primaryKeys.add( new PrimaryKey(index, columnName ) ); // get the primary key information
}
}
rs.close();
}
numKeys = primaryKeys.size();
if ( Driver.logDebug )
Driver.debug( "no of keys=" + i );
if ( i < 1 )
{
throw new SQLException("No Primary Keys");
}
updateable = primaryKeys.size() > 0;
if ( Driver.logDebug )
Driver.debug( "checking primary key " + updateable );
return updateable;
}
public void parseQuery()
{
String[] l_sqlFragments = ((AbstractJdbc2Statement)statement).getSqlFragments();
String l_sql = l_sqlFragments[0];
StringTokenizer st = new StringTokenizer(l_sql, " \r\t");
boolean tableFound = false, tablesChecked = false;
String name = "";
singleTable = true;
while ( !tableFound && !tablesChecked && st.hasMoreTokens() )
{
name = st.nextToken();
if ( !tableFound )
{
if (name.toLowerCase().equals("from"))
{
tableName = st.nextToken();
tableFound = true;
}
}
else
{
tablesChecked = true;
// if the very next token is , then there are multiple tables
singleTable = !name.equalsIgnoreCase(",");
}
}
}
private void updateRowBuffer() throws SQLException
{
Enumeration columns = updateValues.keys();
while ( columns.hasMoreElements() )
{
String columnName = (String) columns.nextElement();
int columnIndex = _findColumn( columnName ) - 1;
Object valueObject = updateValues.get(columnName);
if (valueObject instanceof NullObject) {
rowBuffer[columnIndex] = null;
}
else
{
switch ( connection.getSQLType( fields[columnIndex].getPGType() ) )
{
case Types.DECIMAL:
case Types.BIGINT:
case Types.DOUBLE:
case Types.BIT:
case Types.VARCHAR:
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
case Types.SMALLINT:
case Types.FLOAT:
case Types.INTEGER:
case Types.CHAR:
case Types.NUMERIC:
case Types.REAL:
case Types.TINYINT:
rowBuffer[columnIndex] = connection.getEncoding().encode(String.valueOf( valueObject));
case Types.NULL:
continue;
default:
rowBuffer[columnIndex] = (byte[]) valueObject;
}
}
}
}
public void setStatement(Statement statement)
{
this.statement = statement;
}
protected void updateValue(int columnIndex, Object value) throws SQLException {
if ( !isUpdateable() )
{
throw new PSQLException( "postgresql.updateable.notupdateable" );
}
doingUpdates = !onInsertRow;
if (value == null)
updateNull(columnIndex);
else
updateValues.put(fields[columnIndex - 1].getName(), value);
}
private class PrimaryKey
{
int index; // where in the result set is this primaryKey
String name; // what is the columnName of this primary Key
PrimaryKey( int index, String name)
{
this.index = index;
this.name = name;
}
Object getValue() throws SQLException
{
return getObject(index);
}
};
class NullObject {
};
} |
/**
* cgShape.java
*
* Class that includes routines for tessellating a number of basic shapes
*
* Students are to supply their implementations for the
* functions in this file using the function "addTriangle()" to do the
* tessellation.
*
*/
import java.awt.*;
import java.nio.*;
import java.awt.event.*;
import javax.media.opengl.*;
import javax.media.opengl.awt.GLCanvas;
import java.io.*;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import static java.util.Arrays.asList;
public class cgShape extends simpleShape
{
HashMap<Integer, List<Triangle>> icosahedron;
/**
* constructor
*/
public cgShape()
{
constructIcosahedron();
}
// public enum Axis {
// X, Y, Z;
static class Point {
float x, y, z;
public Point(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public void normalize() {
float d = (float) Math.sqrt((x * x) + (y * y) + (z * z));
if (d != 0.0) {
x /= d;
y /= d;
z /= d;
}
scale();
}
public void scale() {
x /= 2;
y /= 2;
z /= 2;
}
}
static class Triangle {
List<Point> points;
public Triangle(List<Point> points) {
this.points = points;
}
public Point get (int i) {
return points.get(i);
}
public List<Triangle> subdivide() {
List<Triangle> list = new ArrayList<Triangle>(4);
Point m01 = new Point(midX(0), midY(0), midZ(0));
Point m12 = new Point(midX(1), midY(1), midZ(1));
Point m02 = new Point(midX(2), midY(2), midZ(2));
m01.normalize();
m12.normalize();
m02.normalize();
list.add(new Triangle(asList(get(0), m02, m01)));
list.add(new Triangle(asList(m02, m12, m01)));
list.add(new Triangle(asList(m12, get(1), m01)));
list.add(new Triangle(asList(m02, get(2), m12)));
return list;
}
public float midX(int i) {
int j;
j = i >= 2 ? 0 : i+1;
return (points.get(i).x + points.get(j).x) / 2.0f;
}
public float midY(int i) {
int j;
j = i >= 2 ? 0 : i+1;
return (points.get(i).y + points.get(j).y) / 2.0f;
}
public float midZ(int i) {
int j;
j = i >= 2 ? 0 : i+1;
return (points.get(i).z + points.get(j).z) / 2.0f;
}
}
/**
* makeCube - Create a unit cube, centered at the origin, with a given number
* of subdivisions in each direction on each face.
*
* @param subdivision - number of equal subdivisons to be made in each
* direction along each face
*
* Can only use calls to addTriangle()
*/
public void makeCube (int subdivisions)
{
if( subdivisions < 1 )
subdivisions = 1;
drawCube(new Point(-0.5f, -0.5f, 0.5f), subdivisions);
}
/* Find each subsquare and draw on each axis. */
private void drawCube(Point p, int n) {
for (int i = 0; i < n; i++) {
float x0 = (float) i/n - 0.5f;
float x1 = (float) (i+1)/n - 0.5f;
for (int j = 0; j < n; j++) {
float y0 = (float) j/n - 0.5f;
float y1 = (float) (j+1)/n - 0.5f;
addTriangle( x0, y1, p.z,
x1, y0, p.z,
x0, y0, p.z);
addTriangle( x1, y1, p.z,
x1, y0, p.z,
x0, y1, p.z);
addTriangle( x0, y0, -p.z,
x1, y0, -p.z,
x0, y1, -p.z);
addTriangle( x0, y1, -p.z,
x1, y0, -p.z,
x1, y1, -p.z);
addTriangle( p.x, x0, y0,
p.x, x1, y0,
p.x, x0, y1);
addTriangle( p.x, x0, y1,
p.x, x1, y0,
p.x, x1, y1);
addTriangle(-p.x, x0, y1,
-p.x, x1, y0,
-p.x, x0, y0);
addTriangle(-p.x, x1, y1,
-p.x, x1, y0,
-p.x, x0, y1);
addTriangle( x0, p.y, y1,
x1, p.y, y0,
x0, p.y, y0);
addTriangle( x1, p.y, y1,
x1, p.y, y0,
x0, p.y, y1);
addTriangle( x0, -p.y, y0,
x1, -p.y, y0,
x0, -p.y, y1);
addTriangle( x0, -p.y, y1,
x1, -p.y, y0,
x1, -p.y, y1);
}
}
}
/**
* makeCylinder - Create polygons for a cylinder with unit height, centered at
* the origin, with separate number of radial subdivisions and height
* subdivisions.
*
* @param radius - Radius of the base of the cylinder
* @param radialDivision - number of subdivisions on the radial base
* @param heightDivisions - number of subdivisions along the height
*
* Can only use calls to addTriangle()
*/
public void makeCylinder (float radius, int radialDivisions, int heightDivisions)
{
if( radialDivisions < 3 )
radialDivisions = 3;
if( heightDivisions < 1 )
heightDivisions = 1;
makeDisks(radius, radialDivisions, heightDivisions);
}
/* Approximates disks on the y-axis centered at (0,0).
Draws triangles by connecting points at Theta_i, Theta_i+1, and the center.
*/
private void makeDisks(float r, int n, int rect) {
float x0, z0, x1, z1, theta0, theta1;
Point d0 = new Point (0f, -0.5f, 0f);
Point d1 = new Point (0f, 0.5f, 0f);
theta0 = 0;
x0 = r * (float) Math.cos(0);
z0 = r * (float) Math.sin(0);
for (int i = 0; i < n; i++) {
theta1 = theta0 + (float) 360/n;
x1 = r * (float) Math.cos(Math.toRadians(theta1));
z1 = r * (float) Math.sin(Math.toRadians(theta1));
addTriangle( d0.x, d0.y, d0.z,
x0, d0.y, z0,
x1, d0.y, z1);
addTriangle( x1, d1.y, z1,
x0, d1.y, z0,
d1.x, d1.y, d1.z);
Point p0 = new Point(x0, d0.y, z0);
Point p1 = new Point(x1, d0.y, z1);
drawCylinderRect(p0, p1, rect);
x0 = x1;
z0 = z1;
theta0 = theta1;
}
}
private void drawCylinderRect(Point p0, Point p1, int n) {
float y0, y1;
y0 = -0.5f;
for (int i = 0; i < n; i++) {
y1 = y0 + (float) 1/n;
addTriangle(p0.x, y1, p0.z,
p1.x, y1, p1.z,
p0.x, y0, p0.z);
addTriangle(p1.x, y1, p1.z,
p1.x, y0, p1.z,
p0.x, y0, p0.z);
y0 = y1;
}
}
/**
* makeCone - Create polygons for a cone with unit height, centered at the
* origin, with separate number of radial subdivisions and height
* subdivisions.
*
* @param radius - Radius of the base of the cone
* @param radialDivision - number of subdivisions on the radial base
* @param heightDivisions - number of subdivisions along the height
*
* Can only use calls to addTriangle()
*/
public void makeCone (float radius, int radialDivisions, int heightDivisions)
{
if( radialDivisions < 3 )
radialDivisions = 3;
if( heightDivisions < 1 )
heightDivisions = 1;
makeConeDisk(radius, radialDivisions, heightDivisions);
}
/* Approximates disks on the y-axis centered at (0,0).
Draws triangles by connecting points at Theta_i, Theta_i+1, and the center.
*/
private void makeConeDisk(float r, int n, int h) {
float x0, z0, x1, z1, theta0, theta1;
Point d0 = new Point (0f, -0.5f, 0f);
theta0 = 0;
x0 = r * (float) Math.cos(0);
z0 = r * (float) Math.sin(0);
for (int i = 0; i < n; i++) {
theta1 = theta0 + (float) 360/n;
x1 = r * (float) Math.cos(Math.toRadians(theta1));
z1 = r * (float) Math.sin(Math.toRadians(theta1));
addTriangle( d0.x, d0.y, d0.z,
x0, d0.y, z0,
x1, d0.y, z1);
Point p0 = new Point(x0, d0.y, z0);
Point p1 = new Point(x1, d0.y, z1);
makeConeHeight(p0, p1, h);
x0 = x1;
z0 = z1;
theta0 = theta1;
}
}
private void makeConeHeight(Point p0, Point p1, int h) {
float ix0, iz0, ix1, iz1, fx0, fz0, fx1, fz1, y0, y1;
ix0 = p0.x;
iz0 = p0.z;
ix1 = p1.x;
iz1 = p1.z;
y0 = -0.5f;
for (int i = 0; i < h; i++) {
if (i == h-1) {
Point base = new Point(0f, 0.5f, 0f);
addTriangle(ix0, y0, iz0,
ix1, y0, iz1,
base.x, base.y, base.z);
} else {
y1 = y0 + (float) (1/h);
fx0 = (1 - (float) (1/h)) * ix0;
fz0 = (1 - (float) (1/h)) * iz0;
fx1 = (1 - (float) (1/h)) * ix1;
fz1 = (1 - (float) (1/h)) * iz1;
addTriangle(ix0, y0, iz0,
ix1, y0, iz1,
fx0, y1, fz0);
addTriangle(ix1, y0, iz1,
fx1, y1, fz1,
fx0, y1, fz0);
y0 = y1;
ix0 = fx0;
iz0 = fz0;
ix1 = fx1;
iz1 = fz1;
}
}
}
private void constructIcosahedron() {
float a = 2f / (float) (1f + Math.sqrt(5));
Point[] p = new Point[12];
p[0] = new Point( 0, a, -1);
p[1] = new Point(-a, 1, 0);
p[2] = new Point( a, 1, 0);
p[3] = new Point( 0, a, 1);
p[4] = new Point(-1, 0, a);
p[5] = new Point( 0, -a, 1);
p[6] = new Point( 1, 0, a);
p[7] = new Point( 1, 0, -a);
p[8] = new Point( 0, -a, -1);
p[9] = new Point(-1, 0, -a);
p[10] = new Point(-a, -1, 0);
p[11] = new Point( a, -1, 0);
for (Point pt : p) {
pt.normalize();
}
List<Triangle> d0 = new ArrayList<Triangle>();
d0.add(new Triangle(asList(p[0], p[1], p[2])));
d0.add(new Triangle(asList(p[3], p[2], p[1])));
d0.add(new Triangle(asList(p[3], p[4], p[5])));
d0.add(new Triangle(asList(p[3], p[5], p[6])));
d0.add(new Triangle(asList(p[0], p[7], p[8])));
d0.add(new Triangle(asList(p[0], p[8], p[9])));
d0.add(new Triangle(asList(p[5], p[10], p[11])));
d0.add(new Triangle(asList(p[8], p[11], p[10])));
d0.add(new Triangle(asList(p[1], p[9], p[4])));
d0.add(new Triangle(asList(p[10], p[4], p[9])));
d0.add(new Triangle(asList(p[2], p[6], p[7])));
d0.add(new Triangle(asList(p[11], p[7], p[6])));
d0.add(new Triangle(asList(p[3], p[1], p[4])));
d0.add(new Triangle(asList(p[3], p[6], p[2])));
d0.add(new Triangle(asList(p[0], p[9], p[1])));
d0.add(new Triangle(asList(p[0], p[2], p[7])));
d0.add(new Triangle(asList(p[8], p[10], p[9])));
d0.add(new Triangle(asList(p[8], p[7], p[11])));
d0.add(new Triangle(asList(p[5], p[4], p[10])));
d0.add(new Triangle(asList(p[5], p[11], p[6])));
icosahedron = new HashMap<Integer, List<Triangle>>();
icosahedron.put(0, d0);
for (int i = 1; i <= 5; i++)
makeSphereDivision(i);
}
/**
* makeSphere - Create sphere of a given radius, centered at the origin,
* using spherical coordinates with separate number of thetha and
* phi subdivisions.
*
* @param radius - Radius of the sphere
* @param slides - number of subdivisions in the theta direction
* @param stacks - Number of subdivisions in the phi direction.
*
* Can only use calls to addTriangle
*/
public void makeSphere (float radius, int slices, int stacks)
{
if (slices > 5)
slices = 5;
for (Triangle t : icosahedron.get(slices-1)) {
addTriangle(t.get(0).x, t.get(0).y, t.get(0).z,
t.get(1).x, t.get(1).y, t.get(1).z,
t.get(2).x, t.get(2).y, t.get(2).z);
}
}
private void makeSphereDivision(int n) {
List<Triangle> dN = new ArrayList<Triangle>(4*icosahedron.get(n-1).size());
for (Triangle t : icosahedron.get(n-1)) {
for (Triangle tN : t.subdivide()) {
dN.add(tN);
}
}
icosahedron.put(n, dN);
}
} |
package solver.constraints.ternary;
import org.testng.Assert;
import org.testng.annotations.Test;
import solver.Solver;
import solver.constraints.Constraint;
import solver.constraints.ICF;
import solver.constraints.IntConstraintFactory;
import solver.constraints.Propagator;
import solver.exception.ContradictionException;
import solver.variables.EventType;
import solver.variables.IntVar;
import solver.variables.VF;
/**
* <br/>
*
* @author Charles Prud'homme
* @since 07/02/11
*/
public class TimesTest extends AbstractTernaryTest {
@Override
protected int validTuple(int vx, int vy, int vz) {
return vx * vy == vz ? 1 : 0;
}
@Override
protected Constraint make(IntVar[] vars, Solver solver) {
return IntConstraintFactory.times(vars[0], vars[1], vars[2]);
}
@Test(groups = "1s")
public void testJL() {
Solver s = new Solver();
IntVar a = VF.enumerated("a", 0, 3, s);
IntVar b = VF.enumerated("b", -3, 3, s);
IntVar z = VF.enumerated("z", 3, 4, s);
s.post(ICF.arithm(z, "=", 3));
Constraint c = ICF.times(a, b, z);
s.post(c);
try {
s.propagate();
Assert.assertFalse(a.contains(0));
for (Propagator p : c.getPropagators()) {
p.propagate(EventType.FULL_PROPAGATION.mask);
}
Assert.assertFalse(a.contains(0));
}catch (ContradictionException e){
Assert.assertFalse(true);
}
}
} |
package example;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
@Stateless
public class EjbBean {
@PersistenceContext
private EntityManager em;
@EJB
private EjbBean2 ejbBean2;
public void noResultException() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ExampleEntity> q = cb.createQuery(ExampleEntity.class);
Root<ExampleEntity> from = q.from(ExampleEntity.class);
q.where(cb.equal(from.get(ExampleEntity_.id), -1));
em.createQuery(q).getSingleResult();
}
public void optimisticLockException() {
ExampleEntity entity = new ExampleEntity();
entity.setId(2);
entity.setVersion(1);
em.merge(entity);
}
public void exception() throws ExampleException {
ejbBean2.exception();
}
public void runtimeException() {
ejbBean2.runtimeException();
}
} |
package com.msc.serverbrowser;
import java.util.Arrays;
import java.util.Locale;
import java.util.ResourceBundle;
import com.msc.serverbrowser.util.Language;
public class WhatsLeftToTranslate {
public static void main(final String[] args) {
final ResourceBundle englishLanguage = ResourceBundle.getBundle("com.msc.serverbrowser.localization.Lang", new Locale(Language.EN.getShortcut()));
Arrays.stream(Language.values())
.filter(lang -> lang != Language.EN)
.forEach(lang -> {
System.out.println("
System.out.println("```");
final ResourceBundle langProperties = ResourceBundle.getBundle("com.msc.serverbrowser.localization.Lang", new Locale(lang.getShortcut()));
for (final String key : englishLanguage.keySet()) {
final String value = langProperties.getString(key);
if (value.equals(englishLanguage.getString(key))) {
System.out.println(key + "=" + value);
}
}
System.out.println("```");
System.out.println();
});
}
} |
package org.jetel.graph;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.concurrent.Future;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.graph.runtime.GraphRuntimeContext;
import org.jetel.main.runGraph;
import org.jetel.test.CloverTestCase;
import org.jetel.util.file.FileUtils;
import org.jetel.util.string.StringUtils;
public class ResetTest extends CloverTestCase {
private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/";
private final static String[] EXAMPLE_PATH = {
"../cloveretl.examples/SimpleExamples/",
"../cloveretl.examples/AdvancedExamples/",
"../cloveretl.examples/CTL1FunctionsTutorial/",
"../cloveretl.examples/CTL2FunctionsTutorial/",
"../cloveretl.examples/DataProfiling/",
"../cloveretl.examples/DataSampling/",
"../cloveretl.examples/ExtExamples/",
"../cloveretl.test.scenarios/",
"../cloveretl.examples.commercial/",
"../cloveretl.examples/CompanyTransactionsTutorial/"
};
private final static String[] NEEDS_SCENARIOS_CONNECTION = {
"graphRevenues.grf",
"graphDBExecuteMsSql.grf",
"graphDBExecuteMySql.grf",
"graphDBExecuteOracle.grf",
"graphDBExecutePostgre.grf",
"graphDBExecuteSybase.grf",
"graphInfobrightDataWriterRemote.grf",
"graphLdapReaderWriter.grf"
};
private final static String[] NEEDS_SCENARIOS_LIB = {
"graphDBExecuteOracle.grf",
"graphDBExecuteSybase.grf",
"graphLdapReaderWriter.grf"
};
private final static String GRAPHS_DIR = "graph";
private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"};
private final String basePath;
private final File graphFile;
private final boolean batchMode;
private boolean cleanUp = true;
private static Log logger = LogFactory.getLog(ResetTest.class);
public static Test suite() {
final TestSuite suite = new TestSuite();
for (int i = 0; i < EXAMPLE_PATH.length; i++) {
logger.info("Testing graphs in " + EXAMPLE_PATH[i]);
final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR);
if(!graphsDir.exists()){
throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found");
}
File[] graphFiles =graphsDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".grf")
&& !pathname.getName().startsWith("TPCH")// ok, performance tests - last very long
&& !pathname.getName().contains("Performance")// ok, performance tests - last very long
&& !pathname.getName().equals("graphJoinData.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("conversionNum2num.grf") // ok, should fail
&& !pathname.getName().equals("outPortWriting.grf") // ok, should fail
&& !pathname.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client
&& !pathname.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client
&& !pathname.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client
&& !pathname.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client
&& !pathname.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client
&& !pathname.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server
&& !pathname.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server
&& !pathname.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows
&& !pathname.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server
&& !pathname.getName().equals("graphSequenceChecker.grf") // ok, is to fail
&& !pathname.getName().equals("FixedData.grf") // ok, is to fail
&& !pathname.getName().equals("xpathReaderStates.grf") // ok, is to fail
&& !pathname.getName().equals("graphDataPolicy.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDecimal2integer.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDecimal2long.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDouble2integer.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDouble2long.grf") // ok, is to fail
&& !pathname.getName().equals("conversionLong2integer.grf") // ok, is to fail
&& !pathname.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths
&& !pathname.getName().equals("mountainsInformix.grf") // see issue 2550
&& !pathname.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows
&& !pathname.getName().equals("XLSEncryptedFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSInvalidFile.grf") // ok, is to fail
&& !pathname.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSWildcardStrict.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail
&& !pathname.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail
&& !pathname.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail
&& !pathname.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts
&& !pathname.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts
&& !pathname.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail
&& !pathname.getName().equals("FailingGraph.grf") // ok, is to fail
&& !pathname.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts
&& !pathname.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail
&& !pathname.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail
&& !pathname.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail
&& !pathname.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines
&& !pathname.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved
&& !pathname.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate)
&& !pathname.getName().contains("firebird") // remove after CL-2170 solved
&& !pathname.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved
&& !pathname.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved
&& !pathname.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved
&& !pathname.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved
&& !pathname.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved
&& !pathname.getName().equals("manyRecords.grf") // remove after CL-1825 implemented
&& !pathname.getName().equals("packedDecimal.grf") // remove after CL-1811 solved
&& !pathname.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately
&& !pathname.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf
&& !pathname.getName().equals("testdata_intersection.grf") // remove after CL-1792 solved
&& !pathname.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail
&& !pathname.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved
&& !pathname.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail
&& !pathname.getName().equals("HttpConector_errHandlingNoRedir.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail
&& !pathname.getName().equals("RunGraph_differentOutputMetadataFail.grf"); // ok, is to fail
}
});
Arrays.sort(graphFiles);
for( int j = 0; j < graphFiles.length; j++){
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false));
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false));
}
}
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
initEngine();
}
protected static String getTestName(String basePath, File graphFile, boolean batchMode) {
final StringBuilder ret = new StringBuilder();
final String n = graphFile.getName();
int lastDot = n.lastIndexOf('.');
if (lastDot == -1) {
ret.append(n);
} else {
ret.append(n.substring(0, lastDot));
}
if (batchMode) {
ret.append("-batch");
} else {
ret.append("-nobatch");
}
return ret.toString();
}
protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) {
super(getTestName(basePath, graphFile, batchMode));
this.basePath = basePath;
this.graphFile = graphFile;
this.batchMode = batchMode;
this.cleanUp = cleanup;
}
@Override
protected void runTest() throws Throwable {
final String beseAbsolutePath = new File(basePath).getAbsolutePath();
logger.info("Project dir: " + beseAbsolutePath);
logger.info("Analyzing graph " + graphFile.getPath());
logger.info("Batch mode: " + batchMode);
final GraphRuntimeContext runtimeContext = new GraphRuntimeContext();
runtimeContext.setUseJMX(false);
runtimeContext.setContextURL(FileUtils.getFileURL(basePath));
// absolute path in PROJECT parameter is required for graphs using Derby database
runtimeContext.addAdditionalProperty("PROJECT", beseAbsolutePath);
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) {
final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath();
runtimeContext.addAdditionalProperty("CONN_DIR", connDir);
logger.info("CONN_DIR set to " + connDir);
}
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory
final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath();
runtimeContext.addAdditionalProperty("LIB_DIR", libDir);
logger.info("LIB_DIR set to " + libDir);
}
runtimeContext.setBatchMode(batchMode);
final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext);
try {
graph.setDebugMode(false);
EngineInitializer.initGraph(graph);
for (int i = 0; i < 3; i++) {
final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext);
Result result = Result.N_A;
result = futureResult.get();
switch (result) {
case FINISHED_OK:
// everything O.K.
logger.info("Execution of graph successful !");
break;
case ABORTED:
// execution was ABORTED !!
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
break;
default:
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
}
}
} catch (Throwable e) {
throw new IllegalStateException("Error executing grap " + graphFile, e);
} finally {
if (cleanUp) {
cleanupData();
}
logger.info("Transformation graph is freeing.\n");
graph.free();
}
}
private void cleanupData() {
for (String outDir : OUT_DIRS) {
File outDirFile = new File(basePath, outDir);
File[] file = outDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isFile();
}
});
for (int i = 0; i < file.length; i++) {
final boolean drt = file[i].delete();
if (drt) {
logger.info("Cleanup: deleted file " + file[i].getAbsolutePath());
} else {
logger.info("Cleanup: error delete file " + file[i].getAbsolutePath());
}
}
}
}
} |
package org.jetel.graph;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.concurrent.Future;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.graph.runtime.GraphRuntimeContext;
import org.jetel.main.runGraph;
import org.jetel.test.CloverTestCase;
import org.jetel.util.file.FileUtils;
import org.jetel.util.string.StringUtils;
public class ResetTest extends CloverTestCase {
private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/";
private final static String[] EXAMPLE_PATH = {
"../cloveretl.examples/SimpleExamples/",
"../cloveretl.examples/AdvancedExamples/",
"../cloveretl.examples/CTL1FunctionsTutorial/",
"../cloveretl.examples/CTL2FunctionsTutorial/",
"../cloveretl.examples/DataProfiling/",
"../cloveretl.examples/DataSampling/",
"../cloveretl.examples/ExtExamples/",
"../cloveretl.test.scenarios/",
"../cloveretl.examples.commercial/",
"../cloveretl.examples/CompanyTransactionsTutorial/"
};
private final static String[] NEEDS_SCENARIOS_CONNECTION = {
"graphRevenues.grf",
"graphDBExecuteMsSql.grf",
"graphDBExecuteMySql.grf",
"graphDBExecuteOracle.grf",
"graphDBExecutePostgre.grf",
"graphDBExecuteSybase.grf",
"graphInfobrightDataWriterRemote.grf",
"graphLdapReaderWriter.grf"
};
private final static String[] NEEDS_SCENARIOS_LIB = {
"graphDBExecuteOracle.grf",
"graphDBExecuteSybase.grf",
"graphLdapReaderWriter.grf"
};
private final static String GRAPHS_DIR = "graph";
private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"};
private final String basePath;
private final File graphFile;
private final boolean batchMode;
private boolean cleanUp = true;
private static Log logger = LogFactory.getLog(ResetTest.class);
public static Test suite() {
final TestSuite suite = new TestSuite();
for (int i = 0; i < EXAMPLE_PATH.length; i++) {
logger.info("Testing graphs in " + EXAMPLE_PATH[i]);
final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR);
if(!graphsDir.exists()){
throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found");
}
File[] graphFiles =graphsDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".grf")
&& !pathname.getName().startsWith("TPCH")// ok, performance tests - last very long
&& !pathname.getName().contains("Performance")// ok, performance tests - last very long
&& !pathname.getName().equals("graphJoinData.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created
&& !pathname.getName().equals("conversionNum2num.grf") // ok, should fail
&& !pathname.getName().equals("outPortWriting.grf") // ok, should fail
&& !pathname.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client
&& !pathname.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client
&& !pathname.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client
&& !pathname.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client
&& !pathname.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client
&& !pathname.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server
&& !pathname.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server
&& !pathname.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows
&& !pathname.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server
&& !pathname.getName().equals("graphSequenceChecker.grf") // ok, is to fail
&& !pathname.getName().equals("FixedData.grf") // ok, is to fail
&& !pathname.getName().equals("xpathReaderStates.grf") // ok, is to fail
&& !pathname.getName().equals("graphDataPolicy.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDecimal2integer.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDecimal2long.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDouble2integer.grf") // ok, is to fail
&& !pathname.getName().equals("conversionDouble2long.grf") // ok, is to fail
&& !pathname.getName().equals("conversionLong2integer.grf") // ok, is to fail
&& !pathname.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths
&& !pathname.getName().equals("mountainsInformix.grf") // see issue 2550
&& !pathname.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows
&& !pathname.getName().equals("XLSEncryptedFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSInvalidFile.grf") // ok, is to fail
&& !pathname.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail
&& !pathname.getName().equals("XLSWildcardStrict.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail
&& !pathname.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail
&& !pathname.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail
&& !pathname.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail
&& !pathname.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts
&& !pathname.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts
&& !pathname.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail
&& !pathname.getName().equals("FailingGraph.grf") // ok, is to fail
&& !pathname.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts
&& !pathname.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail
&& !pathname.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail
&& !pathname.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail
&& !pathname.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines
&& !pathname.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved
&& !pathname.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate)
&& !pathname.getName().contains("firebird") // remove after CL-2170 solved
&& !pathname.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved
&& !pathname.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved
&& !pathname.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved
&& !pathname.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved
&& !pathname.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved
&& !pathname.getName().equals("manyRecords.grf") // remove after CL-1825 implemented
&& !pathname.getName().equals("packedDecimal.grf") // remove after CL-1811 solved
&& !pathname.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately
&& !pathname.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf
&& !pathname.getName().equals("testdata_intersection.grf") // remove after CL-1792 solved
&& !pathname.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail
&& !pathname.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved
&& !pathname.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail
&& !pathname.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail
&& !pathname.getName().equals("HttpConector_errHandlingNoRedir.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail
&& !pathname.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail
&& !pathname.getName().equals("RunGraph_differentOutputMetadataFail.grf") // ok, is to fail
&& !pathname.getName().equals("SandboxOperationHandlerTest.grf") // runs only on server
&& !pathname.getName().equals("DenormalizerWithoutInputFile.grf"); // probably subgraph not supposed to be executed separately
}
});
Arrays.sort(graphFiles);
for( int j = 0; j < graphFiles.length; j++){
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false));
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false));
}
}
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
initEngine();
}
protected static String getTestName(String basePath, File graphFile, boolean batchMode) {
final StringBuilder ret = new StringBuilder();
final String n = graphFile.getName();
int lastDot = n.lastIndexOf('.');
if (lastDot == -1) {
ret.append(n);
} else {
ret.append(n.substring(0, lastDot));
}
if (batchMode) {
ret.append("-batch");
} else {
ret.append("-nobatch");
}
return ret.toString();
}
protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) {
super(getTestName(basePath, graphFile, batchMode));
this.basePath = basePath;
this.graphFile = graphFile;
this.batchMode = batchMode;
this.cleanUp = cleanup;
}
@Override
protected void runTest() throws Throwable {
final String beseAbsolutePath = new File(basePath).getAbsolutePath().replace('\\', '/');
logger.info("Project dir: " + beseAbsolutePath);
logger.info("Analyzing graph " + graphFile.getPath());
logger.info("Batch mode: " + batchMode);
final GraphRuntimeContext runtimeContext = new GraphRuntimeContext();
runtimeContext.setUseJMX(false);
runtimeContext.setContextURL(FileUtils.getFileURL(basePath));
// absolute path in PROJECT parameter is required for graphs using Derby database
runtimeContext.addAdditionalProperty("PROJECT", beseAbsolutePath);
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) {
final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath();
runtimeContext.addAdditionalProperty("CONN_DIR", connDir);
logger.info("CONN_DIR set to " + connDir);
}
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory
final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath();
runtimeContext.addAdditionalProperty("LIB_DIR", libDir);
logger.info("LIB_DIR set to " + libDir);
}
runtimeContext.setBatchMode(batchMode);
final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext);
try {
graph.setDebugMode(false);
EngineInitializer.initGraph(graph);
for (int i = 0; i < 3; i++) {
final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext);
Result result = Result.N_A;
result = futureResult.get();
switch (result) {
case FINISHED_OK:
// everything O.K.
logger.info("Execution of graph successful !");
break;
case ABORTED:
// execution was ABORTED !!
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
break;
default:
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
}
}
} catch (Throwable e) {
throw new IllegalStateException("Error executing grap " + graphFile, e);
} finally {
if (cleanUp) {
cleanupData();
}
logger.info("Transformation graph is freeing.\n");
graph.free();
}
}
private void cleanupData() {
for (String outDir : OUT_DIRS) {
File outDirFile = new File(basePath, outDir);
File[] file = outDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isFile();
}
});
for (int i = 0; i < file.length; i++) {
final boolean drt = file[i].delete();
if (drt) {
logger.info("Cleanup: deleted file " + file[i].getAbsolutePath());
} else {
logger.info("Cleanup: error delete file " + file[i].getAbsolutePath());
}
}
}
}
} |
package com.podio.sdk.domain;
import com.google.gson.annotations.SerializedName;
import com.podio.sdk.domain.data.Data;
import com.podio.sdk.internal.Utils;
import com.podio.sdk.provider.TaskProvider.GetTaskFilter.Grouping;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
public class Task implements Data {
private final Long task_id = null;
private final String due_date = null;
private final String due_time = null;
private final String due_on = null;
private final Reminder reminder = null;
@SerializedName("private")
private final Boolean is_private = null;
private final String text = null;
private final String description = null;
private final String group = null;
private final Reference ref = null;
private final Profile responsible = null;
private final Status status = null;
private final Comment[] comments = null;
private final Label[] labels = null;
private final File[] files = null;
public static enum Status {
completed,
active,
deleted
}
/**
* A class representing the new task the client wants to create.
*/
public static class CreateData {
public enum ResponsibleType {
user,
space,
mail
}
public static class Responsible {
@SuppressWarnings("unused")
private ResponsibleType type;
public Responsible(ResponsibleType type) {
this.type = type;
}
}
public static class DefaultResponsible extends Responsible {
@SuppressWarnings("unused")
private final long id;
/**
* @param type
* user or space. If you wish to send in mail you have to use MailResponsible.
* @param id
*/
public DefaultResponsible(ResponsibleType type, long id) {
super(type);
this.id = id;
}
}
public static class MailResponsible extends Responsible {
@SuppressWarnings("unused")
private final String id;
public MailResponsible(String mail) {
super(ResponsibleType.mail);
this.id = mail;
}
}
@SuppressWarnings("unused")
private final String text;
@SuppressWarnings("unused")
private String description;
@SuppressWarnings("unused")
private String due_on;
@SuppressWarnings("unused")
private List<Responsible> responsible;
@SuppressWarnings("unused")
@SerializedName("private")
private Boolean isPrivate;
@SuppressWarnings("unused")
private ReferenceType ref_type;
@SuppressWarnings("unused")
private Long ref_id;
@SuppressWarnings("unused")
private List<Long> file_ids;
@SuppressWarnings("unused")
private Reminder reminder;
@SuppressWarnings("unused")
private List<Long> label_ids;
private Boolean completed;
public CreateData(String text) {
this.text = text;
}
public void setDescription(String description) {
this.description = description;
}
public void setDueOn(Date dueOn, boolean hasTime) {
if (hasTime) {
this.due_on = dueOn != null ? Utils.formatDateTimeUtc(dueOn) : null;
} else {
this.due_on = dueOn != null ? Utils.formatDateDefault(dueOn) : null;
}
}
public void setResponsible(List<Responsible> responsible) {
this.responsible = responsible;
}
public void setCompleted(boolean completed){
this.completed = completed;
}
public void setIsPrivate(boolean isPrivate) {
this.isPrivate = isPrivate;
}
/**
* This is only applicable when updating a task. When creating new new task with a reference
* the reference is part of the task create url path.
*
* @param refType
* @param refId
*/
public void setRefeference(ReferenceType refType, long refId) {
this.ref_type = refType;
this.ref_id = refId;
}
public ReferenceType getReferenceType(){
return this.ref_type;
}
public long getReferenceId(){
return Utils.getNative(ref_id,-1L);
}
public void setFileIds(List<Long> file_ids) {
this.file_ids = file_ids;
}
public void setReminder(Reminder reminder) {
this.reminder = reminder;
}
public void setLabelIds(List<Long> label_ids) {
this.label_ids = label_ids;
}
}
public long getTaskId() {
return Utils.getNative(task_id, -1L);
}
/**
* @return returns a timezone independent date component formatted as 2014-11-25
*/
public String getDueDate() {
return due_date;
}
/**
* @return returns the raw string given from the API, representing time formatted as 16:04:00 in
* the timezone of the user's web account
*/
public String getDueTime() {
return due_time;
}
/**
* @return returns the {@link Reminder} object or null if no reminder was set
*/
public Reminder getReminder() {
return reminder;
}
public Profile getResponsible() {
return responsible;
}
public boolean isPrivate() {
return Utils.getNative(is_private, false);
}
public String getText() {
return text;
}
public String getDescription() {
return description;
}
/**
* @return Depending on the given {@link Grouping}, this method will return the raw JSON string
* of which group this task is task is part of. If for example you requested tasks DUE_DATE
* grouping the this method would return a simple JSON structure of a string which either is
* 'overdue', 'today', 'tomorrow', 'upcoming' or 'later'. Consult Podio's developers page for
* full details.
*/
public String getGroup() {
return group;
}
/**
* @return returns the due date of this task in the phone's local time. It accounts for the fact
* that due on may or may not have a usable time component as described by hasTime().
*/
public Date getDueOn() {
if (hasDueTime()) {
return Utils.parseDateTimeUtc(due_on);
} else {
return Utils.parseDateUtc(due_on);
}
}
/**
* @return returns true if you can rely on having a time component in the in the UTC due date
* (i.e. due on) Date object, otherwise false. This is needed as tasks are allowed to have a
* date component set, with no specific time, which means that the time component of the Date
* object returned by getDueOn() is NOT valid
*/
public boolean hasDueTime() {
return due_time != null ? true : false;
}
public String getDueOnString() {
return due_on;
}
public Reference getReference() {
return ref;
}
public Status getStatus() {
return status;
}
public Collection<Comment> getComments() {
return Utils.notEmpty(comments) ? Arrays.asList(comments) : new ArrayList<Comment>(0);
}
public Collection<Label> getLabels() {
return Utils.notEmpty(labels) ? Arrays.asList(labels) : new ArrayList<Label>(0);
}
public List<File> getFiles() {
return Utils.notEmpty(files) ? Arrays.asList(files) : new ArrayList<File>(0);
}
} |
package ServerInterface;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* PC<br>
* TCP<br>
*
*/
public abstract class OriginInterface {
private InetAddress inetAddress;
private int port;
private Socket socket;
private PrintStream printStream;
private ListenThread listenThread;
/**
*
* @param inetAddress
*
* @param port
*
*/
public OriginInterface(InetAddress inetAddress, int port){
this.inetAddress = inetAddress;
this.port = port;
}
/**
*
* @return
*
*/
private boolean connect(){
if(socket != null && socket.isConnected())
return true;
try {
socket = new Socket(inetAddress, port);
printStream = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
onConnectionFail(e.getMessage());
return false;
}
listenThread = new ListenThread(socket, this);
listenThread.start();
return true;
}
/**
*
* @param string
*
*/
private void writeInSocket(String string){
try{
printStream.println(string);
printStream.flush();
}catch (Exception e){
e.printStackTrace();
onLostConnection(e.getMessage());
}
}
/**
* <br>
* REGISTER##
* @param username
*
* @param password
*
*/
final public void register(String username, String password){
if(username.contains("#") || password.contains("#") || username.contains("$") || password.contains("$")){
onRespondRegister(false,"
return;
}
if(username.equals("empty")){
onRespondRegister(false,"empty");
return;
}
if(!connect())
return;
writeInSocket("REGISTER#" + username + "#" +password);
}
/**
* <br>
* LOGIN##
* @param username
*
* @param password
*
*/
final public void login(String username, String password){
if(!connect())
return;
if(username.contains("#") || password.contains("#") || username.contains("$") || password.contains("$")){
onRespondLogin(false, 0, "
return;
}
writeInSocket("LOGIN#" + username + "#" +password);
}
/**
* <br>
* GET_TABLES
*/
final public void getTables(){
writeInSocket("GET_TABLES");
}
/**
* <br>
* ENTER_TABLES#
* @param tableId
*
*/
final public void enterTable(int tableId){
writeInSocket("ENTER_TABLES#" + tableId);
}
/**
* <br>
* HAND_UP
*/
final public void handUp(){
writeInSocket("HAND_UP");
}
/**
* <br>
* MOVE##
* @param row
*
* @param col
*
*/
final public void move(int row, int col){
writeInSocket("MOVE#" + row + "#" + col);
}
/**
* <br>
* GIVE_UP
*/
final public void giveUp(){
writeInSocket("GIVE_UP");
}
/**
* <br>
* RETRACT
*/
final public void retract(){
writeInSocket("RETRACT");
}
/**
* <br>
* RESPOND_RETRACT#
* @param ifAgree
*
*/
final public void respondRetract(boolean ifAgree){
writeInSocket("RESPOND_RETRACT#" + ifAgree);
}
/**
* <br>
* SEND_MESSAGE#
* @param message
*
*/
final public void sengMessage(String message){
if(message.contains("
onReceiveMessage("[]
return;
}
writeInSocket("SEND_MESSAGE#" + message);
}
/**
* <br>
* QUIT_TABLE
*/
final public void quitTable(){
writeInSocket("QUIT_TABLE");
}
/**
* <br>
* ON_RESPOND_REGISTER##
* @param ifRegistered
*
* @param reason
*
*/
abstract public void onRespondRegister(boolean ifRegistered, String reason);
/**
*
* @param reason
*
*/
abstract public void onConnectionFail(String reason);
/**
*
* @param reason
*
*/
abstract public void onLostConnection(String reason);
/**
* <br>
* ON_RESPOND_LOGIN##
* @param ifLogined
*
* @param score
*
* @param reason
*
*/
abstract public void onRespondLogin(boolean ifLogined, int score, String reason);
/**
* <br>
* ON_RESPOND_GET_TABLES#TableInfo.tableInfoArrayToString()
* @param tableInfos
*
*/
abstract public void onRespondGetTables(TableInfo[] tableInfos);
abstract public void onRespondEnterTable(int tableId, boolean ifEntered, String reason);
abstract public void onTableChange(
PlayerInfo myInfo,
PlayerInfo opponentInfo,
boolean ifMyHandUp,
boolean ifOpponentHandUp,
boolean isPlaying,
int board [][],
boolean isBlack,
boolean isMyTurn);
abstract public void onGameOver(boolean isDraw, boolean ifWin, boolean ifGiveUp);
/**
* <br>
* ON_RESPOND_RETRACT#ifAgree
* @param ifAgree
* onBoardChange
*/
abstract public void onRespondRetract(boolean ifAgree);
/**
* <br>
* ON_OPPONENT_RETRACT
*/
abstract public void onOpponentRetract();
/**
* <br>
* ON_RECEIVE_MESSAGE#
* @param message
*
*/
abstract public void onReceiveMessage(String message);
/**
* <br>
* ON_RESPOND_QUIT_TABLE#
* @param ifAgree
*
*/
abstract public void onRespondQuitTable(boolean ifAgree);
} |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
import org.junit.Ignore;
import org.junit.Test;
public class ListOpsTest {
private static final List<Integer> EMPTY_LIST
= Collections.emptyList();
@Test
public void lengthOfAnEmptyListShouldBeZero() {
final int expected = 0;
final int actual = ListOps.length(EMPTY_LIST);
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldReturnTheCorrectLengthOfAnNonEmptyList() {
final List<Integer> list = Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3, 4)
);
final int actual = ListOps.length(list);
final int expected = list.size();
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldReverseAnEmptyList() {
final List<Integer> actual = ListOps.reverse(EMPTY_LIST);
assertNotNull(actual);
assertTrue(actual.isEmpty());
}
@Test
@Ignore("Remove to run test")
public void shouldReverseANonEmptyList() {
final List<Integer> list = Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8)
);
final List<Integer> actual
= ListOps.reverse(list);
final List<Integer> expected
= Arrays.asList(8, 7, 6, 5, 4, 3, 2, 1, 0);
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldMapAnEmptyListAndReturnAnEmptyList() {
final List<Integer> actual = ListOps.map(EMPTY_LIST, x -> x + 1);
assertNotNull(actual);
assertTrue(actual.isEmpty());
}
@Test
@Ignore("Remove to run test")
public void shouldMapNonEmptyList() {
final List<Integer> list
= Collections.unmodifiableList(Arrays.asList(1, 3, 5, 7));
final List<Integer> actual = ListOps.map(list, x -> x + 1);
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(Arrays.asList(2, 4, 6, 8), actual);
}
@Test
@Ignore("Remove to run test")
public void shouldFilterAnEmptyListanddReturnAnEmptyList() {
final List<Integer> actual = ListOps.filter(EMPTY_LIST, x -> x > 0);
assertNotNull(actual);
assertTrue(actual.isEmpty());
}
@Test
@Ignore("Remove to run test")
public void shouldFilterNonEmptyList() {
Predicate<Integer> predicate = x -> x % 2 > 0;
final List<Integer> list = Collections.unmodifiableList(
IntStream.range(0, 100).boxed().collect(Collectors.toList())
);
final List<Integer> actual = ListOps.filter(list, predicate);
final List<Integer> expected = list.stream()
.filter(predicate)
.collect(Collectors.toList());
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldConcatenateZeroLists() {
List<Integer> actual = ListOps.concat();
assertNotNull(actual);
assertTrue(actual.isEmpty());
}
@Test
@Ignore("Remove to run test")
public void shouldConcatenateOneNonEmptyList() {
final List<Integer> list
= Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3, 4)
);
final List<Integer> actual = ListOps.concat(list);
final List<Integer> expected = Arrays.asList(0, 1, 2, 3, 4);
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldConcatenateOneEmptyList() {
final List<Integer> actual = ListOps.concat(EMPTY_LIST);
assertNotNull(actual);
assertTrue(actual.isEmpty());
}
@Test
@Ignore("Remove to run test")
public void shouldConcatenateTwoEmptyLists() {
final List<Integer> actual = ListOps.concat(EMPTY_LIST, EMPTY_LIST);
assertNotNull(actual);
assertTrue(actual.isEmpty());
}
@Test
@Ignore("Remove to run test")
public void shouldConcatenateOneEmptyAndOneNonEmptyLists() {
final List<Integer> list
= Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3, 4)
);
final List<Integer> actual = ListOps.concat(list, EMPTY_LIST);
final List<Integer> expected
= Arrays.asList(0, 1, 2, 3, 4);
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldConcatenateOneNonEmptyAndOneEmptyLists() {
final List<Integer> list
= Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3, 4)
);
final List<Integer> actual = ListOps.concat(EMPTY_LIST, list);
final List<Integer> expected
= Arrays.asList(0, 1, 2, 3, 4);
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldConcatenateTwoListsWithSameElements() {
final List<Integer> list1 = Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3, 4)
);
final List<Integer> list2 = Collections.unmodifiableList(
Arrays.asList(1, 2, 3, 4, 5, 6)
);
final List<Integer> expected
= Arrays.asList(0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6);
final List<Integer> actual = ListOps.concat(list1, list2);
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldConcatenateSeveralLists() {
final List<Integer> list1 = Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3)
);
final List<Integer> list2 = Collections.unmodifiableList(
Arrays.asList(4, 5, 6, 7)
);
final List<Integer> list3 = Collections.unmodifiableList(
Arrays.asList(8, 9, 10, 11)
);
final List<Integer> list4 = Collections.unmodifiableList(
Arrays.asList(12, 13, 14, 15)
);
final List<Integer> expected
= Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15);
final List<Integer> actual
= ListOps.concat(list1, list2, EMPTY_LIST, list3, list4);
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldReturnIdentityWhenAnEmptyListIsReduced() {
final int expected = 0;
final int actual
= ListOps.reduce(EMPTY_LIST, 0, (x, y) -> x + y, Integer::sum);
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldCalculateTheSumOfANonEmptyIntegerList() {
final List<Integer> list = Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3, 4)
);
final int actual = ListOps.reduce(list, 0,
(x, y) -> x + y,
Integer::sum);
assertEquals(10, actual);
}
private BiFunction<List<Integer>, Integer, List<Integer>> accumulator
= (List<Integer> partial, Integer elem) -> {
List<Integer> result = new ArrayList<>(partial);
result.add(elem);
return result;
};
private BinaryOperator<List<Integer>> combiner
= (list1, list2) -> {
List<Integer> result = new ArrayList<>(list1);
result.addAll(list2);
return result;
};
@Test
@Ignore("Remove to run test")
public void shouldReduceAnEmptyListAndANonEmptyListAndReturnConcatenation() {
final List<Integer> list = Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3, 4, 5)
);
final List<Integer> actual
= ListOps.reduce(list,
new ArrayList<Integer>(),
accumulator,
combiner);
final List<Integer> expected
= Arrays.asList(0, 1, 2, 3, 4, 5);
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(expected, actual);
}
@Test
@Ignore("Remove to run test")
public void shouldReduceTwoNonEmptyListsAndReturnConcatenation() {
final List<Integer> listOne = Collections.unmodifiableList(
Arrays.asList(0, 1, 2, 3, 4)
);
final List<Integer> listTwo = Collections.unmodifiableList(
Arrays.asList(5, 6, 7, 8, 9)
);
final List<Integer> actual
= ListOps.reduce(listTwo,
listOne,
accumulator,
combiner);
final List<Integer> expected
= Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
assertNotNull(actual);
assertFalse(actual.isEmpty());
assertEquals(expected, actual);
}
} |
package org.exist.fluent;
import javax.xml.XMLConstants;
import org.w3c.dom.*;
import org.w3c.dom.Document;
/**
* A qualified name, consisting of a namespace and a local name.
*
* @author <a href="mailto:piotr@ideanest.com">Piotr Kaminski</a>
*/
public class QName extends javax.xml.namespace.QName implements Comparable<QName> {
private final String tag;
/**
* Create a qualified name.
*
* @param namespace the namespace of the qualified name, <code>null</code> if none
* @param localName the local part of the qualified name, must not be <code>null</code> or empty
* @param prefix the prefix to use for the qualified name, <code>null</code> if default (empty) prefix
*/
public QName(String namespace, String localName, String prefix) {
super(namespace == null ? XMLConstants.NULL_NS_URI : namespace, localName, prefix == null ? XMLConstants.DEFAULT_NS_PREFIX : prefix);
if (localName == null || localName.length() == 0) throw new IllegalArgumentException("null or empty local name");
if (prefix == null || prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
tag = localName;
} else {
tag = prefix + ":" + localName;
}
}
public int compareTo(QName o) {
return toString().compareTo(o.toString());
}
/**
* Return whether this qualified name is actually qualified by a namespace or not.
*
* @return <code>true</code> if the qualified name has a namespace set, <code>false</code> if it's just a local name
*/
public boolean hasNamespace() {
return !getNamespaceURI().equals(XMLConstants.NULL_NS_URI);
}
/**
* Create an element in the given document whose tag is this qualified name. Correctly calls
* <code>createElement</code> or <code>createElementNS</code> depending on whether
* this name is actually qualified or not.
*
* @param doc the document to use to create the element
* @return a new element whose tag is this qualified name
*/
public Element createElement(Document doc) {
if (hasNamespace()) return doc.createElementNS(getNamespaceURI(), tag);
return doc.createElement(tag);
}
/**
* Create an attribute in the given document whose name is this qualified name. Correctly calls
* <code>createAttribute</code> or <code>createAttributeNS</code> depending on whether
* this name is actually qualified or not.
*
* @param doc the document to use to create the attribute
* @return a new attribute whose name is this qualified name
*/
public Attr createAttribute(Document doc) {
if (hasNamespace()) return doc.createAttributeNS(getNamespaceURI(), tag);
return doc.createAttribute(tag);
}
/**
* Set an attribute value on the given element, where the attribute's name is this qualified name.
* Correctly calls <code>setAttribute</code> or <code>setAttributeNS</code> depending on whether
* this name is actually qualified or not.
*
* @param elem the element on which to set the attribute
* @param value the value of the attribute
*/
public void setAttribute(Element elem, String value) {
if (hasNamespace()) {
elem.setAttributeNS(getNamespaceURI(), tag, value);
} else {
elem.setAttribute(tag, value);
}
}
/**
* Get the attribute with this qualified name from the given element. Correctly calls
* <code>getAttributeNode</code> or <code>getAttributeNodeNS</code> depending on whether
* this name is actually qualified or not.
*
* @param elem the element to read the attribute from
* @return the attribute node with this qualified name
*/
public Attr getAttributeNode(Element elem) {
if (hasNamespace()) return elem.getAttributeNodeNS(getNamespaceURI(), getLocalPart());
return elem.getAttributeNode(tag);
}
/**
* Return the qualified name of the given node.
*
* @param node the target node
* @return the node's qualified name
*/
public static QName of(org.w3c.dom.Node node) {
String localName = node.getLocalName();
if (localName == null) localName = node.getNodeName();
return new QName(node.getNamespaceURI(), localName, node.getPrefix());
}
/**
* Parse the given tag into a qualified name within the context of the given namespace bindings.
*
* @param tag the tag to parse, in standard XML format
* @param namespaces the namespace bindings to use
* @return the qualified name of the given tag
*/
public static QName parse(String tag, NamespaceMap namespaces) {
return parse(tag, namespaces, namespaces.get(""));
}
/**
* Parse the given tag into a qualified name within the context of the given namespace bindings,
* overriding the default namespace binding with the given one. This is useful for parsing
* attribute names, where a lack of prefix should be interpreted as no namespace rather
* than the default namespace currently in effect.
*
* @param tag the tag to parse, in standard XML format
* @param namespaces the namespace bindings to use
* @param defaultNamespace the URI to use as the default namespace, in preference to any specified in the namespace bindings
* @return the qualified name of the given tag
*/
public static QName parse(String tag, NamespaceMap namespaces, String defaultNamespace) {
int colonIndex = tag.indexOf(':');
if (colonIndex == 0 || colonIndex == tag.length()-1) throw new IllegalArgumentException("illegal tag syntax '" + tag + "'");
String prefix = colonIndex == -1 ? "" : tag.substring(0, colonIndex);
String ns = prefix.length() > 0 ? namespaces.get(prefix) : defaultNamespace;
if (ns == null && prefix.length() > 0) throw new IllegalArgumentException("no namespace registered for tag prefix '" + prefix + "'");
return new QName(ns, tag.substring(colonIndex+1), prefix);
}
} |
package edu.umd.cs.findbugs.gui2;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.dom4j.DocumentException;
import com.apple.eawt.Application;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.DetectorFactory;
import edu.umd.cs.findbugs.DetectorFactoryCollection;
import edu.umd.cs.findbugs.FindBugs;
import edu.umd.cs.findbugs.Project;
import edu.umd.cs.findbugs.SortedBugCollection;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.config.UserPreferences;
import edu.umd.cs.findbugs.gui.FindBugsFrame;
/**
* This is where it all begins
* run with -f int to set font size
* run with -clear to clear recent projects menu, or any other issues with program not starting properly due to
* something being corrupted (or just faulty) in backend store for GUISaveState.
*
*/
public class Driver {
private static float fontSize = 12;
private static boolean docking = true;
private static SplashFrame splash;
public static void main(String[] args) throws Exception {
if (SystemProperties.getProperty("os.name").startsWith("Mac"))
{
System.setProperty("apple.laf.useScreenMenuBar","true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "FindBugs");
Debug.println("Mac OS detected");
}
splash = new SplashFrame();
splash.setVisible(true);
try {
Class.forName("net.infonode.docking.DockingWindow");
Class.forName("edu.umd.cs.findbugs.gui2.DockLayout");
} catch (Exception e) {
docking = false;
}
for(int i = 0; i < args.length; i++){
if((args[i].equals("-f")) && (i+1 < args.length)){
float num = 0;
try{
i++;
num = Integer.valueOf(args[i]);
}
catch(NumberFormatException exc){
num = fontSize;
}
fontSize = num;
}
if(args[i].startsWith("--font=")){
float num = 0;
try{
num = Integer.valueOf(args[i].substring("--font=".length()));
}
catch(NumberFormatException exc){
num = fontSize;
}
fontSize = num;
}
if(args[i].equals("-clear")){
GUISaveState.clear();
System.exit(0);
}
if (args[i].equals("-d") || args[i].equals("--nodock"))
docking = false;
}
try {
GUISaveState.loadInstance();
} catch (RuntimeException e) {
GUISaveState.clear();
e.printStackTrace();
}
// System.setProperty("findbugs.home",".."+File.separator+"findbugs");
DetectorFactoryCollection.instance();
// The bug with serializable idiom detection has been fixed on the findbugs end.
// DetectorFactory serializableIdiomDetector=DetectorFactoryCollection.instance().getFactory("SerializableIdiom");
// System.out.println(serializableIdiomDetector.getFullName());
// UserPreferences.getUserPreferences().enableDetector(serializableIdiomDetector,false);
FindBugsLayoutManagerFactory factory;
if (isDocking())
factory = new FindBugsLayoutManagerFactory("edu.umd.cs.findbugs.gui2.DockLayout");
else
factory = new FindBugsLayoutManagerFactory(SplitLayout.class.getName());
MainFrame.makeInstance(factory);
splash.setVisible(false);
splash.dispose();
}
public static void removeSplashScreen() {
splash.setVisible(false);
splash.dispose();
}
public static boolean isDocking()
{
return docking;
}
public static float getFontSize(){
return fontSize;
}
} |
package com.myCard;
import android.graphics.Bitmap;
import android.graphics.Rect;
public class Card {
int x=0; //2222222222222222222222222222
int y=0;
int width;
int height;
Bitmap bitmap;
String name; //Card555555555555555555555555555555
boolean rear=true;
boolean clicked=false;
public Card(int width,int height,Bitmap bitmap){
this.width=width;
this.height=height;
this.bitmap=bitmap;
}
public void setLocation(int x,int y){
this.x=x;
this.y=y;
}
public void setName(String name){
this.name=name;
}
public Rect getSRC(){
return new Rect(0,0,width,height);
}
public Rect getDST(){
return new Rect(x, y,x+width, y+height);
}
} |
package common;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Collection;
/**
* <p>Generates combinations of the elements in a given combination supplied to the constructor.</p>
* @author fiveham
* @author fiveham
*
* @param <T> the type of the elements in the combinations that this
* @param <T> the type of the elements in the combinations that this @param <T> the type of the
* @param <T> the type of the elements in the combinations that this elements in the combinations
* @param <T> the type of the elements in the combinations that this that this class produces
*/
public class ComboGen<T> implements Iterable<List<T>>{
/**
* <p>The minimum possible size ({@value}) of a combination.</p>
*/
public static final int MIN_COMBO_SIZE = 0;
/**
* <p>The internal list from which elements are chosen for the combinations this class
* produces.</p>
*/
private final List<T> source;
private final int minSize;
private final int maxSize;
/**
* <p>Constructs a ComboGen that produces combinations of elements from {@code source} that have
* a size at least {@value #MIN_COMBO_SIZE} and at most {@code source.size()}.</p>
* @param source a collection of elements combinations of which are produced by this ComboGen
*/
public ComboGen(Collection<? extends T> source, int minSize, int maxSize){
this.source = new ArrayList<>(source);
if(minSize < 0){
throw new IllegalArgumentException("minSize " + minSize + " < 0");
} else if(maxSize < 0){
throw new IllegalArgumentException("maxSize " + maxSize + " < 0");
}
this.minSize = minSize < MIN_COMBO_SIZE
? MIN_COMBO_SIZE
: minSize;
this.maxSize = maxSize > this.source.size()
? this.source.size()
: maxSize;
}
public ComboGen(Collection<? extends T> source, int minSize){
this(source, minSize, source.size());
}
public ComboGen(Collection<? extends T> source){
this(source, MIN_COMBO_SIZE, source.size());
}
/**
* <p>Returns an IsoIterator wrapping this ComboGen's normal iterator, allowing elements from
* the underlying element pool to be excluded from combos produced by subsequent calls to
* {@code next()}.</p>
* @return an IsoIterator wrapping this ComboGen's normal iterator
*/
@Override
public IsoIterator<T> iterator(){
return new IsoIterator<>(new ComboIterator());
}
/**
* <p>A combination-navigating iterator for this ComboGen's underlying collection.</p>
* <p>Produces collections of varying sizes from this ComboGen's underlying collection, starting
* from a size of minMag and increasing to maxMag.</p>
*/
private class ComboIterator implements Iterator<List<T>>{
private int size;
private BigInteger combo;
private ComboIterator(){
this.size = minSize;
if(sizeInRange()){
this.combo = firstCombo(size);
}
}
@Override
public boolean hasNext(){
return sizeInRange();
}
private boolean sizeInRange(){
return minSize <= size && size <= maxSize;
}
@Override
public List<T> next(){
if(!sizeInRange()){
throw new NoSuchElementException();
}
List<T> result = genComboList(combo);
updatePosition();
return result;
}
private List<T> genComboList(BigInteger combo){
List<T> result = new ArrayList<>(size);
for(int i = 0; i < source.size(); ++i){
if(combo.testBit(i)){
result.add(source.get(i));
}
}
return result;
}
private void updatePosition(){
if(finalCombo(size).equals(combo)){ //maximum lateral position at this height
size++; //move to next height
if(size <= maxSize){
combo = firstCombo(size);
}
} else{ //nonmaximum lateral position. proceed to next lateral position
combo = comboAfter(combo);
}
}
/**
* <p>Returns a BigInteger {@link #genComboList(BigInteger) pointing} to the first
* {@code size} elements from {@code list}.</p>
* @param size the size of the combo whose backing bitstring is returned
* @return a BigInteger {@link #genComboList(BigInteger) pointing} to the first {@code size}
* elements from {@code list}
*/
private BigInteger finalCombo(int size){
return leastCombo(size);
}
private BigInteger leastCombo(int size){
if(leastComboCache.containsKey(size)){
return leastComboCache.get(size);
}
BigInteger result = BigInteger.ZERO;
for(int i=0; i < size; ++i){
result = result.setBit(i);
}
leastComboCache.put(size, result);
return result;
}
private final Map<Integer, BigInteger> leastComboCache = new HashMap<>();
/**
* <p>Returns a BigInteger {@link #genComboList(BigInteger) pointing} to the last
* {@code size} elements from {@code list}.</p>
* @param size the size of the combo whose backing bitstring is returned
* @return a BigInteger {@link #genComboList(BigInteger) pointing} to the last {@code size}
* elements from {@code list}
*/
private BigInteger firstCombo(int size){
return greatestCombo(size);
}
/**
* </p>Returns a BigInteger having the greatest numerical value of any BigInteger
* {@link #genComboList(BigInteger) pointing} to a combination of the current size. The
* value returned is equal to {@code (2^(size+1) - 1) * 2^(source.size() - size)}, which
* equals {@code 2^(source.size()+1) - 2^(source.size() - size)}.</p>
* @param size the number of set bits in the BigIteger returned
* @return a BigInteger having the greatest numerical value of any BigInteger
* {@link #genComboList(BigInteger) pointing} to a combination of the current size
*/
private BigInteger greatestCombo(int size){
if(greatestComboCache.containsKey(size)){
return greatestComboCache.get(size);
}
BigInteger result = BigInteger.ZERO;
for(int i=source.size() - size; i < source.size(); ++i){
result = result.setBit(i);
}
greatestComboCache.put(size, result);
return result;
}
private final Map<Integer, BigInteger> greatestComboCache = new HashMap<>();
/**
* <p>This implementation, which pulls ones down to lower indices, is tied to the fact that the
* first combo is the greatest value and the final combo is the least value. If that
* relationship between combo precedence and the numerical size of the combo ever changes, this
* method needs to be adapted to the new relationship.</p>
* <p>The combo after a given combo is determined by moving the lowest-indexed movable set bit
* to an index lower by 1. A set bit is movable if the bit at index 1 lower than the movable bit
* is 0.</p>
* @param combo a BigInteger whose bits encode a combination of the elements pertaining to this
* ComboGen
* @return a BigInteger encoding the combination after {@code combo}
*/
private BigInteger comboAfter(BigInteger combo){
int swapIndex = lowerableOne(combo);
int onesBelow = bitsSetToTheRight(swapIndex, combo);
//swap the 1 with the 0 to the right of it
BigInteger result = combo.clearBit(swapIndex);
swapIndex
result = result.setBit(swapIndex);
swapIndex
//move all the 1s from the right of the swapped 0 to a position immediately to the right of
//the swapped 0's initial position
for(int onesSet = 0; onesSet < onesBelow; ++onesSet){
result = result.setBit(swapIndex);
swapIndex
}
//fill the space between the rightmost moved 1 and the ones' place of the BigInteger with 0s
while(swapIndex >= 0){
result = result.clearBit(swapIndex);
swapIndex
}
return result;
}
/**
* <p>Returns the lowest index in {@code combo} of a {@link BigInteger#testBit(int) 1} such
* that the bit at the next lower index is 0. If no such bit exists in {@code combo}, then
* {@code source.size()} is returned.</p>
* @param combo the combo whose lowest-index 1 with a 0 immediately below it (in terms of
* index) is returned
* @return the lowest index in {@code combo} of a {@link BigInteger#testBit(int) 1} such
* that the bit at the next lower index is 0, or {@code source.size()} if no such bit exists
* in {@code combo}
*/
private int lowerableOne(BigInteger combo){
int i = 0;
for(; i < source.size() - 1; ++i){
if(!combo.testBit(i) && combo.testBit(i + 1)){
break;
}
}
return i + 1;
}
/**
* <p>Returns the number of 1s in {@code combo} at indices less than {@code swapIndex}.</p>
* @param swapIndex the index in {@code combo} below which 1s are counted
* @param combo the BigInteger from which 1s are counted
* @return the number of 1s in {@code combo} at indices less than
*/
private int bitsSetToTheRight(int swapIndex, BigInteger combo){
int result = 0;
for(int i=swapIndex - 1; i >= 0; --i){
if(combo.testBit(i)){
++result;
}
}
return result;
}
}
} |
package utilities;
import java.awt.BorderLayout;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFrame;
import org.apache.commons.io.FilenameUtils;
public class CsvOutput {
public static String folderCsvData;
static String SEPARATOR = ";";
static String MISSING_VALUE = "";
// assuming all files in folder are from the same entity. otherwise more
// than one csv file would be needed
public static void main(String args[]) throws IOException {
try {
folderCsvData = utilities.BrowserDialogs.chooseFolder();
if (folderCsvData != null) {
JFrame f = new JFrame();
JButton but = new JButton("... Program is running ... ");
f.add(but, BorderLayout.PAGE_END);
f.pack();
f.setVisible(true);
ArrayList<File> files = utilities.ListsFiles.getPaths(new File(folderCsvData), new ArrayList<File>());
String outputpath = folderCsvData + "//" + "outputCsv.csv"; //should be the content folder, now it's just the same folder
PrintWriter outputCsv = new PrintWriter(new FileWriter(outputpath));
// the first line is always known, Heading Line
String objectType = "Object Type";
String title = "Title";
String alternativeTitle = "Alternative Title";
String preservationType = "Preservation Type";
String usageType = "Usage Type";
String revisionNumber = "Revision Number";
String fileMimeType = "File Mime Type";
String fileName = "File Name";
String fileLabel = "File Label";
outputCsv.println(objectType + SEPARATOR + title + SEPARATOR + alternativeTitle + SEPARATOR + preservationType + SEPARATOR + usageType + SEPARATOR + revisionNumber + SEPARATOR + fileMimeType + SEPARATOR + fileName + SEPARATOR + fileLabel);
for (int i = 0; i < files.size(); i++) {
//the outputfile should be omitted
// String extension = FilenameUtils.getExtension(files.get(i).toString()).toLowerCase();
if (!files.get(i).toString().contains ("outputCsv")) {
objectType = "FILE"; // other possibilities: SIP, IE,
// REPRESENTATION
title = getTitle(files.get(i));
alternativeTitle = getalternativeTitle(files.get(i));
preservationType = "PRESERVATION MASTER";
usageType = "VIEW";
revisionNumber = "1";
fileMimeType = getMimeType(files.get(i));
fileName = getfileName(files.get(i));
fileLabel = getFileLabel(files.get(i));
outputCsv.println(objectType + SEPARATOR + title + SEPARATOR + alternativeTitle + SEPARATOR + preservationType + SEPARATOR + usageType + SEPARATOR + revisionNumber + SEPARATOR + fileMimeType + SEPARATOR + fileName + SEPARATOR + fileLabel);
}
}
outputCsv.close();
f.dispose();
}
} catch (Exception e) {
}
}
private static String getFileLabel(File file) {
// this is the path. Is it the path that is needed?
try {
String fileLabel = file.getParent().toString();
return fileLabel;
} catch (Exception e) {
}
return MISSING_VALUE;
}
private static String getfileName(File file) {
try {
String filename = file.getName();
return filename;
} catch (Exception e) {
}
return MISSING_VALUE;
}
private static String getMimeType(File file) {
try {
String filemime = Files.probeContentType(file.toPath());
return filemime;
} catch (Exception e) {
}
return MISSING_VALUE;
}
private static String getTitle(File file) {
// I am assuming that one folder is one IE and the name of the folder is
// the name of the IE
try {
String titleofIE = file.getParent().toString();
System.out.println(titleofIE);
String[] temp = titleofIE.split(Pattern.quote("\\"));
int len = temp.length;
titleofIE = temp[len - 1];
return titleofIE;
} catch (Exception e) {
}
return MISSING_VALUE;
}
private static String getalternativeTitle(File file) {
try {
// usually there would not be an alternative title
} catch (Exception e) {
}
return MISSING_VALUE;
}
} |
package jolie.lang.parse;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import jolie.lang.Constants.OperandType;
import jolie.lang.parse.ast.AndConditionNode;
import jolie.lang.parse.ast.AssignStatement;
import jolie.lang.parse.ast.CompareConditionNode;
import jolie.lang.parse.ast.CompensateStatement;
import jolie.lang.parse.ast.ConstantIntegerExpression;
import jolie.lang.parse.ast.ConstantRealExpression;
import jolie.lang.parse.ast.ConstantStringExpression;
import jolie.lang.parse.ast.CorrelationSetInfo;
import jolie.lang.parse.ast.CurrentHandlerStatement;
import jolie.lang.parse.ast.DeepCopyStatement;
import jolie.lang.parse.ast.EmbeddedServiceNode;
import jolie.lang.parse.ast.ExecutionInfo;
import jolie.lang.parse.ast.ExitStatement;
import jolie.lang.parse.ast.ExpressionConditionNode;
import jolie.lang.parse.ast.ForEachStatement;
import jolie.lang.parse.ast.ForStatement;
import jolie.lang.parse.ast.IfStatement;
import jolie.lang.parse.ast.InstallFixedVariableExpressionNode;
import jolie.lang.parse.ast.InstallStatement;
import jolie.lang.parse.ast.IsTypeExpressionNode;
import jolie.lang.parse.ast.LinkInStatement;
import jolie.lang.parse.ast.LinkOutStatement;
import jolie.lang.parse.ast.NDChoiceStatement;
import jolie.lang.parse.ast.NotConditionNode;
import jolie.lang.parse.ast.NotificationOperationStatement;
import jolie.lang.parse.ast.NullProcessStatement;
import jolie.lang.parse.ast.OLSyntaxNode;
import jolie.lang.parse.ast.OneWayOperationDeclaration;
import jolie.lang.parse.ast.OneWayOperationStatement;
import jolie.lang.parse.ast.OperationDeclaration;
import jolie.lang.parse.ast.OrConditionNode;
import jolie.lang.parse.ast.OutputPortInfo;
import jolie.lang.parse.ast.ParallelStatement;
import jolie.lang.parse.ast.PointerStatement;
import jolie.lang.parse.ast.PostDecrementStatement;
import jolie.lang.parse.ast.PostIncrementStatement;
import jolie.lang.parse.ast.PreDecrementStatement;
import jolie.lang.parse.ast.PreIncrementStatement;
import jolie.lang.parse.ast.ProductExpressionNode;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.ast.RequestResponseOperationDeclaration;
import jolie.lang.parse.ast.RequestResponseOperationStatement;
import jolie.lang.parse.ast.RunStatement;
import jolie.lang.parse.ast.Scope;
import jolie.lang.parse.ast.SequenceStatement;
import jolie.lang.parse.ast.InputPortInfo;
import jolie.lang.parse.ast.SolicitResponseOperationStatement;
import jolie.lang.parse.ast.DefinitionCallStatement;
import jolie.lang.parse.ast.DefinitionNode;
import jolie.lang.parse.ast.InterfaceDefinition;
import jolie.lang.parse.ast.SpawnStatement;
import jolie.lang.parse.ast.SumExpressionNode;
import jolie.lang.parse.ast.SynchronizedStatement;
import jolie.lang.parse.ast.ThrowStatement;
import jolie.lang.parse.ast.TypeCastExpressionNode;
import jolie.lang.parse.ast.UndefStatement;
import jolie.lang.parse.ast.ValueVectorSizeExpressionNode;
import jolie.lang.parse.ast.VariableExpressionNode;
import jolie.lang.parse.ast.VariablePathNode;
import jolie.lang.parse.ast.WhileStatement;
import jolie.lang.parse.ast.types.TypeDefinition;
import jolie.lang.parse.ast.types.TypeDefinitionLink;
import jolie.lang.parse.ast.types.TypeInlineDefinition;
import jolie.util.Pair;
/**
* Checks the well-formedness and validity of a JOLIE program.
* @see Program
* @author Fabrizio Montesi
*/
public class SemanticVerifier implements OLVisitor
{
private final Program program;
private boolean valid = true;
private final Map< String, InputPortInfo > inputPorts = new HashMap< String, InputPortInfo >();
private final Map< String, OutputPortInfo > outputPorts = new HashMap< String, OutputPortInfo >();
private final Set< String > subroutineNames = new HashSet< String > ();
private final Map< String, OneWayOperationDeclaration > oneWayOperations =
new HashMap< String, OneWayOperationDeclaration >();
private final Map< String, RequestResponseOperationDeclaration > requestResponseOperations =
new HashMap< String, RequestResponseOperationDeclaration >();
private boolean insideInputPort = false;
private boolean mainDefined = false;
private final Logger logger = Logger.getLogger( "JOLIE" );
private final Map< String, TypeDefinition > definedTypes = OLParser.createTypeDeclarationMap();
//private TypeDefinition rootType; // the type representing the whole session state
private final Map< String, Boolean > isConstantMap = new HashMap< String, Boolean >();
public SemanticVerifier( Program program )
{
this.program = program;
/*rootType = new TypeInlineDefinition(
new ParsingContext(),
"#RootType",
NativeType.VOID,
jolie.lang.Constants.RANGE_ONE_TO_ONE
);*/
}
private void encounteredAssignment( String varName )
{
if ( isConstantMap.containsKey( varName ) ) {
isConstantMap.put( varName, false );
} else {
isConstantMap.put( varName, true );
}
}
private void encounteredAssignment( VariablePathNode path )
{
encounteredAssignment( ((ConstantStringExpression)path.path().get( 0 ).key()).value() );
}
public Map< String, Boolean > isConstantMap()
{
return isConstantMap;
}
private void warning( OLSyntaxNode node, String message )
{
if ( node == null ) {
logger.warning( message );
} else {
logger.warning( node.context().sourceName() + ":" + node.context().line() + ": " + message );
}
}
private void error( OLSyntaxNode node, String message )
{
valid = false;
if ( node != null ) {
ParsingContext context = node.context();
logger.severe( context.sourceName() + ":" + context.line() + ": " + message );
} else {
logger.severe( message );
}
}
public boolean validate()
{
program.accept( this );
if ( mainDefined == false ) {
error( null, "Main procedure not defined" );
}
if ( !valid ) {
logger.severe( "Aborting: input file semantically invalid." );
return false;
}
return valid;
}
private boolean isTopLevelType = true;
public void visit( TypeInlineDefinition n )
{
checkCardinality( n );
boolean backupRootType = isTopLevelType;
if ( isTopLevelType ) {
// Check if the type has already been defined with a different structure
TypeDefinition type = definedTypes.get( n.id() );
if ( type != null && type.equals( n ) == false ) {
error( n, "type " + n.id() + " has already been defined with a different structure" );
}
}
isTopLevelType = false;
if ( n.hasSubTypes() ) {
for( Entry< String, TypeDefinition > entry : n.subTypes() ) {
entry.getValue().accept( this );
}
}
isTopLevelType = backupRootType;
if ( isTopLevelType ) {
definedTypes.put( n.id(), n );
}
}
public void visit( TypeDefinitionLink n )
{
checkCardinality( n );
if ( n.isValid() == false ) {
error( n, "type " + n.id() + " points to an undefined type" );
}
if ( isTopLevelType ) {
// Check if the type has already been defined with a different structure
TypeDefinition type = definedTypes.get( n.id() );
if ( type != null && type.equals( n ) == false ) {
error( n, "type " + n.id() + " has already been defined with a different structure" );
}
definedTypes.put( n.id(), n );
}
}
private void checkCardinality( TypeDefinition type )
{
if ( type.cardinality().min() < 0 ) {
error( type, "type " + type.id() + " specifies an invalid minimum range value (must be positive)" );
}
if ( type.cardinality().max() < 0 ) {
error( type, "type " + type.id() + " specifies an invalid maximum range value (must be positive)" );
}
}
public void visit( SpawnStatement n )
{
n.body().accept( this );
}
public void visit( Program n )
{
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
}
}
public void visit( VariablePathNode n )
{}
public void visit( InputPortInfo n )
{
if ( inputPorts.get( n.id() ) != null ) {
error( n, "input port " + n.id() + " has been already defined" );
}
inputPorts.put( n.id(), n );
insideInputPort = true;
Set< String > opSet = new HashSet< String >();
for( OperationDeclaration op : n.operations() ) {
if ( opSet.contains( op.id() ) ) {
error( n, "input port " + n.id() + " declares operation " + op.id() + " multiple times" );
} else {
opSet.add( op.id() );
op.accept( this );
}
}
OutputPortInfo outputPort;
for( String portName : n.aggregationList() ) {
outputPort = outputPorts.get( portName );
if ( outputPort == null ) {
error( n, "input port " + n.id() + " aggregates an undefined output port (" + portName + ")" );
} else {
for( OperationDeclaration op : outputPort.operations() ) {
if ( opSet.contains( op.id() ) ) {
error( n, "input port " + n.id() + " declares duplicate operation " + op.id() + " from aggregated output port " + outputPort.id() );
} else {
opSet.add( op.id() );
}
}
}
}
insideInputPort = false;
}
public void visit( OutputPortInfo n )
{
if ( outputPorts.get( n.id() ) != null )
error( n, "output port " + n.id() + " has been already defined" );
outputPorts.put( n.id(), n );
encounteredAssignment( n.id() );
for( OperationDeclaration op : n.operations() ) {
op.accept( this );
}
}
public void visit( OneWayOperationDeclaration n )
{
if ( definedTypes.get( n.requestType().id() ) == null ) {
error( n, "unknown type: " + n.requestType().id() );
}
if ( insideInputPort ) { // Input operation
if ( oneWayOperations.containsKey( n.id() ) ) {
OneWayOperationDeclaration other = oneWayOperations.get( n.id() );
if ( n.requestType().equals( other.requestType() ) == false ) {
error( n, "input operations sharing the same name cannot declare different types (One-Way operation " + n.id() + ")" );
}
} else {
oneWayOperations.put( n.id(), n );
}
}
}
public void visit( RequestResponseOperationDeclaration n )
{
if ( definedTypes.get( n.requestType().id() ) == null ) {
error( n, "unknown type: " + n.requestType().id() );
}
if ( definedTypes.get( n.responseType().id() ) == null ) {
error( n, "unknown type: " + n.requestType().id() );
}
for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) {
if ( definedTypes.containsKey( fault.getValue().id() ) == false ) {
error( n, "unknown type for fault " + fault.getKey() );
}
}
if ( insideInputPort ) { // Input operation
if ( requestResponseOperations.containsKey( n.id() ) ) {
RequestResponseOperationDeclaration other = requestResponseOperations.get( n.id() );
checkEqualness( n, other );
} else {
requestResponseOperations.put( n.id(), n );
}
}
}
private void checkEqualness( RequestResponseOperationDeclaration n, RequestResponseOperationDeclaration other )
{
if ( n.requestType().equals( other.requestType() ) == false ) {
error( n, "input operations sharing the same name cannot declare different request types (Request-Response operation " + n.id() + ")" );
}
if ( n.responseType().equals( other.responseType() ) == false ) {
error( n, "input operations sharing the same name cannot declare different response types (Request-Response operation " + n.id() + ")" );
}
if ( n.faults().size() != other.faults().size() ) {
error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() );
}
for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) {
if ( fault.getValue() != null ) {
if ( !other.faults().containsKey( fault.getKey() ) || !other.faults().get( fault.getKey() ).equals( fault.getValue() ) ) {
error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() );
}
}
}
}
public void visit( DefinitionNode n )
{
if ( subroutineNames.contains( n.id() ) ) {
error( n, "Procedure " + n.id() + " uses an already defined identifier" );
} else {
subroutineNames.add( n.id() );
}
if ( "main".equals( n.id() ) ) {
mainDefined = true;
}
n.body().accept( this );
}
public void visit( ParallelStatement stm )
{
for( OLSyntaxNode node : stm.children() ) {
node.accept( this );
}
}
public void visit( SequenceStatement stm )
{
for( OLSyntaxNode node : stm.children() ) {
node.accept( this );
}
}
public void visit( NDChoiceStatement stm )
{
for( Pair< OLSyntaxNode, OLSyntaxNode > pair : stm.children() ) {
pair.key().accept( this );
pair.value().accept( this );
}
}
public void visit( NotificationOperationStatement n )
{
OutputPortInfo p = outputPorts.get( n.outputPortId() );
if ( p == null ) {
error( n, n.outputPortId() + " is not a valid output port" );
} else {
OperationDeclaration decl = p.operationsMap().get( n.id() );
if ( decl == null )
error( n, "Operation " + n.id() + " has not been declared in output port type " + p.id() );
else if ( !( decl instanceof OneWayOperationDeclaration ) )
error( n, "Operation " + n.id() + " is not a valid one-way operation in output port " + p.id() );
}
}
public void visit( SolicitResponseOperationStatement n )
{
if ( n.inputVarPath() != null ) {
encounteredAssignment( n.inputVarPath() );
}
OutputPortInfo p = outputPorts.get( n.outputPortId() );
if ( p == null )
error( n, n.outputPortId() + " is not a valid output port" );
else {
OperationDeclaration decl = p.operationsMap().get( n.id() );
if ( decl == null )
error( n, "Operation " + n.id() + " has not been declared in output port " + p.id() );
else if ( !( decl instanceof RequestResponseOperationDeclaration ) )
error( n, "Operation " + n.id() + " is not a valid request-response operation in output port " + p.id() );
}
}
public void visit( ThrowStatement n )
{
verify( n.expression() );
}
public void visit( CompensateStatement n ) {}
public void visit( InstallStatement n )
{
for( Pair< String, OLSyntaxNode > pair : n.handlersFunction().pairs() ) {
pair.value().accept( this );
}
}
public void visit( Scope n )
{
n.body().accept( this );
}
public void visit( OneWayOperationStatement n )
{
verify( n.inputVarPath() );
}
public void visit( RequestResponseOperationStatement n )
{
verify( n.inputVarPath() );
verify( n.process() );
}
public void visit( LinkInStatement n ) {}
public void visit( LinkOutStatement n ) {}
public void visit( SynchronizedStatement n )
{
n.body().accept( this );
}
public void visit( AssignStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
n.expression().accept( this );
}
private void verify( OLSyntaxNode n )
{
if ( n != null ) {
n.accept( this );
}
}
public void visit( PointerStatement n )
{
encounteredAssignment( n.leftPath() );
encounteredAssignment( n.rightPath() );
n.leftPath().accept( this );
n.rightPath().accept( this );
}
public void visit( DeepCopyStatement n )
{
encounteredAssignment( n.leftPath() );
n.leftPath().accept( this );
n.rightPath().accept( this );
}
public void visit( IfStatement n )
{
for( Pair< OLSyntaxNode, OLSyntaxNode > choice : n.children() ) {
choice.key().accept( this );
choice.value().accept( this );
}
verify( n.elseProcess() );
}
public void visit( DefinitionCallStatement n ) {}
public void visit( WhileStatement n )
{
n.condition().accept( this );
n.body().accept( this );
}
public void visit( OrConditionNode n )
{
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
}
}
public void visit( AndConditionNode n )
{
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
}
}
public void visit( NotConditionNode n )
{
n.condition().accept( this );
}
public void visit( CompareConditionNode n )
{
n.leftExpression().accept( this );
n.rightExpression().accept( this );
}
public void visit( ExpressionConditionNode n )
{
n.expression().accept( this );
}
public void visit( ConstantIntegerExpression n ) {}
public void visit( ConstantRealExpression n ) {}
public void visit( ConstantStringExpression n ) {}
public void visit( ProductExpressionNode n )
{
for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) {
pair.value().accept( this );
}
}
public void visit( SumExpressionNode n )
{
for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) {
pair.value().accept( this );
}
}
public void visit( VariableExpressionNode n )
{
n.variablePath().accept( this );
}
public void visit( InstallFixedVariableExpressionNode n )
{
n.variablePath().accept( this );
}
public void visit( NullProcessStatement n ) {}
public void visit( ExitStatement n ) {}
public void visit( ExecutionInfo n ) {}
public void visit( CorrelationSetInfo n ) {}
public void visit( RunStatement n )
{
warning( n, "Run statement is not a stable feature yet." );
}
public void visit( ValueVectorSizeExpressionNode n )
{
n.variablePath().accept( this );
}
public void visit( PreIncrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( PostIncrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( PreDecrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( PostDecrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( UndefStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( ForStatement n )
{
n.init().accept( this );
n.condition().accept( this );
n.post().accept( this );
n.body().accept( this );
}
public void visit( ForEachStatement n )
{
n.keyPath().accept( this );
n.targetPath().accept( this );
n.body().accept( this );
}
public void visit( IsTypeExpressionNode n )
{
n.variablePath().accept( this );
}
public void visit( TypeCastExpressionNode n )
{
n.expression().accept( this );
}
public void visit( EmbeddedServiceNode n )
{}
/**
* @todo Must check if it's inside an install function
*/
public void visit( CurrentHandlerStatement n )
{}
public void visit( InterfaceDefinition n )
{}
} |
package com.afollestad.cardsui;
import android.content.Context;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import com.afollestad.silk.adapters.SilkAdapter;
import java.util.HashMap;
import java.util.Map;
/**
* A {@link SilkAdapter} that displays {@link Card} and {@link CardHeader} objects in a {@link CardListView}.
*
* @author Aidan Follestad (afollestad)
*/
public class CardAdapter<ItemType extends CardBase<ItemType>> extends SilkAdapter<ItemType> {
private final static int TYPE_REGULAR = 0;
private final static int TYPE_NO_CONTENT = 1;
private final static int TYPE_HEADER = 2;
private int mAccentColor;
private int mPopupMenu = -1;
private Card.CardMenuListener<ItemType> mPopupListener;
private boolean mCardsClickable = true;
private int mLayout = R.layout.list_item_card;
private int mLayoutNoContent = R.layout.list_item_card_nocontent;
private final Map<Integer, Integer> mViewTypes;
/**
* Initializes a new CardAdapter instance.
*
* @param context The context used to inflate layouts and retrieve resources.
*/
public CardAdapter(Context context) {
super(context);
mAccentColor = context.getResources().getColor(android.R.color.black);
mViewTypes = new HashMap<Integer, Integer>();
}
/**
* Initializes a new CardAdapter instance.
*
* @param context The context used to inflate layouts and retrieve resources.
* @param cardLayoutRes Sets a custom layout to be used for all cards (not including headers) in the adapter.
* This <b>does not</b> override layouts set to individual cards.
*/
public CardAdapter(Context context, int cardLayoutRes) {
this(context);
mLayout = cardLayoutRes;
}
/**
* Initializes a new CardAdapter instance.
*
* @param context The context used to inflate layouts and retrieve resources.
* @param cardLayoutRes Sets a custom layout to be used for all cards (not including headers) in the adapter.
* This <b>does not</b> override layouts set to individual cards.
* @param cardLayoutNoContentRes Sets a custom layout to be used for all cards (not including headers) in the
* adapter with null content. This <b>does not</b> override layouts set to individual cards.
*/
public CardAdapter(Context context, int cardLayoutRes, int cardLayoutNoContentRes) {
this(context, cardLayoutRes);
mLayoutNoContent = cardLayoutNoContentRes;
}
@Override
public final boolean isEnabled(int position) {
ItemType item = getItem(position);
if (!mCardsClickable && !item.isHeader()) return false;
if (item.isHeader())
return item.getActionCallback() != null;
return item.isClickable();
}
/**
* Sets the accent color used on card titles and header action buttons.
* You <b>should</b> call this method before adding any cards to the adapter to avoid issues.
*
* @param color The resolved color to use as an accent.
*/
public final CardAdapter<ItemType> setAccentColor(int color) {
mAccentColor = color;
return this;
}
/**
* Sets the accent color resource used on card titles and header action buttons.
* You <b>should</b> call this method before adding any cards to the adapter to avoid issues.
*
* @param colorRes The color resource ID to use as an accent.
*/
public final CardAdapter<ItemType> setAccentColorRes(int colorRes) {
setAccentColor(getContext().getResources().getColor(colorRes));
return this;
}
/**
* Sets a popup menu used for every card in the adapter, this will not override individual card popup menus.
* You <b>should</b> call this method before adding any cards to the adapter to avoid issues.
*
* @param menuRes The menu resource ID to use for the card's popup menu.
* @param listener A listener invoked when an option in the popup menu is tapped by the user.
*/
public final CardAdapter<ItemType> setPopupMenu(int menuRes, Card.CardMenuListener<ItemType> listener) {
mPopupMenu = menuRes;
mPopupListener = listener;
return this;
}
/**
* Sets whether or not cards in the adapter are clickable, setting it to false will turn card's list selectors off
* and the list's OnItemClickListener will not be called. This <b>will</b> override individual isClickable values
* set to {@link Card}s.
*/
public final CardAdapter<ItemType> setCardsClickable(boolean clickable) {
mCardsClickable = clickable;
return this;
}
@Override
public final int getLayout(int index, int type) {
CardBase card = getItem(index);
if (type == TYPE_HEADER)
return R.layout.list_item_header;
else if (type == TYPE_NO_CONTENT)
return mLayoutNoContent;
int layout = card.getLayout();
if (layout <= 0) {
// If no layout was specified for the individual card, use the adapter's set layout
layout = mLayout;
}
return layout;
}
private void setupHeader(ItemType header, View view) {
TextView title = (TextView) view.findViewById(android.R.id.title);
if (title == null)
throw new RuntimeException("Your header layout must contain a TextView with the ID @android:id/title.");
TextView subtitle = (TextView) view.findViewById(android.R.id.content);
if (subtitle == null)
throw new RuntimeException("Your header layout must contain a TextView with the ID @android:id/content.");
title.setText(header.getTitle());
if (header.getContent() != null && !header.getContent().trim().isEmpty()) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(header.getContent());
} else subtitle.setVisibility(View.GONE);
TextView button = (TextView) view.findViewById(android.R.id.button1);
if (button == null)
throw new RuntimeException("The header layout must contain a TextView with the ID @android:id/button1.");
if (header.getActionCallback() != null) {
button.setVisibility(View.VISIBLE);
button.setBackgroundColor(mAccentColor);
String titleTxt = header.getActionTitle();
if (header.getActionTitle() == null || header.getActionTitle().trim().isEmpty())
titleTxt = getContext().getString(R.string.see_more);
button.setText(titleTxt);
} else button.setVisibility(View.GONE);
}
private void setupMenu(final ItemType card, final View view) {
if (view == null) return;
if (card.getPopupMenu() < 0) {
// Menu for this card is disabled
view.setVisibility(View.INVISIBLE);
view.setOnClickListener(null);
return;
}
int menuRes = mPopupMenu;
if (card.getPopupMenu() != 0) menuRes = card.getPopupMenu();
if (menuRes < 0) {
// No menu for the adapter or the card
view.setVisibility(View.INVISIBLE);
view.setOnClickListener(null);
return;
}
view.setVisibility(View.VISIBLE);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int menuRes = mPopupMenu;
if (card.getPopupMenu() != 0) menuRes = card.getPopupMenu();
// Force the holo light theme on every card's popup menu
Context themedContext = getContext();
themedContext.setTheme(android.R.style.Theme_Holo_Light);
PopupMenu popup = new PopupMenu(themedContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(menuRes, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (card.getPopupMenu() > 0 && card.getPopupListener() != null) {
// This individual card has it unique menu
card.getPopupListener().onMenuItemClick(card, item);
} else if (mPopupListener != null) {
// The card does not have a unique menu, use the adapter's default
mPopupListener.onMenuItemClick(card, item);
}
return false;
}
});
popup.show();
}
});
}
private void invalidatePadding(int index, View view) {
int top = index == 0 ? R.dimen.card_outer_padding_firstlast : R.dimen.card_outer_padding_top;
int bottom = index == (getCount() - 1) ? R.dimen.card_outer_padding_firstlast : R.dimen.card_outer_padding_top;
view.setPadding(view.getPaddingLeft(),
getContext().getResources().getDimensionPixelSize(top),
view.getPaddingRight(),
getContext().getResources().getDimensionPixelSize(bottom));
}
@Override
public View onViewCreated(int index, View recycled, ItemType item) {
if (item.isHeader()) {
setupHeader(item, recycled);
return recycled;
}
TextView title = (TextView) recycled.findViewById(android.R.id.title);
if (title != null) onProcessTitle(title, item, mAccentColor);
TextView content = (TextView) recycled.findViewById(android.R.id.content);
if (content != null) onProcessContent(content, item);
ImageView icon = (ImageView) recycled.findViewById(android.R.id.icon);
if (icon != null) {
if (onProcessThumbnail(icon, item)) {
icon.setVisibility(View.VISIBLE);
} else {
icon.setVisibility(View.GONE);
}
}
invalidatePadding(index, recycled);
setupMenu(item, recycled.findViewById(android.R.id.button1));
return recycled;
}
@Override
public Object getItemId(ItemType item) {
return item.getSilkId();
}
@Override
public final int getViewTypeCount() {
// There's 3 layout types by default: cards, cards with no content, and card headers.
return mViewTypes.size() + 3;
}
/**
* Registers a custom layout in the adapter, that isn't one of the default layouts, and that was passed in the adapter's constructor.
* <p/>
* This must be used if you override getLayout() and specify custom layouts for certain list items.
*/
public final CardAdapter<ItemType> registerLayout(int layoutRes) {
mViewTypes.put(layoutRes, mViewTypes.size() + 3);
return this;
}
@Override
public final int getItemViewType(int position) {
CardBase item = getItem(position);
if (item.getLayout() > 0) {
if (mViewTypes.containsKey(item.getLayout()))
return mViewTypes.get(item.getLayout());
// Return the default if the layout is not registered
return TYPE_REGULAR;
} else {
if (item.isHeader())
return TYPE_HEADER;
else if ((item.getContent() == null || item.getContent().trim().isEmpty()))
return TYPE_NO_CONTENT;
else return TYPE_REGULAR;
}
}
protected boolean onProcessTitle(TextView title, ItemType card, int accentColor) {
if (title == null) return false;
title.setText(card.getTitle());
title.setTextColor(accentColor);
return true;
}
protected boolean onProcessThumbnail(ImageView icon, ItemType card) {
if (icon == null) return false;
if (card.getThumbnail() == null) return false;
icon.setImageDrawable(card.getThumbnail());
return true;
}
protected boolean onProcessContent(TextView content, ItemType card) {
content.setText(card.getContent());
return false;
}
} |
package Misc.heap;
import java.util.ArrayList;
public abstract class ArrayForHeap<E extends Comparable<E>> {
private ArrayList<E> heap = new ArrayList<E>();
private Integer heapsize = 0;
protected ArrayForHeap(E[] initialElements){
mapToArrayList(initialElements);
heapsize = heap.size();
}
protected Integer heapsize(){
return heapsize;
}
private void mapToArrayList(E[] initialElements){
for(E elem : initialElements){
heap.add(elem);
}
}
protected E get(int index){
if(index-1 >= heapsize){
throw new IndexOutOfBoundsException();
}
return heap.get(index-1);
}
protected E set(int index, E element){
return heap.set(index-1, element);
}
protected void remove(int index){
heap.remove(index-1);
heapsize
}
protected void add(E newElement){
heap.add(newElement);
heapsize++;
}
protected Boolean contains(E toCompare){
for(E element : heap){
if(element.equals(toCompare)){
return true;
}
}
return false;
}
} |
package org.kuali.kra.meeting;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.concurrent.Synchroniser;
import org.junit.Assert;
import org.junit.Test;
import org.kuali.coeus.common.committee.impl.bo.CommitteeMembershipRole;
import org.kuali.coeus.common.committee.impl.bo.MembershipRole;
import org.kuali.coeus.common.committee.impl.meeting.CommScheduleActItemBase;
import org.kuali.coeus.common.committee.impl.meeting.MemberAbsentBean;
import org.kuali.coeus.common.committee.impl.meeting.MemberPresentBean;
import org.kuali.coeus.common.committee.impl.meeting.MinuteEntryType;
import org.kuali.coeus.common.committee.impl.web.struts.form.schedule.Time12HrFmt;
import org.kuali.coeus.common.committee.impl.web.struts.form.schedule.Time12HrFmt.MERIDIEM;
import org.kuali.kra.committee.bo.Committee;
import org.kuali.kra.committee.bo.CommitteeMembership;
import org.kuali.kra.committee.bo.CommitteeSchedule;
import org.kuali.kra.irb.Protocol;
import org.kuali.kra.irb.actions.submit.ProtocolSubmission;
import org.kuali.kra.irb.actions.submit.ProtocolSubmissionLite;
import org.kuali.kra.irb.correspondence.ProtocolCorrespondence;
import org.kuali.kra.irb.personnel.ProtocolPerson;
import org.kuali.kra.test.infrastructure.KcIntegrationTestBase;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.SequenceAccessorService;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MeetingServiceTest extends KcIntegrationTestBase {
private Mockery context = new JUnit4Mockery() {{ setThreadingPolicy(new Synchroniser()); }};
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
private static final String PERSON_ID = "jtester";
private static final String PERSON_ID_1 = "1";
private static final String PERSON_ID_2 = "2";
private static final String PERSON_ID_3 = "3";
private static final String PERSON_NAME_1 = "test 1";
private static final String PERSON_NAME_2 = "test 2";
private static final String PERSON_NAME_3 = "test 3";
private static final Integer ROLODEX_ID = 1746;
private static final String MEMBERSHIP_TYPE_CD = "1";
private static final Date TERM_START_DATE = Date.valueOf("2009-01-01");
private static final Date TERM_END_DATE = Date.valueOf("2009-01-31");
private static final Date SCHEDULE_DATE = Date.valueOf("2009-01-15");
private static final String MEMBERSHIP_ROLE_CD_1 = "1";
private static final String MEMBERSHIP_ROLE_CD_4 = "4";
private static final Date ROLE_START_DATE = Date.valueOf("2009-01-10");
private static final Date ROLE_END_DATE = Date.valueOf("2009-01-20");
private CommitteeSchedule getCommitteeSchedule() throws Exception {
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
committeeSchedule.setId(1L);
committeeSchedule.setCommittee(createCommittee("test", "committeeName"));
committeeSchedule.setScheduledDate(new Date(dateFormat.parse("10/01/2009").getTime()));
committeeSchedule.setTime(new Timestamp(committeeSchedule.getScheduledDate().getTime()));
committeeSchedule.setPlace("iu - poplar");
committeeSchedule.setScheduleStatusCode(1);
return committeeSchedule;
}
private Committee createCommittee(String committeeId, String committeeName) {
Committee committee = new Committee();
committee.setCommitteeId(committeeId);
committee.setCommitteeName(committeeName);
committee.setMaxProtocols(5);
return committee;
}
private List<ScheduleAgenda> getAgendas() throws Exception {
List<ScheduleAgenda> scheduleAgendas = new ArrayList<ScheduleAgenda>();
ScheduleAgenda scheduleAgenda = new ScheduleAgenda();
scheduleAgenda.setScheduleIdFk(1L);
scheduleAgenda.setAgendaNumber(3);
scheduleAgenda.setAgendaName("test");
scheduleAgenda.setScheduleAgendaId(3L);
scheduleAgenda.setCreateTimestamp(new Timestamp(new Date(dateFormat.parse("10/08/2009").getTime()).getTime()));
scheduleAgendas.add(scheduleAgenda);
scheduleAgenda = new ScheduleAgenda();
scheduleAgenda.setScheduleIdFk(1L);
scheduleAgenda.setAgendaNumber(2);
scheduleAgenda.setAgendaName("test");
scheduleAgenda.setScheduleAgendaId(2L);
scheduleAgenda.setCreateTimestamp(new Timestamp(new Date(dateFormat.parse("10/05/2009").getTime()).getTime()));
scheduleAgendas.add(scheduleAgenda);
scheduleAgenda = new ScheduleAgenda();
scheduleAgenda.setScheduleIdFk(1L);
scheduleAgenda.setAgendaNumber(1);
scheduleAgenda.setAgendaName("test");
scheduleAgenda.setScheduleAgendaId(1L);
scheduleAgenda.setCreateTimestamp(new Timestamp(new Date(dateFormat.parse("10/02/2009").getTime()).getTime()));
scheduleAgendas.add(scheduleAgenda);
return scheduleAgendas;
}
@Test
public void testSaveCommitteeSchedule() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class);
final CommitteeSchedule committeeSchedule = getCommitteeSchedule();
committeeSchedule.setEndTime(committeeSchedule.getTime());
committeeSchedule.setStartTime(committeeSchedule.getTime());
committeeSchedule.setViewTime(new Time12HrFmt("01:00", MERIDIEM.PM));
committeeSchedule.setViewStartTime(new Time12HrFmt("01:00", MERIDIEM.PM));
committeeSchedule.setViewEndTime(new Time12HrFmt("02:00", MERIDIEM.PM));
final List<CommScheduleActItem> deletedOtherActions = new ArrayList<CommScheduleActItem>();
CommScheduleActItem actItem = new CommScheduleActItem();
deletedOtherActions.add(actItem);
context.checking(new Expectations() {
{
one(businessObjectService).delete(deletedOtherActions);
one(businessObjectService).save(committeeSchedule);
}
});
meetingService.setBusinessObjectService(businessObjectService);
meetingService.saveMeetingDetails(committeeSchedule, deletedOtherActions);
Assert.assertEquals(committeeSchedule.getParentCommittee().getCommitteeId(), "test");
Assert.assertEquals(committeeSchedule.getParentCommittee().getCommitteeName(), "committeeName");
Assert.assertEquals(committeeSchedule.getPlace(), "iu - poplar");
Assert.assertEquals(committeeSchedule.getScheduledDate(), new Date(dateFormat.parse("10/01/2009").getTime()));
Assert.assertEquals(committeeSchedule.getMaxProtocols(), new Integer(5));
Assert.assertEquals(committeeSchedule.getId(), new Long(1));
Assert.assertNotSame(committeeSchedule.getTime(), new Timestamp(committeeSchedule.getScheduledDate().getTime()));
Assert.assertEquals(committeeSchedule.getScheduleStatusCode(), new Integer(1));
// TODO : need to set up protocolsubmission/otheractions/attendances/minutes for more testing
// to check whetehr it is really persisted in DB ok or assume the mock 'save' and 'delete' are ok ?
}
@Test
public void testgetStandardReviewComment() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class);
final ProtocolContingency protocolContingency = new ProtocolContingency();
protocolContingency.setProtocolContingencyCode("1");
protocolContingency.setDescription("Protocol Contingency comment
context.checking(new Expectations() {
{
Map<String, String> queryMap = new HashMap<String, String>();
queryMap.put("protocolContingencyCode", "1");
one(businessObjectService).findByPrimaryKey(ProtocolContingency.class, queryMap);
will(returnValue(protocolContingency));
}
});
meetingService.setBusinessObjectService(businessObjectService);
String description = meetingService.getStandardReviewComment("1");
Assert.assertEquals(description, "Protocol Contingency comment
context.checking(new Expectations() {
{
Map<String, String> queryMap = new HashMap<String, String>();
queryMap.put("protocolContingencyCode", "2");
one(businessObjectService).findByPrimaryKey(ProtocolContingency.class, queryMap);
will(returnValue(null));
}
});
description = meetingService.getStandardReviewComment("2");
Assert.assertTrue(description == null);
}
@Test
public void testAddOtherAction() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
final SequenceAccessorService sequenceAccessorService = context.mock(SequenceAccessorService.class);
final CommScheduleActItem newOtherAction = getOtherActionItem(1L, "1", 0);
newOtherAction.setScheduleActItemTypeCode("1");
context.checking(new Expectations() {
{
one(sequenceAccessorService).getNextAvailableSequenceNumber("SEQ_MEETING_ID", newOtherAction.getClass());
will(returnValue(newOtherAction.getCommScheduleActItemsId()));
}
});
meetingService.setSequenceAccessorService(sequenceAccessorService);
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
committeeSchedule.setCommScheduleActItems(new ArrayList<CommScheduleActItemBase>());
meetingService.addOtherAction(newOtherAction, committeeSchedule);
Assert.assertTrue(committeeSchedule.getCommScheduleActItems().size() == 1);
Assert.assertEquals(committeeSchedule.getCommScheduleActItems().get(0).getScheduleActItemTypeCode(), "1");
Assert.assertEquals(committeeSchedule.getCommScheduleActItems().get(0).getActionItemNumber(), new Integer(1));
}
@Test
public void testDeleteOtherAction() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
List<CommScheduleActItem> items = new ArrayList<CommScheduleActItem>();
List<CommScheduleActItem> deletedItems = new ArrayList<CommScheduleActItem>();
CommScheduleActItem otherAction1 = getOtherActionItem(1L, "1", 1);
items.add(otherAction1);
CommScheduleActItem otherAction2 = getOtherActionItem(2L, "2", 2);
items.add(otherAction2);
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
committeeSchedule.setCommScheduleActItems((List) items);
meetingService.deleteOtherAction(committeeSchedule, 1, (List) deletedItems);
Assert.assertTrue(committeeSchedule.getCommScheduleActItems().size() == 1);
Assert.assertEquals(committeeSchedule.getCommScheduleActItems().get(0).getScheduleActItemTypeCode(), "1");
Assert.assertEquals(committeeSchedule.getCommScheduleActItems().get(0).getActionItemNumber(), new Integer(1));
Assert.assertTrue(deletedItems.size() == 1);
Assert.assertEquals(deletedItems.get(0).getScheduleActItemTypeCode(), "2");
Assert.assertEquals(deletedItems.get(0).getActionItemNumber(), new Integer(2));
}
private CommScheduleActItem getOtherActionItem(Long commScheduleActItemsId, String scheduleActItemTypeCode, int actionItemNumber) {
CommScheduleActItem otherAction = new CommScheduleActItem() {
@Override
public void refreshReferenceObject(String referenceObjectName) {
if (referenceObjectName.equals("scheduleActItemType")) {
org.kuali.coeus.common.committee.impl.meeting.ScheduleActItemType scheduleActItemType = new org.kuali.coeus.common.committee.impl.meeting.ScheduleActItemType();
scheduleActItemType.setScheduleActItemTypeCode(this.getScheduleActItemTypeCode());
}
}
};
otherAction.setActionItemNumber(actionItemNumber);
otherAction.setScheduleActItemTypeCode(scheduleActItemTypeCode);
otherAction.setCommScheduleActItemsId(commScheduleActItemsId);
return otherAction;
}
@Test
public void testMarkAbsent() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
List<MemberPresentBean> memberPresentBeans = new ArrayList<MemberPresentBean>();
List<MemberAbsentBean> memberAbsentBeans = new ArrayList<MemberAbsentBean>();
memberPresentBeans.add(getMemberPresentBean(PERSON_ID_1, PERSON_NAME_1));
memberPresentBeans.add(getMemberPresentBean(PERSON_ID_2, PERSON_NAME_2));
memberPresentBeans.add(getMemberPresentBean(PERSON_ID_3, PERSON_NAME_3));
meetingService.markAbsent(memberPresentBeans, memberAbsentBeans, 1);
Assert.assertTrue(memberPresentBeans.size() == 2);
Assert.assertTrue(memberAbsentBeans.size() == 1);
Assert.assertEquals(memberPresentBeans.get(0).getAttendance().getPersonId(), PERSON_ID_1);
Assert.assertEquals(memberPresentBeans.get(0).getAttendance().getPersonName(), PERSON_NAME_1);
Assert.assertEquals(memberPresentBeans.get(1).getAttendance().getPersonId(), PERSON_ID_3);
Assert.assertEquals(memberPresentBeans.get(1).getAttendance().getPersonName(), PERSON_NAME_3);
Assert.assertEquals(memberAbsentBeans.get(0).getAttendance().getPersonId(), PERSON_ID_2);
Assert.assertEquals(memberAbsentBeans.get(0).getAttendance().getPersonName(), PERSON_NAME_2);
}
private MemberPresentBean getMemberPresentBean(String personId, String personName) {
MemberPresentBean memberPresentBean = new MemberPresentBean();
CommitteeScheduleAttendance attendance = new CommitteeScheduleAttendance();
attendance.setPersonId(personId);
attendance.setPersonName(personName);
memberPresentBean.setAttendance(attendance);
return memberPresentBean;
}
@Test
public void testPresentVoting() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
List<MemberPresentBean> memberPresentBeans = new ArrayList<MemberPresentBean>();
List<MemberAbsentBean> memberAbsentBeans = new ArrayList<MemberAbsentBean>();
memberAbsentBeans.add(getMemberAbsentBean(PERSON_ID_1, PERSON_NAME_1));
memberAbsentBeans.add(getMemberAbsentBean(PERSON_ID_2, PERSON_NAME_2));
memberAbsentBeans.add(getMemberAbsentBean(PERSON_ID_3, PERSON_NAME_3));
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
committeeSchedule.setCommittee(getCommitteeWithMember());
// TODO : test if "alternate for" role ?
committeeSchedule.setScheduledDate(SCHEDULE_DATE);
MeetingHelper meetingHelper = new MeetingHelper(new MeetingForm());
meetingHelper.setCommitteeSchedule(committeeSchedule);
meetingHelper.setMemberAbsentBeans(memberAbsentBeans);
meetingHelper.setMemberPresentBeans(memberPresentBeans);
meetingService.presentVoting(meetingHelper, 1);
Assert.assertTrue(memberPresentBeans.size() == 1);
Assert.assertTrue(memberAbsentBeans.size() == 2);
Assert.assertEquals(memberAbsentBeans.get(0).getAttendance().getPersonId(), PERSON_ID_1);
Assert.assertEquals(memberAbsentBeans.get(0).getAttendance().getPersonName(), PERSON_NAME_1);
Assert.assertEquals(memberAbsentBeans.get(1).getAttendance().getPersonId(), PERSON_ID_3);
Assert.assertEquals(memberAbsentBeans.get(1).getAttendance().getPersonName(), PERSON_NAME_3);
Assert.assertEquals(memberPresentBeans.get(0).getAttendance().getPersonId(), PERSON_ID_2);
Assert.assertEquals(memberPresentBeans.get(0).getAttendance().getPersonName(), PERSON_NAME_2);
}
@Test
public void testPresentOther() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
List<OtherPresentBean> otherPresentBeans = new ArrayList<OtherPresentBean>();
List<MemberAbsentBean> memberAbsentBeans = new ArrayList<MemberAbsentBean>();
memberAbsentBeans.add(getMemberAbsentBean(PERSON_ID_1, PERSON_NAME_1));
memberAbsentBeans.add(getMemberAbsentBean(PERSON_ID_2, PERSON_NAME_2));
memberAbsentBeans.add(getMemberAbsentBean(PERSON_ID_3, PERSON_NAME_3));
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
committeeSchedule.setCommittee(getCommitteeWithMember());
committeeSchedule.setScheduledDate(SCHEDULE_DATE);
MeetingHelper meetingHelper = new MeetingHelper(new MeetingForm());
meetingHelper.setCommitteeSchedule(committeeSchedule);
meetingHelper.setMemberAbsentBeans(memberAbsentBeans);
meetingHelper.setOtherPresentBeans((List) otherPresentBeans);
meetingService.presentOther(meetingHelper, 1);
Assert.assertTrue(otherPresentBeans.size() == 1);
Assert.assertTrue(memberAbsentBeans.size() == 2);
Assert.assertEquals(memberAbsentBeans.get(0).getAttendance().getPersonId(), PERSON_ID_1);
Assert.assertEquals(memberAbsentBeans.get(0).getAttendance().getPersonName(), PERSON_NAME_1);
Assert.assertEquals(memberAbsentBeans.get(1).getAttendance().getPersonId(), PERSON_ID_3);
Assert.assertEquals(memberAbsentBeans.get(1).getAttendance().getPersonName(), PERSON_NAME_3);
Assert.assertEquals(otherPresentBeans.get(0).getAttendance().getPersonId(), PERSON_ID_2);
Assert.assertEquals(otherPresentBeans.get(0).getAttendance().getPersonName(), PERSON_NAME_2);
}
private CommitteeMembership getMembership(String personID, Integer rolodexID, String membershipTypeCode, Date termStartDate,
Date termEndDate) {
CommitteeMembership committeeMembership = new CommitteeMembership();
committeeMembership.setPersonId(personID);
committeeMembership.setRolodexId(rolodexID);
committeeMembership.setMembershipTypeCode(membershipTypeCode);
committeeMembership.setTermStartDate(termStartDate);
committeeMembership.setTermEndDate(termEndDate);
return committeeMembership;
}
private MemberAbsentBean getMemberAbsentBean(String personId, String personName) {
MemberAbsentBean memberAbsentBean = new MemberAbsentBean();
CommitteeScheduleAttendance attendance = new CommitteeScheduleAttendance();
attendance.setPersonId(personId);
attendance.setPersonName(personName);
memberAbsentBean.setAttendance(attendance);
return memberAbsentBean;
}
private CommitteeMembershipRole getRole(String membershipRoleCode, Date startDate, Date endDate) {
CommitteeMembershipRole committeeMembershipRole = new CommitteeMembershipRole();
committeeMembershipRole.setMembershipRoleCode(membershipRoleCode);
committeeMembershipRole.setStartDate(startDate);
committeeMembershipRole.setEndDate(endDate);
MembershipRole membershipRole = new MembershipRole();
membershipRole.setMembershipRoleCode(membershipRoleCode);
membershipRole.setDescription("Role " + membershipRoleCode);
committeeMembershipRole.setMembershipRole(membershipRole);
return committeeMembershipRole;
}
@Test
public void testAddOtherPresent() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
OtherPresentBean newOtherPresentBean = getOtherPresentBean(PERSON_ID_1, PERSON_NAME_1, true);
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
List<OtherPresentBean> otherPresentBeans = new ArrayList<OtherPresentBean>();
List<MemberAbsentBean> memberAbsentBeans = new ArrayList<MemberAbsentBean>();
memberAbsentBeans.add(getMemberAbsentBean(PERSON_ID_1, PERSON_NAME_1));
committeeSchedule.setCommittee(getCommitteeWithMember());
committeeSchedule.setScheduledDate(SCHEDULE_DATE);
MeetingHelper meetingHelper = new MeetingHelper(new MeetingForm());
meetingHelper.setMemberAbsentBeans(memberAbsentBeans);
meetingHelper.setOtherPresentBeans((List) otherPresentBeans);
meetingHelper.setNewOtherPresentBean(newOtherPresentBean);
meetingHelper.setCommitteeSchedule(committeeSchedule);
meetingService.addOtherPresent(meetingHelper);
Assert.assertTrue(otherPresentBeans.size() == 1);
Assert.assertTrue(memberAbsentBeans.size() == 0);
Assert.assertEquals(otherPresentBeans.get(0).getAttendance().getPersonId(), PERSON_ID_1);
Assert.assertEquals(otherPresentBeans.get(0).getAttendance().getPersonName(), PERSON_NAME_1);
}
private Committee getCommitteeWithMember() {
Committee committee = new Committee();
CommitteeMembership committeeMembership = getMembership(PERSON_ID_1, null, MEMBERSHIP_TYPE_CD, TERM_START_DATE,
TERM_END_DATE);
committeeMembership.getMembershipRoles().add(getRole(MEMBERSHIP_ROLE_CD_1, ROLE_START_DATE, ROLE_END_DATE));
committee.getCommitteeMemberships().add(committeeMembership);
CommitteeMembership rolodexMembership = getMembership(null, ROLODEX_ID, MEMBERSHIP_TYPE_CD, TERM_START_DATE, TERM_END_DATE);
rolodexMembership.getMembershipRoles().add(getRole(MEMBERSHIP_ROLE_CD_1, ROLE_START_DATE, ROLE_END_DATE));
committee.getCommitteeMemberships()
.add(rolodexMembership);
committeeMembership.getMembershipRoles().add(getRole(MEMBERSHIP_ROLE_CD_4, ROLE_START_DATE, ROLE_END_DATE));
return committee;
}
@Test
public void testdeleteOtherPresent() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
List<OtherPresentBean> otherPresentBeans = new ArrayList<OtherPresentBean>();
otherPresentBeans.add(getOtherPresentBean(PERSON_ID_1, PERSON_NAME_1, true));
otherPresentBeans.add(getOtherPresentBean(PERSON_ID_3, PERSON_NAME_3, false));
List<MemberAbsentBean> memberAbsentBeans = new ArrayList<MemberAbsentBean>();
memberAbsentBeans.add(getMemberAbsentBean(PERSON_ID_2, PERSON_NAME_2));
committeeSchedule.setCommittee(getCommitteeWithMember());
committeeSchedule.setScheduledDate(SCHEDULE_DATE);
MeetingHelper meetingHelper = new MeetingHelper(new MeetingForm());
meetingHelper.setMemberAbsentBeans(memberAbsentBeans);
meetingHelper.setOtherPresentBeans((List) otherPresentBeans);
meetingHelper.setCommitteeSchedule(committeeSchedule);
meetingService.deleteOtherPresent(meetingHelper, 0);
Assert.assertTrue(otherPresentBeans.size() == 1);
Assert.assertTrue(memberAbsentBeans.size() == 2);
Assert.assertEquals(otherPresentBeans.get(0).getAttendance().getPersonId(), PERSON_ID_3);
Assert.assertEquals(otherPresentBeans.get(0).getAttendance().getPersonName(), PERSON_NAME_3);
Assert.assertEquals(memberAbsentBeans.get(0).getAttendance().getPersonId(), PERSON_ID_2);
Assert.assertEquals(memberAbsentBeans.get(0).getAttendance().getPersonName(), PERSON_NAME_2);
Assert.assertEquals(memberAbsentBeans.get(1).getAttendance().getPersonId(), PERSON_ID_1);
Assert.assertEquals(memberAbsentBeans.get(1).getAttendance().getPersonName(), PERSON_NAME_1);
}
private OtherPresentBean getOtherPresentBean(String personId, String personName, boolean isMember) {
OtherPresentBean otherPresentBean = new OtherPresentBean();
CommitteeScheduleAttendance attendance = new CommitteeScheduleAttendance();
attendance.setPersonId(personId);
attendance.setPersonName(personName);
otherPresentBean.setAttendance(attendance);
otherPresentBean.setMember(isMember);
return otherPresentBean;
}
@Test
public void testAddCommitteeScheduleMinute() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
final DateTimeService dateTimeService = context.mock(DateTimeService.class);
context.checking(new Expectations() {{
one(dateTimeService).getCurrentTimestamp();
will(returnValue(new Timestamp(System.currentTimeMillis())));
}});
meetingService.setDateTimeService(dateTimeService);
CommitteeScheduleMinute newCommitteeScheduleMinute = getCommitteeScheduleMinute(1L, "1", 1, 2L);
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
committeeSchedule.setId(1L);
committeeSchedule.setCommitteeScheduleMinutes(new ArrayList<CommitteeScheduleMinute>());
List<ProtocolSubmissionLite> protocolSubmissions = new ArrayList<>();
protocolSubmissions.add(getProtocolSubmission(1L));
committeeSchedule.setProtocolSubmissions(protocolSubmissions);
MeetingHelper meetingHelper = new MeetingHelper(new MeetingForm());
meetingHelper.setNewCommitteeScheduleMinute(newCommitteeScheduleMinute);
meetingHelper.setCommitteeSchedule(committeeSchedule);
meetingService.addCommitteeScheduleMinute(meetingHelper);
Assert.assertTrue(committeeSchedule.getCommitteeScheduleMinutes().size() == 1);
Assert.assertEquals(committeeSchedule.getCommitteeScheduleMinutes().get(0).getMinuteEntryTypeCode(), "1");
Assert.assertEquals(committeeSchedule.getCommitteeScheduleMinutes().get(0).getEntryNumber(), new Integer(1));
}
@Test
public void testDeleteCommitteeScheduleMinute() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
List<CommitteeScheduleMinute> items = new ArrayList<CommitteeScheduleMinute>();
List<CommitteeScheduleMinute> deletedItems = new ArrayList<CommitteeScheduleMinute>();
CommitteeScheduleMinute minute1 = getCommitteeScheduleMinute(1L, "1", 1, 3L);
items.add(minute1);
CommitteeScheduleMinute minute2 = getCommitteeScheduleMinute(2L, "2", 2, 3L);
items.add(minute2);
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
committeeSchedule.setCommitteeScheduleMinutes(items);
meetingService.deleteCommitteeScheduleMinute(committeeSchedule, deletedItems, 1);
Assert.assertTrue(committeeSchedule.getCommitteeScheduleMinutes().size() == 1);
Assert.assertEquals(committeeSchedule.getCommitteeScheduleMinutes().get(0).getMinuteEntryTypeCode(), "1");
Assert.assertEquals(committeeSchedule.getCommitteeScheduleMinutes().get(0).getEntryNumber(), new Integer(1));
Assert.assertTrue(deletedItems.size() == 1);
Assert.assertEquals(deletedItems.get(0).getMinuteEntryTypeCode(), "2");
Assert.assertEquals(deletedItems.get(0).getEntryNumber(), new Integer(2));
}
private CommitteeScheduleMinute getCommitteeScheduleMinute(Long commScheduleMinutesId, String minuteEntryTypeCode,
int entryNumber, Long submissionId) {
CommitteeScheduleMinute committeeScheduleMinute = new CommitteeScheduleMinute() {
@Override
public void refreshReferenceObject(String referenceObjectName) {
if (referenceObjectName.equals("minuteEntryType")) {
MinuteEntryType minuteEntryType = new MinuteEntryType();
minuteEntryType.setMinuteEntryTypeCode(this.getMinuteEntryTypeCode());
}
}
};
ProtocolSubmissionLite submission = getProtocolSubmission(submissionId);
committeeScheduleMinute.setEntryNumber(entryNumber);
committeeScheduleMinute.setMinuteEntryTypeCode(minuteEntryTypeCode);
committeeScheduleMinute.setCommScheduleMinutesId(commScheduleMinutesId);
return committeeScheduleMinute;
}
@Test
public void testPopulateFormHelper() throws Exception {
MeetingServiceImpl meetingService = new MeetingServiceImpl();
CommitteeSchedule committeeSchedule = new CommitteeSchedule();
Committee committee = new Committee();
committee.setCommitteeId("1");
committee.setCommitteeName("Test Committee");
CommitteeMembership committeeMembership = getMembership(PERSON_ID, null, MEMBERSHIP_TYPE_CD, TERM_START_DATE, TERM_END_DATE);
committeeMembership.getMembershipRoles().add(getRole(MEMBERSHIP_ROLE_CD_1, ROLE_START_DATE, ROLE_END_DATE));
committee.getCommitteeMemberships().add(committeeMembership);
CommitteeMembership rolodexMembership = getMembership(null, ROLODEX_ID, MEMBERSHIP_TYPE_CD, TERM_START_DATE, TERM_END_DATE);
rolodexMembership.getMembershipRoles().add(getRole(MEMBERSHIP_ROLE_CD_1, ROLE_START_DATE, ROLE_END_DATE));
committee.getCommitteeMemberships()
.add(rolodexMembership);
committeeMembership.getMembershipRoles().add(getRole(MEMBERSHIP_ROLE_CD_4, ROLE_START_DATE, ROLE_END_DATE));
committeeSchedule.setCommittee(committee);
// TODO : test if "alternate for" role ?
committeeSchedule.setScheduledDate(SCHEDULE_DATE);
committeeSchedule.setId(1L);
List<ProtocolSubmissionLite> protocolSubmissions = new ArrayList<>();
protocolSubmissions.add(getProtocolSubmission(1L));
protocolSubmissions.add(getProtocolSubmission(2L));
committeeSchedule.setProtocolSubmissions(protocolSubmissions);
MeetingHelper meetingHelper = new MeetingHelper(new MeetingForm());
final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class);
final List<ScheduleAgenda> agendas = getAgendas();
final List<CommScheduleMinuteDoc> minuteDocs = getMinuteDocs();
final List<ProtocolCorrespondence> correspondences = getCorrespondences();
context.checking(new Expectations() {
{
Map queryMap = new HashMap();
queryMap.put("scheduleIdFk", 1L);
one(businessObjectService).findMatchingOrderBy(ScheduleAgenda.class, queryMap, "createTimestamp", true);
;
will(returnValue(agendas));
one(businessObjectService).findMatchingOrderBy(ScheduleAgenda.class, queryMap, "createTimestamp", true);
;
will(returnValue(agendas));
one(businessObjectService).findMatchingOrderBy(CommScheduleMinuteDoc.class, queryMap, "createTimestamp", true);
;
will(returnValue(minuteDocs));
Map queryMap1 = new HashMap();
queryMap1.put("protocolId", 1L);
one(businessObjectService).findMatching(ProtocolCorrespondence.class, queryMap1);
;
will(returnValue(correspondences));
}
});
meetingService.setBusinessObjectService(businessObjectService);
meetingService.populateFormHelper(meetingHelper, committeeSchedule, 1);
Assert.assertEquals(2, meetingHelper.getMemberAbsentBeans().size());
Assert.assertEquals(2, meetingHelper.getProtocolSubmittedBeans().size());
Assert.assertEquals(0, meetingHelper.getMemberPresentBeans().size());
Assert.assertEquals(0, meetingHelper.getOtherPresentBeans().size());
Assert.assertEquals(meetingHelper.getTabLabel(), "Test Committee #1 Meeting " + dateFormat.format(SCHEDULE_DATE));
Assert.assertEquals(1, meetingHelper.getMinuteDocs().size());
Assert.assertEquals(1, meetingHelper.getCorrespondences().size());
Assert.assertEquals(meetingHelper.getMinuteDocs().get(0).getScheduleIdFk().toString(), "1");
Assert.assertEquals(meetingHelper.getCorrespondences().get(0).getProtocolId().toString(), "1");
}
private List<CommScheduleMinuteDoc> getMinuteDocs() {
List<CommScheduleMinuteDoc> minuteDocs = new ArrayList<CommScheduleMinuteDoc>();
CommScheduleMinuteDoc minuteDoc = new CommScheduleMinuteDoc();
minuteDoc.setScheduleIdFk(1L);
minuteDocs.add(minuteDoc);
return minuteDocs;
}
private List<ProtocolCorrespondence> getCorrespondences() {
List<ProtocolCorrespondence> correspondences = new ArrayList<ProtocolCorrespondence>();
ProtocolCorrespondence correspondence = new ProtocolCorrespondence();
correspondence.setProtocolId(1L);
correspondences.add(correspondence);
return correspondences;
}
private ProtocolSubmissionLite getProtocolSubmission(Long submissionId) {
ProtocolSubmissionLite protocolSubmission = new ProtocolSubmissionLite() {
@Override
public void refreshReferenceObject(String referenceObjectName) {
// do nothing
}
};
protocolSubmission.setSubmissionId(submissionId);
protocolSubmission.setProtocolId(1L);
protocolSubmission.setProtocolActive(true);
return protocolSubmission;
}
private Protocol getProtocol() {
Protocol protocol = new Protocol() {
@Override
public void refreshReferenceObject(String referenceObjectName) {
// do nothing
}
@Override
public ProtocolPerson getPrincipalInvestigator() {
ProtocolPerson protocolPerson = new ProtocolPerson();
protocolPerson.setPersonId(PERSON_ID_1);
protocolPerson.setPersonName(PERSON_NAME_1);
return protocolPerson;
}
};
return protocol;
}
} |
package com.planet_ink.coffee_mud.Abilities.Prayers;
import com.planet_ink.coffee_mud.interfaces.*;
import com.planet_ink.coffee_mud.common.*;
import com.planet_ink.coffee_mud.utils.*;
import java.util.*;
public class Prayer_MassMobility extends Prayer
{
public Prayer_MassMobility()
{
super();
myID=this.getClass().getName().substring(this.getClass().getName().lastIndexOf('.')+1);
name="Mass Mobility";
displayText="(Mass Mobility)";
quality=Ability.BENEFICIAL_OTHERS;
holyQuality=Prayer.HOLY_NEUTRAL;
baseEnvStats().setLevel(20);
recoverEnvStats();
}
public Environmental newInstance()
{
return new Prayer_MassMobility();
}
public boolean okAffect(Affect affect)
{
if((affected==null)||(!(affected instanceof MOB)))
return true;
MOB mob=(MOB)affected;
if((affect.amITarget(mob))
&&(Util.bset(affect.targetCode(),Affect.MASK_MALICIOUS))
&&(affect.targetMinor()==Affect.TYP_CAST_SPELL)
&&(affect.tool()!=null)
&&(affect.tool() instanceof Ability)
&&(!mob.amDead()))
{
Ability A=(Ability)affect.tool();
MOB newMOB=(MOB)CMClass.getMOB("StdMOB").newInstance();
FullMsg msg=new FullMsg(newMOB,null,null,Affect.MSG_SIT,null);
newMOB.recoverEnvStats();
try
{
A.affectEnvStats(newMOB,newMOB.envStats());
if((!Sense.aliveAwakeMobile(newMOB,true))
||(!A.okAffect(msg)))
{
affect.addTrailerMsg(new FullMsg(mob,null,Affect.MSG_OK_VISUAL,"The mobile aura around <S-NAME> repels the "+A.name()+"."));
return false;
}
}
catch(Exception e)
{}
}
return true;
}
public void affectCharStats(MOB affectedMOB, CharStats affectedStats)
{
super.affectCharStats(affectedMOB,affectedStats);
affectedStats.setStat(CharStats.SAVE_PARALYSIS,affectedStats.getStat(CharStats.SAVE_PARALYSIS)+100);
}
public void unInvoke()
{
// undo the affects of this spell
if((affected==null)||(!(affected instanceof MOB)))
return;
MOB mob=(MOB)affected;
super.unInvoke();
mob.tell("The aura of mobility around you fades.");
}
public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto)
{
if(!super.invoke(mob,commands,givenTarget,auto))
return false;
boolean success=profficiencyCheck(0,auto);
Room room=mob.location();
affectType=Affect.MSG_CAST_VERBAL_SPELL;
if(auto) affectType=affectType|Affect.ACT_GENERAL;
if((success)&&(room!=null))
{
FullMsg msg=new FullMsg(mob,null,this,affectType,auto?"":"<S-NAME> pray(s) to <S-HIS-HER> god for an aura of mobility!");
if(mob.location().okAffect(msg))
{
mob.location().send(mob,msg);
for(int i=0;i<room.numInhabitants();i++)
{
MOB target=room.fetchInhabitant(i);
if(target==null) break;
// it worked, so build a copy of this ability,
// and add it to the affects list of the
// affected MOB. Then tell everyone else
// what happened.
msg=new FullMsg(mob,target,this,affectType,"Mobility is invoked upon <T-NAME>.");
if(mob.location().okAffect(msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,0);
}
}
}
}
else
{
beneficialWordsFizzle(mob,null,"<S-NAME> pray(s) to <S-HIS-HER> god, but nothing happens.");
return false;
}
return success;
}
} |
package com.forerunnergames.tools.common;
import com.google.common.collect.Iterables;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
public final class Arguments
{
private enum ArgumentStatus
{
BLANK("is blank"),
BLANK_ELEMENTS("has blank elements"),
EMPTY("is empty"),
EMPTY_ELEMENTS("has empty elements"),
NULL("is null"),
NULL_ELEMENTS("has null elements"),
NULL_KEYS("has null keys"),
NULL_VALUES("has null values"),
NULL_KEYS_AND_VALUES("has null keys & null values");
private final String message;
private String getMessage ()
{
return message;
}
private ArgumentStatus (final String message)
{
this.message = message;
}
}
private enum BoundType
{
LOWER_EXCLUSIVE("strictly greater than"),
UPPER_EXCLUSIVE("strictly less than"),
LOWER_INCLUSIVE("greater than or equal to"),
UPPER_INCLUSIVE("less than or equal to");
private final String message;
private String getMessage ()
{
return message;
}
private BoundType (final String message)
{
this.message = message;
}
}
public static void checkHasNoNullElements (final Iterable <?> iterable, final String iterableName)
{
if (iterable != null && Iterables.contains (iterable, null))
{
illegalArgument (iterableName, ArgumentStatus.NULL_ELEMENTS);
}
}
public static void checkHasNoNullElements (final Object[] array, final String arrayName)
{
if (array != null && Arrays.asList (array).contains (null))
{
illegalArgument (arrayName, ArgumentStatus.NULL_ELEMENTS);
}
}
public static void checkHasNoNullKeys (final Map <?, ?> map, final String mapName)
{
if (hasNullKeys (map)) illegalArgument (mapName, ArgumentStatus.NULL_KEYS);
}
private static boolean hasNullKeys (final Map <?, ?> map)
{
return map != null && Iterables.contains (map.keySet (), null);
}
public static void checkHasNoNullValues (final Map <?, ?> map, final String mapName)
{
if (hasNullValues (map)) illegalArgument (mapName, ArgumentStatus.NULL_VALUES);
}
private static boolean hasNullValues (final Map <?, ?> map)
{
return map != null && Iterables.contains (map.values (), null);
}
public static void checkHasNoNullKeysOrValues (final Map <?, ?> map, final String mapName)
{
final boolean hasNullKeys = hasNullKeys (map);
final boolean hasNullValues = hasNullValues (map);
if (!hasNullKeys && !hasNullValues) return;
if (hasNullKeys && hasNullValues)
{
illegalArgument (mapName, ArgumentStatus.NULL_KEYS_AND_VALUES);
}
else if (hasNullKeys)
{
illegalArgument (mapName, ArgumentStatus.NULL_KEYS);
}
else
{
illegalArgument (mapName, ArgumentStatus.NULL_VALUES);
}
}
public static void checkHasNoNullOrEmptyElements (final Collection <String> strings, final String collectionName)
{
if (strings == null || strings.isEmpty ())
{
return;
}
for (final String s : strings)
{
if (s == null)
{
illegalArgument (collectionName, ArgumentStatus.NULL_ELEMENTS);
}
else if (s.isEmpty ())
{
illegalArgument (collectionName, ArgumentStatus.EMPTY_ELEMENTS);
}
}
}
public static void checkHasNoNullOrEmptyElements (final String[] array, final String arrayName)
{
if (array == null)
{
return;
}
checkHasNoNullOrEmptyElements (Arrays.asList (array), arrayName);
}
public static void checkHasNoNullOrEmptyOrBlankElements (final Collection <String> strings,
final String collectionName)
{
if (strings == null || strings.isEmpty ())
{
return;
}
for (final String s : strings)
{
if (s == null)
{
illegalArgument (collectionName, ArgumentStatus.NULL_ELEMENTS);
}
else if (s.isEmpty ())
{
illegalArgument (collectionName, ArgumentStatus.EMPTY_ELEMENTS);
}
else if (Strings.isWhitespace (s))
{
illegalArgument (collectionName, ArgumentStatus.BLANK_ELEMENTS);
}
}
}
public static void checkHasNoNullOrEmptyOrBlankElements (final String[] array, final String arrayName)
{
if (array == null)
{
return;
}
checkHasNoNullOrEmptyOrBlankElements (Arrays.asList (array), arrayName);
}
public static void checkIsNegative (final int value, final String valueName)
{
checkUpperExclusiveBound ((long) value, 0, valueName, "");
}
public static void checkIsNegative (final long value, final String valueName)
{
checkUpperExclusiveBound (value, 0, valueName, "");
}
public static void checkIsNegative (final float value, final String valueName)
{
checkUpperExclusiveBound ((double) value, 0, valueName, "");
}
public static void checkIsNegative (final double value, final String valueName)
{
checkUpperExclusiveBound (value, 0, valueName, "");
}
public static void checkIsNotNegative (final int value, final String valueName)
{
checkLowerInclusiveBound ((long) value, 0, valueName, "");
}
public static void checkIsNotNegative (final long value, final String valueName)
{
checkLowerInclusiveBound (value, 0, valueName, "");
}
public static void checkIsNotNegative (final float value, final String valueName)
{
checkLowerInclusiveBound ((double) value, 0, valueName, "");
}
public static void checkIsNotNegative (final double value, final String valueName)
{
checkLowerInclusiveBound (value, 0, valueName, "");
}
public static void checkIsTrue (final boolean condition, final String errorMessage)
{
if (!condition) throw new IllegalArgumentException (errorMessage);
}
public static void checkIsFalse (final boolean condition, final String errorMessage)
{
if (condition) throw new IllegalArgumentException (errorMessage);
}
public static <T> void checkIsNotNull (final T object, final String objectName)
{
if (object == null)
{
illegalArgument (objectName, ArgumentStatus.NULL);
}
}
public static void checkIsNotNullOrEmpty (final String s, final String stringName)
{
if (s == null)
{
illegalArgument (stringName, ArgumentStatus.NULL);
}
else if (s.isEmpty ())
{
illegalArgument (stringName, ArgumentStatus.EMPTY);
}
}
public static <T> void checkIsNotNullOrEmpty (final Iterable <T> iterable, final String iterableName)
{
if (iterable == null)
{
illegalArgument (iterableName, ArgumentStatus.NULL);
}
else if (!iterable.iterator ().hasNext ())
{
illegalArgument (iterableName, ArgumentStatus.EMPTY);
}
}
public static void checkIsNotNullOrEmpty (final Object[] array, final String arrayName)
{
if (array == null)
{
illegalArgument (arrayName, ArgumentStatus.NULL);
}
else if (array.length == 0)
{
illegalArgument (arrayName, ArgumentStatus.EMPTY);
}
}
public static void checkIsNotNullOrEmptyOrBlank (final String s, final String stringName)
{
if (s == null)
{
illegalArgument (stringName, ArgumentStatus.NULL);
}
else if (s.isEmpty ())
{
illegalArgument (stringName, ArgumentStatus.EMPTY);
}
else if (Strings.isWhitespace (s))
{
illegalArgument (stringName, ArgumentStatus.BLANK);
}
}
public static void checkLowerInclusiveBound (final int value, final int lowerInclusiveBound, final String valueName)
{
checkLowerInclusiveBound ((long) value, (long) lowerInclusiveBound, valueName, "");
}
public static void checkLowerInclusiveBound (final int value,
final int lowerInclusiveBound,
final String valueName,
final String lowerInclusiveBoundName)
{
checkLowerInclusiveBound ((long) value, (long) lowerInclusiveBound, valueName, lowerInclusiveBoundName);
}
public static void
checkLowerInclusiveBound (final long value, final long lowerInclusiveBound, final String valueName)
{
checkLowerInclusiveBound (value, lowerInclusiveBound, valueName, "");
}
public static void checkLowerInclusiveBound (final long value,
final long lowerInclusiveBound,
final String valueName,
final String lowerInclusiveBoundName)
{
if (value < lowerInclusiveBound)
{
boundsViolation (value, lowerInclusiveBound, valueName, lowerInclusiveBoundName, BoundType.LOWER_INCLUSIVE);
}
}
public static void checkLowerInclusiveBound (final float value,
final float lowerInclusiveBound,
final String valueName)
{
checkLowerInclusiveBound ((double) value, (double) lowerInclusiveBound, valueName, "");
}
public static void checkLowerInclusiveBound (final float value,
final float lowerInclusiveBound,
final String valueName,
final String lowerInclusiveBoundName)
{
checkLowerInclusiveBound ((double) value, (double) lowerInclusiveBound, valueName, lowerInclusiveBoundName);
}
public static void checkLowerInclusiveBound (final double value,
final double lowerInclusiveBound,
final String valueName)
{
checkLowerInclusiveBound (value, lowerInclusiveBound, valueName, "");
}
public static void checkLowerInclusiveBound (final double value,
final double lowerInclusiveBound,
final String valueName,
final String lowerInclusiveBoundName)
{
if (value < lowerInclusiveBound)
{
boundsViolation (value, lowerInclusiveBound, valueName, lowerInclusiveBoundName, BoundType.LOWER_INCLUSIVE);
}
}
public static void checkLowerExclusiveBound (final int value, final int lowerExclusiveBound, final String valueName)
{
checkLowerExclusiveBound ((long) value, (long) lowerExclusiveBound, valueName, "");
}
public static void checkLowerExclusiveBound (final int value,
final int lowerExclusiveBound,
final String valueName,
final String lowerExclusiveBoundName)
{
checkLowerExclusiveBound ((long) value, (long) lowerExclusiveBound, valueName, lowerExclusiveBoundName);
}
public static void
checkLowerExclusiveBound (final long value, final long lowerExclusiveBound, final String valueName)
{
checkLowerExclusiveBound (value, lowerExclusiveBound, valueName, "");
}
public static void checkLowerExclusiveBound (final long value,
final long lowerExclusiveBound,
final String valueName,
final String lowerExclusiveBoundName)
{
if (value <= lowerExclusiveBound)
{
boundsViolation (value, lowerExclusiveBound, valueName, lowerExclusiveBoundName, BoundType.LOWER_EXCLUSIVE);
}
}
public static void checkLowerExclusiveBound (final float value,
final float lowerExclusiveBound,
final String valueName)
{
checkLowerExclusiveBound ((double) value, (double) lowerExclusiveBound, valueName, "");
}
public static void checkLowerExclusiveBound (final float value,
final float lowerExclusiveBound,
final String valueName,
final String lowerExclusiveBoundName)
{
checkLowerExclusiveBound ((double) value, (double) lowerExclusiveBound, valueName, lowerExclusiveBoundName);
}
public static void checkLowerExclusiveBound (final double value,
final double lowerExclusiveBound,
final String valueName)
{
checkLowerExclusiveBound (value, lowerExclusiveBound, valueName, "");
}
public static void checkLowerExclusiveBound (final double value,
final double lowerExclusiveBound,
final String valueName,
final String lowerExclusiveBoundName)
{
if (value <= lowerExclusiveBound)
{
boundsViolation (value, lowerExclusiveBound, valueName, lowerExclusiveBoundName, BoundType.LOWER_EXCLUSIVE);
}
}
public static void checkUpperInclusiveBound (final int value, final int upperInclusiveBound, final String valueName)
{
checkUpperInclusiveBound ((long) value, (long) upperInclusiveBound, valueName, "");
}
public static void checkUpperInclusiveBound (final int value,
final int upperInclusiveBound,
final String valueName,
final String upperInclusiveBoundName)
{
checkUpperInclusiveBound ((long) value, (long) upperInclusiveBound, valueName, upperInclusiveBoundName);
}
public static void
checkUpperInclusiveBound (final long value, final long upperInclusiveBound, final String valueName)
{
checkUpperInclusiveBound (value, upperInclusiveBound, valueName, "");
}
public static void checkUpperInclusiveBound (final long value,
final long upperInclusiveBound,
final String valueName,
final String upperInclusiveBoundName)
{
if (value > upperInclusiveBound)
{
boundsViolation (value, upperInclusiveBound, valueName, upperInclusiveBoundName, BoundType.UPPER_INCLUSIVE);
}
}
public static void checkUpperInclusiveBound (final float value,
final float upperInclusiveBound,
final String valueName)
{
checkUpperInclusiveBound ((double) value, (double) upperInclusiveBound, valueName, "");
}
public static void checkUpperInclusiveBound (final float value,
final float upperInclusiveBound,
final String valueName,
final String upperInclusiveBoundName)
{
checkUpperInclusiveBound ((double) value, (double) upperInclusiveBound, valueName, upperInclusiveBoundName);
}
public static void checkUpperInclusiveBound (final double value,
final double upperInclusiveBound,
final String valueName)
{
checkUpperInclusiveBound (value, upperInclusiveBound, valueName, "");
}
public static void checkUpperInclusiveBound (final double value,
final double upperInclusiveBound,
final String valueName,
final String upperInclusiveBoundName)
{
if (value > upperInclusiveBound)
{
boundsViolation (value, upperInclusiveBound, valueName, upperInclusiveBoundName, BoundType.UPPER_INCLUSIVE);
}
}
public static void checkUpperExclusiveBound (final int value, final int upperExclusiveBound, final String valueName)
{
checkUpperExclusiveBound ((long) value, (long) upperExclusiveBound, valueName, "");
}
public static void checkUpperExclusiveBound (final int value,
final int upperExclusiveBound,
final String valueName,
final String upperExclusiveBoundName)
{
checkUpperExclusiveBound ((long) value, (long) upperExclusiveBound, valueName, upperExclusiveBoundName);
}
public static void
checkUpperExclusiveBound (final long value, final long upperExclusiveBound, final String valueName)
{
checkUpperExclusiveBound (value, upperExclusiveBound, valueName, "");
}
public static void checkUpperExclusiveBound (final long value,
final long upperExclusiveBound,
final String valueName,
final String upperExclusiveBoundName)
{
if (value >= upperExclusiveBound)
{
boundsViolation (value, upperExclusiveBound, valueName, upperExclusiveBoundName, BoundType.UPPER_EXCLUSIVE);
}
}
public static void checkUpperExclusiveBound (final float value,
final float upperExclusiveBound,
final String valueName)
{
checkUpperExclusiveBound ((double) value, (double) upperExclusiveBound, valueName, "");
}
public static void checkUpperExclusiveBound (final float value,
final float upperExclusiveBound,
final String valueName,
final String upperExclusiveBoundName)
{
checkUpperExclusiveBound ((double) value, (double) upperExclusiveBound, valueName, upperExclusiveBoundName);
}
public static void checkUpperExclusiveBound (final double value,
final double upperExclusiveBound,
final String valueName)
{
checkUpperExclusiveBound (value, upperExclusiveBound, valueName, "");
}
public static void checkUpperExclusiveBound (final double value,
final double upperExclusiveBound,
final String valueName,
final String upperExclusiveBoundName)
{
if (value >= upperExclusiveBound)
{
boundsViolation (value, upperExclusiveBound, valueName, upperExclusiveBoundName, BoundType.UPPER_EXCLUSIVE);
}
}
private static void boundsViolation (final Number value,
final Number bound,
final String valueName,
final String boundName,
final BoundType boundType) throws IllegalArgumentException
{
final int stackLevel = getStackLevelOfFirstClassOutsideThisClass ();
throw new IllegalArgumentException ("Argument \"" + valueName + "\" [value: " + value + "]" + " must be "
+ boundType.getMessage () + " " + (boundName.isEmpty () ? "" : "\"" + boundName + "\" ")
+ "[value: " + bound + "]" + " when invoking [" + Classes.getClassName (stackLevel) + "."
+ Methods.getMethodName (stackLevel) + "].");
}
private static int getStackLevelOfFirstClassOutsideThisClass ()
{
final int maxStackLevel = getMaxStackLevel ();
final String thisClassName = Classes.getClassName (0);
for (int stackLevel = 1; stackLevel <= maxStackLevel; ++stackLevel)
{
if (!thisClassName.equals (Classes.getClassName (stackLevel))) return stackLevel - 1;
}
return maxStackLevel - 1;
}
private static int getMaxStackLevel ()
{
return Thread.currentThread ().getStackTrace ().length - 1;
}
private static void illegalArgument (final String argumentName, final ArgumentStatus argumentStatus)
throws IllegalArgumentException
{
final int stackLevel = getStackLevelOfFirstClassOutsideThisClass ();
throw new IllegalArgumentException ("\nLocation: " + Classes.getClassName (stackLevel) + "."
+ Methods.getMethodName (stackLevel) + "\nReason: argument '" + argumentName + "' "
+ argumentStatus.getMessage ());
}
private Arguments ()
{
Classes.instantiationNotAllowed ();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.