lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
34a3195657243fe571d97cd115a5d5f7deb0325e
0
ryantxu/jeo,jeo/jeo,jeo/jeo,jeo/jeo
/* Copyright 2013 The jeo project. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jeo.map; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jeo.util.Interpolate; /** * A color in RGBA color space. * * @author Justin Deoliveira, OpenGeo */ public class RGB { public static final RGB aliceblue = new RGB(240,248,255); public static final RGB antiquewhite = new RGB(250,235,215); public static final RGB aqua = new RGB(0,255,255); public static final RGB aquamarine = new RGB(127,255,212); public static final RGB azure = new RGB(240,255,255); public static final RGB beige = new RGB(245,245,220); public static final RGB bisque = new RGB(255,228,196); public static final RGB black = new RGB(0,0,0); public static final RGB blanchedalmond = new RGB(255,235,205); public static final RGB blue = new RGB(0,0,255); public static final RGB blueviolet = new RGB(138,43,226); public static final RGB brown = new RGB(165,42,42); public static final RGB burlywood = new RGB(222,184,135); public static final RGB cadetblue = new RGB(95,158,160); public static final RGB chartreuse = new RGB(127,255,0); public static final RGB chocolate = new RGB(210,105,30); public static final RGB coral = new RGB(255,127,80); public static final RGB cornflowerblue = new RGB(100,149,237); public static final RGB cornsilk = new RGB(255,248,220); public static final RGB crimson = new RGB(220,20,60); public static final RGB cyan = new RGB(0,255,255); public static final RGB darkblue = new RGB(0,0,139); public static final RGB darkcyan = new RGB(0,139,139); public static final RGB darkgoldenrod = new RGB(184,134,11); public static final RGB darkgray = new RGB(169,169,169); public static final RGB darkgreen = new RGB(0,100,0); public static final RGB darkkhaki = new RGB(189,183,107); public static final RGB darkmagenta = new RGB(139,0,139); public static final RGB darkolivegreen = new RGB(85,107,47); public static final RGB darkorange = new RGB(255,140,0); public static final RGB darkorchid = new RGB(153,50,204); public static final RGB darkred = new RGB(139,0,0); public static final RGB darksalmon = new RGB(233,150,122); public static final RGB darkseagreen = new RGB(143,188,143); public static final RGB darkslateblue = new RGB(72,61,139); public static final RGB darkslategray = new RGB(47,79,79); public static final RGB darkturquoise = new RGB(0,206,209); public static final RGB darkviolet = new RGB(148,0,211); public static final RGB deeppink = new RGB(255,20,147); public static final RGB deepskyblue = new RGB(0,191,255); public static final RGB dimgray = new RGB(105,105,105); public static final RGB dodgerblue = new RGB(30,144,255); public static final RGB firebrick = new RGB(178,34,34); public static final RGB floralwhite = new RGB(255,250,240); public static final RGB forestgreen = new RGB(34,139,34); public static final RGB fuchsia = new RGB(255,0,255); public static final RGB gainsboro = new RGB(220,220,220); public static final RGB ghostwhite = new RGB(248,248,255); public static final RGB gold = new RGB(255,215,0); public static final RGB goldenrod = new RGB(218,165,32); public static final RGB gray = new RGB(128,128,128); public static final RGB green = new RGB(0,128,0); public static final RGB greenyellow = new RGB(173,255,47); public static final RGB grey = new RGB(84,84,84); public static final RGB honeydew = new RGB(240,255,240); public static final RGB hotpink = new RGB(255,105,180); public static final RGB indianred = new RGB(205,92,92); public static final RGB indigo = new RGB(75,0,130); public static final RGB ivory = new RGB(255,255,240); public static final RGB khaki = new RGB(240,230,140); public static final RGB lavender = new RGB(230,230,250); public static final RGB lavenderblush = new RGB(255,240,245); public static final RGB lawngreen = new RGB(124,252,0); public static final RGB lemonchiffon = new RGB(255,250,205); public static final RGB lightblue = new RGB(173,216,230); public static final RGB lightcoral = new RGB(240,128,128); public static final RGB lightcyan = new RGB(224,255,255); public static final RGB lightgoldenrodyellow = new RGB(250,250,210); public static final RGB lightgrey = new RGB(211,211,211); public static final RGB lightgreen = new RGB(144,238,144); public static final RGB lightpink = new RGB(255,182,193); public static final RGB lightsalmon = new RGB(255,160,122); public static final RGB lightseagreen = new RGB(32,178,170); public static final RGB lightskyblue = new RGB(135,206,250); public static final RGB lightslategray = new RGB(119,136,153); public static final RGB lightsteelblue = new RGB(176,196,222); public static final RGB lightyellow = new RGB(255,255,224); public static final RGB lime = new RGB(0,255,0); public static final RGB limegreen = new RGB(50,205,50); public static final RGB linen = new RGB(250,240,230); public static final RGB magenta = new RGB(255,0,255); public static final RGB maroon = new RGB(128,0,0); public static final RGB mediumaquamarine = new RGB(102,205,170); public static final RGB mediumblue = new RGB(0,0,205); public static final RGB mediumorchid = new RGB(186,85,211); public static final RGB mediumpurple = new RGB(147,112,216); public static final RGB mediumseagreen = new RGB(60,179,113); public static final RGB mediumslateblue = new RGB(123,104,238); public static final RGB mediumspringgreen = new RGB(0,250,154); public static final RGB mediumturquoise = new RGB(72,209,204); public static final RGB mediumvioletred = new RGB(199,21,133); public static final RGB midnightblue = new RGB(25,25,112); public static final RGB mintcream = new RGB(245,255,250); public static final RGB mistyrose = new RGB(255,228,225); public static final RGB moccasin = new RGB(255,228,181); public static final RGB navajowhite = new RGB(255,222,173); public static final RGB navy = new RGB(0,0,128); public static final RGB oldlace = new RGB(253,245,230); public static final RGB olive = new RGB(128,128,0); public static final RGB olivedrab = new RGB(107,142,35); public static final RGB orange = new RGB(255,165,0); public static final RGB orangered = new RGB(255,69,0); public static final RGB orchid = new RGB(218,112,214); public static final RGB palegoldenrod = new RGB(238,232,170); public static final RGB palegreen = new RGB(152,251,152); public static final RGB paleturquoise = new RGB(175,238,238); public static final RGB palevioletred = new RGB(216,112,147); public static final RGB papayawhip = new RGB(255,239,213); public static final RGB peachpuff = new RGB(255,218,185); public static final RGB peru = new RGB(205,133,63); public static final RGB pink = new RGB(255,192,203); public static final RGB plum = new RGB(221,160,221); public static final RGB powderblue = new RGB(176,224,230); public static final RGB purple = new RGB(128,0,128); public static final RGB red = new RGB(255,0,0); public static final RGB rosybrown = new RGB(188,143,143); public static final RGB royalblue = new RGB(65,105,225); public static final RGB saddlebrown = new RGB(139,69,19); public static final RGB salmon = new RGB(250,128,114); public static final RGB sandybrown = new RGB(244,164,96); public static final RGB seagreen = new RGB(46,139,87); public static final RGB seashell = new RGB(255,245,238); public static final RGB sienna = new RGB(160,82,45); public static final RGB silver = new RGB(192,192,192); public static final RGB skyblue = new RGB(135,206,235); public static final RGB slateblue = new RGB(106,90,205); public static final RGB slategray = new RGB(112,128,144); public static final RGB snow = new RGB(255,250,250); public static final RGB springgreen = new RGB(0,255,127); public static final RGB steelblue = new RGB(70,130,180); public static final RGB tan = new RGB(210,180,140); public static final RGB teal = new RGB(0,128,128); public static final RGB thistle = new RGB(216,191,216); public static final RGB tomato = new RGB(255,99,71); public static final RGB turquoise = new RGB(64,224,208); public static final RGB violet = new RGB(238,130,238); public static final RGB wheat = new RGB(245,222,179); public static final RGB white = new RGB(255,255,255); public static final RGB whitesmoke = new RGB(245,245,245); public static final RGB yellow = new RGB(255,255,0); public static final RGB yellowgreen = new RGB(154,205,50); int r, g, b; int a = 255; public RGB(int red, int green, int blue) { this(red, green, blue, 255); } public RGB(int red, int green, int blue, int alpha) { this.r = red; this.g = green; this.b = blue; this.a = alpha; } public RGB(String rgb) { parse(rgb); } public int getAlpha() { return a; } public int getRed() { return r; } public int getGreen() { return g; } public int getBlue() { return b; } public float getOpacity() { return (float) (getAlpha() / 255.0); } public RGB alpha(float opacity) { return alpha((int)(255 * opacity)); } public RGB alpha(int alpha) { return new RGB(r, g, b, alpha); } /** * Creates a new color from hue, saturation, lightness (HSL) values. * * @param h The hue value. * @param s The saturation value. * @param l The lightness value. * * @return The new color. */ public static RGB fromHSL(double h, double s, double l) { double r, g, b; if (s == 0) { //achromatic r = g = b = l; } else { double q = l < 0.5 ? l * (1+s) : l + s - l * s; double p = 2 * l - q; r = hueTorgb(p, q, h + 1/3.0); g = hueTorgb(p, q, h); b = hueTorgb(p, q, h - 1/3.0); } return new RGB((int)Math.round(255*r), (int)Math.round(255*g), (int)Math.round(255*b)); } /** * Creates a new color from hue, saturation, lightness (HSL) values. * * @param hsl 3 element array of hue,saturation, and lightness values. * * @return The new color. */ public static RGB fromHSL(double[] hsl) { if (hsl.length != 3) { throw new IllegalArgumentException("input must be array of length 3"); } return fromHSL(hsl[0], hsl[1], hsl[2]); } static double hueTorgb(double p, double q, double t) { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1/6.0) { return p + (q - p) * 6 * t; } if (t < 1/2.0) { return q; } if (t < 2/3.0) { return p + (q - p) * (2/3.0 - t) * 6; } return p; } /** * The hue, saturation, lightness (HSL) representation of the color. */ public double[] hsl() { double r = this.r / 255.0; double g = this.g / 255.0; double b = this.b / 255.0; double lo = Math.min(Math.min(r,g), b); double hi = Math.max(Math.max(r,g), b); double h,s,l; h = s = l = (lo + hi) / 2.0; if (lo == hi) { // achromatic h = s = 0;; } else { double delta = hi - lo; s = l > 0.5 ? delta / (2-hi-lo) : delta / (hi+lo); if (hi == r) { h = (g-b)/delta + (g < b ? 6 : 0); } else if (hi == g) { h = (b-r) / delta + 2; } else { h = (r-g) / delta + 4; } h /= 6.0; } return new double[]{h,s,l}; } /** * Returns the interpolated color value between this color and the specified color. * * @param other The other color. * @param amt Number between 0 and 1 inclusive. * * @return The interpolated value. */ public RGB interpolate(RGB other, double amt) { if (amt < 0 || amt > 1) { throw new IllegalArgumentException("amount must be in range [0,1]"); } double[] hsl1 = hsl(); double[] hsl2 = other.hsl(); double[] dhsl = sub(hsl2, hsl1, hsl2); return fromHSL(doInterpolate(hsl1, dhsl, amt, new double[3])); } /** * Interpolates a number of RGB values between this color and the specified color. * * @param other The color to interpolate to. * @param n The number of values to interpolate. * @param method The interpolation method. * * @return A set of <tt>n+1</tt> RGB values. */ public List<RGB> interpolate(RGB other, int n, Interpolate.Method method) { double[] hsl1 = hsl(); double[] hsl2 = other.hsl(); double[] dhsl = sub(hsl2, hsl1, hsl2); Iterator<Double> alphas = Interpolate.interpolate(a, other.a, n, method).iterator(); List<RGB> vals = new ArrayList<RGB>(n+1); double[] hsl = new double[3]; for (Double d : Interpolate.interpolate(0, n, n, method)) { doInterpolate(hsl1, dhsl, d/((float)n), hsl); vals.add(fromHSL(hsl).alpha(alphas.next().intValue())); } return vals; } double[] doInterpolate(double[] hsl, double[] dhsl, double amt, double[] result) { result[0] = hsl[0] + amt * dhsl[0]; result[1] = hsl[1] + amt * dhsl[1]; result[2] = hsl[2] + amt * dhsl[2]; return result; } double[] sub(double[] d1, double[] d2, double[] res) { for (int i = 0; i < d1.length; i++) { res[i] = d1[i] - d2[i]; } return res; } void parse(String rgb) { if (initFromName(rgb)) { return; } StringBuilder sb = new StringBuilder(rgb); if (rgb.startsWith("#")) { sb.delete(0, 1); } if (sb.length() == 3) { sb.insert(2, sb.charAt(2)); sb.insert(1, sb.charAt(1)); sb.insert(0, sb.charAt(0)); } if (sb.length() == 8) { a = Integer.parseInt(sb.substring(0,2), 16); sb.delete(0, 2); } if (sb.length() != 6) { throw new IllegalArgumentException("Unable to parse " + rgb + " as RGB"); } r = Integer.parseInt(sb.substring(0,2), 16); g = Integer.parseInt(sb.substring(2,4), 16); b = Integer.parseInt(sb.substring(4,6), 16); } boolean initFromName(String name) { try { Field f = getClass().getDeclaredField(name); if (Modifier.isStatic(f.getModifiers())) { Object obj = f.get(null); if (obj instanceof RGB) { RGB rgb = (RGB) obj; this.r = rgb.r; this.g = rgb.g; this.b = rgb.b; this.a = rgb.a; return true; } } } catch (Throwable t) { } return false; } /** * The hex rgb string of this color. * * @return String of the format: <tt>#rrggbb</tt> */ public String rgbhex() { return String.format("#%02x%02x%02x", r, g, b); } /** * The hex rgba string of this color. * * @return String of the format: <tt>#rrggbbaa</tt> */ public String rgbahex() { return String.format("#%02x%02x%02x%02x", r, g, b, a); } @Override public String toString() { return new StringBuilder("RGB(").append(r).append(",").append(g).append(",").append(b) .append(",").append(a).append(")").toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; result = prime * result + g; result = prime * result + r; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RGB other = (RGB) obj; if (a != other.a) return false; if (b != other.b) return false; if (g != other.g) return false; if (r != other.r) return false; return true; } }
core/src/main/java/org/jeo/map/RGB.java
/* Copyright 2013 The jeo project. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jeo.map; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jeo.util.Interpolate; /** * A color in RGBA color space. * * @author Justin Deoliveira, OpenGeo */ public class RGB { public static final RGB aliceblue = new RGB(240,248,255); public static final RGB antiquewhite = new RGB(250,235,215); public static final RGB aqua = new RGB(0,255,255); public static final RGB aquamarine = new RGB(127,255,212); public static final RGB azure = new RGB(240,255,255); public static final RGB beige = new RGB(245,245,220); public static final RGB bisque = new RGB(255,228,196); public static final RGB black = new RGB(0,0,0); public static final RGB blanchedalmond = new RGB(255,235,205); public static final RGB blue = new RGB(0,0,255); public static final RGB blueviolet = new RGB(138,43,226); public static final RGB brown = new RGB(165,42,42); public static final RGB burlywood = new RGB(222,184,135); public static final RGB cadetblue = new RGB(95,158,160); public static final RGB chartreuse = new RGB(127,255,0); public static final RGB chocolate = new RGB(210,105,30); public static final RGB coral = new RGB(255,127,80); public static final RGB cornflowerblue = new RGB(100,149,237); public static final RGB cornsilk = new RGB(255,248,220); public static final RGB crimson = new RGB(220,20,60); public static final RGB cyan = new RGB(0,255,255); public static final RGB darkblue = new RGB(0,0,139); public static final RGB darkcyan = new RGB(0,139,139); public static final RGB darkgoldenrod = new RGB(184,134,11); public static final RGB darkgray = new RGB(169,169,169); public static final RGB darkgreen = new RGB(0,100,0); public static final RGB darkkhaki = new RGB(189,183,107); public static final RGB darkmagenta = new RGB(139,0,139); public static final RGB darkolivegreen = new RGB(85,107,47); public static final RGB darkorange = new RGB(255,140,0); public static final RGB darkorchid = new RGB(153,50,204); public static final RGB darkred = new RGB(139,0,0); public static final RGB darksalmon = new RGB(233,150,122); public static final RGB darkseagreen = new RGB(143,188,143); public static final RGB darkslateblue = new RGB(72,61,139); public static final RGB darkslategray = new RGB(47,79,79); public static final RGB darkturquoise = new RGB(0,206,209); public static final RGB darkviolet = new RGB(148,0,211); public static final RGB deeppink = new RGB(255,20,147); public static final RGB deepskyblue = new RGB(0,191,255); public static final RGB dimgray = new RGB(105,105,105); public static final RGB dodgerblue = new RGB(30,144,255); public static final RGB firebrick = new RGB(178,34,34); public static final RGB floralwhite = new RGB(255,250,240); public static final RGB forestgreen = new RGB(34,139,34); public static final RGB fuchsia = new RGB(255,0,255); public static final RGB gainsboro = new RGB(220,220,220); public static final RGB ghostwhite = new RGB(248,248,255); public static final RGB gold = new RGB(255,215,0); public static final RGB goldenrod = new RGB(218,165,32); public static final RGB gray = new RGB(128,128,128); public static final RGB green = new RGB(0,128,0); public static final RGB greenyellow = new RGB(173,255,47); public static final RGB grey = new RGB(84,84,84); public static final RGB honeydew = new RGB(240,255,240); public static final RGB hotpink = new RGB(255,105,180); public static final RGB indianred = new RGB(205,92,92); public static final RGB indigo = new RGB(75,0,130); public static final RGB ivory = new RGB(255,255,240); public static final RGB khaki = new RGB(240,230,140); public static final RGB lavender = new RGB(230,230,250); public static final RGB lavenderblush = new RGB(255,240,245); public static final RGB lawngreen = new RGB(124,252,0); public static final RGB lemonchiffon = new RGB(255,250,205); public static final RGB lightblue = new RGB(173,216,230); public static final RGB lightcoral = new RGB(240,128,128); public static final RGB lightcyan = new RGB(224,255,255); public static final RGB lightgoldenrodyellow = new RGB(250,250,210); public static final RGB lightgrey = new RGB(211,211,211); public static final RGB lightgreen = new RGB(144,238,144); public static final RGB lightpink = new RGB(255,182,193); public static final RGB lightsalmon = new RGB(255,160,122); public static final RGB lightseagreen = new RGB(32,178,170); public static final RGB lightskyblue = new RGB(135,206,250); public static final RGB lightslategray = new RGB(119,136,153); public static final RGB lightsteelblue = new RGB(176,196,222); public static final RGB lightyellow = new RGB(255,255,224); public static final RGB lime = new RGB(0,255,0); public static final RGB limegreen = new RGB(50,205,50); public static final RGB linen = new RGB(250,240,230); public static final RGB magenta = new RGB(255,0,255); public static final RGB maroon = new RGB(128,0,0); public static final RGB mediumaquamarine = new RGB(102,205,170); public static final RGB mediumblue = new RGB(0,0,205); public static final RGB mediumorchid = new RGB(186,85,211); public static final RGB mediumpurple = new RGB(147,112,216); public static final RGB mediumseagreen = new RGB(60,179,113); public static final RGB mediumslateblue = new RGB(123,104,238); public static final RGB mediumspringgreen = new RGB(0,250,154); public static final RGB mediumturquoise = new RGB(72,209,204); public static final RGB mediumvioletred = new RGB(199,21,133); public static final RGB midnightblue = new RGB(25,25,112); public static final RGB mintcream = new RGB(245,255,250); public static final RGB mistyrose = new RGB(255,228,225); public static final RGB moccasin = new RGB(255,228,181); public static final RGB navajowhite = new RGB(255,222,173); public static final RGB navy = new RGB(0,0,128); public static final RGB oldlace = new RGB(253,245,230); public static final RGB olive = new RGB(128,128,0); public static final RGB olivedrab = new RGB(107,142,35); public static final RGB orange = new RGB(255,165,0); public static final RGB orangered = new RGB(255,69,0); public static final RGB orchid = new RGB(218,112,214); public static final RGB palegoldenrod = new RGB(238,232,170); public static final RGB palegreen = new RGB(152,251,152); public static final RGB paleturquoise = new RGB(175,238,238); public static final RGB palevioletred = new RGB(216,112,147); public static final RGB papayawhip = new RGB(255,239,213); public static final RGB peachpuff = new RGB(255,218,185); public static final RGB peru = new RGB(205,133,63); public static final RGB pink = new RGB(255,192,203); public static final RGB plum = new RGB(221,160,221); public static final RGB powderblue = new RGB(176,224,230); public static final RGB purple = new RGB(128,0,128); public static final RGB red = new RGB(255,0,0); public static final RGB rosybrown = new RGB(188,143,143); public static final RGB royalblue = new RGB(65,105,225); public static final RGB saddlebrown = new RGB(139,69,19); public static final RGB salmon = new RGB(250,128,114); public static final RGB sandybrown = new RGB(244,164,96); public static final RGB seagreen = new RGB(46,139,87); public static final RGB seashell = new RGB(255,245,238); public static final RGB sienna = new RGB(160,82,45); public static final RGB silver = new RGB(192,192,192); public static final RGB skyblue = new RGB(135,206,235); public static final RGB slateblue = new RGB(106,90,205); public static final RGB slategray = new RGB(112,128,144); public static final RGB snow = new RGB(255,250,250); public static final RGB springgreen = new RGB(0,255,127); public static final RGB steelblue = new RGB(70,130,180); public static final RGB tan = new RGB(210,180,140); public static final RGB teal = new RGB(0,128,128); public static final RGB thistle = new RGB(216,191,216); public static final RGB tomato = new RGB(255,99,71); public static final RGB turquoise = new RGB(64,224,208); public static final RGB violet = new RGB(238,130,238); public static final RGB wheat = new RGB(245,222,179); public static final RGB white = new RGB(255,255,255); public static final RGB whitesmoke = new RGB(245,245,245); public static final RGB yellow = new RGB(255,255,0); public static final RGB yellowgreen = new RGB(154,205,50); int r, g, b; int a = 255; public RGB(int red, int green, int blue) { this(red, green, blue, 255); } public RGB(int red, int green, int blue, int alpha) { this.r = red; this.g = green; this.b = blue; this.a = alpha; } public RGB(String rgb) { parse(rgb); } public int getAlpha() { return a; } public int getRed() { return r; } public int getGreen() { return g; } public int getBlue() { return b; } public float getOpacity() { return (float) (getAlpha() / 255.0); } public RGB alpha(float opacity) { return alpha((int)(255 * opacity)); } public RGB alpha(int alpha) { return new RGB(r, g, b, alpha); } /** * Creates a new color from hue, saturation, lightness (HSL) values. * * @param h The hue value. * @param s The saturation value. * @param l The lightness value. * * @return The new color. */ public static RGB fromHSL(double h, double s, double l) { double r, g, b; if (s == 0) { //achromatic r = g = b = l; } else { double q = l < 0.5 ? l * (1+s) : l + s - l * s; double p = 2 * l - q; r = hueTorgb(p, q, h + 1/3.0); g = hueTorgb(p, q, h); b = hueTorgb(p, q, h - 1/3.0); } return new RGB((int)Math.round(255*r), (int)Math.round(255*g), (int)Math.round(255*b)); } static double hueTorgb(double p, double q, double t) { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1/6.0) { return p + (q - p) * 6 * t; } if (t < 1/2.0) { return q; } if (t < 2/3.0) { return p + (q - p) * (2/3.0 - t) * 6; } return p; } /** * The hue, saturation, lightness (HSL) representation of the color. */ public double[] hsl() { double r = this.r / 255.0; double g = this.g / 255.0; double b = this.b / 255.0; double lo = Math.min(Math.min(r,g), b); double hi = Math.max(Math.max(r,g), b); double h,s,l; h = s = l = (lo + hi) / 2.0; if (lo == hi) { // achromatic h = s = 0;; } else { double delta = hi - lo; s = l > 0.5 ? delta / (2-hi-lo) : delta / (hi+lo); if (hi == r) { h = (g-b)/delta + (g < b ? 6 : 0); } else if (hi == g) { h = (b-r) / delta + 2; } else { h = (r-g) / delta + 4; } h /= 6.0; } return new double[]{h,s,l}; } /** * Interpolates a number of RGB values between this color and the specified color. * * @param other The color to interpolate to. * @param n The number of values to interpolate. * @param method The interpolation method. * * @return A set of <tt>n+1</tt> RGB values. */ public List<RGB> interpolate(RGB other, int n, Interpolate.Method method) { double[] hsl1 = hsl(); double[] hsl2 = other.hsl(); double[] dhsl = new double[3]; for (int i = 0; i < dhsl.length; i++) { dhsl[i] = hsl2[i] - hsl1[i]; } Iterator<Double> alphas = Interpolate.interpolate(a, other.a, n, method).iterator(); List<RGB> vals = new ArrayList<RGB>(n+1); for (Double d : Interpolate.interpolate(0, n, n, method)) { double h = hsl1[0] + (d/((float)n)) * dhsl[0]; double s = hsl1[1] + (d/((float)n)) * dhsl[1]; double l = hsl1[2] + (d/((float)n)) * dhsl[2]; vals.add(fromHSL(h, s, l).alpha(alphas.next().intValue())); } return vals; } void parse(String rgb) { if (initFromName(rgb)) { return; } StringBuilder sb = new StringBuilder(rgb); if (rgb.startsWith("#")) { sb.delete(0, 1); } if (sb.length() == 3) { sb.insert(2, sb.charAt(2)); sb.insert(1, sb.charAt(1)); sb.insert(0, sb.charAt(0)); } if (sb.length() == 8) { a = Integer.parseInt(sb.substring(0,2), 16); sb.delete(0, 2); } if (sb.length() != 6) { throw new IllegalArgumentException("Unable to parse " + rgb + " as RGB"); } r = Integer.parseInt(sb.substring(0,2), 16); g = Integer.parseInt(sb.substring(2,4), 16); b = Integer.parseInt(sb.substring(4,6), 16); } boolean initFromName(String name) { try { Field f = getClass().getDeclaredField(name); if (Modifier.isStatic(f.getModifiers())) { Object obj = f.get(null); if (obj instanceof RGB) { RGB rgb = (RGB) obj; this.r = rgb.r; this.g = rgb.g; this.b = rgb.b; this.a = rgb.a; return true; } } } catch (Throwable t) { } return false; } /** * The hex rgb string of this color. * * @return String of the format: <tt>#rrggbb</tt> */ public String rgbhex() { return String.format("#%02x%02x%02x", r, g, b); } /** * The hex rgba string of this color. * * @return String of the format: <tt>#rrggbbaa</tt> */ public String rgbahex() { return String.format("#%02x%02x%02x%02x", r, g, b, a); } @Override public String toString() { return new StringBuilder("RGB(").append(r).append(",").append(g).append(",").append(b) .append(",").append(a).append(")").toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; result = prime * result + g; result = prime * result + r; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RGB other = (RGB) obj; if (a != other.a) return false; if (b != other.b) return false; if (g != other.g) return false; if (r != other.r) return false; return true; } }
Added interpolate method to RGB for interpolating single color value.
core/src/main/java/org/jeo/map/RGB.java
Added interpolate method to RGB for interpolating single color value.
<ide><path>ore/src/main/java/org/jeo/map/RGB.java <ide> return new RGB((int)Math.round(255*r), (int)Math.round(255*g), (int)Math.round(255*b)); <ide> } <ide> <add> /** <add> * Creates a new color from hue, saturation, lightness (HSL) values. <add> * <add> * @param hsl 3 element array of hue,saturation, and lightness values. <add> * <add> * @return The new color. <add> */ <add> public static RGB fromHSL(double[] hsl) { <add> if (hsl.length != 3) { <add> throw new IllegalArgumentException("input must be array of length 3"); <add> } <add> <add> return fromHSL(hsl[0], hsl[1], hsl[2]); <add> } <add> <ide> static double hueTorgb(double p, double q, double t) { <ide> if (t < 0) { <ide> t += 1; <ide> } <ide> <ide> /** <add> * Returns the interpolated color value between this color and the specified color. <add> * <add> * @param other The other color. <add> * @param amt Number between 0 and 1 inclusive. <add> * <add> * @return The interpolated value. <add> */ <add> public RGB interpolate(RGB other, double amt) { <add> if (amt < 0 || amt > 1) { <add> throw new IllegalArgumentException("amount must be in range [0,1]"); <add> } <add> <add> double[] hsl1 = hsl(); <add> double[] hsl2 = other.hsl(); <add> double[] dhsl = sub(hsl2, hsl1, hsl2); <add> <add> return fromHSL(doInterpolate(hsl1, dhsl, amt, new double[3])); <add> } <add> <add> /** <ide> * Interpolates a number of RGB values between this color and the specified color. <ide> * <ide> * @param other The color to interpolate to. <ide> public List<RGB> interpolate(RGB other, int n, Interpolate.Method method) { <ide> double[] hsl1 = hsl(); <ide> double[] hsl2 = other.hsl(); <del> double[] dhsl = new double[3]; <del> for (int i = 0; i < dhsl.length; i++) { <del> dhsl[i] = hsl2[i] - hsl1[i]; <del> } <add> double[] dhsl = sub(hsl2, hsl1, hsl2); <ide> <ide> Iterator<Double> alphas = Interpolate.interpolate(a, other.a, n, method).iterator(); <ide> List<RGB> vals = new ArrayList<RGB>(n+1); <add> double[] hsl = new double[3]; <ide> for (Double d : Interpolate.interpolate(0, n, n, method)) { <del> double h = hsl1[0] + (d/((float)n)) * dhsl[0]; <del> double s = hsl1[1] + (d/((float)n)) * dhsl[1]; <del> double l = hsl1[2] + (d/((float)n)) * dhsl[2]; <del> <del> vals.add(fromHSL(h, s, l).alpha(alphas.next().intValue())); <add> doInterpolate(hsl1, dhsl, d/((float)n), hsl); <add> vals.add(fromHSL(hsl).alpha(alphas.next().intValue())); <ide> } <ide> <ide> return vals; <add> } <add> <add> double[] doInterpolate(double[] hsl, double[] dhsl, double amt, double[] result) { <add> result[0] = hsl[0] + amt * dhsl[0]; <add> result[1] = hsl[1] + amt * dhsl[1]; <add> result[2] = hsl[2] + amt * dhsl[2]; <add> return result; <add> } <add> <add> double[] sub(double[] d1, double[] d2, double[] res) { <add> for (int i = 0; i < d1.length; i++) { <add> res[i] = d1[i] - d2[i]; <add> } <add> return res; <ide> } <ide> <ide> void parse(String rgb) {
Java
mit
0678fa33b7291e8cf712615e677878dd6dbfdf9c
0
rafaelazd/food-lovers,rafaelazd/food-lovers,rafaelazd/food-lovers,rafaelazd/food-lovers
package foodlovers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import foodlovers.storage.StorageProperties; import foodlovers.storage.StorageService; @SpringBootApplication @EnableConfigurationProperties(StorageProperties.class) public class FoodLoversApplication { private static final Logger log = LoggerFactory.getLogger(FoodLoversApplication.class); public static void main(String[] args) { SpringApplication.run(FoodLoversApplication.class, args); } @Bean public CommandLineRunner demo(UsuariosRepository usuariosRepository, PreferenciasRepository preferenciasRepository, StorageService storageService) { return (args) -> { log.info("Antes de criar os registros"); usuariosRepository.save(new Usuario("Kali", "Meinar", "[email protected]", 19, "Homens e Mulheres", "Feminino", "kardashianlostsis", "kalimeinar", "Cinema, arte e fotografia <3","Campinas, São Paulo", "kali.meinar", "(19)99726-9062", "kalim_", "", "kardashianlostsis")); usuariosRepository.save(new Usuario("Mateus", "Takeda", "[email protected]", 21, "Homens", "Masculino", "_mateustakeda", "mateustakeda", "'O que é melhor - nascer bom, ou superar sua natureza maligna através de grande esforço?' - Paarthurnax","Joinville, Santa Catarina", "mateustakeda67", "(47)98890-3627", "mateustk", "matheustakeda", "")); usuariosRepository.save(new Usuario("Thea", "Queen", "[email protected]", 20, "Homens e Mulheres", "Feminino", "theaqueen", "theaqueen", "I'm sorry if I turned out some major disappointment","Curitiba, Paraná", "thea.queen", "(42)99738-2384", "theaqn", "theQueen", "theQueen")); log.info("Depois de criar os registros"); log.info("Antes de criar os registros"); preferenciasRepository.save(new Preferencias("Hot Dog", "/static/img/hotdogico.png")); preferenciasRepository.save(new Preferencias("Bolo", "/static/img/boloico.png")); preferenciasRepository.save(new Preferencias("Sorvete", "/static/img/sorveteico.png")); preferenciasRepository.save(new Preferencias("Batata Frita", "/static/img/batataico.png")); preferenciasRepository.save(new Preferencias("Cafe", "/static/img/cafeico.png")); preferenciasRepository.save(new Preferencias("Churrasco", "/static/img/churrascoico.png")); preferenciasRepository.save(new Preferencias("Sanduiche", "/static/img/icosand.png")); preferenciasRepository.save(new Preferencias("Macarrao", "/static/img/macarraoico.png")); preferenciasRepository.save(new Preferencias("Nachos", "/static/img/nachosico.png")); preferenciasRepository.save(new Preferencias("Panquecas", "/static/img/panquecasico.png")); preferenciasRepository.save(new Preferencias("Pizza", "/static/img/pizzaico.png")); preferenciasRepository.save(new Preferencias("Salada", "/static/img/saladaico.png")); preferenciasRepository.save(new Preferencias("Sopa", "/static/img/sopaico.png")); preferenciasRepository.save(new Preferencias("Sushi", "/static/img/sushico.png")); preferenciasRepository.save(new Preferencias("Tacos", "/static/img/tacosico.png")); log.info("Depois de criar os registros"); storageService.deleteAll(); storageService.demo(); }; } }
web-server/src/main/java/foodlovers/FoodLoversApplication.java
package foodlovers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import foodlovers.storage.StorageProperties; import foodlovers.storage.StorageService; @SpringBootApplication @EnableConfigurationProperties(StorageProperties.class) public class FoodLoversApplication { private static final Logger log = LoggerFactory.getLogger(FoodLoversApplication.class); public static void main(String[] args) { SpringApplication.run(FoodLoversApplication.class, args); } @Bean public CommandLineRunner demo(UsuariosRepository usuariosRepository, PreferenciasRepository preferenciasRepository, StorageService storageService) { return (args) -> { log.info("Antes de criar os registros"); usuariosRepository.save(new Usuario("Kali", "Meinar", "[email protected]", 19, "Homens e Mulheres", "Feminino", "kardashianlostsis", "kalimeinar", "Cinema, arte e fotografia <3","Campinas, São Paulo", "kali.meinar", "(19)99726-9062", "kalim_", "", "kardashianlostsis")); usuariosRepository.save(new Usuario("Mateus", "Takeda", "[email protected]", 21, "Homens", "Masculino", "_mateustakeda", "mateustakeda", "'O que é melhor - nascer bom, ou superar sua natureza maligna através de grande esforço?' - Paarthurnax","Joinville, Santa Catarina", "mateustakeda67", "(47)98890-3627", "mateustk", "matheustakeda", "")); usuariosRepository.save(new Usuario("Thea", "Queen", "[email protected]", 20, "Homens e Mulheres", "Feminino", "theaqueen", "theaqueen", "I'm sorry if I turned out some major disappointment","Curitiba, Paraná", "thea.queen", "(42)99738-2384", "theaqn", "theQueen", "theQueen")); log.info("Depois de criar os registros"); log.info("Antes de criar os registros"); preferenciasRepository.save(new Preferencias("Hot Dog")); preferenciasRepository.save(new Preferencias("Bolo")); preferenciasRepository.save(new Preferencias("Sorvete")); log.info("Depois de criar os registros"); storageService.deleteAll(); storageService.demo(); }; } }
Adicionando as preferências no repositório Adicionando todas as preferências no repositório
web-server/src/main/java/foodlovers/FoodLoversApplication.java
Adicionando as preferências no repositório
<ide><path>eb-server/src/main/java/foodlovers/FoodLoversApplication.java <ide> usuariosRepository.save(new Usuario("Kali", "Meinar", "[email protected]", 19, "Homens e Mulheres", "Feminino", "kardashianlostsis", "kalimeinar", "Cinema, arte e fotografia <3","Campinas, São Paulo", "kali.meinar", "(19)99726-9062", "kalim_", "", "kardashianlostsis")); <ide> usuariosRepository.save(new Usuario("Mateus", "Takeda", "[email protected]", 21, "Homens", "Masculino", "_mateustakeda", "mateustakeda", "'O que é melhor - nascer bom, ou superar sua natureza maligna através de grande esforço?' - Paarthurnax","Joinville, Santa Catarina", "mateustakeda67", "(47)98890-3627", "mateustk", "matheustakeda", "")); <ide> usuariosRepository.save(new Usuario("Thea", "Queen", "[email protected]", 20, "Homens e Mulheres", "Feminino", "theaqueen", "theaqueen", "I'm sorry if I turned out some major disappointment","Curitiba, Paraná", "thea.queen", "(42)99738-2384", "theaqn", "theQueen", "theQueen")); <add> <ide> log.info("Depois de criar os registros"); <ide> <ide> <ide> log.info("Antes de criar os registros"); <del> preferenciasRepository.save(new Preferencias("Hot Dog")); <del> preferenciasRepository.save(new Preferencias("Bolo")); <del> preferenciasRepository.save(new Preferencias("Sorvete")); <add> preferenciasRepository.save(new Preferencias("Hot Dog", "/static/img/hotdogico.png")); <add> preferenciasRepository.save(new Preferencias("Bolo", "/static/img/boloico.png")); <add> preferenciasRepository.save(new Preferencias("Sorvete", "/static/img/sorveteico.png")); <add> preferenciasRepository.save(new Preferencias("Batata Frita", "/static/img/batataico.png")); <add> preferenciasRepository.save(new Preferencias("Cafe", "/static/img/cafeico.png")); <add> preferenciasRepository.save(new Preferencias("Churrasco", "/static/img/churrascoico.png")); <add> preferenciasRepository.save(new Preferencias("Sanduiche", "/static/img/icosand.png")); <add> preferenciasRepository.save(new Preferencias("Macarrao", "/static/img/macarraoico.png")); <add> preferenciasRepository.save(new Preferencias("Nachos", "/static/img/nachosico.png")); <add> preferenciasRepository.save(new Preferencias("Panquecas", "/static/img/panquecasico.png")); <add> preferenciasRepository.save(new Preferencias("Pizza", "/static/img/pizzaico.png")); <add> preferenciasRepository.save(new Preferencias("Salada", "/static/img/saladaico.png")); <add> preferenciasRepository.save(new Preferencias("Sopa", "/static/img/sopaico.png")); <add> preferenciasRepository.save(new Preferencias("Sushi", "/static/img/sushico.png")); <add> preferenciasRepository.save(new Preferencias("Tacos", "/static/img/tacosico.png")); <ide> log.info("Depois de criar os registros"); <ide> <ide> storageService.deleteAll();
Java
mit
ab5566378b613cbef2bdb7d149c112903a7b7910
0
spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror
// Copyright (c) 2003, 2009 Per M.A. Bothner. // This is free software; for terms and warranty disclaimer see ./COPYING. package gnu.expr; import gnu.bytecode.*; import gnu.mapping.*; import gnu.text.SourceLocator; /** * The static information associated with a local variable binding. * @author Per Bothner * * These are the kinds of Declaration we use: * * A local variable that is not captured by an inner lambda is stored * in a Java local variables slot (register). The predicate isSimple () * is true, and offset is the number of the local variable slot. * * If a local variable is captured by an inner lambda, the * variable is stored in a field of the LambdaExp's heapFrame variable. * (The latter declaration has isSimple and isArtificial true.) * The Declaration's field specifies the Field used. * * If a function takes a fixed number of parameters, at most four, * then the arguments are passed in Java registers 1..4. * If a parameter is not captured by an inner lambda, the parameter * has the flags isSimple and isParameter true. * * If a function takes more than 4 or a variable number of parameters, * the arguments are passed in an array (using the applyN virtual method). * This array is referenced by the argsArray declaration, which has * isSimple(), isParameter(), and isArtificial() true, and its offset is 1. * The parameters are copied into the program-named variables by the * procedure prologue, so the parameters henceforth act like local variables. */ public class Declaration implements SourceLocator { static int counter; /** Unique id number, to ease print-outs and debugging. * If negative, a code to specify a builtin function. */ protected int id = ++counter; /** The name of the new variable, either an interned String or a Symbol. * This is the source-level (non-mangled) name. */ Object symbol; public void setCode (int code) { if (code >= 0) throw new Error("code must be negative"); this.id = code; } public int getCode () { return id; } public ScopeExp context; /** The type of the value of this Declaration. * It is null if the type is un-specified and not yet inferred. * Will get set implicitly by getType, to avoid inconsistencies. */ protected Type type; protected Expression typeExp; public final Expression getTypeExp() { if (typeExp == null) setType(Type.objectType); return typeExp; } public final Type getType() { if (type == null) setType(Type.objectType); return type; } public final void setType(Type type) { this.type = type; if (var != null) var.setType(type); typeExp = QuoteExp.getInstance(type); } public final void setTypeExp (Expression typeExp) { this.typeExp = typeExp; Type t = null; if (typeExp instanceof TypeValue) t = ((TypeValue) typeExp).getImplementationType(); else t = Language.getDefaultLanguage().getTypeFor(typeExp, false); if (t == null) t = Type.pointer_type; this.type = t; if (var != null) var.setType(t); } public final String getName() { return symbol == null ? null : symbol instanceof Symbol ? ((Symbol) symbol).getName() : symbol.toString(); } public final void setName(Object symbol) { this.symbol = symbol; } public final Object getSymbol() { return symbol; } public final void setSymbol(Object symbol) { this.symbol = symbol; } /* Declarations in a ScopeExp are linked together in a linked list. */ Declaration next; public final Declaration nextDecl() { return next; } public final void setNext(Declaration next) { this.next = next; } /** Index in evalFrame for this scope, if interpreting. */ int evalIndex; Variable var; public Variable getVariable() { return var; } public final boolean isSimple() { return (flags & IS_SIMPLE) != 0; } public final void setSimple(boolean b) { setFlag(b, IS_SIMPLE); if (var != null && ! var.isParameter()) var.setSimple(b); } public final void setSyntax () { setSimple(false); setFlag(IS_CONSTANT|IS_SYNTAX|EARLY_INIT); } /** Return the ScopeExp that contains (declares) this Declaration. */ public final ScopeExp getContext() { return context; } /** Used to link Declarations in a LambdaExp's capturedVars list. */ Declaration nextCapturedVar; /** If non-null, field is relative to base. * If IS_FLUID, base points to IS_UNKNOWN Symbol. */ public Declaration base; public Field field; /** If this is a field in some object, load a reference to that object. */ void loadOwningObject (Declaration owner, Compilation comp) { if (owner == null) owner = base; if (owner != null) owner.load(null, 0, comp, Target.pushObject); else getContext().currentLambda().loadHeapFrame(comp); } public void load (AccessExp access, int flags, Compilation comp, Target target) { if (target instanceof IgnoreTarget) return; Declaration owner = access == null ? null : access.contextDecl(); if (isAlias() && value instanceof ReferenceExp) { ReferenceExp rexp = (ReferenceExp) value; Declaration orig = rexp.binding; if (orig != null && ((flags & ReferenceExp.DONT_DEREFERENCE) == 0 || orig.isIndirectBinding()) && (owner == null || ! orig.needsContext())) { orig.load(rexp, flags, comp, target); return; } } CodeAttr code = comp.getCode(); Type rtype = getType(); if (! isIndirectBinding() && (flags & ReferenceExp.DONT_DEREFERENCE) != 0) { if (field == null) throw new Error("internal error: cannot take location of "+this); Method meth; ClassType ltype; boolean immediate = comp.immediate; if (field.getStaticFlag()) { ltype = ClassType.make("gnu.kawa.reflect.StaticFieldLocation"); meth = ltype.getDeclaredMethod("make", immediate ? 1 : 2); } else { ltype = ClassType.make("gnu.kawa.reflect.FieldLocation"); meth = ltype.getDeclaredMethod("make", immediate ? 2 : 3); loadOwningObject(owner, comp); } if (immediate) comp.compileConstant(this); else { comp.compileConstant(field.getDeclaringClass().getName()); comp.compileConstant(field.getName()); } code.emitInvokeStatic(meth); rtype = ltype; } else { Object val; if (field != null) { comp.usedClass(field.getDeclaringClass()); comp.usedClass(field.getType()); if (! field.getStaticFlag()) { loadOwningObject(owner, comp); code.emitGetField(field); } else code.emitGetStatic(field); } else if (isIndirectBinding() && comp.immediate && getVariable() == null) { // This is a bit of a kludge. See comment in ModuleExp.evalModule. Environment env = Environment.getCurrent(); Symbol sym = symbol instanceof Symbol ? (Symbol) symbol : env.getSymbol(symbol.toString()); Object property = null; if (isProcedureDecl() && comp.getLanguage().hasSeparateFunctionNamespace()) property = EnvironmentKey.FUNCTION; gnu.mapping.Location loc = env.getLocation(sym, property); comp.compileConstant(loc, Target.pushValue(Compilation.typeLocation)); } else if (comp.immediate && (val = getConstantValue()) != null) { comp.compileConstant(val, target); return; } else if (value != QuoteExp.undefined_exp && ignorable()) { value.compile(comp, target); return; } else { Variable var = getVariable(); ClassExp cl; if (context instanceof ClassExp && var == null && ! getFlag(PROCEDURE) && (cl = (ClassExp) context).isMakingClassPair()) { String getName = ClassExp.slotToMethodName("get", getName()); Method getter = cl.type.getDeclaredMethod(getName, 0); cl.loadHeapFrame(comp); code.emitInvoke(getter); } else { if (var == null) var = allocateVariable(code); code.emitLoad(var); } } if (isIndirectBinding() && (flags & ReferenceExp.DONT_DEREFERENCE) == 0) { String filename; int line; if (access != null && (filename = access.getFileName()) != null && (line = access.getLineNumber()) > 0) { // Wrap call to Location.get by a catch handler that // calls setLine on the UnboundLocationException. ClassType typeUnboundLocationException = ClassType.make("gnu.mapping.UnboundLocationException"); // See comment in CheckedTarget.emitCheckedCoerce. boolean isInTry = code.isInTry(); int column = access.getColumnNumber(); Label startTry = new Label(code); startTry.define(code); code.emitInvokeVirtual(Compilation.getLocationMethod); Label endTry = new Label(code); endTry.define(code); Label endLabel = new Label(code); endLabel.setTypes(code); if (isInTry) code.emitGoto(endLabel); else code.setUnreachable(); int fragment_cookie = 0; if (! isInTry) fragment_cookie = code.beginFragment(endLabel); code.addHandler(startTry, endTry, typeUnboundLocationException); code.emitDup(typeUnboundLocationException); code.emitPushString(filename); code.emitPushInt(line); code.emitPushInt(column); code.emitInvokeVirtual(typeUnboundLocationException .getDeclaredMethod("setLine", 3)); code.emitThrow(); if (isInTry) endLabel.define(code); else code.endFragment(fragment_cookie); } else code.emitInvokeVirtual(Compilation.getLocationMethod); rtype = Type.pointer_type; } } target.compileFromStack(comp, rtype); } /* Compile code to store a value (which must already be on the stack) into this variable. */ public void compileStore (Compilation comp) { gnu.bytecode.CodeAttr code = comp.getCode(); if (isSimple ()) code.emitStore(getVariable()); else { if (! field.getStaticFlag()) { loadOwningObject(null, comp); code.emitSwap(); code.emitPutField(field); } else code.emitPutStatic(field); } } /** If non-null, the single expression used to set this variable. * If the variable can be set more than once, then value is null. */ protected Expression value = QuoteExp.undefined_exp; /** The value of this <code>Declaration</code>, if known. * Usually the expression used to initialize the <code>Declaration</code>, * or null if the <code>Declaration</code> can be assigned a different * value after initialization. Note that this is the semantic value: If the * <code>INDIRECT_LOCATION</code> is set, then <code>getValue</code> is the * value <em>after</em> de-referencing the resulting <code>Location</code>. * An exception is if <code>isAlias()</code>; in that case * <code>getValue()</code> is an expression yielding a <code>Location</code> * which needs to be de-referenced to get this <code>Declaration</code>'s * actual value. */ public final Expression getValue() { if (value == QuoteExp.undefined_exp) { if (field != null && ((field.getModifiers() & Access.STATIC+Access.FINAL) == Access.STATIC+Access.FINAL) && ! isIndirectBinding()) { try { value = new QuoteExp(field.getReflectField().get(null)); } catch (Throwable ex) { } } } else if (value instanceof QuoteExp && getFlag(TYPE_SPECIFIED) && value.getType() != type) { try { Object val = ((QuoteExp) value).getValue(); Type t = getType(); value = new QuoteExp(t.coerceFromObject(val), t); } catch (Throwable ex) { } } return value; } /** Set the value assoociated with this Declaration. * Most code should use noteValue instead. */ public final void setValue(Expression value) { this.value = value; } /** If getValue() is a constant, return the constant value, otherwise null. */ public final Object getConstantValue() { Object v = getValue(); if (! (v instanceof QuoteExp) || v == QuoteExp.undefined_exp) return null; return ((QuoteExp) v).getValue(); } public final boolean hasConstantValue () { Object v = getValue(); return (v instanceof QuoteExp) && v != QuoteExp.undefined_exp; } boolean shouldEarlyInit () { return getFlag(EARLY_INIT) || isCompiletimeConstant (); } public boolean isCompiletimeConstant () { return getFlag(IS_CONSTANT) && hasConstantValue(); } /** This prefix is prepended to field names for unknown names. */ static final String UNKNOWN_PREFIX = "loc$"; /** This prefix is used in field names for a declaration that has * both EXTERNAL_ACCESS and IS_PRIVATE set. */ public static final String PRIVATE_PREFIX = "$Prvt$"; /** If this flag is set then to get the actual value you have to dereference * a <code>gnu.mapping.Location</code>. I.e. this <code>Declaration</code>'s * <code>var</code> or <code>field</code> does not contain the * <code>Declaration</code>'s value directly, but rather yields a * <code>Location</code> that contains the <code>Declaration</code>'s value. * Note that this flag indicates the <em>representation</em>: * The result of <code>getValue()</code> is not the location, but the * semantic value. after dereferencing. Likewise <code>getType</code> is * the value after de-referencing, not a <code>Location</code> sub-class. */ static final int INDIRECT_BINDING = 1; static final int CAN_READ = 2; static final int CAN_CALL = 4; static final int CAN_WRITE = 8; static final int IS_FLUID = 0x10; static final int PRIVATE = 0x20; static final int IS_SIMPLE = 0x40; /** True if in the function namespace, for languages that distinguishes them. * I.e. a function definition or macro definition. */ static final int PROCEDURE = 0x80; public static final int IS_ALIAS = 0x100; /** Set if this is just a declaration, not a definition. */ public static final int NOT_DEFINING = 0x200; public static final int EXPORT_SPECIFIED = 0x400; public static final int STATIC_SPECIFIED = 0x800; public static final int NONSTATIC_SPECIFIED = 0x1000; public static final int TYPE_SPECIFIED = 0x2000; public static final int IS_CONSTANT = 0x4000; public static final int IS_SYNTAX = 0x8000; public static final int IS_UNKNOWN = 0x10000; public static final int IS_IMPORTED = 0x20000; // This should be a type property, not a variable property, at some point! public static final int IS_SINGLE_VALUE = 0x40000; /** This flag bit is set if this can be be acceessed from other modules. * Ignored unless PRIVATE. * Used when an exported macro references a non-exported name. */ public static final int EXTERNAL_ACCESS = 0x80000; public final boolean needsExternalAccess () { return (flags & EXTERNAL_ACCESS+PRIVATE) == EXTERNAL_ACCESS+PRIVATE // Kludge - needed for macros - see Savannah bug #13601. || (flags & IS_NAMESPACE_PREFIX+PRIVATE) == IS_NAMESPACE_PREFIX+PRIVATE; } /** If we need a 'context' supplied from a ReferenceExp or 'this. */ public final boolean needsContext () { return base == null && field != null && ! field.getStaticFlag(); } /** True if this is a field or method in a class definition. */ public static final int FIELD_OR_METHOD = 0x100000; /** Set if this declares a namespace prefix (as in XML namespaces). */ public static final int IS_NAMESPACE_PREFIX = 0x200000; public static final int PRIVATE_ACCESS = 0x1000000; public static final int PRIVATE_SPECIFIED = PRIVATE_ACCESS; /* deprecated*/ public static final int PROTECTED_ACCESS = 0x2000000; public static final int PUBLIC_ACCESS = 0x4000000; public static final int PACKAGE_ACCESS = 0x8000000; public static final int IS_DYNAMIC = 0x10000000; /** Initialize in {@code <init>}/{@code <clinit>} * rather than in {@code run}/{@code $run$}. */ public static final int EARLY_INIT = 0x20000000; /** A reference to a module instance. */ public static final int MODULE_REFERENCE = 0x40000000; public static final long VOLATILE_ACCESS = 0x80000000; public static final long TRANSIENT_ACCESS = 0x100000000l; protected long flags = IS_SIMPLE; public final boolean getFlag (long flag) { return (flags & flag) != 0; } public final void setFlag (boolean setting, long flag) { if (setting) flags |= flag; else flags &= ~flag; } public final void setFlag (long flag) { flags |= flag; } public final boolean isPublic() { return context instanceof ModuleExp && (flags & PRIVATE) == 0; } public final boolean isPrivate() { return (flags & PRIVATE) != 0; } public final void setPrivate(boolean isPrivate) { setFlag(isPrivate, PRIVATE); } public short getAccessFlags (short defaultFlags) { short flags; if (getFlag(PRIVATE_ACCESS|PROTECTED_ACCESS|PACKAGE_ACCESS|PUBLIC_ACCESS)) { flags = 0; if (getFlag(PRIVATE_ACCESS)) flags |= Access.PRIVATE; if (getFlag(PROTECTED_ACCESS)) flags |= Access.PROTECTED; if (getFlag(PUBLIC_ACCESS)) flags |= Access.PUBLIC; } else flags = defaultFlags; if (getFlag(VOLATILE_ACCESS)) flags |= Access.VOLATILE; if (getFlag(TRANSIENT_ACCESS)) flags |= Access.TRANSIENT; return flags; } public final boolean isAlias() { return (flags & IS_ALIAS) != 0; } public final void setAlias(boolean flag) { setFlag(flag, IS_ALIAS); } /** True if this is a fluid binding (in a FluidLetExp). */ public final boolean isFluid () { return (flags & IS_FLUID) != 0; } public final void setFluid (boolean fluid) { setFlag(fluid, IS_FLUID); } public final boolean isProcedureDecl () { return (flags & PROCEDURE) != 0; } public final void setProcedureDecl (boolean val) { setFlag(val, PROCEDURE); } public final boolean isNamespaceDecl () { return (flags & IS_NAMESPACE_PREFIX) != 0; } /** True if the value of the variable is the contents of a Location. * @see #INDIRECT_BINDING */ public final boolean isIndirectBinding() { return (flags & INDIRECT_BINDING) != 0; } /** Note that the value of the variable is the contents of a Location. * @see #INDIRECT_BINDING */ public final void setIndirectBinding(boolean indirectBinding) { setFlag(indirectBinding, INDIRECT_BINDING); } public void maybeIndirectBinding (Compilation comp) { if (isLexical() && ! (context instanceof ModuleExp) || context == comp.mainLambda) setIndirectBinding(true); } /* Note: You probably want to use !ignorable(). */ public final boolean getCanRead() { return (flags & CAN_READ) != 0; } public final void setCanRead(boolean read) { setFlag(read, CAN_READ); } public final void setCanRead() { setFlag(true, CAN_READ); if (base != null) base.setCanRead(); } public final boolean getCanCall() { return (flags & CAN_CALL) != 0; } public final void setCanCall(boolean called) { setFlag(called, CAN_CALL); } public final void setCanCall() { setFlag(true, CAN_CALL); if (base != null) base.setCanRead(); } public final boolean getCanWrite() { return (flags & CAN_WRITE) != 0; } public final void setCanWrite(boolean written) { if (written) flags |= CAN_WRITE; else flags &= ~CAN_WRITE; } public final void setCanWrite() { flags |= CAN_WRITE; if (base != null) base.setCanRead(); } /** Is this an implicit 'this' parameter? */ public final boolean isThisParameter () { return symbol == ThisExp.THIS_NAME; } /** True if we never need to access this declaration. */ // rename to isAccessed? public boolean ignorable() { if (getCanRead() || isPublic()) return false; if (getCanWrite() && getFlag(IS_UNKNOWN)) return false; if (! getCanCall()) return true; Expression value = getValue(); if (value == null || ! (value instanceof LambdaExp)) return false; LambdaExp lexp = (LambdaExp) value; return ! lexp.isHandlingTailCalls() || lexp.getInlineOnly(); } /** Does this variable need to be initialized or is default ok */ public boolean needsInit() { // This is a kludge. Ideally, we should do some data-flow analysis. // But at least it makes sure require'd variables are not initialized. return ! ignorable() && ! (value == QuoteExp.nullExp && base != null); } public boolean isStatic() { if (field != null) return field.getStaticFlag(); if (getFlag(STATIC_SPECIFIED) || isCompiletimeConstant()) return true; if (getFlag(NONSTATIC_SPECIFIED)) return false; LambdaExp lambda = context.currentLambda(); return lambda instanceof ModuleExp && ((ModuleExp) lambda).isStatic(); } public final boolean isLexical() { return (flags & (IS_FLUID|IS_DYNAMIC|IS_UNKNOWN)) == 0; } public static final boolean isUnknown (Declaration decl) { return decl == null || decl.getFlag(IS_UNKNOWN); } /** List of ApplyExp where this declaration is the function called. * The applications are chained using their nextCall fields. * The chain is not built if STATIC_SPECIFIED. */ public ApplyExp firstCall; public void noteValue (Expression value) { // We allow assigning a real value after undefined ... if (this.value == QuoteExp.undefined_exp) { if (value instanceof LambdaExp) ((LambdaExp) value).nameDecl = this; this.value = value; } else if (this.value != value) { if (this.value instanceof LambdaExp) ((LambdaExp) this.value).nameDecl = null; this.value = null; } } protected Declaration() { } public Declaration (Variable var) { this(var.getName(), var.getType()); this.var = var; } public Declaration (Object name) { setName(name); } public Declaration (Object name, Type type) { setName(name); setType(type); } public Declaration (Object name, Field field) { this(name, field.getType()); this.field = field; setSimple(false); } Method makeLocationMethod = null; /** Create a Location object, given that isIndirectBinding(). Assume the initial value is already pushed on the stack; leaves initialized Location object on stack. */ public void pushIndirectBinding (Compilation comp) { CodeAttr code = comp.getCode(); code.emitPushString(getName()); if (makeLocationMethod == null) { Type[] args = new Type[2]; args[0] = Type.pointer_type; args[1] = Type.string_type; makeLocationMethod = Compilation.typeLocation.addMethod("make", args, Compilation.typeLocation, Access.PUBLIC|Access.STATIC); } code.emitInvokeStatic(makeLocationMethod); } public final Variable allocateVariable(CodeAttr code) { if (! isSimple() || var == null) { String vname = null; if (symbol != null) vname = Compilation.mangleNameIfNeeded(getName()); if (isAlias() && getValue() instanceof ReferenceExp) { Declaration base = followAliases(this); var = base == null ? null : base.var; } else { Type type = isIndirectBinding() ? Compilation.typeLocation : getType().getImplementationType(); var = context.getVarScope().addVariable(code, type, vname); } } return var; } String filename; int position; public final void setLocation (SourceLocator location) { this.filename = location.getFileName(); setLine(location.getLineNumber(), location.getColumnNumber()); } public final void setFile (String filename) { this.filename = filename; } public final void setLine (int lineno, int colno) { if (lineno < 0) lineno = 0; if (colno < 0) colno = 0; position = (lineno << 12) + colno; } public final void setLine (int lineno) { setLine (lineno, 0); } public final String getFileName () { return filename; } public String getPublicId () { return null; } public String getSystemId () { return filename; } /** Get the line number of (the start of) this Expression. * The "first" line is line 1; unknown is -1. */ public final int getLineNumber() { int line = position >> 12; return line == 0 ? -1 : line; } public final int getColumnNumber() { int column = position & ((1 << 12) - 1); return column == 0 ? -1 : column; } public boolean isStableSourceLocation() { return true; } public void printInfo(OutPort out) { StringBuffer sbuf = new StringBuffer(); printInfo(sbuf); out.print(sbuf.toString()); } public void printInfo(StringBuffer sbuf) { sbuf.append(symbol); if (true || // DEBUGGING symbol == null) ; else if (symbol instanceof SimpleSymbol) sbuf.append("[simple-symbol]"); else if (symbol instanceof Symbol) sbuf.append("[symbol]"); else if (symbol.toString().intern() == symbol) sbuf.append("[interned-string]"); else if (symbol instanceof String) sbuf.append("[noninterned-string]"); sbuf.append('/'); sbuf.append(id); /* int line = getLineNumber(); if (line != 0) { sbuf.append("/line:"); sbuf.append(line); int column = getColumnNumber(); if (column != 0) { sbuf.append(':'); sbuf.append(column); } } */ sbuf.append("/fl:"); sbuf.append(Long.toHexString(flags)); if (ignorable()) sbuf.append("(ignorable)"); Expression tx = typeExp; Type t = getType(); if (tx != null && ! (tx instanceof QuoteExp)) { sbuf.append("::"); sbuf.append(tx); } else if (type != null && t != Type.pointer_type) { sbuf.append("::"); sbuf.append(t.getName()); } } public String toString() { return "Declaration["+symbol+'/'+id+']'; /* StringBuffer sbuf = new StringBuffer(); sbuf.append("Declaration["); printInfo(sbuf); sbuf.append(']'); return sbuf.toString(); */ } public static Declaration followAliases (Declaration decl) { while (decl != null && decl.isAlias()) { Expression declValue = decl.getValue(); if (! (declValue instanceof ReferenceExp)) break; ReferenceExp rexp = (ReferenceExp) declValue; Declaration orig = rexp.binding; if (orig == null) break; decl = orig; } return decl; } public void makeField(Compilation comp, Expression value) { setSimple(false); makeField(comp.mainClass, comp, value); } public void makeField(ClassType frameType, Compilation comp, Expression value) { boolean external_access = needsExternalAccess(); int fflags = 0; boolean isConstant = getFlag(IS_CONSTANT); boolean typeSpecified = getFlag(TYPE_SPECIFIED); if (comp.immediate && context instanceof ModuleExp && ! isConstant && ! typeSpecified) setIndirectBinding(true); // In immediate mode we may need to access the field from a future // command in a different "runtime package" (see JVM spec) because it // gets loaded by a different class loader. So make the field public. if (isPublic() || external_access || comp.immediate) fflags |= Access.PUBLIC; if (isStatic() // "Dynamic" variables use ThreadLocation, based on the current // Environment, so we don't need more than one static field. || (getFlag(Declaration.IS_UNKNOWN |Declaration.IS_DYNAMIC|Declaration.IS_FLUID) && isIndirectBinding() && ! isAlias()) || (value instanceof ClassExp && ! ((LambdaExp) value).getNeedsClosureEnv())) fflags |= Access.STATIC; if ((isIndirectBinding() || (isConstant && (shouldEarlyInit() || (context instanceof ModuleExp && ((ModuleExp) context).staticInitRun())))) && (context instanceof ClassExp || context instanceof ModuleExp)) fflags |= Access.FINAL; Type ftype = getType().getImplementationType(); if (isIndirectBinding() && ! ftype.isSubtype(Compilation.typeLocation)) ftype = Compilation.typeLocation; if (! ignorable()) { String fname = getName(); int nlength; if (fname==null) { fname = "$unnamed$0"; nlength = fname.length() - 2; // Without the "$0". } else { fname = Compilation.mangleNameIfNeeded(fname); if (getFlag(IS_UNKNOWN)) fname = UNKNOWN_PREFIX + fname; if (external_access && ! getFlag(Declaration.MODULE_REFERENCE)) fname = PRIVATE_PREFIX + fname; nlength = fname.length(); } int counter = 0; while (frameType.getDeclaredField(fname) != null) fname = fname.substring(0, nlength) + '$' + (++ counter); field = frameType.addField (fname, ftype, fflags); if (value instanceof QuoteExp) { Object val = ((QuoteExp) value).getValue(); if (field.getStaticFlag() && val.getClass().getName().equals(ftype.getName())) { Literal literal = comp.litTable.findLiteral(val); if (literal.field == null) literal.assign(field, comp.litTable); } else if (ftype instanceof PrimType || "java.lang.String".equals(ftype.getName())) { if (val instanceof gnu.text.Char) val = gnu.math.IntNum.make(((gnu.text.Char) val).intValue()); field.setConstantValue(val, frameType); return; } } } // The EARLY_INIT case is handled in SetExp.compile. if (! shouldEarlyInit() && (isIndirectBinding() || (value != null && ! (value instanceof ClassExp)))) { BindingInitializer.create(this, value, comp); } } /* Used when evaluating for an indirect binding. */ gnu.mapping.Location makeIndirectLocationFor () { Symbol sym = symbol instanceof Symbol ? (Symbol) symbol : Namespace.EmptyNamespace.getSymbol(symbol.toString().intern()); return gnu.mapping.Location.make(sym); } /** Create a declaration corresponding to a static field. * @param cname name of class containing field * @param fname name of static field */ public static Declaration getDeclarationFromStatic (String cname, String fname) { ClassType clas = ClassType.make(cname); Field fld = clas.getDeclaredField(fname); Declaration decl = new Declaration(fname, fld); decl.setFlag(Declaration.IS_CONSTANT|Declaration.STATIC_SPECIFIED); return decl; } /** Similar to {@code getDeclarationFromStatic}, * but also do {@code noteValue} with the field's value. */ public static Declaration getDeclarationValueFromStatic (String className, String fieldName, String name) { try { Class cls = Class.forName(className); java.lang.reflect.Field fld = cls.getDeclaredField(fieldName); Object value = fld.get(null); Declaration decl = new Declaration(name, ClassType.make(className) .getDeclaredField(fieldName)); decl.noteValue(new QuoteExp(value)); decl.setFlag(Declaration.IS_CONSTANT|Declaration.STATIC_SPECIFIED); return decl; } catch (Exception ex) { throw new WrappedException(ex); } } public static Declaration getDeclaration(Named proc) { return getDeclaration(proc, proc.getName()); } public static Declaration getDeclaration(Object proc, String name) { gnu.bytecode.Field procField = null; if (name != null) { /* // This is a way to map from the Procedure's name to a Field, // by assuming the name as the form "classname:fieldname". // It may be better to use names of the form "{classname}fieldname". // For now we don't need this feature. int colon = name.indexOf(':'); if (colon > 0) { try { ClassType procType = (ClassType) ClassType.make(name.substring(0, colon)); name = name.substring(colon+1); String fname = Compilation.mangleNameIfNeeded(name); procField = procType.getDeclaredField(fname); } catch (Throwable ex) { System.err.println("CAUGHT "+ex+" in getDeclaration for "+proc); return null; } } else */ { Class procClass = PrimProcedure.getProcedureClass(proc); if (procClass != null) { ClassType procType = (ClassType) Type.make(procClass); String fname = Compilation.mangleNameIfNeeded(name); procField = procType.getDeclaredField(fname); } } } if (procField != null) { int fflags = procField.getModifiers(); if ((fflags & Access.STATIC) != 0) { Declaration decl = new Declaration(name, procField); decl.noteValue(new QuoteExp(proc)); if ((fflags & Access.FINAL) != 0) decl.setFlag(Declaration.IS_CONSTANT); return decl; } } return null; } }
gnu/expr/Declaration.java
// Copyright (c) 2003, 2009 Per M.A. Bothner. // This is free software; for terms and warranty disclaimer see ./COPYING. package gnu.expr; import gnu.bytecode.*; import gnu.mapping.*; import gnu.text.SourceLocator; /** * The static information associated with a local variable binding. * @author Per Bothner * * These are the kinds of Declaration we use: * * A local variable that is not captured by an inner lambda is stored * in a Java local variables slot (register). The predicate isSimple () * is true, and offset is the number of the local variable slot. * * If a local variable is captured by an inner lambda, the * variable is stored in a field of the LambdaExp's heapFrame variable. * (The latter declaration has isSimple and isArtificial true.) * The Declaration's field specifies the Field used. * * If a function takes a fixed number of parameters, at most four, * then the arguments are passed in Java registers 1..4. * If a parameter is not captured by an inner lambda, the parameter * has the flags isSimple and isParameter true. * * If a function takes more than 4 or a variable number of parameters, * the arguments are passed in an array (using the applyN virtual method). * This array is referenced by the argsArray declaration, which has * isSimple(), isParameter(), and isArtificial() true, and its offset is 1. * The parameters are copied into the program-named variables by the * procedure prologue, so the parameters henceforth act like local variables. */ public class Declaration implements SourceLocator { static int counter; /** Unique id number, to ease print-outs and debugging. * If negative, a code to specify a builtin function. */ protected int id = ++counter; /** The name of the new variable, either an interned String or a Symbol. * This is the source-level (non-mangled) name. */ Object symbol; public void setCode (int code) { if (code >= 0) throw new Error("code must be negative"); this.id = code; } public int getCode () { return id; } public ScopeExp context; /** The type of the value of this Declaration. * It is null if the type is un-specified and not yet inferred. * Will get set implicitly by getType, to avoid inconsistencies. */ protected Type type; protected Expression typeExp; public final Expression getTypeExp() { if (typeExp == null) setType(Type.objectType); return typeExp; } public final Type getType() { if (type == null) setType(Type.objectType); return type; } public final void setType(Type type) { this.type = type; if (var != null) var.setType(type); typeExp = QuoteExp.getInstance(type); } public final void setTypeExp (Expression typeExp) { this.typeExp = typeExp; Type t = null; if (typeExp instanceof TypeValue) t = ((TypeValue) typeExp).getImplementationType(); else t = Language.getDefaultLanguage().getTypeFor(typeExp, false); if (t == null) t = Type.pointer_type; this.type = t; if (var != null) var.setType(t); } public final String getName() { return symbol == null ? null : symbol instanceof Symbol ? ((Symbol) symbol).getName() : symbol.toString(); } public final void setName(Object symbol) { this.symbol = symbol; } public final Object getSymbol() { return symbol; } public final void setSymbol(Object symbol) { this.symbol = symbol; } /* Declarations in a ScopeExp are linked together in a linked list. */ Declaration next; public final Declaration nextDecl() { return next; } public final void setNext(Declaration next) { this.next = next; } /** Index in evalFrame for this scope, if interpreting. */ int evalIndex; Variable var; public Variable getVariable() { return var; } public final boolean isSimple() { return (flags & IS_SIMPLE) != 0; } public final void setSimple(boolean b) { setFlag(b, IS_SIMPLE); if (var != null && ! var.isParameter()) var.setSimple(b); } public final void setSyntax () { setSimple(false); setFlag(IS_CONSTANT|IS_SYNTAX|EARLY_INIT); } /** Return the ScopeExp that contains (declares) this Declaration. */ public final ScopeExp getContext() { return context; } /** Used to link Declarations in a LambdaExp's capturedVars list. */ Declaration nextCapturedVar; /** If non-null, field is relative to base. * If IS_FLUID, base points to IS_UNKNOWN Symbol. */ public Declaration base; public Field field; /** If this is a field in some object, load a reference to that object. */ void loadOwningObject (Declaration owner, Compilation comp) { if (owner == null) owner = base; if (owner != null) owner.load(null, 0, comp, Target.pushObject); else getContext().currentLambda().loadHeapFrame(comp); } public void load (AccessExp access, int flags, Compilation comp, Target target) { if (target instanceof IgnoreTarget) return; Declaration owner = access == null ? null : access.contextDecl(); if (isAlias() && value instanceof ReferenceExp) { ReferenceExp rexp = (ReferenceExp) value; Declaration orig = rexp.binding; if (orig != null && ((flags & ReferenceExp.DONT_DEREFERENCE) == 0 || orig.isIndirectBinding()) && (owner == null || ! orig.needsContext())) { orig.load(rexp, flags, comp, target); return; } } CodeAttr code = comp.getCode(); Type rtype = getType(); if (! isIndirectBinding() && (flags & ReferenceExp.DONT_DEREFERENCE) != 0) { if (field == null) throw new Error("internal error: cannot take location of "+this); Method meth; ClassType ltype; boolean immediate = comp.immediate; if (field.getStaticFlag()) { ltype = ClassType.make("gnu.kawa.reflect.StaticFieldLocation"); meth = ltype.getDeclaredMethod("make", immediate ? 1 : 2); } else { ltype = ClassType.make("gnu.kawa.reflect.FieldLocation"); meth = ltype.getDeclaredMethod("make", immediate ? 2 : 3); loadOwningObject(owner, comp); } if (immediate) comp.compileConstant(this); else { comp.compileConstant(field.getDeclaringClass().getName()); comp.compileConstant(field.getName()); } code.emitInvokeStatic(meth); rtype = ltype; } else { Object val; if (field != null) { comp.usedClass(field.getDeclaringClass()); comp.usedClass(field.getType()); if (! field.getStaticFlag()) { loadOwningObject(owner, comp); code.emitGetField(field); } else code.emitGetStatic(field); } else if (isIndirectBinding() && comp.immediate && getVariable() == null) { // This is a bit of a kludge. See comment in ModuleExp.evalModule. Environment env = Environment.getCurrent(); Symbol sym = symbol instanceof Symbol ? (Symbol) symbol : env.getSymbol(symbol.toString()); Object property = null; if (isProcedureDecl() && comp.getLanguage().hasSeparateFunctionNamespace()) property = EnvironmentKey.FUNCTION; gnu.mapping.Location loc = env.getLocation(sym, property); comp.compileConstant(loc, Target.pushValue(Compilation.typeLocation)); } else if (comp.immediate && (val = getConstantValue()) != null) { comp.compileConstant(val, target); return; } else if (value != QuoteExp.undefined_exp && ignorable()) { value.compile(comp, target); return; } else { Variable var = getVariable(); ClassExp cl; if (context instanceof ClassExp && var == null && ! getFlag(PROCEDURE) && (cl = (ClassExp) context).isMakingClassPair()) { String getName = ClassExp.slotToMethodName("get", getName()); Method getter = cl.type.getDeclaredMethod(getName, 0); cl.loadHeapFrame(comp); code.emitInvoke(getter); } else { if (var == null) var = allocateVariable(code); code.emitLoad(var); } } if (isIndirectBinding() && (flags & ReferenceExp.DONT_DEREFERENCE) == 0) { String filename; int line; if (access != null && (filename = access.getFileName()) != null && (line = access.getLineNumber()) > 0) { // Wrap call to Location.get by a catch handler that // calls setLine on the UnboundLocationException. ClassType typeUnboundLocationException = ClassType.make("gnu.mapping.UnboundLocationException"); // See comment in CheckedTarget.emitCheckedCoerce. boolean isInTry = code.isInTry(); int column = access.getColumnNumber(); Label startTry = new Label(code); startTry.define(code); code.emitInvokeVirtual(Compilation.getLocationMethod); Label endTry = new Label(code); endTry.define(code); Label endLabel = new Label(code); endLabel.setTypes(code); if (isInTry) code.emitGoto(endLabel); else code.setUnreachable(); int fragment_cookie = 0; if (! isInTry) fragment_cookie = code.beginFragment(endLabel); code.addHandler(startTry, endTry, typeUnboundLocationException); code.emitDup(typeUnboundLocationException); code.emitPushString(filename); code.emitPushInt(line); code.emitPushInt(column); code.emitInvokeVirtual(typeUnboundLocationException .getDeclaredMethod("setLine", 3)); code.emitThrow(); if (isInTry) endLabel.define(code); else code.endFragment(fragment_cookie); } else code.emitInvokeVirtual(Compilation.getLocationMethod); rtype = Type.pointer_type; } } target.compileFromStack(comp, rtype); } /* Compile code to store a value (which must already be on the stack) into this variable. */ public void compileStore (Compilation comp) { gnu.bytecode.CodeAttr code = comp.getCode(); if (isSimple ()) code.emitStore(getVariable()); else { if (! field.getStaticFlag()) { loadOwningObject(null, comp); code.emitSwap(); code.emitPutField(field); } else code.emitPutStatic(field); } } /** If non-null, the single expression used to set this variable. * If the variable can be set more than once, then value is null. */ protected Expression value = QuoteExp.undefined_exp; /** The value of this <code>Declaration</code>, if known. * Usually the expression used to initialize the <code>Declaration</code>, * or null if the <code>Declaration</code> can be assigned a different * value after initialization. Note that this is the semantic value: If the * <code>INDIRECT_LOCATION</code> is set, then <code>getValue</code> is the * value <em>after</em> de-referencing the resulting <code>Location</code>. * An exception is if <code>isAlias()</code>; in that case * <code>getValue()</code> is an expression yielding a <code>Location</code> * which needs to be de-referenced to get this <code>Declaration</code>'s * actual value. */ public final Expression getValue() { if (value == QuoteExp.undefined_exp) { if (field != null && ((field.getModifiers() & Access.STATIC+Access.FINAL) == Access.STATIC+Access.FINAL) && ! isIndirectBinding()) { try { value = new QuoteExp(field.getReflectField().get(null)); } catch (Throwable ex) { } } } else if (value instanceof QuoteExp && getFlag(TYPE_SPECIFIED) && value.getType() != type) { try { Object val = ((QuoteExp) value).getValue(); Type t = getType(); value = new QuoteExp(t.coerceFromObject(val), t); } catch (Throwable ex) { } } return value; } /** Set the value assoociated with this Declaration. * Most code should use noteValue instead. */ public final void setValue(Expression value) { this.value = value; } /** If getValue() is a constant, return the constant value, otherwise null. */ public final Object getConstantValue() { Object v = getValue(); if (! (v instanceof QuoteExp) || v == QuoteExp.undefined_exp) return null; return ((QuoteExp) v).getValue(); } public final boolean hasConstantValue () { Object v = getValue(); return (v instanceof QuoteExp) && v != QuoteExp.undefined_exp; } boolean shouldEarlyInit () { return getFlag(EARLY_INIT) || isCompiletimeConstant (); } public boolean isCompiletimeConstant () { return getFlag(IS_CONSTANT) && hasConstantValue(); } /** This prefix is prepended to field names for unknown names. */ static final String UNKNOWN_PREFIX = "loc$"; /** This prefix is used in field names for a declaration that has * both EXTERNAL_ACCESS and IS_PRIVATE set. */ public static final String PRIVATE_PREFIX = "$Prvt$"; /** If this flag is set then to get the actual value you have to dereference * a <code>gnu.mapping.Location</code>. I.e. this <code>Declaration</code>'s * <code>var</code> or <code>field</code> does not contain the * <code>Declaration</code>'s value directly, but rather yields a * <code>Location</code> that contains the <code>Declaration</code>'s value. * Note that this flag indicates the <em>representation</em>: * The result of <code>getValue()</code> is not the location, but the * semantic value. after dereferencing. Likewise <code>getType</code> is * the value after de-referencing, not a <code>Location</code> sub-class. */ static final int INDIRECT_BINDING = 1; static final int CAN_READ = 2; static final int CAN_CALL = 4; static final int CAN_WRITE = 8; static final int IS_FLUID = 0x10; static final int PRIVATE = 0x20; static final int IS_SIMPLE = 0x40; /** True if in the function namespace, for languages that distinguishes them. * I.e. a function definition or macro definition. */ static final int PROCEDURE = 0x80; public static final int IS_ALIAS = 0x100; /** Set if this is just a declaration, not a definition. */ public static final int NOT_DEFINING = 0x200; public static final int EXPORT_SPECIFIED = 0x400; public static final int STATIC_SPECIFIED = 0x800; public static final int NONSTATIC_SPECIFIED = 0x1000; public static final int TYPE_SPECIFIED = 0x2000; public static final int IS_CONSTANT = 0x4000; public static final int IS_SYNTAX = 0x8000; public static final int IS_UNKNOWN = 0x10000; public static final int IS_IMPORTED = 0x20000; // This should be a type property, not a variable property, at some point! public static final int IS_SINGLE_VALUE = 0x40000; /** This flag bit is set if this can be be acceessed from other modules. * Ignored unless PRIVATE. * Used when an exported macro references a non-exported name. */ public static final int EXTERNAL_ACCESS = 0x80000; public final boolean needsExternalAccess () { return (flags & EXTERNAL_ACCESS+PRIVATE) == EXTERNAL_ACCESS+PRIVATE // Kludge - needed for macros - see Savannah bug #13601. || (flags & IS_NAMESPACE_PREFIX+PRIVATE) == IS_NAMESPACE_PREFIX+PRIVATE; } /** If we need a 'context' supplied from a ReferenceExp or 'this. */ public final boolean needsContext () { return base == null && field != null && ! field.getStaticFlag(); } /** True if this is a field or method in a class definition. */ public static final int FIELD_OR_METHOD = 0x100000; /** Set if this declares a namespace prefix (as in XML namespaces). */ public static final int IS_NAMESPACE_PREFIX = 0x200000; public static final int PRIVATE_ACCESS = 0x1000000; public static final int PRIVATE_SPECIFIED = PRIVATE_ACCESS; /* deprecated*/ public static final int PROTECTED_ACCESS = 0x2000000; public static final int PUBLIC_ACCESS = 0x4000000; public static final int PACKAGE_ACCESS = 0x8000000; public static final int IS_DYNAMIC = 0x10000000; /** Initialize in {@code <init>}/{@code <clinit>} * rather than in {@code run}/{@code $run$}>. */ public static final int EARLY_INIT = 0x20000000; /** A reference to a module instance. */ public static final int MODULE_REFERENCE = 0x40000000; public static final long VOLATILE_ACCESS = 0x80000000; public static final long TRANSIENT_ACCESS = 0x100000000l; protected long flags = IS_SIMPLE; public final boolean getFlag (long flag) { return (flags & flag) != 0; } public final void setFlag (boolean setting, long flag) { if (setting) flags |= flag; else flags &= ~flag; } public final void setFlag (long flag) { flags |= flag; } public final boolean isPublic() { return context instanceof ModuleExp && (flags & PRIVATE) == 0; } public final boolean isPrivate() { return (flags & PRIVATE) != 0; } public final void setPrivate(boolean isPrivate) { setFlag(isPrivate, PRIVATE); } public short getAccessFlags (short defaultFlags) { short flags; if (getFlag(PRIVATE_ACCESS|PROTECTED_ACCESS|PACKAGE_ACCESS|PUBLIC_ACCESS)) { flags = 0; if (getFlag(PRIVATE_ACCESS)) flags |= Access.PRIVATE; if (getFlag(PROTECTED_ACCESS)) flags |= Access.PROTECTED; if (getFlag(PUBLIC_ACCESS)) flags |= Access.PUBLIC; } else flags = defaultFlags; if (getFlag(VOLATILE_ACCESS)) flags |= Access.VOLATILE; if (getFlag(TRANSIENT_ACCESS)) flags |= Access.TRANSIENT; return flags; } public final boolean isAlias() { return (flags & IS_ALIAS) != 0; } public final void setAlias(boolean flag) { setFlag(flag, IS_ALIAS); } /** True if this is a fluid binding (in a FluidLetExp). */ public final boolean isFluid () { return (flags & IS_FLUID) != 0; } public final void setFluid (boolean fluid) { setFlag(fluid, IS_FLUID); } public final boolean isProcedureDecl () { return (flags & PROCEDURE) != 0; } public final void setProcedureDecl (boolean val) { setFlag(val, PROCEDURE); } public final boolean isNamespaceDecl () { return (flags & IS_NAMESPACE_PREFIX) != 0; } /** True if the value of the variable is the contents of a Location. * @see #INDIRECT_BINDING */ public final boolean isIndirectBinding() { return (flags & INDIRECT_BINDING) != 0; } /** Note that the value of the variable is the contents of a Location. * @see #INDIRECT_BINDING */ public final void setIndirectBinding(boolean indirectBinding) { setFlag(indirectBinding, INDIRECT_BINDING); } public void maybeIndirectBinding (Compilation comp) { if (isLexical() && ! (context instanceof ModuleExp) || context == comp.mainLambda) setIndirectBinding(true); } /* Note: You probably want to use !ignorable(). */ public final boolean getCanRead() { return (flags & CAN_READ) != 0; } public final void setCanRead(boolean read) { setFlag(read, CAN_READ); } public final void setCanRead() { setFlag(true, CAN_READ); if (base != null) base.setCanRead(); } public final boolean getCanCall() { return (flags & CAN_CALL) != 0; } public final void setCanCall(boolean called) { setFlag(called, CAN_CALL); } public final void setCanCall() { setFlag(true, CAN_CALL); if (base != null) base.setCanRead(); } public final boolean getCanWrite() { return (flags & CAN_WRITE) != 0; } public final void setCanWrite(boolean written) { if (written) flags |= CAN_WRITE; else flags &= ~CAN_WRITE; } public final void setCanWrite() { flags |= CAN_WRITE; if (base != null) base.setCanRead(); } /** Is this an implicit 'this' parameter? */ public final boolean isThisParameter () { return symbol == ThisExp.THIS_NAME; } /** True if we never need to access this declaration. */ // rename to isAccessed? public boolean ignorable() { if (getCanRead() || isPublic()) return false; if (getCanWrite() && getFlag(IS_UNKNOWN)) return false; if (! getCanCall()) return true; Expression value = getValue(); if (value == null || ! (value instanceof LambdaExp)) return false; LambdaExp lexp = (LambdaExp) value; return ! lexp.isHandlingTailCalls() || lexp.getInlineOnly(); } /** Does this variable need to be initialized or is default ok */ public boolean needsInit() { // This is a kludge. Ideally, we should do some data-flow analysis. // But at least it makes sure require'd variables are not initialized. return ! ignorable() && ! (value == QuoteExp.nullExp && base != null); } public boolean isStatic() { if (field != null) return field.getStaticFlag(); if (getFlag(STATIC_SPECIFIED) || isCompiletimeConstant()) return true; if (getFlag(NONSTATIC_SPECIFIED)) return false; LambdaExp lambda = context.currentLambda(); return lambda instanceof ModuleExp && ((ModuleExp) lambda).isStatic(); } public final boolean isLexical() { return (flags & (IS_FLUID|IS_DYNAMIC|IS_UNKNOWN)) == 0; } public static final boolean isUnknown (Declaration decl) { return decl == null || decl.getFlag(IS_UNKNOWN); } /** List of ApplyExp where this declaration is the function called. * The applications are chained using their nextCall fields. * The chain is not built if STATIC_SPECIFIED. */ public ApplyExp firstCall; public void noteValue (Expression value) { // We allow assigning a real value after undefined ... if (this.value == QuoteExp.undefined_exp) { if (value instanceof LambdaExp) ((LambdaExp) value).nameDecl = this; this.value = value; } else if (this.value != value) { if (this.value instanceof LambdaExp) ((LambdaExp) this.value).nameDecl = null; this.value = null; } } protected Declaration() { } public Declaration (Variable var) { this(var.getName(), var.getType()); this.var = var; } public Declaration (Object name) { setName(name); } public Declaration (Object name, Type type) { setName(name); setType(type); } public Declaration (Object name, Field field) { this(name, field.getType()); this.field = field; setSimple(false); } Method makeLocationMethod = null; /** Create a Location object, given that isIndirectBinding(). Assume the initial value is already pushed on the stack; leaves initialized Location object on stack. */ public void pushIndirectBinding (Compilation comp) { CodeAttr code = comp.getCode(); code.emitPushString(getName()); if (makeLocationMethod == null) { Type[] args = new Type[2]; args[0] = Type.pointer_type; args[1] = Type.string_type; makeLocationMethod = Compilation.typeLocation.addMethod("make", args, Compilation.typeLocation, Access.PUBLIC|Access.STATIC); } code.emitInvokeStatic(makeLocationMethod); } public final Variable allocateVariable(CodeAttr code) { if (! isSimple() || var == null) { String vname = null; if (symbol != null) vname = Compilation.mangleNameIfNeeded(getName()); if (isAlias() && getValue() instanceof ReferenceExp) { Declaration base = followAliases(this); var = base == null ? null : base.var; } else { Type type = isIndirectBinding() ? Compilation.typeLocation : getType().getImplementationType(); var = context.getVarScope().addVariable(code, type, vname); } } return var; } String filename; int position; public final void setLocation (SourceLocator location) { this.filename = location.getFileName(); setLine(location.getLineNumber(), location.getColumnNumber()); } public final void setFile (String filename) { this.filename = filename; } public final void setLine (int lineno, int colno) { if (lineno < 0) lineno = 0; if (colno < 0) colno = 0; position = (lineno << 12) + colno; } public final void setLine (int lineno) { setLine (lineno, 0); } public final String getFileName () { return filename; } public String getPublicId () { return null; } public String getSystemId () { return filename; } /** Get the line number of (the start of) this Expression. * The "first" line is line 1; unknown is -1. */ public final int getLineNumber() { int line = position >> 12; return line == 0 ? -1 : line; } public final int getColumnNumber() { int column = position & ((1 << 12) - 1); return column == 0 ? -1 : column; } public boolean isStableSourceLocation() { return true; } public void printInfo(OutPort out) { StringBuffer sbuf = new StringBuffer(); printInfo(sbuf); out.print(sbuf.toString()); } public void printInfo(StringBuffer sbuf) { sbuf.append(symbol); if (true || // DEBUGGING symbol == null) ; else if (symbol instanceof SimpleSymbol) sbuf.append("[simple-symbol]"); else if (symbol instanceof Symbol) sbuf.append("[symbol]"); else if (symbol.toString().intern() == symbol) sbuf.append("[interned-string]"); else if (symbol instanceof String) sbuf.append("[noninterned-string]"); sbuf.append('/'); sbuf.append(id); /* int line = getLineNumber(); if (line != 0) { sbuf.append("/line:"); sbuf.append(line); int column = getColumnNumber(); if (column != 0) { sbuf.append(':'); sbuf.append(column); } } */ sbuf.append("/fl:"); sbuf.append(Long.toHexString(flags)); if (ignorable()) sbuf.append("(ignorable)"); Expression tx = typeExp; Type t = getType(); if (tx != null && ! (tx instanceof QuoteExp)) { sbuf.append("::"); sbuf.append(tx); } else if (type != null && t != Type.pointer_type) { sbuf.append("::"); sbuf.append(t.getName()); } } public String toString() { return "Declaration["+symbol+'/'+id+']'; /* StringBuffer sbuf = new StringBuffer(); sbuf.append("Declaration["); printInfo(sbuf); sbuf.append(']'); return sbuf.toString(); */ } public static Declaration followAliases (Declaration decl) { while (decl != null && decl.isAlias()) { Expression declValue = decl.getValue(); if (! (declValue instanceof ReferenceExp)) break; ReferenceExp rexp = (ReferenceExp) declValue; Declaration orig = rexp.binding; if (orig == null) break; decl = orig; } return decl; } public void makeField(Compilation comp, Expression value) { setSimple(false); makeField(comp.mainClass, comp, value); } public void makeField(ClassType frameType, Compilation comp, Expression value) { boolean external_access = needsExternalAccess(); int fflags = 0; boolean isConstant = getFlag(IS_CONSTANT); boolean typeSpecified = getFlag(TYPE_SPECIFIED); if (comp.immediate && context instanceof ModuleExp && ! isConstant && ! typeSpecified) setIndirectBinding(true); // In immediate mode we may need to access the field from a future // command in a different "runtime package" (see JVM spec) because it // gets loaded by a different class loader. So make the field public. if (isPublic() || external_access || comp.immediate) fflags |= Access.PUBLIC; if (isStatic() // "Dynamic" variables use ThreadLocation, based on the current // Environment, so we don't need more than one static field. || (getFlag(Declaration.IS_UNKNOWN |Declaration.IS_DYNAMIC|Declaration.IS_FLUID) && isIndirectBinding() && ! isAlias()) || (value instanceof ClassExp && ! ((LambdaExp) value).getNeedsClosureEnv())) fflags |= Access.STATIC; if ((isIndirectBinding() || (isConstant && (shouldEarlyInit() || (context instanceof ModuleExp && ((ModuleExp) context).staticInitRun())))) && (context instanceof ClassExp || context instanceof ModuleExp)) fflags |= Access.FINAL; Type ftype = getType().getImplementationType(); if (isIndirectBinding() && ! ftype.isSubtype(Compilation.typeLocation)) ftype = Compilation.typeLocation; if (! ignorable()) { String fname = getName(); int nlength; if (fname==null) { fname = "$unnamed$0"; nlength = fname.length() - 2; // Without the "$0". } else { fname = Compilation.mangleNameIfNeeded(fname); if (getFlag(IS_UNKNOWN)) fname = UNKNOWN_PREFIX + fname; if (external_access && ! getFlag(Declaration.MODULE_REFERENCE)) fname = PRIVATE_PREFIX + fname; nlength = fname.length(); } int counter = 0; while (frameType.getDeclaredField(fname) != null) fname = fname.substring(0, nlength) + '$' + (++ counter); field = frameType.addField (fname, ftype, fflags); if (value instanceof QuoteExp) { Object val = ((QuoteExp) value).getValue(); if (field.getStaticFlag() && val.getClass().getName().equals(ftype.getName())) { Literal literal = comp.litTable.findLiteral(val); if (literal.field == null) literal.assign(field, comp.litTable); } else if (ftype instanceof PrimType || "java.lang.String".equals(ftype.getName())) { if (val instanceof gnu.text.Char) val = gnu.math.IntNum.make(((gnu.text.Char) val).intValue()); field.setConstantValue(val, frameType); return; } } } // The EARLY_INIT case is handled in SetExp.compile. if (! shouldEarlyInit() && (isIndirectBinding() || (value != null && ! (value instanceof ClassExp)))) { BindingInitializer.create(this, value, comp); } } /* Used when evaluating for an indirect binding. */ gnu.mapping.Location makeIndirectLocationFor () { Symbol sym = symbol instanceof Symbol ? (Symbol) symbol : Namespace.EmptyNamespace.getSymbol(symbol.toString().intern()); return gnu.mapping.Location.make(sym); } /** Create a declaration corresponding to a static field. * @param cname name of class containing field * @param fname name of static field */ public static Declaration getDeclarationFromStatic (String cname, String fname) { ClassType clas = ClassType.make(cname); Field fld = clas.getDeclaredField(fname); Declaration decl = new Declaration(fname, fld); decl.setFlag(Declaration.IS_CONSTANT|Declaration.STATIC_SPECIFIED); return decl; } /** Similar to {@code getDeclarationFromStatic}, * but also do {@code noteValue} with the field's value. */ public static Declaration getDeclarationValueFromStatic (String className, String fieldName, String name) { try { Class cls = Class.forName(className); java.lang.reflect.Field fld = cls.getDeclaredField(fieldName); Object value = fld.get(null); Declaration decl = new Declaration(name, ClassType.make(className) .getDeclaredField(fieldName)); decl.noteValue(new QuoteExp(value)); decl.setFlag(Declaration.IS_CONSTANT|Declaration.STATIC_SPECIFIED); return decl; } catch (Exception ex) { throw new WrappedException(ex); } } public static Declaration getDeclaration(Named proc) { return getDeclaration(proc, proc.getName()); } public static Declaration getDeclaration(Object proc, String name) { gnu.bytecode.Field procField = null; if (name != null) { /* // This is a way to map from the Procedure's name to a Field, // by assuming the name as the form "classname:fieldname". // It may be better to use names of the form "{classname}fieldname". // For now we don't need this feature. int colon = name.indexOf(':'); if (colon > 0) { try { ClassType procType = (ClassType) ClassType.make(name.substring(0, colon)); name = name.substring(colon+1); String fname = Compilation.mangleNameIfNeeded(name); procField = procType.getDeclaredField(fname); } catch (Throwable ex) { System.err.println("CAUGHT "+ex+" in getDeclaration for "+proc); return null; } } else */ { Class procClass = PrimProcedure.getProcedureClass(proc); if (procClass != null) { ClassType procType = (ClassType) Type.make(procClass); String fname = Compilation.mangleNameIfNeeded(name); procField = procType.getDeclaredField(fname); } } } if (procField != null) { int fflags = procField.getModifiers(); if ((fflags & Access.STATIC) != 0) { Declaration decl = new Declaration(name, procField); decl.noteValue(new QuoteExp(proc)); if ((fflags & Access.FINAL) != 0) decl.setFlag(Declaration.IS_CONSTANT); return decl; } } return null; } }
Fix javadoc typo. git-svn-id: 169764d5f12c41a1cff66b81d896619f3ce5473d@6473 5e0a886f-7f45-49c5-bc19-40643649e37f
gnu/expr/Declaration.java
Fix javadoc typo.
<ide><path>nu/expr/Declaration.java <ide> public static final int IS_DYNAMIC = 0x10000000; <ide> <ide> /** Initialize in {@code <init>}/{@code <clinit>} <del> * rather than in {@code run}/{@code $run$}>. */ <add> * rather than in {@code run}/{@code $run$}. */ <ide> public static final int EARLY_INIT = 0x20000000; <ide> /** A reference to a module instance. */ <ide> public static final int MODULE_REFERENCE = 0x40000000;
Java
apache-2.0
error: pathspec 'metastore/src/test/org/apache/hadoop/hive/metastore/TestRawStoreProxy.java' did not match any file(s) known to git
066704f7e3cb1f3a949e4f158ffde64d8dbc003e
1
nishantmonu51/hive,anishek/hive,vineetgarg02/hive,vergilchiu/hive,b-slim/hive,alanfgates/hive,jcamachor/hive,lirui-apache/hive,lirui-apache/hive,sankarh/hive,anishek/hive,jcamachor/hive,vergilchiu/hive,nishantmonu51/hive,alanfgates/hive,lirui-apache/hive,sankarh/hive,sankarh/hive,alanfgates/hive,nishantmonu51/hive,vineetgarg02/hive,alanfgates/hive,alanfgates/hive,alanfgates/hive,vineetgarg02/hive,b-slim/hive,b-slim/hive,anishek/hive,jcamachor/hive,anishek/hive,vineetgarg02/hive,vergilchiu/hive,jcamachor/hive,anishek/hive,lirui-apache/hive,nishantmonu51/hive,jcamachor/hive,sankarh/hive,anishek/hive,vergilchiu/hive,vergilchiu/hive,alanfgates/hive,alanfgates/hive,anishek/hive,b-slim/hive,lirui-apache/hive,nishantmonu51/hive,vineetgarg02/hive,sankarh/hive,sankarh/hive,lirui-apache/hive,anishek/hive,vineetgarg02/hive,vergilchiu/hive,lirui-apache/hive,vineetgarg02/hive,b-slim/hive,jcamachor/hive,jcamachor/hive,lirui-apache/hive,b-slim/hive,anishek/hive,sankarh/hive,nishantmonu51/hive,vineetgarg02/hive,b-slim/hive,nishantmonu51/hive,lirui-apache/hive,b-slim/hive,nishantmonu51/hive,alanfgates/hive,vineetgarg02/hive,sankarh/hive,vergilchiu/hive,vergilchiu/hive,jcamachor/hive,nishantmonu51/hive,jcamachor/hive,sankarh/hive,b-slim/hive,vergilchiu/hive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.metastore; import static org.junit.Assert.fail; import java.util.concurrent.TimeUnit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.api.MetaException; import org.junit.Test; public class TestRawStoreProxy { static class TestStore extends ObjectStore { @Override public void setConf(Configuration conf) { // noop } public void noopMethod() throws MetaException { Deadline.checkTimeout(); } public void exceptions() throws IllegalStateException, MetaException { Deadline.checkTimeout(); throw new IllegalStateException("throwing an exception"); } } @Test public void testExceptionDispatch() throws Throwable { HiveConf hiveConf = new HiveConf(); hiveConf.setTimeVar(HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT, 10, TimeUnit.MILLISECONDS); RawStoreProxy rsp = new RawStoreProxy(hiveConf, hiveConf, TestStore.class, 1); try { rsp.invoke(null, TestStore.class.getMethod("exceptions"), new Object[] {}); fail("an exception is expected"); } catch (IllegalStateException ise) { // expected } Thread.sleep(20); // this shouldn't throw an exception rsp.invoke(null, TestStore.class.getMethod("noopMethod"), new Object[] {}); } }
metastore/src/test/org/apache/hadoop/hive/metastore/TestRawStoreProxy.java
HIVE-13937 : Unit test for HIVE13051 (Zoltan Haindrich via Ashutosh Chauhan) Signed-off-by: Ashutosh Chauhan <[email protected]>
metastore/src/test/org/apache/hadoop/hive/metastore/TestRawStoreProxy.java
HIVE-13937 : Unit test for HIVE13051 (Zoltan Haindrich via Ashutosh Chauhan)
<ide><path>etastore/src/test/org/apache/hadoop/hive/metastore/TestRawStoreProxy.java <add>/** <add> * Licensed to the Apache Software Foundation (ASF) under one <add> * or more contributor license agreements. See the NOTICE file <add> * distributed with this work for additional information <add> * regarding copyright ownership. The ASF licenses this file <add> * to you under the Apache License, Version 2.0 (the <add> * "License"); you may not use this file except in compliance <add> * with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.apache.hadoop.hive.metastore; <add> <add>import static org.junit.Assert.fail; <add> <add>import java.util.concurrent.TimeUnit; <add> <add>import org.apache.hadoop.conf.Configuration; <add>import org.apache.hadoop.hive.conf.HiveConf; <add>import org.apache.hadoop.hive.metastore.api.MetaException; <add>import org.junit.Test; <add> <add>public class TestRawStoreProxy { <add> <add> static class TestStore extends ObjectStore { <add> @Override <add> public void setConf(Configuration conf) { <add> // noop <add> } <add> <add> public void noopMethod() throws MetaException { <add> Deadline.checkTimeout(); <add> } <add> <add> public void exceptions() throws IllegalStateException, MetaException { <add> Deadline.checkTimeout(); <add> throw new IllegalStateException("throwing an exception"); <add> } <add> } <add> <add> @Test <add> public void testExceptionDispatch() throws Throwable { <add> HiveConf hiveConf = new HiveConf(); <add> hiveConf.setTimeVar(HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT, 10, <add> TimeUnit.MILLISECONDS); <add> RawStoreProxy rsp = new RawStoreProxy(hiveConf, hiveConf, TestStore.class, 1); <add> try { <add> rsp.invoke(null, TestStore.class.getMethod("exceptions"), new Object[] {}); <add> fail("an exception is expected"); <add> } catch (IllegalStateException ise) { <add> // expected <add> } <add> Thread.sleep(20); <add> // this shouldn't throw an exception <add> rsp.invoke(null, TestStore.class.getMethod("noopMethod"), new Object[] {}); <add> } <add>}
Java
lgpl-2.1
9ce25f2a8ac742ada2c0e5853281c1bc6119a83f
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
/* * Copyright (C) 2002-2004 David Pavlis <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jetel.interpreter; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.Properties; import java.util.regex.Matcher; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataField; import org.jetel.data.DataRecord; import org.jetel.data.primitive.CloverDouble; import org.jetel.data.primitive.CloverInteger; import org.jetel.data.primitive.CloverLong; import org.jetel.data.primitive.DecimalFactory; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.graph.TransformationGraph; import org.jetel.interpreter.ASTnode.CLVFAddNode; import org.jetel.interpreter.ASTnode.CLVFAnd; import org.jetel.interpreter.ASTnode.CLVFAssignment; import org.jetel.interpreter.ASTnode.CLVFBlock; import org.jetel.interpreter.ASTnode.CLVFBreakStatement; import org.jetel.interpreter.ASTnode.CLVFBreakpointNode; import org.jetel.interpreter.ASTnode.CLVFCaseExpression; import org.jetel.interpreter.ASTnode.CLVFComparison; import org.jetel.interpreter.ASTnode.CLVFContinueStatement; import org.jetel.interpreter.ASTnode.CLVFDate2NumNode; import org.jetel.interpreter.ASTnode.CLVFDateAddNode; import org.jetel.interpreter.ASTnode.CLVFDateDiffNode; import org.jetel.interpreter.ASTnode.CLVFDivNode; import org.jetel.interpreter.ASTnode.CLVFDoStatement; import org.jetel.interpreter.ASTnode.CLVFForStatement; import org.jetel.interpreter.ASTnode.CLVFForeachStatement; import org.jetel.interpreter.ASTnode.CLVFFunctionCallStatement; import org.jetel.interpreter.ASTnode.CLVFFunctionDeclaration; import org.jetel.interpreter.ASTnode.CLVFIfStatement; import org.jetel.interpreter.ASTnode.CLVFIffNode; import org.jetel.interpreter.ASTnode.CLVFImportSource; import org.jetel.interpreter.ASTnode.CLVFInputFieldLiteral; import org.jetel.interpreter.ASTnode.CLVFIsNullNode; import org.jetel.interpreter.ASTnode.CLVFLiteral; import org.jetel.interpreter.ASTnode.CLVFLookupNode; import org.jetel.interpreter.ASTnode.CLVFMapping; import org.jetel.interpreter.ASTnode.CLVFMinusMinusNode; import org.jetel.interpreter.ASTnode.CLVFMinusNode; import org.jetel.interpreter.ASTnode.CLVFModNode; import org.jetel.interpreter.ASTnode.CLVFMulNode; import org.jetel.interpreter.ASTnode.CLVFNVLNode; import org.jetel.interpreter.ASTnode.CLVFOperator; import org.jetel.interpreter.ASTnode.CLVFOr; import org.jetel.interpreter.ASTnode.CLVFOutputFieldLiteral; import org.jetel.interpreter.ASTnode.CLVFPlusPlusNode; import org.jetel.interpreter.ASTnode.CLVFPostfixExpression; import org.jetel.interpreter.ASTnode.CLVFPrintErrNode; import org.jetel.interpreter.ASTnode.CLVFPrintLogNode; import org.jetel.interpreter.ASTnode.CLVFPrintStackNode; import org.jetel.interpreter.ASTnode.CLVFRaiseErrorNode; import org.jetel.interpreter.ASTnode.CLVFRegexLiteral; import org.jetel.interpreter.ASTnode.CLVFReturnStatement; import org.jetel.interpreter.ASTnode.CLVFSequenceNode; import org.jetel.interpreter.ASTnode.CLVFSizeNode; import org.jetel.interpreter.ASTnode.CLVFStart; import org.jetel.interpreter.ASTnode.CLVFStartExpression; import org.jetel.interpreter.ASTnode.CLVFStatementExpression; import org.jetel.interpreter.ASTnode.CLVFStr2NumNode; import org.jetel.interpreter.ASTnode.CLVFSubNode; import org.jetel.interpreter.ASTnode.CLVFSwitchStatement; import org.jetel.interpreter.ASTnode.CLVFSymbolNameExp; import org.jetel.interpreter.ASTnode.CLVFTruncNode; import org.jetel.interpreter.ASTnode.CLVFUnaryExpression; import org.jetel.interpreter.ASTnode.CLVFVarDeclaration; import org.jetel.interpreter.ASTnode.CLVFVariableLiteral; import org.jetel.interpreter.ASTnode.CLVFWhileStatement; import org.jetel.interpreter.ASTnode.Node; import org.jetel.interpreter.ASTnode.SimpleNode; import org.jetel.interpreter.data.TLListVariable; import org.jetel.interpreter.data.TLMapVariable; import org.jetel.interpreter.data.TLValue; import org.jetel.interpreter.data.TLValueType; import org.jetel.interpreter.data.TLVariable; import org.jetel.metadata.DataFieldMetadata; import org.jetel.util.Compare; import org.jetel.util.StringUtils; /** * Executor of FilterExpression parse tree. * * @author dpavlis * @since 16.9.2004 * * Executor of FilterExpression parse tree */ public class TransformLangExecutor implements TransformLangParserVisitor, TransformLangParserConstants{ public static final int BREAK_BREAK=1; public static final int BREAK_CONTINUE=2; public static final int BREAK_RETURN=3; protected Stack stack; protected boolean breakFlag; protected int breakType; protected Properties globalParameters; protected DataRecord[] inputRecords; protected DataRecord[] outputRecords; protected Node emptyNode; // used as replacement for empty statements protected TransformationGraph graph; protected Log runtimeLogger; static Log logger = LogFactory.getLog(TransformLangExecutor.class); /** * Constructor */ public TransformLangExecutor(Properties globalParameters) { stack = new Stack(); breakFlag = false; this.globalParameters=globalParameters; emptyNode = new SimpleNode(Integer.MAX_VALUE); } public TransformLangExecutor() { this(null); } public TransformationGraph getGraph() { return graph; } public void setGraph(TransformationGraph graph) { this.graph = graph; } public Log getRuntimeLogger() { return runtimeLogger; } public void setRuntimeLogger(Log runtimeLogger) { this.runtimeLogger = runtimeLogger; } /** * Set input data records for processing.<br> * Referenced input data fields will be resolved from * these data records. * * @param inputRecords array of input data records carrying values */ public void setInputRecords(DataRecord[] inputRecords){ this.inputRecords=inputRecords; } /** * Set output data records for processing.<br> * Referenced output data fields will be resolved from * these data records - assignment (in code) to output data field * will result in assignment to one of these data records. * * @param outputRecords array of output data records for setting values */ public void setOutputRecords(DataRecord[] outputRecords){ this.outputRecords=outputRecords; } /** * Set global parameters which may be reference from within the * transformation source code * * @param parameters */ public void setGlobalParameters(Properties parameters){ this.globalParameters=parameters; } /** * Allows to store parameter/value on stack from * where it can be read by executed script/function. * @param obj Object/value to be stored * @since 10.12.2006 */ public void setParameter(String obj){ stack.push(new TLValue(TLValueType.STRING,obj)); } /** * Method which returns result of executing parse tree.<br> * Basically, it returns whatever object was left on top of executor's * stack (usually as a result of last executed expression/operation).<br> * It can be called repetitively in order to read all objects from stack. * * @return Object saved on stack or NULL if no more objects are available */ public TLValue getResult() { return stack.pop(); } /** * Return value of globally defined variable determined by slot number. * Slot can be obtained by calling <code>TransformLangParser.getGlobalVariableSlot(<i>varname</i>)</code> * * @param varSlot * @return Object - depending of Global variable type * @since 6.12.2006 */ public TLVariable getGlobalVariable(int varSlot){ return stack.getGlobalVar(varSlot); } /** * Allows to set value of defined global variable. * * @param varSlot * @param value * @since 6.12.2006 */ public void setGlobalVariable(int varSlot,TLVariable value){ stack.storeGlobalVar(varSlot,value); } /* *********************************************************** */ /* implementation of visit methods for each class of AST node */ /* *********************************************************** */ /* it seems to be necessary to define a visit() method for SimpleNode */ public Object visit(SimpleNode node, Object data) { // throw new TransformLangExecutorRuntimeException(node, // "Error: Call to visit for SimpleNode"); return data; } public Object visit(CLVFStart node, Object data) { int i, k = node.jjtGetNumChildren(); for (i = 0; i < k; i++) node.jjtGetChild(i).jjtAccept(this, data); return data; // this value is ignored in this example } public Object visit(CLVFStartExpression node, Object data) { int i, k = node.jjtGetNumChildren(); for (i = 0; i < k; i++) node.jjtGetChild(i).jjtAccept(this, data); return data; // this value is ignored in this example } public Object visit(CLVFOr node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a=stack.pop(); if (a.type!=TLValueType.BOOLEAN){ Object params[]=new Object[]{a}; throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value"); }else if (a.getBoolean()){ stack.push(Stack.TRUE_VAL); return data; } node.jjtGetChild(1).jjtAccept(this, data); a=stack.pop(); if (a.type!=TLValueType.BOOLEAN){ Object params[]=new Object[]{a}; throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value"); } stack.push( a.getBoolean() ? Stack.TRUE_VAL : Stack.FALSE_VAL); return data; } public Object visit(CLVFAnd node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a=stack.pop(); if (a.type!=TLValueType.BOOLEAN){ Object params[]=new Object[]{a}; throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value"); }else if (!a.getBoolean()){ stack.push(Stack.FALSE_VAL); return data; } node.jjtGetChild(1).jjtAccept(this, data); a=stack.pop(); if (a.type!=TLValueType.BOOLEAN){ Object params[]=new Object[]{a}; throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value"); } stack.push(a.getBoolean() ? Stack.TRUE_VAL : Stack.FALSE_VAL); return data; } public Object visit(CLVFComparison node, Object data) { int cmpResult = 2; boolean lValue = false; // special handling for Regular expression if (node.cmpType == REGEX_EQUAL) { node.jjtGetChild(0).jjtAccept(this, data); TLValue field1 = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue field2 = stack.pop(); if (field1.type == TLValueType.STRING && field2.getValue() instanceof Matcher) { Matcher regex = (Matcher) field2.getValue(); regex.reset(field1.getCharSequence()); if (regex.matches()) { lValue = true; } else { lValue = false; } } else { Object[] arguments = { field1, field2 }; throw new TransformLangExecutorRuntimeException(node, arguments, "regex equal - wrong type of literal(s)"); } // other types of comparison } else { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (!a.type.isCompatible(b.type)) { Object arguments[] = { a, b }; throw new TransformLangExecutorRuntimeException(node, arguments, "compare - incompatible literals/expressions"); } switch (a.type) { case INTEGER: case LONG: case DOUBLE: case DECIMAL: cmpResult = a.getNumeric().compareTo(b.getNumeric()); break; case DATE: cmpResult = a.getDate().compareTo(b.getDate()); break; case STRING: cmpResult = Compare.compare(a.getCharSequence(), b .getCharSequence()); break; case BOOLEAN: if (node.cmpType == EQUAL || node.cmpType == NON_EQUAL) { cmpResult = a.getBoolean() == b.getBoolean() ? 0 : -1; } else { Object arguments[] = { a, b }; throw new TransformLangExecutorRuntimeException(node, arguments, "compare - unsupported comparison operator [" + tokenImage[node.cmpType] + "] for literals/expressions"); } break; default: Object arguments[] = { a, b }; throw new TransformLangExecutorRuntimeException(node, arguments, "compare - don't know how to compare literals/expressions"); } switch (node.cmpType) { case EQUAL: if (cmpResult == 0) { lValue = true; } break;// equal case LESS_THAN: if (cmpResult == -1) { lValue = true; } break;// less than case GREATER_THAN: if (cmpResult == 1) { lValue = true; } break;// grater than case LESS_THAN_EQUAL: if (cmpResult <= 0) { lValue = true; } break;// less than equal case GREATER_THAN_EQUAL: if (cmpResult >= 0) { lValue = true; } break;// greater than equal case NON_EQUAL: if (cmpResult != 0) { lValue = true; } break; default: // this should never happen !!! logger .fatal("Internal error: Unsupported comparison operator !"); throw new RuntimeException( "Internal error - Unsupported comparison operator !"); } } stack.push(lValue ? Stack.TRUE_VAL : Stack.FALSE_VAL); return data; } public Object visit(CLVFAddNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { //TODO: (check) we allow empty strings to be concatenated if (a.type!=TLValueType.STRING) throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "add - NULL value not allowed"); } if (node.nodeVal==null) { node.nodeVal= a.isNull() ? TLValue.create(a.type) : a.duplicate(); } try { if (a.type.isNumeric() && b.type.isNumeric()) { node.nodeVal.getNumeric().setValue(a.getNumeric()); node.nodeVal.getNumeric().add(b.getNumeric()); stack.push(node.nodeVal); } else if (a.type==TLValueType.DATE && b.type.isNumeric()) { Calendar result = Calendar.getInstance(); result.setTime(a.getDate()); result.add(Calendar.DATE, b.getInt()); node.nodeVal.getDate().setTime(result.getTimeInMillis()); stack.push(node.nodeVal); } else if (a.type==TLValueType.STRING) { CharSequence a1 = a.getCharSequence(); StringBuilder buf=(StringBuilder)node.nodeVal.getValue(); buf.setLength(0); StringUtils.strBuffAppend(buf,a1); if (b.type==TLValueType.STRING) { StringUtils.strBuffAppend(buf,b.getCharSequence()); } else { buf.append(b); } stack.push(node.nodeVal); } else { Object[] arguments = { a, b }; throw new TransformLangExecutorRuntimeException(node,arguments, "add - wrong type of literal(s)"); } } catch (ClassCastException ex) { Object arguments[] = { a, b }; throw new TransformLangExecutorRuntimeException(node,arguments, "add - wrong type of literal(s)"); } return data; } public Object visit(CLVFSubNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "sub - NULL value not allowed"); } if (!b.type.isNumeric()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { b }, "sub - wrong type of literal"); } if (node.nodeVal==null) { node.nodeVal=a.duplicate(); } if(a.type.isNumeric()) { node.nodeVal.getNumeric().setValue(a.getNumeric()); node.nodeVal.getNumeric().sub(b.getNumeric()); stack.push(node.nodeVal); } else if (a.type==TLValueType.DATE) { Calendar result = Calendar.getInstance(); result.setTime(a.getDate()); result.add(Calendar.DATE, b.getInt() * -1); node.nodeVal.getDate().setTime(result.getTimeInMillis()); stack.push(node.nodeVal); } else { Object[] arguments = { a, b }; throw new TransformLangExecutorRuntimeException(node,arguments, "sub - wrong type of literal(s)"); } return data; } public Object visit(CLVFMulNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "mul - NULL value not allowed"); } if (!a.type.isNumeric() && !b.type.isNumeric()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b }, "mul - wrong type of literals"); } if (node.nodeVal==null) { node.nodeVal=a.duplicate(); } node.nodeVal.getNumeric().setValue(a.getNumeric()); node.nodeVal.getNumeric().mul(b.getNumeric()); stack.push(node.nodeVal); return data; } public Object visit(CLVFDivNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "div - NULL value not allowed"); } if (!a.type.isNumeric() && !b.type.isNumeric()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b }, "div - wrong type of literals"); } if (node.nodeVal==null || node.nodeVal.type!=a.type) { node.nodeVal=TLValue.create(a.type); } node.nodeVal.getNumeric().setValue(a.getNumeric()); try { node.nodeVal.getNumeric().div(b.getNumeric()); }catch(ArithmeticException ex){ throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b }, "div - arithmetic exception",ex); }catch (Exception ex) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b }, "div - error during operation",ex); } stack.push(node.nodeVal); return data; } public Object visit(CLVFModNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "mod - NULL value not allowed"); } if (!a.type.isNumeric() && !b.type.isNumeric()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "mod - wrong type of literals"); } if (node.nodeVal==null) { node.nodeVal=a.duplicate(); } node.nodeVal.getNumeric().setValue(a.getNumeric()); node.nodeVal.getNumeric().mod(b.getNumeric()); stack.push(node.nodeVal); return data; } /* public Object visit(CLVFNegation node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); if (value.type==TLValueType.BOOLEAN) { stack.push(value.getBoolean() ? Stack.FALSE_VAL : Stack.TRUE_VAL); } else { throw new TransformLangExecutorRuntimeException(node, new Object[] { value }, "logical condition does not evaluate to BOOLEAN value"); } return data; } */ public Object visit(CLVFIsNullNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); if (value.isNull()) { stack.push(Stack.TRUE_VAL); } else { if (value.type==TLValueType.STRING) { stack.push( value.getCharSequence().length()==0 ? Stack.TRUE_VAL : Stack.FALSE_VAL); }else { stack.push(Stack.FALSE_VAL); } } return data; } public Object visit(CLVFNVLNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); if (value.isNull()) { node.jjtGetChild(1).jjtAccept(this, data); } else { if (value.type==TLValueType.STRING && value.getCharSequence().length()==0) { node.jjtGetChild(1).jjtAccept(this, data); }else { stack.push(value); } } return data; } public Object visit(CLVFLiteral node, Object data) { stack.push(node.valueTL); return data; } public Object visit(CLVFInputFieldLiteral node, Object data) { DataRecord record = inputRecords[node.recordNo]; if (record == null) { stack.push(Stack.NULL_VAL); } else { DataField field = record.getField(node.fieldNo); if (field.isNull()) stack.push(Stack.NULL_VAL); else stack.push(new TLValue(field)); } // old // stack.push(inputRecords[node.recordNo].getField(node.fieldNo).getValue()); // we return reference to DataField so we can // perform extra checking in special cases return node.field; } public Object visit(CLVFOutputFieldLiteral node, Object data) { //stack.push(inputRecords[node.recordNo].getField(node.fieldNo)); // we return reference to DataField so we can // perform extra checking in special cases return data; } public Object visit(CLVFRegexLiteral node, Object data) { stack.push(new TLValue(TLValueType.OBJECT,node.matcher)); return data; } public Object visit(CLVFDateAddNode node, Object data) { int shiftAmount; node.jjtGetChild(0).jjtAccept(this, data); TLValue date = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue amount = stack.pop(); if (amount.type.isNumeric()) { shiftAmount = amount.getInt(); } else { Object arguments[] = { amount }; throw new TransformLangExecutorRuntimeException(node,arguments, "dateadd - amount is not a Numeric value"); } if (date.type!=TLValueType.DATE) { Object arguments[] = { date }; throw new TransformLangExecutorRuntimeException(node,arguments, "dateadd - no Date expression"); } if (node.nodeVal==null) { node.nodeVal=date.duplicate(); } node.calendar.setTime(date.getDate()); node.calendar.add(node.calendarField, shiftAmount); node.nodeVal.getDate().setTime(node.calendar.getTimeInMillis()); stack.push(node.nodeVal); return data; } public Object visit(CLVFDate2NumNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue date = stack.pop(); if (date.type==TLValueType.DATE) { node.calendar.setTime(date.getDate()); stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(node.calendar.get(node.calendarField)))); } else { Object arguments[] = { date }; throw new TransformLangExecutorRuntimeException(node,arguments, "date2num - no Date expression"); } return data; } public Object visit(CLVFDateDiffNode node, Object data) { TLValue date1, date2; node.jjtGetChild(0).jjtAccept(this, data); date1 = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); date2 = stack.pop(); if (date1.type==TLValueType.DATE && date1.type==date2.type) { long diffSec = (date1.getDate().getTime() - date2.getDate().getTime()) / 1000; int diff = 0; switch (node.calendarField) { case Calendar.SECOND: // we have the difference in seconds diff = (int) diffSec; break; case Calendar.MINUTE: // how many minutes' diff = (int) diffSec / 60; break; case Calendar.HOUR_OF_DAY: diff = (int) diffSec / 3600; break; case Calendar.DAY_OF_MONTH: // how many days is the difference diff = (int) diffSec / 86400; break; case Calendar.WEEK_OF_YEAR: // how many weeks diff = (int) diffSec / 604800; break; case Calendar.MONTH: node.start.setTime(date1.getDate()); node.end.setTime(date2.getDate()); diff = (node.start.get(Calendar.MONTH) + node.start .get(Calendar.YEAR) * 12) - (node.end.get(Calendar.MONTH) + node.end .get(Calendar.YEAR) * 12); break; case Calendar.YEAR: node.start.setTime(date1.getDate()); node.end.setTime(date2.getDate()); diff = node.start.get(node.calendarField) - node.end.get(node.calendarField); break; default: Object arguments[] = { new Integer(node.calendarField) }; throw new TransformLangExecutorRuntimeException(node,arguments, "datediff - wrong difference unit"); } stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(diff))); } else { Object arguments[] = { date1, date2 }; throw new TransformLangExecutorRuntimeException(node,arguments, "datediff - no Date expression"); } return data; } public Object visit(CLVFMinusNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); if (value.type.isNumeric()) { TLValue newVal=value.duplicate(); newVal.getNumeric().mul(Stack.NUM_MINUS_ONE_P); stack.push(newVal); } else { Object arguments[] = { value }; throw new TransformLangExecutorRuntimeException(node,arguments, "minus - not a number"); } return data; } public Object visit(CLVFStr2NumNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type==TLValueType.STRING) { try { TLValue value = null; switch (node.numType) { case INT_VAR: value = new TLValue(TLValueType.INTEGER,new CloverInteger(Integer.parseInt( a.getString(), node.radix))); break; case LONG_VAR: value = new TLValue(TLValueType.LONG,new CloverLong(Long.parseLong(a.getString(), node.radix))); break; case DECIMAL_VAR: if (node.radix == 10) { value = new TLValue(TLValueType.LONG,DecimalFactory.getDecimal(a.getString())); } else { Object[] arguments = { a, new Integer(node.radix) }; throw new TransformLangExecutorRuntimeException(node, arguments, "str2num - can't convert string to decimal number using specified radix"); } break; default: // get double/number type switch (node.radix) { case 10: case 16: value = new TLValue(TLValueType.DOUBLE,new CloverDouble(Double .parseDouble(a.getString()))); break; default: Object[] arguments = { a, new Integer(node.radix) }; throw new TransformLangExecutorRuntimeException(node, arguments, "str2num - can't convert string to number/double number using specified radix"); } } stack.push(value); } catch (NumberFormatException ex) { Object[] arguments = { a }; throw new TransformLangExecutorRuntimeException(node, arguments, "str2num - can't convert \"" + a + "\""); } } else { Object[] arguments = { a }; throw new TransformLangExecutorRuntimeException(node, arguments, "str2num - wrong type of literal"); } return data; } public Object visit(CLVFIffNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue condition = stack.pop(); if (condition.type==TLValueType.BOOLEAN) { if (condition.getBoolean()) { node.jjtGetChild(1).jjtAccept(this, data); } else { node.jjtGetChild(2).jjtAccept(this, data); } stack.push(stack.pop()); } else { Object[] arguments = { condition }; throw new TransformLangExecutorRuntimeException(node,arguments, "iif - condition does not evaluate to BOOLEAN value"); } return data; } public Object visit(CLVFPrintErrNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (node.printLine){ StringBuilder buf=new StringBuilder((a != null ? a.toString() : "<null>")); buf.append(" (on line: ").append(node.getLineNumber()); buf.append(" col: ").append(node.getColumnNumber()).append(")"); System.err.println(buf); }else{ System.err.println(a != null ? a : "<null>"); } return data; } public Object visit(CLVFPrintStackNode node, Object data) { for (int i=stack.top;i>=0;i--){ System.err.println("["+i+"] : "+stack.stack[i]); } return data; } /*************************************************************************** * Transformation Language executor starts here. **************************************************************************/ public Object visit(CLVFForStatement node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); // set up of the loop boolean condition = false; Node loopCondition = node.jjtGetChild(1); Node increment = node.jjtGetChild(2); Node body; try{ body=node.jjtGetChild(3); }catch(ArrayIndexOutOfBoundsException ex){ body=emptyNode; } try { loopCondition.jjtAccept(this, data); // evaluate the condition condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); }catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition"); } // loop execution while (condition) { body.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) { return data; } } increment.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // evaluate the condition loopCondition.jjtAccept(this, data); try { condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); } } return data; } public Object visit(CLVFForeachStatement node, Object data) { CLVFVariableLiteral varNode=(CLVFVariableLiteral)node.jjtGetChild(0); CLVFVariableLiteral arrayNode=(CLVFVariableLiteral)node.jjtGetChild(1); TLVariable variableToAssign = stack.getVar(varNode.localVar, varNode.varSlot); TLVariable arrayVariable=stack.getVar(arrayNode.localVar, arrayNode.varSlot); Node body; try{ body=node.jjtGetChild(2); }catch(ArrayIndexOutOfBoundsException ex){ body=emptyNode; } Iterator<TLValue> iter; switch(arrayVariable.getType()) { case LIST: iter=((TLListVariable)arrayVariable).getList().iterator(); break; case MAP: iter=((TLMapVariable)arrayVariable).getMap().values().iterator(); break; default: throw new TransformLangExecutorRuntimeException(node,"not a Map or List variable"); } while(iter.hasNext()) { variableToAssign.setValue(iter.next()); body.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) { return data; } } } return data; } public Object visit(CLVFWhileStatement node, Object data) { boolean condition = false; Node loopCondition = node.jjtGetChild(0); Node body; try{ body=node.jjtGetChild(1); }catch(ArrayIndexOutOfBoundsException ex){ body=emptyNode; } try { loopCondition.jjtAccept(this, data); // evaluate the condition condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); }catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition"); } // loop execution while (condition) { body.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data; } // evaluate the condition loopCondition.jjtAccept(this, data); try { condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); } } return data; } public Object visit(CLVFIfStatement node, Object data) { boolean condition = false; try { node.jjtGetChild(0).jjtAccept(this, data); // evaluate the // condition condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"condition does not evaluate to BOOLEAN value"); } catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition"); } // first if if (condition) { node.jjtGetChild(1).jjtAccept(this, data); } else { // if else part exists if (node.jjtGetNumChildren() > 2) { node.jjtGetChild(2).jjtAccept(this, data); } } return data; } public Object visit(CLVFDoStatement node, Object data) { boolean condition = false; Node loopCondition = node.jjtGetChild(1); Node body = node.jjtGetChild(0); // loop execution do { body.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data; } // evaluate the condition loopCondition.jjtAccept(this, data); try { condition = stack.pop().getBoolean(); }catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); }catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition"); } } while (condition); return data; } public Object visit(CLVFSwitchStatement node, Object data) { // get value of switch && push/leave it on stack boolean match=false; node.jjtGetChild(0).jjtAccept(this, data); TLValue switchVal=stack.pop(); int numChildren = node.jjtGetNumChildren(); int numCases = node.hasDefaultClause ? numChildren-1 : numChildren; // loop over remaining case statements for (int i = 1; i < numCases; i++) { stack.push(switchVal); if (node.jjtGetChild(i).jjtAccept(this, data)==Stack.TRUE_VAL){ match=true; } if (breakFlag) { if (breakType == BREAK_BREAK) { breakFlag = false; } break; } } // test whether execute default branch if (node.hasDefaultClause && !match){ node.jjtGetChild(numChildren-1).jjtAccept(this, data); } return data; } public Object visit(CLVFCaseExpression node, Object data) { // test if literal (as child 0) is equal to data on stack // if so, execute block (child 1) boolean match = false; TLValue switchVal = stack.pop(); node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); try { switch(switchVal.type) { case INTEGER: case LONG: case DOUBLE: case DECIMAL: match = (value.getNumeric().compareTo(switchVal.getNumeric()) == 0); break; case STRING: match = (Compare.compare(switchVal.getCharSequence(), value.getCharSequence()) == 0); break; case DATE: match = ( switchVal.getDate().compareTo(value.getDate()) == 0); break; case BOOLEAN: match = (switchVal.getBoolean()==value.getBoolean()); break; default: } } catch (ClassCastException ex) { Object[] args=new Object[] {switchVal,value}; throw new TransformLangExecutorRuntimeException(node,args,"incompatible literals in case clause"); }catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid case value"); } if (match){ node.jjtGetChild(1).jjtAccept(this, data); return Stack.TRUE_VAL; } return Stack.FALSE_VAL; } public Object visit(CLVFPlusPlusNode node, Object data) { Node childNode = node.jjtGetChild(0); if (node.statement) { CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode; TLVariable var=stack.getVar(varNode.localVar, varNode.varSlot); if (var.getType().isNumeric()) { var.getValue().getNumeric().add(Stack.NUM_ONE_P); }else if (var.getType()==TLValueType.DATE) { stack.calendar.setTime(var.getValue().getDate()); stack.calendar.add(Calendar.DATE, 1); var.getValue().setValue(stack.calendar.getTime()); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } } return data; } public Object visit(CLVFMinusMinusNode node, Object data) { Node childNode = node.jjtGetChild(0); if (node.statement) { CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode; TLVariable var=stack.getVar(varNode.localVar, varNode.varSlot); if (var.getType().isNumeric()) { var.getValue().getNumeric().sub(Stack.NUM_ONE_P); }else if (var.getType()==TLValueType.DATE) { stack.calendar.setTime(var.getValue().getDate()); stack.calendar.add(Calendar.DATE, -1); var.getValue().setValue(stack.calendar.getTime()); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } } return data; } public Object visit(CLVFBlock node, Object data) { int childern = node.jjtGetNumChildren(); for (int i = 0; i < childern; i++) { node.jjtGetChild(i).jjtAccept(this, data); // have we seen contiue/break/return statement ?? if (breakFlag){ if (breakType!=BREAK_RETURN) stack.pop(); return data; } stack.pop(); } return data; } /* * Loop & block & function control nodes */ public Object visit(CLVFBreakStatement node, Object data) { breakFlag = true; // we encountered break statement; breakType=BREAK_BREAK; return data; } public Object visit(CLVFContinueStatement node, Object data) { breakFlag = true; // we encountered continue statement; breakType= BREAK_CONTINUE; return data; } public Object visit(CLVFReturnStatement node, Object data) { if (node.jjtHasChildren()){ node.jjtGetChild(0).jjtAccept(this, data); } breakFlag = true; breakType = BREAK_RETURN; return data; } public Object visit(CLVFBreakpointNode node, Object data) { // list all variables System.err.println("** list of global variables ***"); for (int i=0;i<stack.globalVarSlot.length;System.out.println(stack.globalVarSlot[i++])); System.err.println("** list of local variables ***"); for (int i=0;i<stack.localVarCounter;i++) System.out.println(stack.localVarSlot[stack.localVarSlotOffset+i]); return data; } /* * Variable declarations */ public Object visit(CLVFVarDeclaration node, Object data) { TLValue value=null; TLVariable variable=null; // create global/local variable switch (node.type) { case INT_VAR: value = new TLValue(TLValueType.INTEGER, new CloverInteger(0)); break; case LONG_VAR: value = new TLValue(TLValueType.LONG,new CloverLong(0)); break; case DOUBLE_VAR: value = new TLValue(TLValueType.DOUBLE, new CloverDouble(0)); break; case DECIMAL_VAR: if (node.length > 0) { if (node.precision > 0) { value = new TLValue(TLValueType.DECIMAL, DecimalFactory.getDecimal(node.length, node.precision)); } else { value = new TLValue(TLValueType.DECIMAL,DecimalFactory.getDecimal(node.length, 0)); } } else { value = new TLValue(TLValueType.DECIMAL,DecimalFactory.getDecimal()); } break; case STRING_VAR: value = new TLValue(TLValueType.STRING,new StringBuilder()); break; case DATE_VAR: value = new TLValue(TLValueType.DATE,new Date()); break; case BOOLEAN_VAR: value = Stack.FALSE_VAL; break; case LIST_VAR: if (node.length>0) { variable = new TLListVariable(node.name,node.length); ((TLListVariable)variable).fill(Stack.NULL_VAL, node.length); }else { variable = new TLListVariable(node.name); } break; case MAP_VAR: if (node.length>0){ variable = new TLMapVariable(node.name,node.length); }else { variable = new TLMapVariable(node.name); } break; default: throw new TransformLangExecutorRuntimeException(node, "variable declaration - " + "unknown type for variable \"" + node.name + "\""); } if (variable==null) variable=new TLVariable(node.name,value); stack.storeVar(node.localVar, node.varSlot,variable ); if (node.jjtHasChildren()) { node.jjtGetChild(0).jjtAccept(this, data); TLValue initValue = stack.pop(); TLValueType type =variable.getType(); if (type.isStrictlyCompatible(initValue.type)) { variable.setValue(initValue); }else { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + initValue + "\" to variable \"" + node.name + "\" - incompatible data types"); } } return data; } public Object visit(CLVFVariableLiteral node, Object data) { TLVariable var = stack.getVar(node.localVar, node.varSlot); TLValue index = null; if (node.indexSet) { try { switch (var.getType()) { case LIST: node.jjtGetChild(0).jjtAccept(this, data); index = stack.pop(); stack.push(var.getValue(index.getInt())); break; case MAP: node.jjtGetChild(0).jjtAccept(this, data); index = stack.pop(); stack.push(var.getValue(index.getString())); break; } } catch (Exception ex) { throw new TransformLangExecutorRuntimeException(node, "invalid index \"" + index + "\" of variable \"" + var.getName() + "\" - type " + var.getType().toString(), ex); } }else { stack.push(var.getValue()); } return data; } public Object visit(CLVFAssignment node, Object data) { CLVFVariableLiteral varNode = (CLVFVariableLiteral) node.jjtGetChild(0); TLVariable variableToAssign = stack.getVar(varNode.localVar, varNode.varSlot); node.jjtGetChild(1).jjtAccept(this, data); TLValue valueToAssign = stack.pop(); if (valueToAssign==null) { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + valueToAssign + "\" to variable \"" + varNode.varName+"\""); } TLValue index = null; switch (varNode.varType) { case LIST_VAR: try { if (varNode.indexSet) { varNode.jjtGetChild(0).jjtAccept(this, data); index = stack.pop(); variableToAssign.setValue(index.getInt(), valueToAssign); }else { variableToAssign.setValue(-1,valueToAssign); } } catch (IndexOutOfBoundsException ex) { throw new TransformLangExecutorRuntimeException(node, "index \""+index+"\" is outside current limits of list/array \"" + varNode.varName+"\"", ex); } catch (Exception ex) { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + valueToAssign + "\" to variable \"" + varNode.varName+"\"", ex); } break; case MAP_VAR: try { varNode.jjtGetChild(0).jjtAccept(this, data); index = stack.pop(); variableToAssign.setValue(index.getString(), valueToAssign); } catch (Exception ex) { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + valueToAssign + "\" to variable \"" + varNode.varName+"\"", ex); } break; default: TLValueType type=variableToAssign.getType(); if (type.isCompatible(valueToAssign.type)) { variableToAssign.setValue(valueToAssign); } else { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + valueToAssign + "[" + valueToAssign.type + "] \" to variable \"" + variableToAssign.getName() + "\" [" + variableToAssign.getType() + "] \" - incompatible data types"); } } return data; } public Object visit(CLVFMapping node, Object data) { DataField field=outputRecords[node.recordNo].getField(node.fieldNo); int arity=node.jjtGetNumChildren(); // how many children we have defined TLValue value=null; try{ // we try till success or no more options for (int i=0;i<arity;i++){ node.jjtGetChild(i).jjtAccept(this, data); value=stack.pop(); try{ value.copyToDataField(field); break; // success during assignment, finish looping }catch(Exception ex){ if (i == arity-1) throw ex; } } }catch(BadDataFormatException ex){ if (!outputRecords[node.recordNo].getField(node.fieldNo).getMetadata().isNullable()){ throw new TransformLangExecutorRuntimeException(node,"can't assign NULL to \"" + node.fieldName + "\""); } throw new TransformLangExecutorRuntimeException(node,"data format exception when mapping \"" + node.fieldName + "\" - assigning \"" + value + "\""); }catch(TransformLangExecutorRuntimeException ex){ throw ex; }catch(Exception ex){ String msg=ex.getMessage(); throw new TransformLangExecutorRuntimeException(node, (msg!=null ? msg : "") + " when mapping \"" + node.fieldName + "\" ("+DataFieldMetadata.type2Str(field.getType()) +") - assigning \"" + value + "\" ("+(value!=null ? value.getType().getName(): "unknown type" )+")"); } return data; } /* * Declaration & calling of Functions here */ public Object visit(CLVFFunctionCallStatement node, Object data) { // EXTERNAL FUNCTION if (node.externalFunction != null) { // put call parameters on stack node.childrenAccept(this, data); // convert stack content into values try { TLValue returnVal = node.externalFunction.execute(stack.pop( node.externalFunctionParams, node.jjtGetNumChildren()), node.context); stack.push(returnVal); } catch (TransformLangExecutorRuntimeException ex) { ex.setNode(node); throw ex; } } else { // INTERNAL FUNCTION // put call parameters on stack node.childrenAccept(this, data); CLVFFunctionDeclaration executionNode = node.callNode; // open call frame stack.pushFuncCallFrame(); // store call parameters from stack as local variables for (int i = executionNode.numParams - 1; i >= 0; stack .storeLocalVar(i--, new TLVariable("local", stack.pop()))) ; // execute function body // loop execution TLValue returnData; int numChildren = executionNode.jjtGetNumChildren(); for (int i = 0; i < numChildren; i++) { executionNode.jjtGetChild(i).jjtAccept(this, data); returnData = stack.pop(); // in case there is anything on top // of stack // check for break or continue statements if (breakFlag) { breakFlag = false; if (breakType == BREAK_RETURN) { if (returnData != null) stack.push(returnData); break; } } } stack.popFuncCallFrame(); } return data; } public Object visit(CLVFFunctionDeclaration node, Object data) { return data; } public Object visit(CLVFStatementExpression node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); return data; } public Object executeFunction(CLVFFunctionDeclaration executionNode, TLValue[] data) { //put call parameters on stack if (data==null){ data=new TLValue[0]; } //TODO - check for function call parameter types // open call frame stack.pushFuncCallFrame(); // store call parameters from stack as local variables for (int i=executionNode.numParams-1;i>=0; i--) { stack.storeLocalVar(i, new TLVariable(executionNode.varNames[i], data[i])); } // execute function body // loop execution TLValue returnData; int numChildren=executionNode.jjtGetNumChildren(); for (int i=0;i<numChildren;i++){ executionNode.jjtGetChild(i).jjtAccept(this,data); returnData=stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_RETURN){ if (returnData!=null) stack.push(returnData); break; } } } stack.popFuncCallFrame(); return data; } /* * MATH functions log,log10,exp,pow,sqrt,round */ /* public Object visit(CLVFSqrtNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble(Math.sqrt(((Numeric)a).getDouble()) ))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing SQRT function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "sqrt - wrong type of literal(s)"); } return data; } public Object visit(CLVFLogNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble(Math.log(((Numeric)a).getDouble()) ))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "log - wrong type of literal(s)"); } return data; } public Object visit(CLVFLog10Node node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble( Math.log10(((Numeric)a).getDouble())))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG10 function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "log10 - wrong type of literal(s)"); } return data; } public Object visit(CLVFExpNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble( Math.exp(((Numeric)a).getDouble())))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing EXP function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "exp - wrong type of literal(s)"); } return data; } public Object visit(CLVFRoundNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverLong(Math.round(((Numeric)a).getDouble())))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing ROUND function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "round - wrong type of literal(s)"); } return data; } public Object visit(CLVFPowNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.type.isNumeric() && b.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble(Math.pow(a.getDouble(), b.getDouble())))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing POW function",ex); } }else { Object[] arguments = { a, b }; throw new TransformLangExecutorRuntimeException(node,arguments, "pow - wrong type of literal(s)"); } return data; } public Object visit(CLVFPINode node, Object data) { stack.push(Stack.NUM_PI); return data; } */ public Object visit(CLVFTruncNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type==TLValueType.DATE ) { stack.calendar.setTime(a.getDate()); stack.calendar.set(Calendar.HOUR_OF_DAY, 0); stack.calendar.set(Calendar.MINUTE , 0); stack.calendar.set(Calendar.SECOND , 0); stack.calendar.set(Calendar.MILLISECOND , 0); stack.push( new TLValue(TLValueType.DATE,stack.calendar.getTime() )); }else if (a.type.isNumeric()){ stack.push(new TLValue(TLValueType.LONG,new CloverLong(a.getLong()))); }else { Object[] arguments = { a }; throw new TransformLangExecutorRuntimeException(node,arguments, "trunc - wrong type of literal(s)"); } return data; } public Object visit(CLVFRaiseErrorNode node,Object data){ node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); throw new TransformLangExecutorRuntimeException(node,null, "!!! Exception raised by user: "+((a!=null) ? a.toString() : "no message")); } public Object visit(CLVFSequenceNode node,Object data){ Object seqVal=null; TLValueType type=null; if (node.sequence==null){ if (graph!=null){ node.sequence=graph.getSequence(node.sequenceName); }else{ throw new TransformLangExecutorRuntimeException(node, "Can't obtain Sequence \""+node.sequenceName+ "\" from graph - graph is not assigned"); } if (node.sequence==null){ throw new TransformLangExecutorRuntimeException(node, "Can't obtain Sequence \""+node.sequenceName+ "\" from graph \""+graph.getName()+"\""); } } switch(node.opType){ case CLVFSequenceNode.OP_RESET: node.sequence.reset(); seqVal=Stack.NUM_ZERO; type=TLValueType.INTEGER; break; case CLVFSequenceNode.OP_CURRENT: switch(node.retType){ case LONG_VAR: seqVal=new CloverLong(node.sequence.currentValueLong()); type=TLValueType.LONG; break; case STRING_VAR: seqVal=node.sequence.currentValueString(); type=TLValueType.STRING; default: seqVal=new CloverInteger(node.sequence.currentValueInt()); type=TLValueType.INTEGER; } default: // default is next value from sequence switch(node.retType){ case LONG_VAR: seqVal=new CloverLong(node.sequence.nextValueLong()); type=TLValueType.LONG; break; case STRING_VAR: seqVal=node.sequence.nextValueString(); type=TLValueType.STRING; default: seqVal=new CloverInteger(node.sequence.nextValueInt()); } } stack.push(new TLValue(type,seqVal)); return data; } public Object visit(CLVFLookupNode node,Object data){ DataRecord record=null; if (node.lookup==null){ node.lookup=graph.getLookupTable(node.lookupName); if (node.lookup==null){ throw new TransformLangExecutorRuntimeException(node, "Can't obtain LookupTable \""+node.lookupName+ "\" from graph \""+graph.getName()+"\""); } node.fieldNum=node.lookup.getMetadata().getFieldPosition(node.fieldName); if (node.fieldNum<0){ throw new TransformLangExecutorRuntimeException(node, "Invalid field name \""+node.fieldName+"\" at LookupTable \""+node.lookupName+ "\" in graph \""+graph.getName()+"\""); } } switch(node.opType){ case CLVFLookupNode.OP_INIT: try{ node.lookup.init(); }catch(ComponentNotReadyException ex){ throw new TransformLangExecutorRuntimeException(node, "Error when initializing lookup table \""+node.lookupName+"\" :", ex); } return data; case CLVFLookupNode.OP_FREE: node.lookup.free(); return data; case CLVFLookupNode.OP_NUM_FOUND: stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(node.lookup.getNumFound()))); return data; case CLVFLookupNode.OP_GET: Object keys[]=new Object[node.jjtGetNumChildren()]; for(int i=0;i<node.jjtGetNumChildren();i++){ node.jjtGetChild(i).jjtAccept(this, data); keys[i]=stack.pop(); } record=node.lookup.get(keys); break; case CLVFLookupNode.OP_NEXT: record=node.lookup.getNext(); } if(record!=null){ stack.push(new TLValue(record.getField(node.fieldNum))); }else{ stack.push(Stack.NULL_VAL); } return data; } public Object visit(CLVFPrintLogNode node, Object data) { if (runtimeLogger == null) { throw new TransformLangExecutorRuntimeException(node, "Can NOT perform logging operation - no logger defined"); } node.jjtGetChild(0).jjtAccept(this, data); TLValue msg = stack.pop(); switch (node.level) { case 1: //| "debug" runtimeLogger.debug(msg); break; case 2: //| "info" runtimeLogger.info(msg); break; case 3: //| "warn" runtimeLogger.warn(msg); break; case 4: //| "error" runtimeLogger.error(msg); break; case 5: //| "fatal" runtimeLogger.fatal(msg); break; default: runtimeLogger.trace(msg); } return data; } public Object visit(CLVFSizeNode node, Object data) { CLVFVariableLiteral varNode=(CLVFVariableLiteral) node.jjtGetChild(0); TLVariable var=stack.getVar(varNode.localVar, varNode.varSlot); stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(var.getLength()))); return data; } public Object visit(CLVFImportSource node,Object data) { node.childrenAccept(this, data); return data; } public Object visit(CLVFSymbolNameExp node,Object data) { stack.push(node.value); return data; } public Object visit(CLVFOperator node,Object data) { return data; } public Object visit(CLVFPostfixExpression node,Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue val=stack.pop(); int operatorType=((CLVFOperator)node.jjtGetChild(1)).kind; if (operatorType==INCR) { if (val.type.isNumeric()) { val=val.duplicate(); val.getNumeric().add(Stack.NUM_ONE_P); stack.push(val); }else if (val.type==TLValueType.DATE) { stack.calendar.setTime(val.getDate()); stack.calendar.add(Calendar.DATE, 1); val.value=stack.calendar.getTime(); stack.push(val); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } }else{ if (val.type.isNumeric()) { val=val.duplicate(); val.getNumeric().sub(Stack.NUM_ONE_P); stack.push(val); }else if (val.type==TLValueType.DATE) { stack.calendar.setTime(val.getDate()); stack.calendar.add(Calendar.DATE, -1); val.value=stack.calendar.getTime(); stack.push(val); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } } return data; } public Object visit(CLVFUnaryExpression node,Object data) { int operatorType=((CLVFOperator)node.jjtGetChild(0)).kind; node.jjtGetChild(1).jjtAccept(this, data); TLValue val=stack.pop(); switch(operatorType){ case INCR: if (val.type.isNumeric()) { val=val.duplicate(); val.getNumeric().add(Stack.NUM_ONE_P); stack.push(val); }else if (val.type==TLValueType.DATE) { stack.calendar.setTime(val.getDate()); stack.calendar.add(Calendar.DATE, 1); val.value=stack.calendar.getTime(); stack.push(val); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } break; case DECR: if (val.type.isNumeric()) { val=val.duplicate(); val.getNumeric().sub(Stack.NUM_ONE_P); stack.push(val); }else if (val.type==TLValueType.DATE) { stack.calendar.setTime(val.getDate()); stack.calendar.add(Calendar.DATE, -1); val.value=stack.calendar.getTime(); stack.push(val); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } break; case NOT: if (val.type==TLValueType.BOOLEAN) { stack.push(val.getBoolean() ? Stack.FALSE_VAL : Stack.TRUE_VAL); } else { throw new TransformLangExecutorRuntimeException(node, new Object[] { val }, "logical condition does not evaluate to BOOLEAN value"); } case MINUS: if (val.type.isNumeric()) { val=val.duplicate(); val.getNumeric().neg(); stack.push(val); }else { throw new TransformLangExecutorRuntimeException(node,new Object[] { val }, "variable is not of numeric type"); } break; case PLUS: if (val.type.isNumeric()) { val=val.duplicate(); val.getNumeric().abs(); stack.push(val); }else { throw new TransformLangExecutorRuntimeException(node,new Object[] { val }, "variable is not of numeric type"); } break; default: throw new TransformLangExecutorRuntimeException(node, "unsupported operation"); } return data; } }
cloveretl.engine/src/org/jetel/interpreter/TransformLangExecutor.java
/* * Copyright (C) 2002-2004 David Pavlis <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jetel.interpreter; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.Properties; import java.util.regex.Matcher; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataField; import org.jetel.data.DataRecord; import org.jetel.data.primitive.CloverDouble; import org.jetel.data.primitive.CloverInteger; import org.jetel.data.primitive.CloverLong; import org.jetel.data.primitive.DecimalFactory; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.graph.TransformationGraph; import org.jetel.interpreter.ASTnode.CLVFAddNode; import org.jetel.interpreter.ASTnode.CLVFAnd; import org.jetel.interpreter.ASTnode.CLVFAssignment; import org.jetel.interpreter.ASTnode.CLVFBlock; import org.jetel.interpreter.ASTnode.CLVFBreakStatement; import org.jetel.interpreter.ASTnode.CLVFBreakpointNode; import org.jetel.interpreter.ASTnode.CLVFCaseExpression; import org.jetel.interpreter.ASTnode.CLVFComparison; import org.jetel.interpreter.ASTnode.CLVFContinueStatement; import org.jetel.interpreter.ASTnode.CLVFDate2NumNode; import org.jetel.interpreter.ASTnode.CLVFDateAddNode; import org.jetel.interpreter.ASTnode.CLVFDateDiffNode; import org.jetel.interpreter.ASTnode.CLVFDivNode; import org.jetel.interpreter.ASTnode.CLVFDoStatement; import org.jetel.interpreter.ASTnode.CLVFForStatement; import org.jetel.interpreter.ASTnode.CLVFForeachStatement; import org.jetel.interpreter.ASTnode.CLVFFunctionCallStatement; import org.jetel.interpreter.ASTnode.CLVFFunctionDeclaration; import org.jetel.interpreter.ASTnode.CLVFGlobalParameterLiteral; import org.jetel.interpreter.ASTnode.CLVFIfStatement; import org.jetel.interpreter.ASTnode.CLVFIffNode; import org.jetel.interpreter.ASTnode.CLVFImportSource; import org.jetel.interpreter.ASTnode.CLVFInputFieldLiteral; import org.jetel.interpreter.ASTnode.CLVFIsNullNode; import org.jetel.interpreter.ASTnode.CLVFLiteral; import org.jetel.interpreter.ASTnode.CLVFLookupNode; import org.jetel.interpreter.ASTnode.CLVFMapping; import org.jetel.interpreter.ASTnode.CLVFMinusMinusNode; import org.jetel.interpreter.ASTnode.CLVFMinusNode; import org.jetel.interpreter.ASTnode.CLVFModNode; import org.jetel.interpreter.ASTnode.CLVFMulNode; import org.jetel.interpreter.ASTnode.CLVFNVLNode; import org.jetel.interpreter.ASTnode.CLVFNegation; import org.jetel.interpreter.ASTnode.CLVFOr; import org.jetel.interpreter.ASTnode.CLVFOutputFieldLiteral; import org.jetel.interpreter.ASTnode.CLVFPlusPlusNode; import org.jetel.interpreter.ASTnode.CLVFPrintErrNode; import org.jetel.interpreter.ASTnode.CLVFPrintLogNode; import org.jetel.interpreter.ASTnode.CLVFPrintStackNode; import org.jetel.interpreter.ASTnode.CLVFRaiseErrorNode; import org.jetel.interpreter.ASTnode.CLVFRegexLiteral; import org.jetel.interpreter.ASTnode.CLVFReturnStatement; import org.jetel.interpreter.ASTnode.CLVFSequenceNode; import org.jetel.interpreter.ASTnode.CLVFSizeNode; import org.jetel.interpreter.ASTnode.CLVFStart; import org.jetel.interpreter.ASTnode.CLVFStartExpression; import org.jetel.interpreter.ASTnode.CLVFStatementExpression; import org.jetel.interpreter.ASTnode.CLVFStr2NumNode; import org.jetel.interpreter.ASTnode.CLVFSubNode; import org.jetel.interpreter.ASTnode.CLVFSwitchStatement; import org.jetel.interpreter.ASTnode.CLVFSymbolNameExp; import org.jetel.interpreter.ASTnode.CLVFTruncNode; import org.jetel.interpreter.ASTnode.CLVFVarDeclaration; import org.jetel.interpreter.ASTnode.CLVFVariableLiteral; import org.jetel.interpreter.ASTnode.CLVFWhileStatement; import org.jetel.interpreter.ASTnode.Node; import org.jetel.interpreter.ASTnode.SimpleNode; import org.jetel.interpreter.data.TLListVariable; import org.jetel.interpreter.data.TLMapVariable; import org.jetel.interpreter.data.TLValue; import org.jetel.interpreter.data.TLValueType; import org.jetel.interpreter.data.TLVariable; import org.jetel.metadata.DataFieldMetadata; import org.jetel.util.Compare; import org.jetel.util.StringUtils; /** * Executor of FilterExpression parse tree. * * @author dpavlis * @since 16.9.2004 * * Executor of FilterExpression parse tree */ public class TransformLangExecutor implements TransformLangParserVisitor, TransformLangParserConstants{ public static final int BREAK_BREAK=1; public static final int BREAK_CONTINUE=2; public static final int BREAK_RETURN=3; protected Stack stack; protected boolean breakFlag; protected int breakType; protected Properties globalParameters; protected DataRecord[] inputRecords; protected DataRecord[] outputRecords; protected Node emptyNode; // used as replacement for empty statements protected TransformationGraph graph; protected Log runtimeLogger; static Log logger = LogFactory.getLog(TransformLangExecutor.class); /** * Constructor */ public TransformLangExecutor(Properties globalParameters) { stack = new Stack(); breakFlag = false; this.globalParameters=globalParameters; emptyNode = new SimpleNode(Integer.MAX_VALUE); } public TransformLangExecutor() { this(null); } public TransformationGraph getGraph() { return graph; } public void setGraph(TransformationGraph graph) { this.graph = graph; } public Log getRuntimeLogger() { return runtimeLogger; } public void setRuntimeLogger(Log runtimeLogger) { this.runtimeLogger = runtimeLogger; } /** * Set input data records for processing.<br> * Referenced input data fields will be resolved from * these data records. * * @param inputRecords array of input data records carrying values */ public void setInputRecords(DataRecord[] inputRecords){ this.inputRecords=inputRecords; } /** * Set output data records for processing.<br> * Referenced output data fields will be resolved from * these data records - assignment (in code) to output data field * will result in assignment to one of these data records. * * @param outputRecords array of output data records for setting values */ public void setOutputRecords(DataRecord[] outputRecords){ this.outputRecords=outputRecords; } /** * Set global parameters which may be reference from within the * transformation source code * * @param parameters */ public void setGlobalParameters(Properties parameters){ this.globalParameters=parameters; } /** * Allows to store parameter/value on stack from * where it can be read by executed script/function. * @param obj Object/value to be stored * @since 10.12.2006 */ public void setParameter(String obj){ stack.push(new TLValue(TLValueType.STRING,obj)); } /** * Method which returns result of executing parse tree.<br> * Basically, it returns whatever object was left on top of executor's * stack (usually as a result of last executed expression/operation).<br> * It can be called repetitively in order to read all objects from stack. * * @return Object saved on stack or NULL if no more objects are available */ public TLValue getResult() { return stack.pop(); } /** * Return value of globally defined variable determined by slot number. * Slot can be obtained by calling <code>TransformLangParser.getGlobalVariableSlot(<i>varname</i>)</code> * * @param varSlot * @return Object - depending of Global variable type * @since 6.12.2006 */ public TLVariable getGlobalVariable(int varSlot){ return stack.getGlobalVar(varSlot); } /** * Allows to set value of defined global variable. * * @param varSlot * @param value * @since 6.12.2006 */ public void setGlobalVariable(int varSlot,TLVariable value){ stack.storeGlobalVar(varSlot,value); } /* *********************************************************** */ /* implementation of visit methods for each class of AST node */ /* *********************************************************** */ /* it seems to be necessary to define a visit() method for SimpleNode */ public Object visit(SimpleNode node, Object data) { // throw new TransformLangExecutorRuntimeException(node, // "Error: Call to visit for SimpleNode"); return data; } public Object visit(CLVFStart node, Object data) { int i, k = node.jjtGetNumChildren(); for (i = 0; i < k; i++) node.jjtGetChild(i).jjtAccept(this, data); return data; // this value is ignored in this example } public Object visit(CLVFStartExpression node, Object data) { int i, k = node.jjtGetNumChildren(); for (i = 0; i < k; i++) node.jjtGetChild(i).jjtAccept(this, data); return data; // this value is ignored in this example } public Object visit(CLVFOr node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a=stack.pop(); if (a.type!=TLValueType.BOOLEAN){ Object params[]=new Object[]{a}; throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value"); }else if (a.getBoolean()){ stack.push(Stack.TRUE_VAL); return data; } node.jjtGetChild(1).jjtAccept(this, data); a=stack.pop(); if (a.type!=TLValueType.BOOLEAN){ Object params[]=new Object[]{a}; throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value"); } stack.push( a.getBoolean() ? Stack.TRUE_VAL : Stack.FALSE_VAL); return data; } public Object visit(CLVFAnd node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a=stack.pop(); if (a.type!=TLValueType.BOOLEAN){ Object params[]=new Object[]{a}; throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value"); }else if (!a.getBoolean()){ stack.push(Stack.FALSE_VAL); return data; } node.jjtGetChild(1).jjtAccept(this, data); a=stack.pop(); if (a.type!=TLValueType.BOOLEAN){ Object params[]=new Object[]{a}; throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value"); } stack.push(a.getBoolean() ? Stack.TRUE_VAL : Stack.FALSE_VAL); return data; } public Object visit(CLVFComparison node, Object data) { int cmpResult = 2; boolean lValue = false; // special handling for Regular expression if (node.cmpType == REGEX_EQUAL) { node.jjtGetChild(0).jjtAccept(this, data); TLValue field1 = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue field2 = stack.pop(); if (field1.type == TLValueType.STRING && field2.getValue() instanceof Matcher) { Matcher regex = (Matcher) field2.getValue(); regex.reset(field1.getCharSequence()); if (regex.matches()) { lValue = true; } else { lValue = false; } } else { Object[] arguments = { field1, field2 }; throw new TransformLangExecutorRuntimeException(node, arguments, "regex equal - wrong type of literal(s)"); } // other types of comparison } else { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (!a.type.isCompatible(b.type)) { Object arguments[] = { a, b }; throw new TransformLangExecutorRuntimeException(node, arguments, "compare - incompatible literals/expressions"); } switch (a.type) { case INTEGER: case LONG: case DOUBLE: case DECIMAL: cmpResult = a.getNumeric().compareTo(b.getNumeric()); break; case DATE: cmpResult = a.getDate().compareTo(b.getDate()); break; case STRING: cmpResult = Compare.compare(a.getCharSequence(), b .getCharSequence()); break; case BOOLEAN: if (node.cmpType == EQUAL || node.cmpType == NON_EQUAL) { cmpResult = a.getBoolean() == b.getBoolean() ? 0 : -1; } else { Object arguments[] = { a, b }; throw new TransformLangExecutorRuntimeException(node, arguments, "compare - unsupported comparison operator [" + tokenImage[node.cmpType] + "] for literals/expressions"); } break; default: Object arguments[] = { a, b }; throw new TransformLangExecutorRuntimeException(node, arguments, "compare - don't know how to compare literals/expressions"); } switch (node.cmpType) { case EQUAL: if (cmpResult == 0) { lValue = true; } break;// equal case LESS_THAN: if (cmpResult == -1) { lValue = true; } break;// less than case GREATER_THAN: if (cmpResult == 1) { lValue = true; } break;// grater than case LESS_THAN_EQUAL: if (cmpResult <= 0) { lValue = true; } break;// less than equal case GREATER_THAN_EQUAL: if (cmpResult >= 0) { lValue = true; } break;// greater than equal case NON_EQUAL: if (cmpResult != 0) { lValue = true; } break; default: // this should never happen !!! logger .fatal("Internal error: Unsupported comparison operator !"); throw new RuntimeException( "Internal error - Unsupported comparison operator !"); } } stack.push(lValue ? Stack.TRUE_VAL : Stack.FALSE_VAL); return data; } public Object visit(CLVFAddNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { //TODO: (check) we allow empty strings to be concatenated if (a.type!=TLValueType.STRING) throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "add - NULL value not allowed"); } if (node.nodeVal==null) { node.nodeVal= a.isNull() ? TLValue.create(a.type) : a.duplicate(); } try { if (a.type.isNumeric() && b.type.isNumeric()) { node.nodeVal.getNumeric().setValue(a.getNumeric()); node.nodeVal.getNumeric().add(b.getNumeric()); stack.push(node.nodeVal); } else if (a.type==TLValueType.DATE && b.type.isNumeric()) { Calendar result = Calendar.getInstance(); result.setTime(a.getDate()); result.add(Calendar.DATE, b.getInt()); node.nodeVal.getDate().setTime(result.getTimeInMillis()); stack.push(node.nodeVal); } else if (a.type==TLValueType.STRING) { CharSequence a1 = a.getCharSequence(); StringBuilder buf=(StringBuilder)node.nodeVal.getValue(); buf.setLength(0); StringUtils.strBuffAppend(buf,a1); if (b.type==TLValueType.STRING) { StringUtils.strBuffAppend(buf,b.getCharSequence()); } else { buf.append(b); } stack.push(node.nodeVal); } else { Object[] arguments = { a, b }; throw new TransformLangExecutorRuntimeException(node,arguments, "add - wrong type of literal(s)"); } } catch (ClassCastException ex) { Object arguments[] = { a, b }; throw new TransformLangExecutorRuntimeException(node,arguments, "add - wrong type of literal(s)"); } return data; } public Object visit(CLVFSubNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "sub - NULL value not allowed"); } if (!b.type.isNumeric()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { b }, "sub - wrong type of literal"); } if (node.nodeVal==null) { node.nodeVal=a.duplicate(); } if(a.type.isNumeric()) { node.nodeVal.getNumeric().setValue(a.getNumeric()); node.nodeVal.getNumeric().sub(b.getNumeric()); stack.push(node.nodeVal); } else if (a.type==TLValueType.DATE) { Calendar result = Calendar.getInstance(); result.setTime(a.getDate()); result.add(Calendar.DATE, b.getInt() * -1); node.nodeVal.getDate().setTime(result.getTimeInMillis()); stack.push(node.nodeVal); } else { Object[] arguments = { a, b }; throw new TransformLangExecutorRuntimeException(node,arguments, "sub - wrong type of literal(s)"); } return data; } public Object visit(CLVFMulNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "mul - NULL value not allowed"); } if (!a.type.isNumeric() && !b.type.isNumeric()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b }, "mul - wrong type of literals"); } if (node.nodeVal==null) { node.nodeVal=a.duplicate(); } node.nodeVal.getNumeric().setValue(a.getNumeric()); node.nodeVal.getNumeric().mul(b.getNumeric()); stack.push(node.nodeVal); return data; } public Object visit(CLVFDivNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "div - NULL value not allowed"); } if (!a.type.isNumeric() && !b.type.isNumeric()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b }, "div - wrong type of literals"); } if (node.nodeVal==null || node.nodeVal.type!=a.type) { node.nodeVal=TLValue.create(a.type); } node.nodeVal.getNumeric().setValue(a.getNumeric()); try { node.nodeVal.getNumeric().div(b.getNumeric()); }catch(ArithmeticException ex){ throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b }, "div - arithmetic exception",ex); }catch (Exception ex) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a,b }, "div - error during operation",ex); } stack.push(node.nodeVal); return data; } public Object visit(CLVFModNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.isNull()|| b.isNull()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "mod - NULL value not allowed"); } if (!a.type.isNumeric() && !b.type.isNumeric()) { throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b }, "mod - wrong type of literals"); } if (node.nodeVal==null) { node.nodeVal=a.duplicate(); } node.nodeVal.getNumeric().setValue(a.getNumeric()); node.nodeVal.getNumeric().mod(b.getNumeric()); stack.push(node.nodeVal); return data; } public Object visit(CLVFNegation node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); if (value.type==TLValueType.BOOLEAN) { stack.push(value.getBoolean() ? Stack.FALSE_VAL : Stack.TRUE_VAL); } else { throw new TransformLangExecutorRuntimeException(node, new Object[] { value }, "logical condition does not evaluate to BOOLEAN value"); } return data; } public Object visit(CLVFIsNullNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); if (value.isNull()) { stack.push(Stack.TRUE_VAL); } else { if (value.type==TLValueType.STRING) { stack.push( value.getCharSequence().length()==0 ? Stack.TRUE_VAL : Stack.FALSE_VAL); }else { stack.push(Stack.FALSE_VAL); } } return data; } public Object visit(CLVFNVLNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); if (value.isNull()) { node.jjtGetChild(1).jjtAccept(this, data); } else { if (value.type==TLValueType.STRING && value.getCharSequence().length()==0) { node.jjtGetChild(1).jjtAccept(this, data); }else { stack.push(value); } } return data; } public Object visit(CLVFLiteral node, Object data) { stack.push(node.valueTL); return data; } public Object visit(CLVFInputFieldLiteral node, Object data) { DataRecord record = inputRecords[node.recordNo]; if (record == null) { stack.push(Stack.NULL_VAL); } else { DataField field = record.getField(node.fieldNo); if (field.isNull()) stack.push(Stack.NULL_VAL); else stack.push(new TLValue(field)); } // old // stack.push(inputRecords[node.recordNo].getField(node.fieldNo).getValue()); // we return reference to DataField so we can // perform extra checking in special cases return node.field; } public Object visit(CLVFOutputFieldLiteral node, Object data) { //stack.push(inputRecords[node.recordNo].getField(node.fieldNo)); // we return reference to DataField so we can // perform extra checking in special cases return data; } public Object visit(CLVFGlobalParameterLiteral node, Object data) { stack.push(new TLValue(TLValueType.STRING,globalParameters!=null ? globalParameters.getProperty(node.name) : null)); return data; } public Object visit(CLVFRegexLiteral node, Object data) { stack.push(new TLValue(TLValueType.OBJECT,node.matcher)); return data; } public Object visit(CLVFDateAddNode node, Object data) { int shiftAmount; node.jjtGetChild(0).jjtAccept(this, data); TLValue date = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue amount = stack.pop(); if (amount.type.isNumeric()) { shiftAmount = amount.getInt(); } else { Object arguments[] = { amount }; throw new TransformLangExecutorRuntimeException(node,arguments, "dateadd - amount is not a Numeric value"); } if (date.type!=TLValueType.DATE) { Object arguments[] = { date }; throw new TransformLangExecutorRuntimeException(node,arguments, "dateadd - no Date expression"); } if (node.nodeVal==null) { node.nodeVal=date.duplicate(); } node.calendar.setTime(date.getDate()); node.calendar.add(node.calendarField, shiftAmount); node.nodeVal.getDate().setTime(node.calendar.getTimeInMillis()); stack.push(node.nodeVal); return data; } public Object visit(CLVFDate2NumNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue date = stack.pop(); if (date.type==TLValueType.DATE) { node.calendar.setTime(date.getDate()); stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(node.calendar.get(node.calendarField)))); } else { Object arguments[] = { date }; throw new TransformLangExecutorRuntimeException(node,arguments, "date2num - no Date expression"); } return data; } public Object visit(CLVFDateDiffNode node, Object data) { TLValue date1, date2; node.jjtGetChild(0).jjtAccept(this, data); date1 = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); date2 = stack.pop(); if (date1.type==TLValueType.DATE && date1.type==date2.type) { long diffSec = (date1.getDate().getTime() - date2.getDate().getTime()) / 1000; int diff = 0; switch (node.calendarField) { case Calendar.SECOND: // we have the difference in seconds diff = (int) diffSec; break; case Calendar.MINUTE: // how many minutes' diff = (int) diffSec / 60; break; case Calendar.HOUR_OF_DAY: diff = (int) diffSec / 3600; break; case Calendar.DAY_OF_MONTH: // how many days is the difference diff = (int) diffSec / 86400; break; case Calendar.WEEK_OF_YEAR: // how many weeks diff = (int) diffSec / 604800; break; case Calendar.MONTH: node.start.setTime(date1.getDate()); node.end.setTime(date2.getDate()); diff = (node.start.get(Calendar.MONTH) + node.start .get(Calendar.YEAR) * 12) - (node.end.get(Calendar.MONTH) + node.end .get(Calendar.YEAR) * 12); break; case Calendar.YEAR: node.start.setTime(date1.getDate()); node.end.setTime(date2.getDate()); diff = node.start.get(node.calendarField) - node.end.get(node.calendarField); break; default: Object arguments[] = { new Integer(node.calendarField) }; throw new TransformLangExecutorRuntimeException(node,arguments, "datediff - wrong difference unit"); } stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(diff))); } else { Object arguments[] = { date1, date2 }; throw new TransformLangExecutorRuntimeException(node,arguments, "datediff - no Date expression"); } return data; } public Object visit(CLVFMinusNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); if (value.type.isNumeric()) { TLValue newVal=value.duplicate(); newVal.getNumeric().mul(Stack.NUM_MINUS_ONE_P); stack.push(newVal); } else { Object arguments[] = { value }; throw new TransformLangExecutorRuntimeException(node,arguments, "minus - not a number"); } return data; } public Object visit(CLVFStr2NumNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type==TLValueType.STRING) { try { TLValue value = null; switch (node.numType) { case INT_VAR: value = new TLValue(TLValueType.INTEGER,new CloverInteger(Integer.parseInt( a.getString(), node.radix))); break; case LONG_VAR: value = new TLValue(TLValueType.LONG,new CloverLong(Long.parseLong(a.getString(), node.radix))); break; case DECIMAL_VAR: if (node.radix == 10) { value = new TLValue(TLValueType.LONG,DecimalFactory.getDecimal(a.getString())); } else { Object[] arguments = { a, new Integer(node.radix) }; throw new TransformLangExecutorRuntimeException(node, arguments, "str2num - can't convert string to decimal number using specified radix"); } break; default: // get double/number type switch (node.radix) { case 10: case 16: value = new TLValue(TLValueType.DOUBLE,new CloverDouble(Double .parseDouble(a.getString()))); break; default: Object[] arguments = { a, new Integer(node.radix) }; throw new TransformLangExecutorRuntimeException(node, arguments, "str2num - can't convert string to number/double number using specified radix"); } } stack.push(value); } catch (NumberFormatException ex) { Object[] arguments = { a }; throw new TransformLangExecutorRuntimeException(node, arguments, "str2num - can't convert \"" + a + "\""); } } else { Object[] arguments = { a }; throw new TransformLangExecutorRuntimeException(node, arguments, "str2num - wrong type of literal"); } return data; } public Object visit(CLVFIffNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue condition = stack.pop(); if (condition.type==TLValueType.BOOLEAN) { if (condition.getBoolean()) { node.jjtGetChild(1).jjtAccept(this, data); } else { node.jjtGetChild(2).jjtAccept(this, data); } stack.push(stack.pop()); } else { Object[] arguments = { condition }; throw new TransformLangExecutorRuntimeException(node,arguments, "iif - condition does not evaluate to BOOLEAN value"); } return data; } public Object visit(CLVFPrintErrNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (node.printLine){ StringBuilder buf=new StringBuilder((a != null ? a.toString() : "<null>")); buf.append(" (on line: ").append(node.getLineNumber()); buf.append(" col: ").append(node.getColumnNumber()).append(")"); System.err.println(buf); }else{ System.err.println(a != null ? a : "<null>"); } return data; } public Object visit(CLVFPrintStackNode node, Object data) { for (int i=stack.top;i>=0;i--){ System.err.println("["+i+"] : "+stack.stack[i]); } return data; } /*************************************************************************** * Transformation Language executor starts here. **************************************************************************/ public Object visit(CLVFForStatement node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); // set up of the loop boolean condition = false; Node loopCondition = node.jjtGetChild(1); Node increment = node.jjtGetChild(2); Node body; try{ body=node.jjtGetChild(3); }catch(ArrayIndexOutOfBoundsException ex){ body=emptyNode; } try { loopCondition.jjtAccept(this, data); // evaluate the condition condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); }catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition"); } // loop execution while (condition) { body.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) { return data; } } increment.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // evaluate the condition loopCondition.jjtAccept(this, data); try { condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); } } return data; } public Object visit(CLVFForeachStatement node, Object data) { CLVFVariableLiteral varNode=(CLVFVariableLiteral)node.jjtGetChild(0); CLVFVariableLiteral arrayNode=(CLVFVariableLiteral)node.jjtGetChild(1); TLVariable variableToAssign = stack.getVar(varNode.localVar, varNode.varSlot); TLVariable arrayVariable=stack.getVar(arrayNode.localVar, arrayNode.varSlot); Node body; try{ body=node.jjtGetChild(2); }catch(ArrayIndexOutOfBoundsException ex){ body=emptyNode; } Iterator<TLValue> iter; switch(arrayVariable.getType()) { case LIST: iter=((TLListVariable)arrayVariable).getList().iterator(); break; case MAP: iter=((TLMapVariable)arrayVariable).getMap().values().iterator(); break; default: throw new TransformLangExecutorRuntimeException(node,"not a Map or List variable"); } while(iter.hasNext()) { variableToAssign.setValue(iter.next()); body.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) { return data; } } } return data; } public Object visit(CLVFWhileStatement node, Object data) { boolean condition = false; Node loopCondition = node.jjtGetChild(0); Node body; try{ body=node.jjtGetChild(1); }catch(ArrayIndexOutOfBoundsException ex){ body=emptyNode; } try { loopCondition.jjtAccept(this, data); // evaluate the condition condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); }catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition"); } // loop execution while (condition) { body.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data; } // evaluate the condition loopCondition.jjtAccept(this, data); try { condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); } } return data; } public Object visit(CLVFIfStatement node, Object data) { boolean condition = false; try { node.jjtGetChild(0).jjtAccept(this, data); // evaluate the // condition condition = stack.pop().getBoolean(); } catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"condition does not evaluate to BOOLEAN value"); } catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition"); } // first if if (condition) { node.jjtGetChild(1).jjtAccept(this, data); } else { // if else part exists if (node.jjtGetNumChildren() > 2) { node.jjtGetChild(2).jjtAccept(this, data); } } return data; } public Object visit(CLVFDoStatement node, Object data) { boolean condition = false; Node loopCondition = node.jjtGetChild(1); Node body = node.jjtGetChild(0); // loop execution do { body.jjtAccept(this, data); stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data; } // evaluate the condition loopCondition.jjtAccept(this, data); try { condition = stack.pop().getBoolean(); }catch (ClassCastException ex) { throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value"); }catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition"); } } while (condition); return data; } public Object visit(CLVFSwitchStatement node, Object data) { // get value of switch && push/leave it on stack boolean match=false; node.jjtGetChild(0).jjtAccept(this, data); TLValue switchVal=stack.pop(); int numChildren = node.jjtGetNumChildren(); int numCases = node.hasDefaultClause ? numChildren-1 : numChildren; // loop over remaining case statements for (int i = 1; i < numCases; i++) { stack.push(switchVal); if (node.jjtGetChild(i).jjtAccept(this, data)==Stack.TRUE_VAL){ match=true; } if (breakFlag) { if (breakType == BREAK_BREAK) { breakFlag = false; } break; } } // test whether execute default branch if (node.hasDefaultClause && !match){ node.jjtGetChild(numChildren-1).jjtAccept(this, data); } return data; } public Object visit(CLVFCaseExpression node, Object data) { // test if literal (as child 0) is equal to data on stack // if so, execute block (child 1) boolean match = false; TLValue switchVal = stack.pop(); node.jjtGetChild(0).jjtAccept(this, data); TLValue value = stack.pop(); try { switch(switchVal.type) { case INTEGER: case LONG: case DOUBLE: case DECIMAL: match = (value.getNumeric().compareTo(switchVal.getNumeric()) == 0); break; case STRING: match = (Compare.compare(switchVal.getCharSequence(), value.getCharSequence()) == 0); break; case DATE: match = ( switchVal.getDate().compareTo(value.getDate()) == 0); break; case BOOLEAN: match = (switchVal.getBoolean()==value.getBoolean()); break; default: } } catch (ClassCastException ex) { Object[] args=new Object[] {switchVal,value}; throw new TransformLangExecutorRuntimeException(node,args,"incompatible literals in case clause"); }catch (NullPointerException ex){ throw new TransformLangExecutorRuntimeException(node,"missing or invalid case value"); } if (match){ node.jjtGetChild(1).jjtAccept(this, data); return Stack.TRUE_VAL; } return Stack.FALSE_VAL; } public Object visit(CLVFPlusPlusNode node, Object data) { Node childNode = node.jjtGetChild(0); if (node.statement) { CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode; TLVariable var=stack.getVar(varNode.localVar, varNode.varSlot); if (var.getType().isNumeric()) { var.getValue().getNumeric().add(Stack.NUM_ONE_P); }else if (var.getType()==TLValueType.DATE) { stack.calendar.setTime(var.getValue().getDate()); stack.calendar.add(Calendar.DATE, 1); var.getValue().setValue(stack.calendar.getTime()); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } }else { // expression childNode.jjtAccept(this, data); TLValue val=stack.pop(); if (val.type.isNumeric()) { val=val.duplicate(); val.getNumeric().add(Stack.NUM_ONE_P); stack.push(val); }else if (val.type==TLValueType.DATE) { stack.calendar.setTime(val.getDate()); stack.calendar.add(Calendar.DATE, 1); val.value=stack.calendar.getTime(); stack.push(val); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } } return data; } public Object visit(CLVFMinusMinusNode node, Object data) { Node childNode = node.jjtGetChild(0); if (node.statement) { CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode; TLVariable var=stack.getVar(varNode.localVar, varNode.varSlot); if (var.getType().isNumeric()) { var.getValue().getNumeric().sub(Stack.NUM_ONE_P); }else if (var.getType()==TLValueType.DATE) { stack.calendar.setTime(var.getValue().getDate()); stack.calendar.add(Calendar.DATE, -1); var.getValue().setValue(stack.calendar.getTime()); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } }else { // expression childNode.jjtAccept(this, data); TLValue val=stack.pop(); if (val.type.isNumeric()) { val=val.duplicate(); val.getNumeric().sub(Stack.NUM_ONE_P); stack.push(val); }else if (val.type==TLValueType.DATE) { stack.calendar.setTime(val.getDate()); stack.calendar.add(Calendar.DATE, -1); val.value=stack.calendar.getTime(); stack.push(val); }else { throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); } } return data; } public Object visit(CLVFBlock node, Object data) { int childern = node.jjtGetNumChildren(); for (int i = 0; i < childern; i++) { node.jjtGetChild(i).jjtAccept(this, data); // have we seen contiue/break/return statement ?? if (breakFlag){ if (breakType!=BREAK_RETURN) stack.pop(); return data; } stack.pop(); } return data; } /* * Loop & block & function control nodes */ public Object visit(CLVFBreakStatement node, Object data) { breakFlag = true; // we encountered break statement; breakType=BREAK_BREAK; return data; } public Object visit(CLVFContinueStatement node, Object data) { breakFlag = true; // we encountered continue statement; breakType= BREAK_CONTINUE; return data; } public Object visit(CLVFReturnStatement node, Object data) { if (node.jjtHasChildren()){ node.jjtGetChild(0).jjtAccept(this, data); } breakFlag = true; breakType = BREAK_RETURN; return data; } public Object visit(CLVFBreakpointNode node, Object data) { // list all variables System.err.println("** list of global variables ***"); for (int i=0;i<stack.globalVarSlot.length;System.out.println(stack.globalVarSlot[i++])); System.err.println("** list of local variables ***"); for (int i=0;i<stack.localVarCounter;i++) System.out.println(stack.localVarSlot[stack.localVarSlotOffset+i]); return data; } /* * Variable declarations */ public Object visit(CLVFVarDeclaration node, Object data) { TLValue value=null; TLVariable variable=null; // create global/local variable switch (node.type) { case INT_VAR: value = new TLValue(TLValueType.INTEGER, new CloverInteger(0)); break; case LONG_VAR: value = new TLValue(TLValueType.LONG,new CloverLong(0)); break; case DOUBLE_VAR: value = new TLValue(TLValueType.DOUBLE, new CloverDouble(0)); break; case DECIMAL_VAR: if (node.length > 0) { if (node.precision > 0) { value = new TLValue(TLValueType.DECIMAL, DecimalFactory.getDecimal(node.length, node.precision)); } else { value = new TLValue(TLValueType.DECIMAL,DecimalFactory.getDecimal(node.length, 0)); } } else { value = new TLValue(TLValueType.DECIMAL,DecimalFactory.getDecimal()); } break; case STRING_VAR: value = new TLValue(TLValueType.STRING,new StringBuilder()); break; case DATE_VAR: value = new TLValue(TLValueType.DATE,new Date()); break; case BOOLEAN_VAR: value = Stack.FALSE_VAL; break; case LIST_VAR: if (node.length>0) { variable = new TLListVariable(node.name,node.length); ((TLListVariable)variable).fill(Stack.NULL_VAL, node.length); }else { variable = new TLListVariable(node.name); } break; case MAP_VAR: if (node.length>0){ variable = new TLMapVariable(node.name,node.length); }else { variable = new TLMapVariable(node.name); } break; default: throw new TransformLangExecutorRuntimeException(node, "variable declaration - " + "unknown type for variable \"" + node.name + "\""); } if (variable==null) variable=new TLVariable(node.name,value); stack.storeVar(node.localVar, node.varSlot,variable ); if (node.jjtHasChildren()) { node.jjtGetChild(0).jjtAccept(this, data); TLValue initValue = stack.pop(); TLValueType type =variable.getType(); if (type.isStrictlyCompatible(initValue.type)) { variable.setValue(initValue); }else { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + initValue + "\" to variable \"" + node.name + "\" - incompatible data types"); } } return data; } public Object visit(CLVFVariableLiteral node, Object data) { TLVariable var = stack.getVar(node.localVar, node.varSlot); TLValue index = null; if (node.indexSet) { try { switch (var.getType()) { case LIST: node.jjtGetChild(0).jjtAccept(this, data); index = stack.pop(); stack.push(var.getValue(index.getInt())); break; case MAP: node.jjtGetChild(0).jjtAccept(this, data); index = stack.pop(); stack.push(var.getValue(index.getString())); break; } } catch (Exception ex) { throw new TransformLangExecutorRuntimeException(node, "invalid index \"" + index + "\" of variable \"" + var.getName() + "\" - type " + var.getType().toString(), ex); } }else { stack.push(var.getValue()); } return data; } public Object visit(CLVFAssignment node, Object data) { CLVFVariableLiteral varNode = (CLVFVariableLiteral) node.jjtGetChild(0); TLVariable variableToAssign = stack.getVar(varNode.localVar, varNode.varSlot); node.jjtGetChild(1).jjtAccept(this, data); TLValue valueToAssign = stack.pop(); if (valueToAssign==null) { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + valueToAssign + "\" to variable \"" + varNode.varName+"\""); } TLValue index = null; switch (varNode.varType) { case LIST_VAR: try { if (varNode.indexSet) { varNode.jjtGetChild(0).jjtAccept(this, data); index = stack.pop(); variableToAssign.setValue(index.getInt(), valueToAssign); }else { variableToAssign.setValue(-1,valueToAssign); } } catch (IndexOutOfBoundsException ex) { throw new TransformLangExecutorRuntimeException(node, "index \""+index+"\" is outside current limits of list/array \"" + varNode.varName+"\"", ex); } catch (Exception ex) { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + valueToAssign + "\" to variable \"" + varNode.varName+"\"", ex); } break; case MAP_VAR: try { varNode.jjtGetChild(0).jjtAccept(this, data); index = stack.pop(); variableToAssign.setValue(index.getString(), valueToAssign); } catch (Exception ex) { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + valueToAssign + "\" to variable \"" + varNode.varName+"\"", ex); } break; default: TLValueType type=variableToAssign.getType(); if (type.isCompatible(valueToAssign.type)) { variableToAssign.setValue(valueToAssign); } else { throw new TransformLangExecutorRuntimeException(node, "invalid assignment of \"" + valueToAssign + "[" + valueToAssign.type + "] \" to variable \"" + variableToAssign.getName() + "\" [" + variableToAssign.getType() + "] \" - incompatible data types"); } } return data; } public Object visit(CLVFMapping node, Object data) { DataField field=outputRecords[node.recordNo].getField(node.fieldNo); int arity=node.jjtGetNumChildren(); // how many children we have defined TLValue value=null; try{ // we try till success or no more options for (int i=0;i<arity;i++){ node.jjtGetChild(i).jjtAccept(this, data); value=stack.pop(); try{ value.copyToDataField(field); break; // success during assignment, finish looping }catch(Exception ex){ if (i == arity-1) throw ex; } } }catch(BadDataFormatException ex){ if (!outputRecords[node.recordNo].getField(node.fieldNo).getMetadata().isNullable()){ throw new TransformLangExecutorRuntimeException(node,"can't assign NULL to \"" + node.fieldName + "\""); } throw new TransformLangExecutorRuntimeException(node,"data format exception when mapping \"" + node.fieldName + "\" - assigning \"" + value + "\""); }catch(TransformLangExecutorRuntimeException ex){ throw ex; }catch(Exception ex){ String msg=ex.getMessage(); throw new TransformLangExecutorRuntimeException(node, (msg!=null ? msg : "") + " when mapping \"" + node.fieldName + "\" ("+DataFieldMetadata.type2Str(field.getType()) +") - assigning \"" + value + "\" ("+(value!=null ? value.getType().getName(): "unknown type" )+")"); } return data; } /* * Declaration & calling of Functions here */ public Object visit(CLVFFunctionCallStatement node, Object data) { // EXTERNAL FUNCTION if (node.externalFunction != null) { // put call parameters on stack node.childrenAccept(this, data); // convert stack content into values try { TLValue returnVal = node.externalFunction.execute(stack.pop( node.externalFunctionParams, node.jjtGetNumChildren()), node.context); stack.push(returnVal); } catch (TransformLangExecutorRuntimeException ex) { ex.setNode(node); throw ex; } } else { // INTERNAL FUNCTION // put call parameters on stack node.childrenAccept(this, data); CLVFFunctionDeclaration executionNode = node.callNode; // open call frame stack.pushFuncCallFrame(); // store call parameters from stack as local variables for (int i = executionNode.numParams - 1; i >= 0; stack .storeLocalVar(i--, new TLVariable("local", stack.pop()))) ; // execute function body // loop execution TLValue returnData; int numChildren = executionNode.jjtGetNumChildren(); for (int i = 0; i < numChildren; i++) { executionNode.jjtGetChild(i).jjtAccept(this, data); returnData = stack.pop(); // in case there is anything on top // of stack // check for break or continue statements if (breakFlag) { breakFlag = false; if (breakType == BREAK_RETURN) { if (returnData != null) stack.push(returnData); break; } } } stack.popFuncCallFrame(); } return data; } public Object visit(CLVFFunctionDeclaration node, Object data) { return data; } public Object visit(CLVFStatementExpression node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); return data; } public Object executeFunction(CLVFFunctionDeclaration executionNode, TLValue[] data) { //put call parameters on stack if (data==null){ data=new TLValue[0]; } //TODO - check for function call parameter types // open call frame stack.pushFuncCallFrame(); // store call parameters from stack as local variables for (int i=executionNode.numParams-1;i>=0; i--) { stack.storeLocalVar(i, new TLVariable(executionNode.varNames[i], data[i])); } // execute function body // loop execution TLValue returnData; int numChildren=executionNode.jjtGetNumChildren(); for (int i=0;i<numChildren;i++){ executionNode.jjtGetChild(i).jjtAccept(this,data); returnData=stack.pop(); // in case there is anything on top of stack // check for break or continue statements if (breakFlag){ breakFlag=false; if (breakType==BREAK_RETURN){ if (returnData!=null) stack.push(returnData); break; } } } stack.popFuncCallFrame(); return data; } /* * MATH functions log,log10,exp,pow,sqrt,round */ /* public Object visit(CLVFSqrtNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble(Math.sqrt(((Numeric)a).getDouble()) ))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing SQRT function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "sqrt - wrong type of literal(s)"); } return data; } public Object visit(CLVFLogNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble(Math.log(((Numeric)a).getDouble()) ))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "log - wrong type of literal(s)"); } return data; } public Object visit(CLVFLog10Node node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble( Math.log10(((Numeric)a).getDouble())))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG10 function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "log10 - wrong type of literal(s)"); } return data; } public Object visit(CLVFExpNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble( Math.exp(((Numeric)a).getDouble())))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing EXP function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "exp - wrong type of literal(s)"); } return data; } public Object visit(CLVFRoundNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverLong(Math.round(((Numeric)a).getDouble())))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing ROUND function",ex); } }else { Object[] arguments = { a}; throw new TransformLangExecutorRuntimeException(node,arguments, "round - wrong type of literal(s)"); } return data; } public Object visit(CLVFPowNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); node.jjtGetChild(1).jjtAccept(this, data); TLValue b = stack.pop(); if (a.type.isNumeric() && b.type.isNumeric()) { try{ stack.push(new TLValue(TLValueType.DOUBLE,new CloverDouble(Math.pow(a.getDouble(), b.getDouble())))); }catch(Exception ex){ throw new TransformLangExecutorRuntimeException(node,"Error when executing POW function",ex); } }else { Object[] arguments = { a, b }; throw new TransformLangExecutorRuntimeException(node,arguments, "pow - wrong type of literal(s)"); } return data; } public Object visit(CLVFPINode node, Object data) { stack.push(Stack.NUM_PI); return data; } */ public Object visit(CLVFTruncNode node, Object data) { node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); if (a.type==TLValueType.DATE ) { stack.calendar.setTime(a.getDate()); stack.calendar.set(Calendar.HOUR_OF_DAY, 0); stack.calendar.set(Calendar.MINUTE , 0); stack.calendar.set(Calendar.SECOND , 0); stack.calendar.set(Calendar.MILLISECOND , 0); stack.push( new TLValue(TLValueType.DATE,stack.calendar.getTime() )); }else if (a.type.isNumeric()){ stack.push(new TLValue(TLValueType.LONG,new CloverLong(a.getLong()))); }else { Object[] arguments = { a }; throw new TransformLangExecutorRuntimeException(node,arguments, "trunc - wrong type of literal(s)"); } return data; } public Object visit(CLVFRaiseErrorNode node,Object data){ node.jjtGetChild(0).jjtAccept(this, data); TLValue a = stack.pop(); throw new TransformLangExecutorRuntimeException(node,null, "!!! Exception raised by user: "+((a!=null) ? a.toString() : "no message")); } public Object visit(CLVFSequenceNode node,Object data){ Object seqVal=null; TLValueType type=null; if (node.sequence==null){ if (graph!=null){ node.sequence=graph.getSequence(node.sequenceName); }else{ throw new TransformLangExecutorRuntimeException(node, "Can't obtain Sequence \""+node.sequenceName+ "\" from graph - graph is not assigned"); } if (node.sequence==null){ throw new TransformLangExecutorRuntimeException(node, "Can't obtain Sequence \""+node.sequenceName+ "\" from graph \""+graph.getName()+"\""); } } switch(node.opType){ case CLVFSequenceNode.OP_RESET: node.sequence.reset(); seqVal=Stack.NUM_ZERO; type=TLValueType.INTEGER; break; case CLVFSequenceNode.OP_CURRENT: switch(node.retType){ case LONG_VAR: seqVal=new CloverLong(node.sequence.currentValueLong()); type=TLValueType.LONG; break; case STRING_VAR: seqVal=node.sequence.currentValueString(); type=TLValueType.STRING; default: seqVal=new CloverInteger(node.sequence.currentValueInt()); type=TLValueType.INTEGER; } default: // default is next value from sequence switch(node.retType){ case LONG_VAR: seqVal=new CloverLong(node.sequence.nextValueLong()); type=TLValueType.LONG; break; case STRING_VAR: seqVal=node.sequence.nextValueString(); type=TLValueType.STRING; default: seqVal=new CloverInteger(node.sequence.nextValueInt()); } } stack.push(new TLValue(type,seqVal)); return data; } public Object visit(CLVFLookupNode node,Object data){ DataRecord record=null; if (node.lookup==null){ node.lookup=graph.getLookupTable(node.lookupName); if (node.lookup==null){ throw new TransformLangExecutorRuntimeException(node, "Can't obtain LookupTable \""+node.lookupName+ "\" from graph \""+graph.getName()+"\""); } node.fieldNum=node.lookup.getMetadata().getFieldPosition(node.fieldName); if (node.fieldNum<0){ throw new TransformLangExecutorRuntimeException(node, "Invalid field name \""+node.fieldName+"\" at LookupTable \""+node.lookupName+ "\" in graph \""+graph.getName()+"\""); } } switch(node.opType){ case CLVFLookupNode.OP_INIT: try{ node.lookup.init(); }catch(ComponentNotReadyException ex){ throw new TransformLangExecutorRuntimeException(node, "Error when initializing lookup table \""+node.lookupName+"\" :", ex); } return data; case CLVFLookupNode.OP_FREE: node.lookup.free(); return data; case CLVFLookupNode.OP_NUM_FOUND: stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(node.lookup.getNumFound()))); return data; case CLVFLookupNode.OP_GET: Object keys[]=new Object[node.jjtGetNumChildren()]; for(int i=0;i<node.jjtGetNumChildren();i++){ node.jjtGetChild(i).jjtAccept(this, data); keys[i]=stack.pop(); } record=node.lookup.get(keys); break; case CLVFLookupNode.OP_NEXT: record=node.lookup.getNext(); } if(record!=null){ stack.push(new TLValue(record.getField(node.fieldNum))); }else{ stack.push(Stack.NULL_VAL); } return data; } public Object visit(CLVFPrintLogNode node, Object data) { if (runtimeLogger == null) { throw new TransformLangExecutorRuntimeException(node, "Can NOT perform logging operation - no logger defined"); } node.jjtGetChild(0).jjtAccept(this, data); TLValue msg = stack.pop(); switch (node.level) { case 1: //| "debug" runtimeLogger.debug(msg); break; case 2: //| "info" runtimeLogger.info(msg); break; case 3: //| "warn" runtimeLogger.warn(msg); break; case 4: //| "error" runtimeLogger.error(msg); break; case 5: //| "fatal" runtimeLogger.fatal(msg); break; default: runtimeLogger.trace(msg); } return data; } public Object visit(CLVFSizeNode node, Object data) { CLVFVariableLiteral varNode=(CLVFVariableLiteral) node.jjtGetChild(0); TLVariable var=stack.getVar(varNode.localVar, varNode.varSlot); stack.push(new TLValue(TLValueType.INTEGER,new CloverInteger(var.getLength()))); return data; } public Object visit(CLVFImportSource node,Object data) { node.childrenAccept(this, data); return data; } public Object visit(CLVFSymbolNameExp node,Object data) { stack.push(node.value); return data; } }
UPDATE: several changes, mostly implemented new UnaryExpression exec section git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@2980 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/src/org/jetel/interpreter/TransformLangExecutor.java
UPDATE: several changes, mostly implemented new UnaryExpression exec section
<ide><path>loveretl.engine/src/org/jetel/interpreter/TransformLangExecutor.java <ide> import org.jetel.interpreter.ASTnode.CLVFForeachStatement; <ide> import org.jetel.interpreter.ASTnode.CLVFFunctionCallStatement; <ide> import org.jetel.interpreter.ASTnode.CLVFFunctionDeclaration; <del>import org.jetel.interpreter.ASTnode.CLVFGlobalParameterLiteral; <ide> import org.jetel.interpreter.ASTnode.CLVFIfStatement; <ide> import org.jetel.interpreter.ASTnode.CLVFIffNode; <ide> import org.jetel.interpreter.ASTnode.CLVFImportSource; <ide> import org.jetel.interpreter.ASTnode.CLVFModNode; <ide> import org.jetel.interpreter.ASTnode.CLVFMulNode; <ide> import org.jetel.interpreter.ASTnode.CLVFNVLNode; <del>import org.jetel.interpreter.ASTnode.CLVFNegation; <add>import org.jetel.interpreter.ASTnode.CLVFOperator; <ide> import org.jetel.interpreter.ASTnode.CLVFOr; <ide> import org.jetel.interpreter.ASTnode.CLVFOutputFieldLiteral; <ide> import org.jetel.interpreter.ASTnode.CLVFPlusPlusNode; <add>import org.jetel.interpreter.ASTnode.CLVFPostfixExpression; <ide> import org.jetel.interpreter.ASTnode.CLVFPrintErrNode; <ide> import org.jetel.interpreter.ASTnode.CLVFPrintLogNode; <ide> import org.jetel.interpreter.ASTnode.CLVFPrintStackNode; <ide> import org.jetel.interpreter.ASTnode.CLVFSwitchStatement; <ide> import org.jetel.interpreter.ASTnode.CLVFSymbolNameExp; <ide> import org.jetel.interpreter.ASTnode.CLVFTruncNode; <add>import org.jetel.interpreter.ASTnode.CLVFUnaryExpression; <ide> import org.jetel.interpreter.ASTnode.CLVFVarDeclaration; <ide> import org.jetel.interpreter.ASTnode.CLVFVariableLiteral; <ide> import org.jetel.interpreter.ASTnode.CLVFWhileStatement; <ide> return data; <ide> } <ide> <add> /* <ide> public Object visit(CLVFNegation node, Object data) { <ide> node.jjtGetChild(0).jjtAccept(this, data); <ide> TLValue value = stack.pop(); <ide> return data; <ide> } <ide> <del> <add>*/ <ide> public Object visit(CLVFIsNullNode node, Object data) { <ide> node.jjtGetChild(0).jjtAccept(this, data); <ide> TLValue value = stack.pop(); <ide> return data; <ide> } <ide> <del> public Object visit(CLVFGlobalParameterLiteral node, Object data) { <del> stack.push(new TLValue(TLValueType.STRING,globalParameters!=null ? globalParameters.getProperty(node.name) : null)); <del> return data; <del> } <add> <ide> <ide> public Object visit(CLVFRegexLiteral node, Object data) { <ide> stack.push(new TLValue(TLValueType.OBJECT,node.matcher)); <ide> }else { <ide> throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); <ide> } <del> }else { <del> // expression <del> childNode.jjtAccept(this, data); <del> TLValue val=stack.pop(); <del> if (val.type.isNumeric()) { <del> val=val.duplicate(); <del> val.getNumeric().add(Stack.NUM_ONE_P); <del> stack.push(val); <del> }else if (val.type==TLValueType.DATE) { <del> stack.calendar.setTime(val.getDate()); <del> stack.calendar.add(Calendar.DATE, 1); <del> val.value=stack.calendar.getTime(); <del> stack.push(val); <del> }else { <del> throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); <del> } <del> <ide> } <ide> <ide> return data; <ide> }else { <ide> throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); <ide> } <del> }else { <del> // expression <del> childNode.jjtAccept(this, data); <del> TLValue val=stack.pop(); <del> if (val.type.isNumeric()) { <del> val=val.duplicate(); <del> val.getNumeric().sub(Stack.NUM_ONE_P); <del> stack.push(val); <del> }else if (val.type==TLValueType.DATE) { <del> stack.calendar.setTime(val.getDate()); <del> stack.calendar.add(Calendar.DATE, -1); <del> val.value=stack.calendar.getTime(); <del> stack.push(val); <del> }else { <del> throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); <del> } <del> <ide> } <ide> <ide> return data; <ide> return data; <ide> } <ide> <add> public Object visit(CLVFOperator node,Object data) { <add> return data; <add> } <add> <add> public Object visit(CLVFPostfixExpression node,Object data) { <add> node.jjtGetChild(0).jjtAccept(this, data); <add> TLValue val=stack.pop(); <add> int operatorType=((CLVFOperator)node.jjtGetChild(1)).kind; <add> <add> if (operatorType==INCR) { <add> if (val.type.isNumeric()) { <add> val=val.duplicate(); <add> val.getNumeric().add(Stack.NUM_ONE_P); <add> stack.push(val); <add> }else if (val.type==TLValueType.DATE) { <add> stack.calendar.setTime(val.getDate()); <add> stack.calendar.add(Calendar.DATE, 1); <add> val.value=stack.calendar.getTime(); <add> stack.push(val); <add> }else { <add> throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); <add> } <add> }else{ <add> if (val.type.isNumeric()) { <add> val=val.duplicate(); <add> val.getNumeric().sub(Stack.NUM_ONE_P); <add> stack.push(val); <add> }else if (val.type==TLValueType.DATE) { <add> stack.calendar.setTime(val.getDate()); <add> stack.calendar.add(Calendar.DATE, -1); <add> val.value=stack.calendar.getTime(); <add> stack.push(val); <add> }else { <add> throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); <add> } <add> <add> } <add> <add> return data; <add> } <add> <add> public Object visit(CLVFUnaryExpression node,Object data) { <add> int operatorType=((CLVFOperator)node.jjtGetChild(0)).kind; <add> node.jjtGetChild(1).jjtAccept(this, data); <add> TLValue val=stack.pop(); <add> <add> switch(operatorType){ <add> case INCR: <add> if (val.type.isNumeric()) { <add> val=val.duplicate(); <add> val.getNumeric().add(Stack.NUM_ONE_P); <add> stack.push(val); <add> }else if (val.type==TLValueType.DATE) { <add> stack.calendar.setTime(val.getDate()); <add> stack.calendar.add(Calendar.DATE, 1); <add> val.value=stack.calendar.getTime(); <add> stack.push(val); <add> }else { <add> throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); <add> } <add> break; <add> case DECR: <add> if (val.type.isNumeric()) { <add> val=val.duplicate(); <add> val.getNumeric().sub(Stack.NUM_ONE_P); <add> stack.push(val); <add> }else if (val.type==TLValueType.DATE) { <add> stack.calendar.setTime(val.getDate()); <add> stack.calendar.add(Calendar.DATE, -1); <add> val.value=stack.calendar.getTime(); <add> stack.push(val); <add> }else { <add> throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type"); <add> } <add> break; <add> case NOT: <add> if (val.type==TLValueType.BOOLEAN) { <add> stack.push(val.getBoolean() ? Stack.FALSE_VAL <add> : Stack.TRUE_VAL); <add> } else { <add> throw new TransformLangExecutorRuntimeException(node, new Object[] { val }, <add> "logical condition does not evaluate to BOOLEAN value"); <add> } <add> <add> case MINUS: <add> if (val.type.isNumeric()) { <add> val=val.duplicate(); <add> val.getNumeric().neg(); <add> stack.push(val); <add> }else { <add> throw new TransformLangExecutorRuntimeException(node,new Object[] { val }, "variable is not of numeric type"); <add> } <add> break; <add> case PLUS: <add> if (val.type.isNumeric()) { <add> val=val.duplicate(); <add> val.getNumeric().abs(); <add> stack.push(val); <add> }else { <add> throw new TransformLangExecutorRuntimeException(node,new Object[] { val }, "variable is not of numeric type"); <add> } <add> break; <add> default: <add> throw new TransformLangExecutorRuntimeException(node, "unsupported operation"); <add> } <add> <add> <add> return data; <add> } <add> <ide> } <add>
JavaScript
mit
6a1b7626e32e61e146c56dcef2087e3f877b4c38
0
phillipalexander/lodash,therebelbeta/lodash,lzheng571/lodash,benweet/lodash,leolin1229/lodash,nsamarcos/lodash,hitesh97/lodash,krrg/lodash,transGLUKator/lodash,Droogans/lodash,Lottid/lodash,zhangguangyong/lodash,therebelbeta/lodash,gutenye/lodash,BernhardRode/lodash,polarbird/lodash,tquetano-r7/lodash,hitesh97/lodash,jasnell/lodash,tejokumar/lodash,jshanson7/lodash,Droogans/lodash,Jaspersoft/lodash,justintung/lodash,naoina/lodash,dgoncalves1/lodash,tgriesser/lodash,AneesMohammed/lodash,jshanson7/lodash,ror/lodash,naoina/lodash,dgoncalves1/lodash,gutenye/lodash,felixshu/lodash,phillipalexander/lodash,studiowangfei/lodash,boneskull/lodash,samuelbeek/lodash,nbellowe/lodash,dgoncalves1/lodash,jacwright/lodash,stewx/lodash,tejokumar/lodash,andersonaguiar/lodash,lekkas/lodash,codydaig/lodash,timruffles/lodash,imjerrybao/lodash,developer-prosenjit/lodash,gutenye/lodash,mjosh954/lodash,huyinghuan/lodash,mjosh954/lodash,stewx/lodash,ror/lodash,Xotic750/lodash,PhiLhoSoft/lodash,imjerrybao/lodash,beaugunderson/lodash,xiwc/lodash,lekoaf/lodash,MaxPRafferty/lodash,AndBicScadMedia/lodash,samuelbeek/lodash,codydaig/lodash,ajefremovs/lodash,krrg/lodash,rtorr/lodash,chrootsu/lodash,xiwc/lodash,PhiLhoSoft/lodash,developer-prosenjit/lodash,reggi/lodash,IveWong/lodash,schnerd/lodash,schnerd/lodash,javiosyc/lodash,msmorgan/lodash,studiowangfei/lodash,bnicart/lodash,BernhardRode/lodash,chrootsu/lodash,nbellowe/lodash,krahman/lodash,MaxPRafferty/lodash,woldie/lodash,zestia/lodash,ricardohbin/lodash,imjerrybao/lodash,jasnell/lodash,codydaig/lodash,neouser99/lodash,phillipalexander/lodash,prawnsalad/lodash,javiosyc/lodash,steelsojka/lodash,tquetano-r7/lodash,shwaydogg/lodash,tonyonodi/lodash,Droogans/lodash,af7/lodash,Moykn/lodash,chrootsu/lodash,xixilive/lodash,joshuaprior/lodash,Xotic750/lodash,r14r-work/fork_javascript_lodash,Moykn/lodash,tgriesser/lodash,polarbird/lodash,jacwright/lodash,af7/lodash,hitesh97/lodash,nsamarcos/lodash,xixilive/lodash,hafeez-syed/lodash,enng0227/lodash,Jaspersoft/lodash,xiwc/lodash,lekoaf/lodash,justintung/lodash,polarbird/lodash,greyhwndz/lodash,AndBicScadMedia/lodash,therebelbeta/lodash,jasnell/lodash,r14r-work/fork_javascript_lodash,bnicart/lodash,tgriesser/lodash,jacwright/lodash,transGLUKator/lodash,zestia/lodash,zhangguangyong/lodash,tejokumar/lodash,leolin1229/lodash,hafeez-syed/lodash,mshoaibraja/lodash,Moykn/lodash,jshanson7/lodash,PhiLhoSoft/lodash,jzning-martian/lodash,nsamarcos/lodash,neouser99/lodash,Jaspersoft/lodash,justintung/lodash,timruffles/lodash,greyhwndz/lodash,ajefremovs/lodash,lzheng571/lodash,reggi/lodash,youprofit/lodash,lekoaf/lodash,r14r/fork_javascript_lodash,bnicart/lodash,developer-prosenjit/lodash,Andrey-Pavlov/lodash,MaxPRafferty/lodash,Andrey-Pavlov/lodash,huyinghuan/lodash,BernhardRode/lodash,schnerd/lodash,stewx/lodash,youprofit/lodash,AneesMohammed/lodash,xixilive/lodash,krahman/lodash,neouser99/lodash,msmorgan/lodash,prawnsalad/lodash,felixshu/lodash,mjosh954/lodash,boneskull/lodash,shwaydogg/lodash,IveWong/lodash,af7/lodash,lekkas/lodash,enng0227/lodash,prawnsalad/lodash,Lottid/lodash,rlugojr/lodash,timruffles/lodash,rlugojr/lodash,woldie/lodash,enng0227/lodash,ricardohbin/lodash,youprofit/lodash,benweet/lodash,felixshu/lodash,beaugunderson/lodash,zestia/lodash,AndBicScadMedia/lodash,reggi/lodash,AneesMohammed/lodash,krahman/lodash,studiowangfei/lodash,r14r/fork_javascript_lodash,samuelbeek/lodash,lekkas/lodash,mshoaibraja/lodash,Xotic750/lodash,benweet/lodash,javiosyc/lodash,tonyonodi/lodash,jzning-martian/lodash,nbellowe/lodash,Lottid/lodash,naoina/lodash,ror/lodash,tquetano-r7/lodash,andersonaguiar/lodash,steelsojka/lodash,IveWong/lodash,r14r-work/fork_javascript_lodash,lzheng571/lodash,shwaydogg/lodash,huyinghuan/lodash,r14r/fork_javascript_lodash,hafeez-syed/lodash,andersonaguiar/lodash,joshuaprior/lodash,woldie/lodash,Andrey-Pavlov/lodash,joshuaprior/lodash,greyhwndz/lodash,jzning-martian/lodash,zhangguangyong/lodash,rtorr/lodash,transGLUKator/lodash,ricardohbin/lodash,leolin1229/lodash,krrg/lodash,rtorr/lodash,ajefremovs/lodash,mshoaibraja/lodash
;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used to detect when a function becomes hot. */ var HOT_COUNT = 150; /** Used as the size to cover large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used as references for the max length and index of an array. */ var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1; /** Used as the maximum length an array-like object. */ var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; /** `Object#toString` result references. */ var funcTag = '[object Function]', numberTag = '[object Number]', objectTag = '[object Object]'; /** Used as a reference to the global object. */ var root = (typeof global == 'object' && global) || this; /** Used to store lodash to test for bad extensions/shims. */ var lodashBizarro = root.lodashBizarro; /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, funcProto = Function.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Method and object shortcuts. */ var phantom = root.phantom, amd = root.define && define.amd, argv = root.process && process.argv, ArrayBuffer = root.ArrayBuffer, document = !phantom && root.document, body = root.document && root.document.body, create = Object.create, fnToString = funcProto.toString, freeze = Object.freeze, hasOwnProperty = objectProto.hasOwnProperty, JSON = root.JSON, objToString = objectProto.toString, noop = function() {}, params = root.arguments, push = arrayProto.push, slice = arrayProto.slice, Symbol = root.Symbol, system = root.system, Uint8Array = root.Uint8Array; /** Math helpers. */ var add = function(x, y) { return x + y; }, square = function(n) { return n * n; }; /** Used to set property descriptors. */ var defineProperty = (function() { try { var o = {}, func = Object.defineProperty, result = func(o, o, o) && func; } catch(e) {} return result; }()); /** The file path of the lodash file to test. */ var filePath = (function() { var min = 0, result = []; if (phantom) { result = params = phantom.args; } else if (system) { min = 1; result = params = system.args; } else if (argv) { min = 2; result = params = argv; } else if (params) { result = params; } var last = result[result.length - 1]; result = (result.length > min && !/test(?:\.js)?$/.test(last)) ? last : '../lodash.src.js'; if (!amd) { try { result = require('fs').realpathSync(result); } catch(e) {} try { result = require.resolve(result); } catch(e) {} } return result; }()); /** The `ui` object. */ var ui = root.ui || (root.ui = { 'buildPath': filePath, 'loaderPath': '', 'isModularize': /\b(?:amd|commonjs|es6?|node|npm|(index|main)\.js)\b/.test(filePath), 'isStrict': /\bes6?\b/.test(filePath), 'urlParams': {} }); /** The basename of the lodash file to test. */ var basename = /[\w.-]+$/.exec(filePath)[0]; /** Detect if in a Java environment. */ var isJava = !document && !!root.java; /** Used to indicate testing a modularized build. */ var isModularize = ui.isModularize; /** Detect if testing `npm` modules. */ var isNpm = isModularize && /\bnpm\b/.test([ui.buildPath, ui.urlParams.build]); /** Detect if running in PhantomJS. */ var isPhantom = phantom || typeof callPhantom == 'function'; /** Detect if running in Rhino. */ var isRhino = isJava && typeof global == 'function' && global().Array === root.Array; /** Detect if lodash is in strict mode. */ var isStrict = ui.isStrict; /** Used to test Web Workers. */ var Worker = !(ui.isForeign || ui.isSauceLabs || isModularize) && document && root.Worker; /** Used to test host objects in IE. */ try { var xml = new ActiveXObject('Microsoft.XMLDOM'); } catch(e) {} /** Use a single "load" function. */ var load = (typeof require == 'function' && !amd) ? require : (isJava ? root.load : noop); /** The unit testing framework. */ var QUnit = root.QUnit || (root.QUnit = ( QUnit = load('../node_modules/qunitjs/qunit/qunit.js') || root.QUnit, QUnit = QUnit.QUnit || QUnit )); /** Load QUnit Extras and ES6 Set/WeakMap shims. */ (function() { var paths = [ './asset/set.js', './asset/weakmap.js', '../node_modules/qunit-extras/qunit-extras.js' ]; var index = -1, length = paths.length; while (++index < length) { var object = load(paths[index]); if (object) { object.runInContext(root); } } }()); /*--------------------------------------------------------------------------*/ // Log params provided to `test.js`. if (params) { console.log('test.js invoked with arguments: ' + JSON.stringify(slice.call(params))); } // Exit early if going to run tests in a PhantomJS web page. if (phantom && isModularize) { var page = require('webpage').create(); page.open(filePath, function(status) { if (status != 'success') { console.log('PhantomJS failed to load page: ' + filePath); phantom.exit(1); } }); page.onCallback = function(details) { var coverage = details.coverage; if (coverage) { var fs = require('fs'), cwd = fs.workingDirectory, sep = fs.separator; fs.write([cwd, 'coverage', 'coverage.json'].join(sep), JSON.stringify(coverage)); } phantom.exit(details.failed ? 1 : 0); }; page.onConsoleMessage = function(message) { console.log(message); }; page.onInitialized = function() { page.evaluate(function() { document.addEventListener('DOMContentLoaded', function() { QUnit.done(function(details) { details.coverage = window.__coverage__; callPhantom(details); }); }); }); }; return; } /*--------------------------------------------------------------------------*/ /** The `lodash` function to test. */ var _ = root._ || (root._ = ( _ = load(filePath) || root._, _ = _._ || (isStrict = ui.isStrict = isStrict || 'default' in _, _['default']) || _, (_.runInContext ? _.runInContext(root) : _) )); /** List of latin-1 supplementary letters to basic latin letters. */ var burredLetters = [ '\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7', '\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf', '\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf', '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef', '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff' ]; /** List of `burredLetters` translated to basic latin letters. */ var deburredLetters = [ 'A', 'A', 'A', 'A', 'A', 'A', 'Ae', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'Th', 'ss', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'd', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'th', 'y' ]; /** Used to provide falsey values to methods. */ var falsey = [, '', 0, false, NaN, null, undefined]; /** Used to provide empty values to methods. */ var empties = [[], {}].concat(falsey.slice(1)); /** Used to test error objects. */ var errors = [ new Error, new EvalError, new RangeError, new ReferenceError, new SyntaxError, new TypeError, new URIError ]; /** Used to check problem JScript properties (a.k.a. the `[[DontEnum]]` bug). */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used to check problem JScript properties too. */ var shadowObject = _.invert(shadowProps); /** Used to check whether methods support typed arrays. */ var typedArrays = [ 'Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array' ]; /** * Used to check for problems removing whitespace. For a whitespace reference * see V8's unit test https://code.google.com/p/v8/source/browse/branches/bleeding_edge/test/mjsunit/whitespaces.js. */ var whitespace = ' \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'; /** * Extracts the unwrapped value from its wrapper. * * @private * @param {Object} wrapper The wrapper to unwrap. * @returns {*} Returns the unwrapped value. */ function getUnwrappedValue(wrapper) { var index = -1, actions = wrapper.__actions__, length = actions.length, result = wrapper.__wrapped__; while (++index < length) { var args = [result], action = actions[index]; push.apply(args, action.args); result = action.func.apply(action.thisArg, args); } return result; } /** * Removes all own enumerable properties from a given object. * * @private * @param {Object} object The object to empty. */ function emptyObject(object) { _.forOwn(object, function(value, key, object) { delete object[key]; }); } /** * Sets a non-enumerable property value on `object`. * * Note: This function is used to avoid a bug in older versions of V8 where * overwriting non-enumerable built-ins makes them enumerable. * See https://code.google.com/p/v8/issues/detail?id=1623 * * @private * @param {Object} object The object augment. * @param {string} key The name of the property to set. * @param {*} value The property value. */ function setProperty(object, key, value) { try { defineProperty(object, key, { 'configurable': true, 'enumerable': false, 'writable': true, 'value': value }); } catch(e) { object[key] = value; } } /** * Skips a given number of tests with a passing result. * * @private * @param {number} [count=1] The number of tests to skip. */ function skipTest(count) { count || (count = 1); while (count--) { ok(true, 'test skipped'); } } /*--------------------------------------------------------------------------*/ // Setup values for Node.js. (function() { if (amd) { return; } try { // Add values from a different realm. _.extend(_, require('vm').runInNewContext([ '(function() {', ' var object = {', " '_arguments': (function() { return arguments; }(1, 2, 3)),", " '_array': [1, 2, 3],", " '_boolean': Object(false),", " '_date': new Date,", " '_errors': [new Error, new EvalError, new RangeError, new ReferenceError, new SyntaxError, new TypeError, new URIError],", " '_function': function() {},", " '_nan': NaN,", " '_null': null,", " '_number': Object(0),", " '_object': { 'a': 1, 'b': 2, 'c': 3 },", " '_regexp': /x/,", " '_string': Object('a'),", " '_undefined': undefined", ' };', '', " ['" + typedArrays.join("', '") + "'].forEach(function(type) {", " var Ctor = Function('return typeof ' + type + \" != 'undefined' && \" + type)()", ' if (Ctor) {', " object['_' + type.toLowerCase()] = new Ctor(new ArrayBuffer(24));", ' }', " });", '', ' return object;', '}())' ].join('\n'))); } catch(e) { if (!phantom) { return; } } var nativeString = fnToString.call(toString), reToString = /toString/g; function createToString(funcName) { return _.constant(nativeString.replace(reToString, funcName)); } // Expose internal modules for better code coverage. if (isModularize && !isNpm) { _.each(['baseEach', 'isIndex', 'isIterateeCall', 'isLength'], function(funcName) { var path = require('path'), func = require(path.join(path.dirname(filePath), 'internal', funcName + '.js')); _['_' + funcName] = func[funcName] || func['default'] || func; }); } // Allow bypassing native checks. setProperty(funcProto, 'toString', function wrapper() { setProperty(funcProto, 'toString', fnToString); var result = _.has(this, 'toString') ? this.toString() : fnToString.call(this); setProperty(funcProto, 'toString', wrapper); return result; }); // Add built-in prototype extensions. funcProto._method = _.noop; // Set bad shims. var _isArray = Array.isArray; setProperty(Array, 'isArray', _.noop); var _now = Date.now; setProperty(Date, 'now', _.noop); var _getPrototypeOf = Object.getPrototypeOf; setProperty(Object, 'getPrototypeOf', _.noop); var _keys = Object.keys; setProperty(Object, 'keys', _.noop); var _propertyIsEnumerable = objectProto.propertyIsEnumerable; setProperty(objectProto, 'propertyIsEnumerable', function(key) { if (key == '1' && _.isArguments(this) && _.isEqual(_.values(this), [0, 0])) { throw new Error; } return _.has(this, key); }); var _isFinite = Number.isFinite; setProperty(Number, 'isFinite', _.noop); var _ArrayBuffer = ArrayBuffer; setProperty(root, 'ArrayBuffer', (function() { function ArrayBuffer(byteLength) { var buffer = new _ArrayBuffer(byteLength); if (!byteLength) { setProperty(buffer, 'slice', buffer.slice ? null : bufferSlice); } return buffer; } function bufferSlice() { var newBuffer = new _ArrayBuffer(this.byteLength), view = new Uint8Array(newBuffer); view.set(new Uint8Array(this)); return newBuffer; } setProperty(ArrayBuffer, 'toString', createToString('ArrayBuffer')); setProperty(bufferSlice, 'toString', createToString('slice')); return ArrayBuffer; }())); if (!root.Float64Array) { setProperty(root, 'Float64Array', (function() { function Float64Array(buffer, byteOffset, length) { return arguments.length == 1 ? new Uint8Array(buffer) : new Uint8Array(buffer, byteOffset || 0, length || buffer.byteLength); } setProperty(Float64Array, 'BYTES_PER_ELEMENT', 8); setProperty(Float64Array, 'toString', createToString('Float64Array')); return Float64Array; }())); } var _parseInt = parseInt; setProperty(root, 'parseInt', (function() { var checkStr = whitespace + '08', isFaked = _parseInt(checkStr) != 8, reHexPrefix = /^0[xX]/, reTrim = RegExp('^[' + whitespace + ']+|[' + whitespace + ']+$'); return function(value, radix) { if (value == checkStr && !isFaked) { isFaked = true; return 0; } value = String(value == null ? '' : value).replace(reTrim, ''); return _parseInt(value, +radix || (reHexPrefix.test(value) ? 16 : 10)); }; }())); var _Set = root.Set; setProperty(root, 'Set', _.noop); var _WeakMap = root.WeakMap; setProperty(root, 'WeakMap', _.noop); // Fake the DOM. setProperty(root, 'window', {}); setProperty(root.window, 'document', {}); setProperty(root.window.document, 'createDocumentFragment', function() { return { 'nodeType': 11 }; }); // Fake `WinRTError`. setProperty(root, 'WinRTError', Error); // Clear cache so lodash can be reloaded. emptyObject(require.cache); // Load lodash and expose it to the bad extensions/shims. lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro; // Restore built-in methods. setProperty(Array, 'isArray', _isArray); setProperty(Date, 'now', _now); setProperty(Object, 'getPrototypeOf', _getPrototypeOf); setProperty(Object, 'keys', _keys); setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable); setProperty(root, 'parseInt', _parseInt); if (_isFinite) { setProperty(Number, 'isFinite', _isFinite); } else { delete Number.isFinite; } if (_ArrayBuffer) { setProperty(root, 'ArrayBuffer', _ArrayBuffer); } else { delete root.ArrayBuffer; } if (_Set) { setProperty(root, 'Set', Set); } else { delete root.Set; } if (_WeakMap) { setProperty(root, 'WeakMap', WeakMap); } else { delete root.WeakMap; } delete root.WinRTError; delete root.window; delete funcProto._method; }()); // Add values from an iframe. (function() { if (_._object || !document) { return; } var iframe = document.createElement('iframe'); iframe.frameBorder = iframe.height = iframe.width = 0; body.appendChild(iframe); var idoc = (idoc = iframe.contentDocument || iframe.contentWindow).document || idoc; idoc.write([ '<script>', 'parent._._arguments = (function() { return arguments; }(1, 2, 3));', 'parent._._array = [1, 2, 3];', 'parent._._boolean = Object(false);', 'parent._._date = new Date;', "parent._._element = document.createElement('div');", 'parent._._errors = [new Error, new EvalError, new RangeError, new ReferenceError, new SyntaxError, new TypeError, new URIError];', 'parent._._function = function() {};', 'parent._._nan = NaN;', 'parent._._null = null;', 'parent._._number = Object(0);', "parent._._object = { 'a': 1, 'b': 2, 'c': 3 };", 'parent._._regexp = /x/;', "parent._._string = Object('a');", 'parent._._undefined = undefined;', '', 'var root = this;', "parent._.each(['" + typedArrays.join("', '") + "'], function(type) {", ' var Ctor = root[type];', ' if (Ctor) {', " parent._['_' + type.toLowerCase()] = new Ctor(new ArrayBuffer(24));", ' }', '});', '<\/script>' ].join('\n')); idoc.close(); }()); // Add a web worker. (function() { if (!Worker) { return; } var worker = new Worker('./asset/worker.js?t=' + (+new Date)); worker.addEventListener('message', function(e) { _._VERSION = e.data || ''; }, false); worker.postMessage(ui.buildPath); }()); /*--------------------------------------------------------------------------*/ QUnit.module(basename); (function() { test('should support loading ' + basename + ' as the "lodash" module', 1, function() { if (amd) { strictEqual((lodashModule || {}).moduleName, 'lodash'); } else { skipTest(); } }); test('should support loading ' + basename + ' with the Require.js "shim" configuration option', 1, function() { if (amd && _.includes(ui.loaderPath, 'requirejs')) { strictEqual((shimmedModule || {}).moduleName, 'shimmed'); } else { skipTest(); } }); test('should support loading ' + basename + ' as the "underscore" module', 1, function() { if (amd) { strictEqual((underscoreModule || {}).moduleName, 'underscore'); } else { skipTest(); } }); asyncTest('should support loading ' + basename + ' in a web worker', 1, function() { if (Worker) { var limit = 30000 / QUnit.config.asyncRetries, start = +new Date; var attempt = function() { var actual = _._VERSION; if ((new Date - start) < limit && typeof actual != 'string') { setTimeout(attempt, 16); return; } strictEqual(actual, _.VERSION); QUnit.start(); }; attempt(); } else { skipTest(); QUnit.start(); } }); test('should not add `Function.prototype` extensions to lodash', 1, function() { if (lodashBizarro) { ok(!('_method' in lodashBizarro)); } else { skipTest(); } }); test('should avoid overwritten native methods', 12, function() { function Foo() {} function message(lodashMethod, nativeMethod) { return '`' + lodashMethod + '` should avoid overwritten native `' + nativeMethod + '`'; } var object = { 'a': 1 }, otherObject = { 'b': 2 }, largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object)); if (lodashBizarro) { try { var actual = [lodashBizarro.isArray([]), lodashBizarro.isArray({ 'length': 0 })]; } catch(e) { actual = null; } deepEqual(actual, [true, false], message('_.isArray', 'Array.isArray')); try { actual = lodashBizarro.now(); } catch(e) { actual = null; } ok(typeof actual == 'number', message('_.now', 'Date.now')); try { actual = [lodashBizarro.isPlainObject({}), lodashBizarro.isPlainObject([])]; } catch(e) { actual = null; } deepEqual(actual, [true, false], message('_.isPlainObject', 'Object.getPrototypeOf')); try { actual = [lodashBizarro.keys(object), lodashBizarro.keys()]; } catch(e) { actual = null; } deepEqual(actual, [['a'], []], message('_.keys', 'Object.keys')); try { actual = [lodashBizarro.isFinite(1), lodashBizarro.isFinite(NaN)]; } catch(e) { actual = null; } deepEqual(actual, [true, false], message('_.isFinite', 'Number.isFinite')); try { actual = [ lodashBizarro.difference([object, otherObject], largeArray), lodashBizarro.intersection(largeArray, [object]), lodashBizarro.uniq(largeArray) ]; } catch(e) { actual = null; } deepEqual(actual, [[otherObject], [object], [object]], message('_.difference`, `_.intersection`, and `_.uniq', 'Set')); try { actual = _.map(['6', '08', '10'], lodashBizarro.parseInt); } catch(e) { actual = null; } deepEqual(actual, [6, 8, 10], '`_.parseInt` should work in its bizarro form'); if (ArrayBuffer) { try { var buffer = new ArrayBuffer(10); actual = lodashBizarro.clone(buffer); } catch(e) { actual = null; } deepEqual(actual, buffer, message('_.clone', 'ArrayBuffer#slice')); notStrictEqual(actual, buffer, message('_.clone', 'ArrayBuffer#slice')); } else { skipTest(2); } if (ArrayBuffer && Uint8Array) { try { var array = new Uint8Array(new ArrayBuffer(10)); actual = lodashBizarro.cloneDeep(array); } catch(e) { actual = null; } deepEqual(actual, array, message('_.cloneDeep', 'Float64Array')); notStrictEqual(actual && actual.buffer, array.buffer, message('_.cloneDeep', 'Float64Array')); notStrictEqual(actual, array, message('_.cloneDeep', 'Float64Array')); } else { skipTest(3); } } else { skipTest(12); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('isIndex'); (function() { var func = _._isIndex; test('should return `true` for indexes', 4, function() { if (func) { strictEqual(func(0), true); strictEqual(func('1'), true); strictEqual(func(3, 4), true); strictEqual(func(MAX_SAFE_INTEGER - 1), true); } else { skipTest(4); } }); test('should return `false` for non-indexes', 4, function() { if (func) { strictEqual(func(-1), false); strictEqual(func(3, 3), false); strictEqual(func(1.1), false); strictEqual(func(MAX_SAFE_INTEGER), false); } else { skipTest(4); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('isIterateeCall'); (function() { var array = [1], func = _._isIterateeCall, object = { 'a': 1 }; test('should return `true` for iteratee calls', 3, function() { function Foo() {} Foo.prototype.a = 1; if (func) { strictEqual(func(1, 0, array), true); strictEqual(func(1, 'a', object), true); strictEqual(func(1, 'a', new Foo), true); } else { skipTest(3); } }); test('should return `false` for non-iteratee calls', 4, function() { if (func) { strictEqual(func(2, 0, array), false); strictEqual(func(1, 1.1, array), false); strictEqual(func(1, 0, { 'length': MAX_SAFE_INTEGER + 1 }), false); strictEqual(func(1, 'b', object), false); } else { skipTest(4); } }); test('should work with `NaN` values', 2, function() { if (func) { strictEqual(func(NaN, 0, [NaN]), true); strictEqual(func(NaN, 'a', { 'a': NaN }), true); } else { skipTest(2); } }); test('should not error when `index` is an object without a `toString` method', 1, function() { if (func) { try { var actual = func(1, { 'toString': null }, [1]); } catch(e) { var message = e.message; } strictEqual(actual, false, message || ''); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('isLength'); (function() { var func = _._isLength; test('should return `true` for lengths', 3, function() { if (func) { strictEqual(func(0), true); strictEqual(func(3), true); strictEqual(func(MAX_SAFE_INTEGER), true); } else { skipTest(3); } }); test('should return `false` for non-lengths', 4, function() { if (func) { strictEqual(func(-1), false); strictEqual(func('1'), false); strictEqual(func(1.1), false); strictEqual(func(MAX_SAFE_INTEGER + 1), false); } else { skipTest(4); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash constructor'); (function() { var values = empties.concat(true, 1, 'a'), expected = _.map(values, _.constant(true)); test('creates a new instance when called without the `new` operator', 1, function() { if (!isNpm) { var actual = _.map(values, function(value) { return _(value) instanceof _; }); deepEqual(actual, expected); } else { skipTest(); } }); test('should return provided `lodash` instances', 1, function() { if (!isNpm) { var actual = _.map(values, function(value) { var wrapped = _(value); return _(wrapped) === wrapped; }); deepEqual(actual, expected); } else { skipTest(); } }); test('should convert foreign wrapped values to `lodash` instances', 1, function() { if (!isNpm && lodashBizarro) { var actual = _.map(values, function(value) { var wrapped = _(lodashBizarro(value)), unwrapped = wrapped.value(); return wrapped instanceof _ && (unwrapped === value || (_.isNaN(unwrapped) && _.isNaN(value))); }); deepEqual(actual, expected); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.add'); (function() { test('should add two numbers together', 1, function() { equal(_.add(6, 4), 10); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_(1).add(2), 3); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(1).chain().add(2) instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.after'); (function() { function after(n, times) { var count = 0; _.times(times, _.after(n, function() { count++; })); return count; } test('should create a function that invokes `func` after `n` calls', 4, function() { strictEqual(after(5, 5), 1, 'after(n) should invoke `func` after being called `n` times'); strictEqual(after(5, 4), 0, 'after(n) should not invoke `func` before being called `n` times'); strictEqual(after(0, 0), 0, 'after(0) should not invoke `func` immediately'); strictEqual(after(0, 1), 1, 'after(0) should invoke `func` when called once'); }); test('should coerce non-finite `n` values to `0`', 1, function() { var values = [-Infinity, NaN, Infinity], expected = _.map(values, _.constant(1)); var actual = _.map(values, function(n) { return after(n, 1); }); deepEqual(actual, expected); }); test('should allow `func` as the first argument', 1, function() { var count = 0; try { var after = _.after(function() { count++; }, 1); after(); after(); } catch(e) {} strictEqual(count, 2); }); test('should not set a `this` binding', 2, function() { var after = _.after(1, function() { return ++this.count; }), object = { 'count': 0, 'after': after }; object.after(); strictEqual(object.after(), 2); strictEqual(object.count, 2); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.ary'); (function() { function fn(a, b, c) { return slice.call(arguments); } test('should cap the numer of params provided to `func`', 2, function() { var actual = _.map(['6', '8', '10'], _.ary(parseInt, 1)); deepEqual(actual, [6, 8, 10]); var capped = _.ary(fn, 2); deepEqual(capped('a', 'b', 'c', 'd'), ['a', 'b']); }); test('should use `func.length` if `n` is not provided', 1, function() { var capped = _.ary(fn); deepEqual(capped('a', 'b', 'c', 'd'), ['a', 'b', 'c']); }); test('should treat a negative `n` as `0`', 1, function() { var capped = _.ary(fn, -1); try { var actual = capped('a'); } catch(e) {} deepEqual(actual, []); }); test('should work when provided less than the capped numer of arguments', 1, function() { var capped = _.ary(fn, 3); deepEqual(capped('a'), ['a']); }); test('should work as an iteratee for `_.map`', 1, function() { var funcs = _.map([fn], _.ary), actual = funcs[0]('a', 'b', 'c'); deepEqual(actual, ['a', 'b', 'c']); }); test('should work when combined with other methods that use metadata', 2, function() { var array = ['a', 'b', 'c'], includes = _.curry(_.rearg(_.ary(_.includes, 2), 1, 0), 2); strictEqual(includes('b')(array, 2), true); if (!isNpm) { includes = _(_.includes).ary(2).rearg(1, 0).curry(2).value(); strictEqual(includes('b')(array, 2), true); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.assign'); (function() { test('should assign properties of a source object to the destination object', 1, function() { deepEqual(_.assign({ 'a': 1 }, { 'b': 2 }), { 'a': 1, 'b': 2 }); }); test('should accept multiple source objects', 2, function() { var expected = { 'a': 1, 'b': 2, 'c': 3 }; deepEqual(_.assign({ 'a': 1 }, { 'b': 2 }, { 'c': 3 }), expected); deepEqual(_.assign({ 'a': 1 }, { 'b': 2, 'c': 2 }, { 'c': 3 }), expected); }); test('should overwrite destination properties', 1, function() { var expected = { 'a': 3, 'b': 2, 'c': 1 }; deepEqual(_.assign({ 'a': 1, 'b': 2 }, expected), expected); }); test('should assign source properties with `null` and `undefined` values', 1, function() { var expected = { 'a': null, 'b': undefined, 'c': null }; deepEqual(_.assign({ 'a': 1, 'b': 2 }, expected), expected); }); test('should work with a `customizer` callback', 1, function() { var actual = _.assign({ 'a': 1, 'b': 2 }, { 'a': 3, 'c': 3 }, function(a, b) { return typeof a == 'undefined' ? b : a; }); deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 }); }); test('should work with a `customizer` that returns `undefined`', 1, function() { var expected = { 'a': undefined }; deepEqual(_.assign({}, expected, _.identity), expected); }); test('should be aliased', 1, function() { strictEqual(_.extend, _.assign); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.at'); (function() { var args = arguments, array = ['a', 'b', 'c']; array['1.1'] = array['-1'] = 1; test('should return the elements corresponding to the specified keys', 1, function() { var actual = _.at(array, [0, 2]); deepEqual(actual, ['a', 'c']); }); test('should return `undefined` for nonexistent keys', 1, function() { var actual = _.at(array, [2, 4, 0]); deepEqual(actual, ['c', undefined, 'a']); }); test('should use `undefined` for non-index keys on array-like values', 1, function() { var values = _.reject(empties, function(value) { return value === 0 || _.isArray(value); }).concat(-1, 1.1); var expected = _.map(values, _.constant(undefined)), actual = _.at(array, values); deepEqual(actual, expected); }); test('should return an empty array when no keys are provided', 2, function() { deepEqual(_.at(array), []); deepEqual(_.at(array, [], []), []); }); test('should accept multiple key arguments', 1, function() { var actual = _.at(['a', 'b', 'c', 'd'], 3, 0, 2); deepEqual(actual, ['d', 'a', 'c']); }); test('should work with a falsey `collection` argument when keys are provided', 1, function() { var expected = _.map(falsey, _.constant([undefined, undefined])); var actual = _.map(falsey, function(value) { try { return _.at(value, 0, 1); } catch(e) {} }); deepEqual(actual, expected); }); test('should work with an `arguments` object for `collection`', 1, function() { var actual = _.at(args, [2, 0]); deepEqual(actual, [3, 1]); }); test('should work with `arguments` object as secondary arguments', 1, function() { var actual = _.at([1, 2, 3, 4, 5], args); deepEqual(actual, [2, 3, 4]); }); test('should work with an object for `collection`', 1, function() { var actual = _.at({ 'a': 1, 'b': 2, 'c': 3 }, ['c', 'a']); deepEqual(actual, [3, 1]); }); test('should pluck inherited property values', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var actual = _.at(new Foo, 'b'); deepEqual(actual, [2]); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 1, function() { deepEqual(_.at(collection, [2, 0]), ['c', 'a']); }); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.attempt'); (function() { test('should return the result of `func`', 1, function() { strictEqual(_.attempt(_.constant('x')), 'x'); }); test('should provide additional arguments to `func`', 1, function() { var actual = _.attempt(function() { return slice.call(arguments); }, 1, 2); deepEqual(actual, [1, 2]); }); test('should return the caught error', 1, function() { var expected = _.map(errors, _.constant(true)); var actual = _.map(errors, function(error) { return _.attempt(function() { throw error; }) === error; }); deepEqual(actual, expected); }); test('should coerce errors to error objects', 1, function() { var actual = _.attempt(function() { throw 'x'; }); ok(_.isEqual(actual, Error('x'))); }); test('should work with an error object from another realm', 1, function() { if (_._object) { var expected = _.map(_._errors, _.constant(true)); var actual = _.map(_._errors, function(error) { return _.attempt(function() { throw error; }) === error; }); deepEqual(actual, expected); } else { skipTest(); } }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_(_.constant('x')).attempt(), 'x'); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(_.constant('x')).chain().attempt() instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.before'); (function() { function before(n, times) { var count = 0; _.times(times, _.before(n, function() { count++; })); return count; } test('should create a function that invokes `func` after `n` calls', 4, function() { strictEqual(before(5, 4), 4, 'before(n) should invoke `func` before being called `n` times'); strictEqual(before(5, 6), 4, 'before(n) should not invoke `func` after being called `n - 1` times'); strictEqual(before(0, 0), 0, 'before(0) should not invoke `func` immediately'); strictEqual(before(0, 1), 0, 'before(0) should not invoke `func` when called'); }); test('should coerce non-finite `n` values to `0`', 1, function() { var values = [-Infinity, NaN, Infinity], expected = _.map(values, _.constant(0)); var actual = _.map(values, function(n) { return before(n); }); deepEqual(actual, expected); }); test('should allow `func` as the first argument', 1, function() { var count = 0; try { var before = _.before(function() { count++; }, 2); before(); before(); } catch(e) {} strictEqual(count, 1); }); test('should not set a `this` binding', 2, function() { var before = _.before(2, function() { return ++this.count; }), object = { 'count': 0, 'before': before }; object.before(); strictEqual(object.before(), 1); strictEqual(object.count, 1); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.bind'); (function() { function fn() { var result = [this]; push.apply(result, arguments); return result; } test('should bind a function to an object', 1, function() { var object = {}, bound = _.bind(fn, object); deepEqual(bound('a'), [object, 'a']); }); test('should accept a falsey `thisArg` argument', 1, function() { var values = _.reject(falsey.slice(1), function(value) { return value == null; }), expected = _.map(values, function(value) { return [value]; }); var actual = _.map(values, function(value) { try { var bound = _.bind(fn, value); return bound(); } catch(e) {} }); ok(_.every(actual, function(value, index) { return _.isEqual(value, expected[index]); })); }); test('should bind a function to `null` or `undefined`', 6, function() { var bound = _.bind(fn, null), actual = bound('a'); ok(actual[0] === null || actual[0] && actual[0].Array); strictEqual(actual[1], 'a'); _.times(2, function(index) { bound = index ? _.bind(fn, undefined) : _.bind(fn); actual = bound('b'); ok(actual[0] === undefined || actual[0] && actual[0].Array); strictEqual(actual[1], 'b'); }); }); test('should partially apply arguments ', 4, function() { var object = {}, bound = _.bind(fn, object, 'a'); deepEqual(bound(), [object, 'a']); bound = _.bind(fn, object, 'a'); deepEqual(bound('b'), [object, 'a', 'b']); bound = _.bind(fn, object, 'a', 'b'); deepEqual(bound(), [object, 'a', 'b']); deepEqual(bound('c', 'd'), [object, 'a', 'b', 'c', 'd']); }); test('should support placeholders', 4, function() { var object = {}, ph = _.bind.placeholder, bound = _.bind(fn, object, ph, 'b', ph); deepEqual(bound('a', 'c'), [object, 'a', 'b', 'c']); deepEqual(bound('a'), [object, 'a', 'b', undefined]); deepEqual(bound('a', 'c', 'd'), [object, 'a', 'b', 'c', 'd']); deepEqual(bound(), [object, undefined, 'b', undefined]); }); test('should create a function with a `length` of `0`', 2, function() { var fn = function(a, b, c) {}, bound = _.bind(fn, {}); strictEqual(bound.length, 0); bound = _.bind(fn, {}, 1); strictEqual(bound.length, 0); }); test('should ignore binding when called with the `new` operator', 3, function() { function Foo() { return this; } var bound = _.bind(Foo, { 'a': 1 }), newBound = new bound; strictEqual(newBound.a, undefined); strictEqual(bound().a, 1); ok(newBound instanceof Foo); }); test('ensure `new bound` is an instance of `func`', 2, function() { function Foo(value) { return value && object; } var bound = _.bind(Foo), object = {}; ok(new bound instanceof Foo); strictEqual(new bound(true), object); }); test('should append array arguments to partially applied arguments (test in IE < 9)', 1, function() { var object = {}, bound = _.bind(fn, object, 'a'); deepEqual(bound(['b'], 'c'), [object, 'a', ['b'], 'c']); }); test('should rebind functions correctly', 3, function() { var object1 = {}, object2 = {}, object3 = {}; var bound1 = _.bind(fn, object1), bound2 = _.bind(bound1, object2, 'a'), bound3 = _.bind(bound1, object3, 'b'); deepEqual(bound1(), [object1]); deepEqual(bound2(), [object1, 'a']); deepEqual(bound3(), [object1, 'b']); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var object = {}, bound = _(fn).bind({}, 'a', 'b'); ok(bound instanceof _); var actual = bound.value()('c'); deepEqual(actual, [object, 'a', 'b', 'c']); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.bindAll'); (function() { var args = arguments; test('should bind all methods of `object`', 1, function() { function Foo() { this._a = 1; this._b = 2; this.a = function() { return this._a; }; } Foo.prototype.b = function() { return this._b; }; var object = new Foo; _.bindAll(object); var actual = _.map(_.functions(object).sort(), function(methodName) { return object[methodName].call({}); }); deepEqual(actual, [1, 2]); }); test('should accept individual method names', 1, function() { var object = { '_a': 1, '_b': 2, '_c': 3, 'a': function() { return this._a; }, 'b': function() { return this._b; }, 'c': function() { return this._c; } }; _.bindAll(object, 'a', 'b'); var actual = _.map(_.functions(object).sort(), function(methodName) { return object[methodName].call({}); }); deepEqual(actual, [1, 2, undefined]); }); test('should accept arrays of method names', 1, function() { var object = { '_a': 1, '_b': 2, '_c': 3, '_d': 4, 'a': function() { return this._a; }, 'b': function() { return this._b; }, 'c': function() { return this._c; }, 'd': function() { return this._d; } }; _.bindAll(object, ['a', 'b'], ['c']); var actual = _.map(_.functions(object).sort(), function(methodName) { return object[methodName].call({}); }); deepEqual(actual, [1, 2, 3, undefined]); }); test('should work with an array `object` argument', 1, function() { var array = ['push', 'pop']; _.bindAll(array); strictEqual(array.pop, arrayProto.pop); }); test('should work with `arguments` objects as secondary arguments', 1, function() { var object = { '_a': 1, 'a': function() { return this._a; } }; _.bindAll(object, args); var actual = _.map(_.functions(object).sort(), function(methodName) { return object[methodName].call({}); }); deepEqual(actual, [1]); }); }('a')); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.bindKey'); (function() { test('should work when the target function is overwritten', 2, function() { var object = { 'user': 'fred', 'greet': function(greeting) { return this.user + ' says: ' + greeting; } }; var bound = _.bindKey(object, 'greet', 'hi'); strictEqual(bound(), 'fred says: hi'); object.greet = function(greeting) { return this.user + ' says: ' + greeting + '!'; }; strictEqual(bound(), 'fred says: hi!'); }); test('should support placeholders', 4, function() { var object = { 'fn': function() { return slice.call(arguments); } }; var ph = _.bindKey.placeholder, bound = _.bindKey(object, 'fn', ph, 'b', ph); deepEqual(bound('a', 'c'), ['a', 'b', 'c']); deepEqual(bound('a'), ['a', 'b', undefined]); deepEqual(bound('a', 'c', 'd'), ['a', 'b', 'c', 'd']); deepEqual(bound(), [undefined, 'b', undefined]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('case methods'); _.each(['camel', 'kebab', 'snake', 'start'], function(caseName) { var methodName = caseName + 'Case', func = _[methodName]; var strings = [ 'foo bar', 'Foo bar', 'foo Bar', 'Foo Bar', 'FOO BAR', 'fooBar', '--foo-bar', '__foo_bar__' ]; var converted = (function() { switch (caseName) { case 'camel': return 'fooBar'; case 'kebab': return 'foo-bar'; case 'snake': return 'foo_bar'; case 'start': return 'Foo Bar'; } }()); test('`_.' + methodName + '` should convert `string` to ' + caseName + ' case', 1, function() { var actual = _.map(strings, function(string) { var expected = (caseName === 'start' && string === 'FOO BAR') ? string : converted; return func(string) === expected; }); deepEqual(actual, _.map(strings, _.constant(true))); }); test('`_.' + methodName + '` should handle double-converting strings', 1, function() { var actual = _.map(strings, function(string) { var expected = (caseName === 'start' && string === 'FOO BAR') ? string : converted; return func(func(string)) === expected; }); deepEqual(actual, _.map(strings, _.constant(true))); }); test('`_.' + methodName + '` should deburr letters', 1, function() { var actual = _.map(burredLetters, function(burred, index) { var letter = deburredLetters[index]; letter = caseName == 'start' ? _.capitalize(letter) : letter.toLowerCase(); return func(burred) === letter; }); deepEqual(actual, _.map(burredLetters, _.constant(true))); }); test('`_.' + methodName + '` should trim latin-1 mathematical operators', 1, function() { var actual = _.map(['\xd7', '\xf7'], func); deepEqual(actual, ['', '']); }); test('`_.' + methodName + '` should coerce `string` to a string', 2, function() { var string = 'foo bar'; strictEqual(func(Object(string)), converted); strictEqual(func({ 'toString': _.constant(string) }), converted); }); test('`_.' + methodName + '` should return an unwrapped value implicitly when chaining', 1, function() { if (!isNpm) { strictEqual(_('foo bar')[methodName](), converted); } else { skipTest(); } }); test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_('foo bar').chain()[methodName]() instanceof _); } else { skipTest(); } }); }); (function() { test('should get the original value after cycling through all case methods', 1, function() { var funcs = [_.camelCase, _.kebabCase, _.snakeCase, _.startCase, _.camelCase]; var actual = _.reduce(funcs, function(result, func) { return func(result); }, 'enable 24h format'); strictEqual(actual, 'enable24HFormat'); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.camelCase'); (function() { test('should work with numbers', 4, function() { strictEqual(_.camelCase('enable 24h format'), 'enable24HFormat'); strictEqual(_.camelCase('too legit 2 quit'), 'tooLegit2Quit'); strictEqual(_.camelCase('walk 500 miles'), 'walk500Miles'); strictEqual(_.camelCase('xhr2 request'), 'xhr2Request'); }); test('should handle acronyms', 6, function() { _.each(['safe HTML', 'safeHTML'], function(string) { strictEqual(_.camelCase(string), 'safeHtml'); }); _.each(['escape HTML entities', 'escapeHTMLEntities'], function(string) { strictEqual(_.camelCase(string), 'escapeHtmlEntities'); }); _.each(['XMLHttpRequest', 'XmlHTTPRequest'], function(string) { strictEqual(_.camelCase(string), 'xmlHttpRequest'); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.capitalize'); (function() { test('should capitalize the first character of a string', 3, function() { strictEqual(_.capitalize('fred'), 'Fred'); strictEqual(_.capitalize('Fred'), 'Fred'); strictEqual(_.capitalize(' fred'), ' fred'); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_('fred').capitalize(), 'Fred'); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_('fred').chain().capitalize() instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.chain'); (function() { test('should return a wrapped value', 1, function() { if (!isNpm) { var actual = _.chain({ 'a': 0 }); ok(actual instanceof _); } else { skipTest(); } }); test('should return existing wrapped values', 2, function() { if (!isNpm) { var wrapped = _({ 'a': 0 }); strictEqual(_.chain(wrapped), wrapped); strictEqual(wrapped.chain(), wrapped); } else { skipTest(2); } }); test('should enable chaining of methods that return unwrapped values by default', 6, function() { if (!isNpm) { var array = ['c', 'b', 'a']; ok(_.chain(array).first() instanceof _); ok(_(array).chain().first() instanceof _); ok(_.chain(array).isArray() instanceof _); ok(_(array).chain().isArray() instanceof _); ok(_.chain(array).sortBy().first() instanceof _); ok(_(array).chain().sortBy().first() instanceof _); } else { skipTest(6); } }); test('should chain multiple methods', 6, function() { if (!isNpm) { _.times(2, function(index) { var array = ['one two three four', 'five six seven eight', 'nine ten eleven twelve'], expected = { ' ': 9, 'e': 14, 'f': 2, 'g': 1, 'h': 2, 'i': 4, 'l': 2, 'n': 6, 'o': 3, 'r': 2, 's': 2, 't': 5, 'u': 1, 'v': 4, 'w': 2, 'x': 1 }, wrapped = index ? _(array).chain() : _.chain(array); var actual = wrapped .chain() .map(function(value) { return value.split(''); }) .flatten() .reduce(function(object, chr) { object[chr] || (object[chr] = 0); object[chr]++; return object; }, {}) .value(); deepEqual(actual, expected); array = [1, 2, 3, 4, 5, 6]; wrapped = index ? _(array).chain() : _.chain(array); actual = wrapped .chain() .filter(function(n) { return n % 2; }) .reject(function(n) { return n % 3 == 0; }) .sortBy(function(n) { return -n; }) .value(); deepEqual(actual, [5, 1]); array = [3, 4]; wrapped = index ? _(array).chain() : _.chain(array); actual = wrapped .reverse() .concat([2, 1]) .unshift(5) .tap(function(value) { value.pop(); }) .map(square) .value(); deepEqual(actual,[25, 16, 9, 4]); }); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.chunk'); (function() { var array = [0, 1, 2, 3, 4, 5]; test('should return chunked arrays', 1, function() { var actual = _.chunk(array, 3); deepEqual(actual, [[0, 1, 2], [3, 4, 5]]); }); test('should return the last chunk as remaining elements', 1, function() { var actual = _.chunk(array, 4); deepEqual(actual, [[0, 1, 2, 3], [4, 5]]); }); test('should ensure the minimum `chunkSize` is `1`', 1, function() { var values = falsey.concat(-1, -Infinity), expected = _.map(values, _.constant([[0], [1], [2], [3], [4], [5]])); var actual = _.map(values, function(value, index) { return index ? _.chunk(array, value) : _.chunk(array); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([[1, 2], [3, 4]], _.chunk); deepEqual(actual, [[[1], [2]], [[3], [4]]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('clone methods'); (function() { function Foo() { this.a = 1; } Foo.prototype = { 'b': 1 }; Foo.c = function() {}; var objects = { '`arguments` objects': arguments, 'arrays': ['a', ''], 'array-like-objects': { '0': 'a', '1': '', 'length': 3 }, 'booleans': false, 'boolean objects': Object(false), 'Foo instances': new Foo, 'objects': { 'a': 0, 'b': 1, 'c': 3 }, 'objects with object values': { 'a': /a/, 'b': ['B'], 'c': { 'C': 1 } }, 'objects from another document': _._object || {}, 'null values': null, 'numbers': 3, 'number objects': Object(3), 'regexes': /a/gim, 'strings': 'a', 'string objects': Object('a'), 'undefined values': undefined }; objects['arrays'].length = 3; var uncloneable = { 'DOM elements': body, 'functions': Foo }; _.each(errors, function(error) { uncloneable[error.name + 's'] = error; }); test('`_.clone` should perform a shallow clone', 2, function() { var array = [{ 'a': 0 }, { 'b': 1 }], actual = _.clone(array); deepEqual(actual, array); ok(actual !== array && actual[0] === array[0]); }); test('`_.clone` should work with `isDeep`', 8, function() { var array = [{ 'a': 0 }, { 'b': 1 }], values = [true, 1, {}, '1']; _.each(values, function(isDeep) { var actual = _.clone(array, isDeep); deepEqual(actual, array); ok(actual !== array && actual[0] !== array[0]); }); }); test('`_.cloneDeep` should deep clone objects with circular references', 1, function() { var object = { 'foo': { 'b': { 'c': { 'd': {} } } }, 'bar': {} }; object.foo.b.c.d = object; object.bar.b = object.foo.b; var actual = _.cloneDeep(object); ok(actual.bar.b === actual.foo.b && actual === actual.foo.b.c.d && actual !== object); }); _.each(['clone', 'cloneDeep'], function(methodName) { var func = _[methodName], isDeep = methodName == 'cloneDeep'; _.forOwn(objects, function(object, key) { test('`_.' + methodName + '` should clone ' + key, 2, function() { var actual = func(object); ok(_.isEqual(actual, object)); if (_.isObject(object)) { notStrictEqual(actual, object); } else { strictEqual(actual, object); } }); }); _.forOwn(uncloneable, function(value, key) { test('`_.' + methodName + '` should not clone ' + key, 3, function() { var object = { 'a': value, 'b': { 'c': value } }, actual = func(object); deepEqual(actual, object); notStrictEqual(actual, object); var expected = typeof value == 'function' ? { 'c': Foo.c } : (value && {}); deepEqual(func(value), expected); }); test('`_.' + methodName + '` should work with a `customizer` callback and ' + key, 4, function() { var customizer = function(value) { return _.isPlainObject(value) ? undefined : value; }; var actual = func(value, customizer); deepEqual(actual, value); strictEqual(actual, value); var object = { 'a': value, 'b': { 'c': value } }; actual = func(object, customizer); deepEqual(actual, object); notStrictEqual(actual, object); }); }); test('`_.' + methodName + '` should clone array buffers', 2, function() { if (ArrayBuffer) { var buffer = new ArrayBuffer(10), actual = func(buffer); strictEqual(actual.byteLength, buffer.byteLength); notStrictEqual(actual, buffer); } else { skipTest(2); } }); _.each(typedArrays, function(type) { test('`_.' + methodName + '` should clone ' + type + ' arrays', 10, function() { var Ctor = root[type]; _.times(2, function(index) { if (Ctor) { var buffer = new ArrayBuffer(24), array = index ? new Ctor(buffer, 8, 1) : new Ctor(buffer), actual = func(array); deepEqual(actual, array); notStrictEqual(actual, array); strictEqual(actual.buffer === array.buffer, !isDeep); strictEqual(actual.byteOffset, array.byteOffset); strictEqual(actual.length, array.length); } else { skipTest(5); } }); }); }); test('`_.' + methodName + '` should clone problem JScript properties (test in IE < 9)', 2, function() { var actual = func(shadowObject); deepEqual(actual, shadowObject); notStrictEqual(actual, shadowObject); }); test('`_.' + methodName + '` should provide the correct `customizer` arguments', 1, function() { var argsList = [], foo = new Foo; func(foo, function() { argsList.push(slice.call(arguments)); }); deepEqual(argsList, isDeep ? [[foo], [1, 'a', foo]] : [[foo]]); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func('a', function(value) { return this[value]; }, { 'a': 'A' }); strictEqual(actual, 'A'); }); test('`_.' + methodName + '` should handle cloning if `customizer` returns `undefined`', 1, function() { var actual = func({ 'a': { 'b': 'c' } }, _.noop); deepEqual(actual, { 'a': { 'b': 'c' } }); }); test('`_.' + methodName + '` should clone `index` and `input` array properties', 2, function() { var array = /x/.exec('vwxyz'), actual = func(array); strictEqual(actual.index, 2); strictEqual(actual.input, 'vwxyz'); }); test('`_.' + methodName + '` should clone `lastIndex` regexp property', 1, function() { // Avoid a regexp literal for older Opera and use `exec` for older Safari. var regexp = RegExp('x', 'g'); regexp.exec('vwxyz'); var actual = func(regexp); strictEqual(actual.lastIndex, 3); }); test('`_.' + methodName + '` should not error on DOM elements', 1, function() { if (document) { var element = document.createElement('div'); try { deepEqual(func(element), {}); } catch(e) { ok(false, e.message); } } else { skipTest(); } }); test('`_.' + methodName + '` should perform a ' + (isDeep ? 'deep' : 'shallow') + ' clone when used as an iteratee for `_.map`', 3, function() { var expected = [{ 'a': [0] }, { 'b': [1] }], actual = _.map(expected, func); deepEqual(actual, expected); if (isDeep) { ok(actual[0] !== expected[0] && actual[0].a !== expected[0].a && actual[1].b !== expected[1].b); } else { ok(actual[0] !== expected[0] && actual[0].a === expected[0].a && actual[1].b === expected[1].b); } actual = _.map(isDeep ? Object('abc') : 'abc', func); deepEqual(actual, ['a', 'b', 'c']); }); test('`_.' + methodName + '` should create an object from the same realm as `value`', 1, function() { var props = []; var objects = _.transform(_, function(result, value, key) { if (_.startsWith(key, '_') && _.isObject(value) && !_.isArguments(value) && !_.isElement(value) && !_.isFunction(value)) { props.push(_.capitalize(_.camelCase(key))); result.push(value); } }, []); var expected = _.times(objects.length, _.constant(true)); var actual = _.map(objects, function(object) { var Ctor = object.constructor, result = func(object); return result !== object && (result instanceof Ctor || !(new Ctor instanceof Ctor)); }); deepEqual(actual, expected, props.join(', ')); }); test('`_.' + methodName + '` should return a unwrapped value when chaining', 2, function() { if (!isNpm) { var object = objects['objects'], actual = _(object)[methodName](); deepEqual(actual, object); notStrictEqual(actual, object); } else { skipTest(2); } }); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.compact'); (function() { test('should filter falsey values', 1, function() { var array = ['0', '1', '2']; deepEqual(_.compact(falsey.concat(array)), array); }); test('should work when in between lazy operators', 2, function() { if (!isNpm) { var actual = _(falsey).thru(_.slice).compact().thru(_.slice).value(); deepEqual(actual, []); actual = _(falsey).thru(_.slice).push(true, 1).compact().push('a').value(); deepEqual(actual, [true, 1, 'a']); } else { skipTest(2); } }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, null, 3], actual = _(array).map(square).compact().reverse().take().value(); deepEqual(actual, [9]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.flowRight'); (function() { test('should be aliased', 2, function() { strictEqual(_.backflow, _.flowRight); strictEqual(_.compose, _.flowRight); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('flow methods'); _.each(['flow', 'flowRight'], function(methodName) { var func = _[methodName], isFlow = methodName == 'flow'; test('`_.' + methodName + '` should supply each function with the return value of the previous', 1, function() { var fixed = function(n) { return n.toFixed(1); }, combined = isFlow ? func(add, square, fixed) : func(fixed, square, add); strictEqual(combined(1, 2), '9.0'); }); test('`_.' + methodName + '` should return a new function', 1, function() { notStrictEqual(func(_.noop), _.noop); }); test('`_.' + methodName + '` should return an identity function when no arguments are provided', 2, function() { var combined = func(); try { strictEqual(combined('a'), 'a'); } catch(e) { ok(false, e.message); } notStrictEqual(combined, _.identity); }); test('`_.' + methodName + '` should return a wrapped value when chaining', 1, function() { if (!isNpm) { var wrapped = _(_.noop)[methodName](); ok(wrapped instanceof _); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.constant'); (function() { test('should create a function that returns `value`', 1, function() { var object = { 'a': 1 }, values = Array(2).concat(empties, true, 1, 'a'), constant = _.constant(object), expected = _.map(values, function() { return true; }); var actual = _.map(values, function(value, index) { if (index == 0) { var result = constant(); } else if (index == 1) { result = constant.call({}); } else { result = constant(value); } return result === object; }); deepEqual(actual, expected); }); test('should work with falsey values', 1, function() { var expected = _.map(falsey, function() { return true; }); var actual = _.map(falsey, function(value, index) { var constant = index ? _.constant(value) : _.constant(), result = constant(); return result === value || (_.isNaN(result) && _.isNaN(value)); }); deepEqual(actual, expected); }); test('should return a wrapped value when chaining', 1, function() { if (!isNpm) { var wrapped = _(true).constant(); ok(wrapped instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.countBy'); (function() { var array = [4.2, 6.1, 6.4]; test('should work with an iteratee', 1, function() { var actual = _.countBy(array, function(num) { return Math.floor(num); }, Math); deepEqual(actual, { '4': 1, '6': 2 }); }); test('should use `_.identity` when `iteratee` is nullish', 1, function() { var array = [4, 6, 6], values = [, null, undefined], expected = _.map(values, _.constant({ '4': 1, '6': 2 })); var actual = _.map(values, function(value, index) { return index ? _.countBy(array, value) : _.countBy(array); }); deepEqual(actual, expected); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.countBy(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [4.2, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.countBy(array, function(num) { return this.floor(num); }, Math); deepEqual(actual, { '4': 1, '6': 2 }); }); test('should only add values to own, not inherited, properties', 2, function() { var actual = _.countBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); deepEqual(actual.constructor, 1); deepEqual(actual.hasOwnProperty, 2); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.countBy(['one', 'two', 'three'], 'length'); deepEqual(actual, { '3': 2, '5': 1 }); }); test('should work with a number for `iteratee`', 2, function() { var array = [ [1, 'a'], [2, 'a'], [2, 'b'] ]; deepEqual(_.countBy(array, 0), { '1': 1, '2': 2 }); deepEqual(_.countBy(array, 1), { 'a': 2, 'b': 1 }); }); test('should work with an object for `collection`', 1, function() { var actual = _.countBy({ 'a': 4.2, 'b': 6.1, 'c': 6.4 }, function(num) { return Math.floor(num); }); deepEqual(actual, { '4': 1, '6': 2 }); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 1, 3], predicate = function(value) { return value > 2; }, actual = _(array).countBy(_.identity).map(square).filter(predicate).take().value(); deepEqual(actual, [4]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.create'); (function() { function Shape() { this.x = 0; this.y = 0; } function Circle() { Shape.call(this); } test('should create an object that inherits from the given `prototype` object', 3, function() { Circle.prototype = _.create(Shape.prototype); Circle.prototype.constructor = Circle; var actual = new Circle; ok(actual instanceof Circle); ok(actual instanceof Shape); notStrictEqual(Circle.prototype, Shape.prototype); }); test('should assign `properties` to the created object', 3, function() { var expected = { 'constructor': Circle, 'radius': 0 }; Circle.prototype = _.create(Shape.prototype, expected); var actual = new Circle; ok(actual instanceof Circle); ok(actual instanceof Shape); deepEqual(Circle.prototype, expected); }); test('should assign own properties', 1, function() { function Foo() { this.a = 1; this.c = 3; } Foo.prototype.b = 2; deepEqual(_.create({}, new Foo), { 'a': 1, 'c': 3 }); }); test('should accept a falsey `prototype` argument', 1, function() { var expected = _.map(falsey, _.constant({})); var actual = _.map(falsey, function(value, index) { return index ? _.create(value) : _.create(); }); deepEqual(actual, expected); }); test('should ignore primitive `prototype` arguments and use an empty object instead', 1, function() { var primitives = [true, null, 1, 'a', undefined], expected = _.map(primitives, _.constant(true)); var actual = _.map(primitives, function(value, index) { return _.isPlainObject(index ? _.create(value) : _.create()); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [{ 'a': 1 }, { 'a': 1 }, { 'a': 1 }], expected = _.map(array, _.constant(true)), objects = _.map(array, _.create); var actual = _.map(objects, function(object) { return object.a === 1 && !_.keys(object).length; }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.callback'); (function() { test('should provide arguments to `func`', 3, function() { function fn() { var result = [this]; push.apply(result, arguments); return result; } var callback = _.callback(fn), actual = callback('a', 'b', 'c', 'd', 'e', 'f'); ok(actual[0] === null || actual[0] && actual[0].Array); deepEqual(actual.slice(1), ['a', 'b', 'c', 'd', 'e', 'f']); var object = {}; callback = _.callback(fn, object); actual = callback('a', 'b'); deepEqual(actual, [object, 'a', 'b']); }); test('should return `_.identity` when `func` is nullish', 1, function() { var object = {}, values = [, null, undefined], expected = _.map(values, _.constant(object)); var actual = _.map(values, function(value, index) { var callback = index ? _.callback(value) : _.callback(); return callback(object); }); deepEqual(actual, expected); }); test('should not error when `func` is nullish and a `thisArg` is provided', 2, function() { var object = {}; _.each([null, undefined], function(value) { try { var callback = _.callback(value, {}); strictEqual(callback(object), object); } catch(e) { ok(false, e.message); } }); }); test('should create a callback with a falsey `thisArg`', 1, function() { var fn = function() { return this; }, object = {}; var expected = _.map(falsey, function(value) { var result = fn.call(value); return (result && result.Array) ? object : result; }); var actual = _.map(falsey, function(value) { var callback = _.callback(fn, value), result = callback(); return (result && result.Array) ? object : result; }); ok(_.isEqual(actual, expected)); }); test('should return a callback created by `_.matches` when `func` is an object', 2, function() { var callback = _.callback({ 'a': 1 }); strictEqual(callback({ 'a': 1, 'b': 2 }), true); strictEqual(callback({}), false); }); test('should return a callback created by `_.matchesProperty` when `func` is a number or string and `thisArg` is not `undefined`', 3, function() { var array = ['a'], callback = _.callback(0, 'a'); strictEqual(callback(array), true); callback = _.callback('0', 'a'); strictEqual(callback(array), true); callback = _.callback(1, undefined); strictEqual(callback(array), undefined); }); test('should return a callback created by `_.property` when `func` is a number or string', 2, function() { var array = ['a'], callback = _.callback(0); strictEqual(callback(array), 'a'); callback = _.callback('0'); strictEqual(callback(array), 'a'); }); test('should work with functions created by `_.partial` and `_.partialRight`', 2, function() { function fn() { var result = [this.a]; push.apply(result, arguments); return result; } var expected = [1, 2, 3], object = { 'a': 1 }, callback = _.callback(_.partial(fn, 2), object); deepEqual(callback(3), expected); callback = _.callback(_.partialRight(fn, 3), object); deepEqual(callback(2), expected); }); test('should support binding built-in methods', 2, function() { var fn = function() {}, object = { 'a': 1 }, bound = fn.bind && fn.bind(object), callback = _.callback(hasOwnProperty, object); strictEqual(callback('a'), true); if (bound) { callback = _.callback(bound, object); notStrictEqual(callback, bound); } else { skipTest(); } }); test('should return the function provided when there is no `this` reference', 2, function() { function a() {} function b() { return this.b; } var object = {}; if (_.support.funcDecomp) { strictEqual(_.callback(a, object), a); notStrictEqual(_.callback(b, object), b); } else { skipTest(2); } }); test('should work with bizarro `_.support.funcNames`', 6, function() { function a() {} var b = function() {}; function c() { return this; } var object = {}, supportBizarro = lodashBizarro ? lodashBizarro.support : {}, funcDecomp = supportBizarro.funcDecomp, funcNames = supportBizarro.funcNames; supportBizarro.funcNames = !supportBizarro.funcNames; supportBizarro.funcDecomp = true; _.each([a, b, c], function(fn) { if (lodashBizarro && _.support.funcDecomp) { var callback = lodashBizarro.callback(fn, object); strictEqual(callback(), fn === c ? object : undefined); strictEqual(callback === fn, _.support.funcNames && fn === a); } else { skipTest(2); } }); supportBizarro.funcDecomp = funcDecomp; supportBizarro.funcNames = funcNames; }); test('should work as an iteratee for `_.map`', 1, function() { var fn = function() { return this instanceof Number; }, array = [fn, fn, fn], callbacks = _.map(array, _.callback), expected = _.map(array, _.constant(false)); var actual = _.map(callbacks, function(callback) { return callback(); }); deepEqual(actual, expected); }); test('should be aliased', 1, function() { strictEqual(_.iteratee, _.callback); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('custom `_.callback` methods'); (function() { var array = ['one', 'two', 'three'], callback = _.callback, getPropA = _.partial(_.property, 'a'), getPropB = _.partial(_.property, 'b'), getLength = _.partial(_.property, 'length'); var getSum = function() { return function(result, object) { return result + object.a; }; }; var objects = [ { 'a': 0, 'b': 0 }, { 'a': 1, 'b': 0 }, { 'a': 1, 'b': 1 } ]; test('`_.countBy` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getLength; deepEqual(_.countBy(array), { '3': 2, '5': 1 }); _.callback = callback; } else { skipTest(); } }); test('`_.dropRightWhile` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.dropRightWhile(objects), objects.slice(0, 2)); _.callback = callback; } else { skipTest(); } }); test('`_.dropWhile` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.dropWhile(objects.reverse()).reverse(), objects.reverse().slice(0, 2)); _.callback = callback; } else { skipTest(); } }); test('`_.every` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.every(objects.slice(1)), true); _.callback = callback; } else { skipTest(); } }); test('`_.filter` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 0 }, { 'a': 1 }]; _.callback = getPropA; deepEqual(_.filter(objects), [objects[1]]); _.callback = callback; } else { skipTest(); } }); test('`_.find` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.find(objects), objects[1]); _.callback = callback; } else { skipTest(); } }); test('`_.findIndex` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.findIndex(objects), 1); _.callback = callback; } else { skipTest(); } }); test('`_.findLast` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.findLast(objects), objects[2]); _.callback = callback; } else { skipTest(); } }); test('`_.findLastIndex` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.findLastIndex(objects), 2); _.callback = callback; } else { skipTest(); } }); test('`_.findLastKey` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; strictEqual(_.findKey(objects), '2'); _.callback = callback; } else { skipTest(); } }); test('`_.findKey` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; strictEqual(_.findLastKey(objects), '2'); _.callback = callback; } else { skipTest(); } }); test('`_.groupBy` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getLength; deepEqual(_.groupBy(array), { '3': ['one', 'two'], '5': ['three'] }); _.callback = callback; } else { skipTest(); } }); test('`_.indexBy` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getLength; deepEqual(_.indexBy(array), { '3': 'two', '5': 'three' }); _.callback = callback; } else { skipTest(); } }); test('`_.map` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; deepEqual(_.map(objects), [0, 1, 1]); _.callback = callback; } else { skipTest(); } }); test('`_.mapValues` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.mapValues({ 'a': { 'b': 1 } }), { 'a': 1 }); _.callback = callback; } else { skipTest(); } }); test('`_.max` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.max(objects), objects[2]); _.callback = callback; } else { skipTest(); } }); test('`_.min` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.min(objects), objects[0]); _.callback = callback; } else { skipTest(); } }); test('`_.partition` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 1 }, { 'a': 1 }, { 'b': 2 }]; _.callback = getPropA; deepEqual(_.partition(objects), [objects.slice(0, 2), objects.slice(2)]); _.callback = callback; } else { skipTest(); } }); test('`_.reduce` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getSum; strictEqual(_.reduce(objects, undefined, 0), 2); _.callback = callback; } else { skipTest(); } }); test('`_.reduceRight` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getSum; strictEqual(_.reduceRight(objects, undefined, 0), 2); _.callback = callback; } else { skipTest(); } }); test('`_.reject` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 0 }, { 'a': 1 }]; _.callback = getPropA; deepEqual(_.reject(objects), [objects[0]]); _.callback = callback; } else { skipTest(); } }); test('`_.remove` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 0 }, { 'a': 1 }]; _.callback = getPropA; _.remove(objects); deepEqual(objects, [{ 'a': 0 }]); _.callback = callback; } else { skipTest(); } }); test('`_.some` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; strictEqual(_.some(objects), true); _.callback = callback; } else { skipTest(); } }); test('`_.sortBy` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; deepEqual(_.sortBy(objects.slice().reverse()), [objects[0], objects[2], objects[1]]); _.callback = callback; } else { skipTest(); } }); test('`_.sortedIndex` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 30 }, { 'a': 50 }]; _.callback = getPropA; strictEqual(_.sortedIndex(objects, { 'a': 40 }), 1); _.callback = callback; } else { skipTest(); } }); test('`_.sortedLastIndex` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 30 }, { 'a': 50 }]; _.callback = getPropA; strictEqual(_.sortedLastIndex(objects, { 'a': 40 }), 1); _.callback = callback; } else { skipTest(); } }); test('`_.takeRightWhile` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.takeRightWhile(objects), objects.slice(2)); _.callback = callback; } else { skipTest(); } }); test('`_.takeWhile` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.takeWhile(objects.reverse()), objects.reverse().slice(2)); _.callback = callback; } else { skipTest(); } }); test('`_.transform` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = function() { return function(result, object) { result.sum += object.a; }; }; deepEqual(_.transform(objects, undefined, { 'sum': 0 }), { 'sum': 2 }); _.callback = callback; } else { skipTest(); } }); test('`_.uniq` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.uniq(objects), [objects[0], objects[2]]); _.callback = callback; } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.curry'); (function() { function fn(a, b, c, d) { return slice.call(arguments); } test('should curry based on the number of arguments provided', 3, function() { var curried = _.curry(fn), expected = [1, 2, 3, 4]; deepEqual(curried(1)(2)(3)(4), expected); deepEqual(curried(1, 2)(3, 4), expected); deepEqual(curried(1, 2, 3, 4), expected); }); test('should allow specifying `arity`', 3, function() { var curried = _.curry(fn, 3), expected = [1, 2, 3]; deepEqual(curried(1)(2, 3), expected); deepEqual(curried(1, 2)(3), expected); deepEqual(curried(1, 2, 3), expected); }); test('should coerce `arity` to a number', 2, function() { var values = ['0', 'xyz'], expected = _.map(values, _.constant([])); var actual = _.map(values, function(arity) { return _.curry(fn, arity)(); }); deepEqual(actual, expected); deepEqual(_.curry(fn, '2')(1)(2), [1, 2]); }); test('should support placeholders', 4, function() { var curried = _.curry(fn), ph = curried.placeholder; deepEqual(curried(1)(ph, 3)(ph, 4)(2), [1, 2, 3, 4]); deepEqual(curried(ph, 2)(1)(ph, 4)(3), [1, 2, 3, 4]); deepEqual(curried(ph, ph, 3)(ph, 2)(ph, 4)(1), [1, 2, 3, 4]); deepEqual(curried(ph, ph, ph, 4)(ph, ph, 3)(ph, 2)(1), [1, 2, 3, 4]); }); test('should work with partialed methods', 2, function() { var curried = _.curry(fn), expected = [1, 2, 3, 4]; var a = _.partial(curried, 1), b = _.bind(a, null, 2), c = _.partialRight(b, 4), d = _.partialRight(b(3), 4); deepEqual(c(3), expected); deepEqual(d(), expected); }); test('should provide additional arguments after reaching the target arity', 3, function() { var curried = _.curry(fn, 3); deepEqual(curried(1)(2, 3, 4), [1, 2, 3, 4]); deepEqual(curried(1, 2)(3, 4, 5), [1, 2, 3, 4, 5]); deepEqual(curried(1, 2, 3, 4, 5, 6), [1, 2, 3, 4, 5, 6]); }); test('should return a function with a `length` of `0`', 6, function() { _.times(2, function(index) { var curried = index ? _.curry(fn, 4) : _.curry(fn); strictEqual(curried.length, 0); strictEqual(curried(1).length, 0); strictEqual(curried(1, 2).length, 0); }); }); test('ensure `new curried` is an instance of `func`', 2, function() { var Foo = function(value) { return value && object; }; var curried = _.curry(Foo), object = {}; ok(new curried(false) instanceof Foo); strictEqual(new curried(true), object); }); test('should not set a `this` binding', 9, function() { var fn = function(a, b, c) { var value = this || {}; return [value[a], value[b], value[c]]; }; var object = { 'a': 1, 'b': 2, 'c': 3 }, expected = [1, 2, 3]; deepEqual(_.curry(_.bind(fn, object), 3)('a')('b')('c'), expected); deepEqual(_.curry(_.bind(fn, object), 3)('a', 'b')('c'), expected); deepEqual(_.curry(_.bind(fn, object), 3)('a', 'b', 'c'), expected); deepEqual(_.bind(_.curry(fn), object)('a')('b')('c'), Array(3)); deepEqual(_.bind(_.curry(fn), object)('a', 'b')('c'), Array(3)); deepEqual(_.bind(_.curry(fn), object)('a', 'b', 'c'), expected); object.curried = _.curry(fn); deepEqual(object.curried('a')('b')('c'), Array(3)); deepEqual(object.curried('a', 'b')('c'), Array(3)); deepEqual(object.curried('a', 'b', 'c'), expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.curryRight'); (function() { function fn(a, b, c, d) { return slice.call(arguments); } test('should curry based on the number of arguments provided', 3, function() { var curried = _.curryRight(fn), expected = [1, 2, 3, 4]; deepEqual(curried(4)(3)(2)(1), expected); deepEqual(curried(3, 4)(1, 2), expected); deepEqual(curried(1, 2, 3, 4), expected); }); test('should allow specifying `arity`', 3, function() { var curried = _.curryRight(fn, 3), expected = [1, 2, 3]; deepEqual(curried(3)(1, 2), expected); deepEqual(curried(2, 3)(1), expected); deepEqual(curried(1, 2, 3), expected); }); test('should work with partialed methods', 2, function() { var curried = _.curryRight(fn), expected = [1, 2, 3, 4]; var a = _.partialRight(curried, 4), b = _.partialRight(a, 3), c = _.bind(b, null, 1), d = _.partial(b(2), 1); deepEqual(c(2), expected); deepEqual(d(), expected); }); test('should support placeholders', 4, function() { var curried = _.curryRight(fn), expected = [1, 2, 3, 4], ph = curried.placeholder; deepEqual(curried(4)(2, ph)(1, ph)(3), expected); deepEqual(curried(3, ph)(4)(1, ph)(2), expected); deepEqual(curried(ph, ph, 4)(ph, 3)(ph, 2)(1), expected); deepEqual(curried(ph, ph, ph, 4)(ph, ph, 3)(ph, 2)(1), expected); }); test('should provide additional arguments after reaching the target arity', 3, function() { var curried = _.curryRight(fn, 3); deepEqual(curried(4)(1, 2, 3), [1, 2, 3, 4]); deepEqual(curried(4, 5)(1, 2, 3), [1, 2, 3, 4, 5]); deepEqual(curried(1, 2, 3, 4, 5, 6), [1, 2, 3, 4, 5, 6]); }); test('should return a function with a `length` of `0`', 6, function() { _.times(2, function(index) { var curried = index ? _.curryRight(fn, 4) : _.curryRight(fn); strictEqual(curried.length, 0); strictEqual(curried(4).length, 0); strictEqual(curried(3, 4).length, 0); }); }); test('ensure `new curried` is an instance of `func`', 2, function() { var Foo = function(value) { return value && object; }; var curried = _.curryRight(Foo), object = {}; ok(new curried(false) instanceof Foo); strictEqual(new curried(true), object); }); test('should not set a `this` binding', 9, function() { var fn = function(a, b, c) { var value = this || {}; return [value[a], value[b], value[c]]; }; var object = { 'a': 1, 'b': 2, 'c': 3 }, expected = [1, 2, 3]; deepEqual(_.curryRight(_.bind(fn, object), 3)('c')('b')('a'), expected); deepEqual(_.curryRight(_.bind(fn, object), 3)('b', 'c')('a'), expected); deepEqual(_.curryRight(_.bind(fn, object), 3)('a', 'b', 'c'), expected); deepEqual(_.bind(_.curryRight(fn), object)('c')('b')('a'), Array(3)); deepEqual(_.bind(_.curryRight(fn), object)('b', 'c')('a'), Array(3)); deepEqual(_.bind(_.curryRight(fn), object)('a', 'b', 'c'), expected); object.curried = _.curryRight(fn); deepEqual(object.curried('c')('b')('a'), Array(3)); deepEqual(object.curried('b', 'c')('a'), Array(3)); deepEqual(object.curried('a', 'b', 'c'), expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('curry methods'); _.each(['curry', 'curryRight'], function(methodName) { var func = _[methodName], fn = function(a, b) { return slice.call(arguments); }, isCurry = methodName == 'curry'; test('`_.' + methodName + '` should work as an iteratee for `_.map`', 2, function() { var array = [fn, fn, fn], object = { 'a': fn, 'b': fn, 'c': fn }; _.each([array, object], function(collection) { var curries = _.map(collection, func), expected = _.map(collection, _.constant(isCurry ? ['a', 'b'] : ['b', 'a'])); var actual = _.map(curries, function(curried) { return curried('a')('b'); }); deepEqual(actual, expected); }); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.debounce'); (function() { asyncTest('should debounce a function', 2, function() { if (!(isRhino && isModularize)) { var callCount = 0, debounced = _.debounce(function() { callCount++; }, 32); debounced(); debounced(); debounced(); strictEqual(callCount, 0); setTimeout(function() { strictEqual(callCount, 1); QUnit.start(); }, 96); } else { skipTest(2); QUnit.start(); } }); asyncTest('subsequent debounced calls return the last `func` result', 2, function() { if (!(isRhino && isModularize)) { var debounced = _.debounce(_.identity, 32); debounced('x'); setTimeout(function() { notEqual(debounced('y'), 'y'); }, 64); setTimeout(function() { notEqual(debounced('z'), 'z'); QUnit.start(); }, 128); } else { skipTest(2); QUnit.start(); } }); asyncTest('subsequent "immediate" debounced calls return the last `func` result', 2, function() { if (!(isRhino && isModularize)) { var debounced = _.debounce(_.identity, 32, true), result = [debounced('x'), debounced('y')]; deepEqual(result, ['x', 'x']); setTimeout(function() { var result = [debounced('a'), debounced('b')]; deepEqual(result, ['a', 'a']); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); asyncTest('should apply default options correctly', 2, function() { if (!(isRhino && isModularize)) { var callCount = 0; var debounced = _.debounce(function(value) { callCount++; return value; }, 32, {}); strictEqual(debounced('x'), undefined); setTimeout(function() { strictEqual(callCount, 1); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); asyncTest('should support a `leading` option', 7, function() { if (!(isRhino && isModularize)) { var withLeading, callCounts = [0, 0, 0]; _.each([true, { 'leading': true }], function(options, index) { var debounced = _.debounce(function(value) { callCounts[index]++; return value; }, 32, options); if (index == 1) { withLeading = debounced; } strictEqual(debounced('x'), 'x'); }); _.each([false, { 'leading': false }], function(options) { var withoutLeading = _.debounce(_.identity, 32, options); strictEqual(withoutLeading('x'), undefined); }); var withLeadingAndTrailing = _.debounce(function() { callCounts[2]++; }, 32, { 'leading': true }); withLeadingAndTrailing(); withLeadingAndTrailing(); strictEqual(callCounts[2], 1); setTimeout(function() { deepEqual(callCounts, [1, 1, 2]); withLeading('x'); strictEqual(callCounts[1], 2); QUnit.start(); }, 64); } else { skipTest(7); QUnit.start(); } }); asyncTest('should support a `trailing` option', 4, function() { if (!(isRhino && isModularize)) { var withCount = 0, withoutCount = 0; var withTrailing = _.debounce(function(value) { withCount++; return value; }, 32, { 'trailing': true }); var withoutTrailing = _.debounce(function(value) { withoutCount++; return value; }, 32, { 'trailing': false }); strictEqual(withTrailing('x'), undefined); strictEqual(withoutTrailing('x'), undefined); setTimeout(function() { strictEqual(withCount, 1); strictEqual(withoutCount, 0); QUnit.start(); }, 64); } else { skipTest(4); QUnit.start(); } }); asyncTest('should support a `maxWait` option', 1, function() { if (!(isRhino && isModularize)) { var limit = (argv || isPhantom) ? 1000 : 320, withCount = 0, withoutCount = 0; var withMaxWait = _.debounce(function() { withCount++; }, 64, { 'maxWait': 128 }); var withoutMaxWait = _.debounce(function() { withoutCount++; }, 96); var start = +new Date; while ((new Date - start) < limit) { withMaxWait(); withoutMaxWait(); } var actual = [Boolean(withCount), Boolean(withoutCount)]; setTimeout(function() { deepEqual(actual, [true, false]); QUnit.start(); }, 1); } else { skipTest(); QUnit.start(); } }); asyncTest('should cancel `maxDelayed` when `delayed` is invoked', 1, function() { if (!(isRhino && isModularize)) { var callCount = 0; var debounced = _.debounce(function() { callCount++; }, 32, { 'maxWait': 64 }); debounced(); setTimeout(function() { strictEqual(callCount, 1); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); asyncTest('should invoke the `trailing` call with the correct arguments and `this` binding', 2, function() { if (!(isRhino && isModularize)) { var actual, callCount = 0, object = {}; var debounced = _.debounce(function(value) { actual = [this]; push.apply(actual, arguments); return ++callCount != 2; }, 32, { 'leading': true, 'maxWait': 64 }); while (true) { if (!debounced.call(object, 'a')) { break; } } setTimeout(function() { strictEqual(callCount, 2); deepEqual(actual, [object, 'a']); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.deburr'); (function() { test('should convert latin-1 supplementary letters to basic latin', 1, function() { var actual = _.map(burredLetters, _.deburr); deepEqual(actual, deburredLetters); }); test('should not deburr latin-1 mathematical operators', 1, function() { var operators = ['\xd7', '\xf7'], actual = _.map(operators, _.deburr); deepEqual(actual, operators); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.defaults'); (function() { test('should assign properties of a source object if missing on the destination object', 1, function() { deepEqual(_.defaults({ 'a': 1 }, { 'a': 2, 'b': 2 }), { 'a': 1, 'b': 2 }); }); test('should accept multiple source objects', 2, function() { var expected = { 'a': 1, 'b': 2, 'c': 3 }; deepEqual(_.defaults({ 'a': 1, 'b': 2 }, { 'b': 3 }, { 'c': 3 }), expected); deepEqual(_.defaults({ 'a': 1, 'b': 2 }, { 'b': 3, 'c': 3 }, { 'c': 2 }), expected); }); test('should not overwrite `null` values', 1, function() { var actual = _.defaults({ 'a': null }, { 'a': 1 }); strictEqual(actual.a, null); }); test('should overwrite `undefined` values', 1, function() { var actual = _.defaults({ 'a': undefined }, { 'a': 1 }); strictEqual(actual.a, 1); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.defer'); (function() { asyncTest('should defer `func` execution', 1, function() { if (!(isRhino && isModularize)) { var pass = false; _.defer(function() { pass = true; }); setTimeout(function() { ok(pass); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); asyncTest('should provide additional arguments to `func`', 1, function() { if (!(isRhino && isModularize)) { var args; _.defer(function() { args = slice.call(arguments); }, 1, 2); setTimeout(function() { deepEqual(args, [1, 2]); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); asyncTest('should be cancelable', 1, function() { if (!(isRhino && isModularize)) { var pass = true; var timerId = _.defer(function() { pass = false; }); clearTimeout(timerId); setTimeout(function() { ok(pass); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.delay'); (function() { asyncTest('should delay `func` execution', 2, function() { if (!(isRhino && isModularize)) { var pass = false; _.delay(function() { pass = true; }, 96); setTimeout(function() { ok(!pass); }, 32); setTimeout(function() { ok(pass); QUnit.start(); }, 160); } else { skipTest(2); QUnit.start(); } }); asyncTest('should provide additional arguments to `func`', 1, function() { if (!(isRhino && isModularize)) { var args; _.delay(function() { args = slice.call(arguments); }, 32, 1, 2); setTimeout(function() { deepEqual(args, [1, 2]); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); asyncTest('should be cancelable', 1, function() { if (!(isRhino && isModularize)) { var pass = true; var timerId = _.delay(function() { pass = false; }, 32); clearTimeout(timerId); setTimeout(function() { ok(pass); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.difference'); (function() { var args = arguments; test('should return the difference of the given arrays', 2, function() { var actual = _.difference([1, 2, 3, 4, 5], [5, 2, 10]); deepEqual(actual, [1, 3, 4]); actual = _.difference([1, 2, 3, 4, 5], [5, 2, 10], [8, 4]); deepEqual(actual, [1, 3]); }); test('should match `NaN`', 1, function() { deepEqual(_.difference([1, NaN, 3], [NaN, 5, NaN]), [1, 3]); }); test('should work with large arrays', 1, function() { var array1 = _.range(LARGE_ARRAY_SIZE + 1), array2 = _.range(LARGE_ARRAY_SIZE), a = {}, b = {}, c = {}; array1.push(a, b, c); array2.push(b, c, a); deepEqual(_.difference(array1, array2), [LARGE_ARRAY_SIZE]); }); test('should work with large arrays of objects', 1, function() { var object1 = {}, object2 = {}, largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object1)); deepEqual(_.difference([object1, object2], largeArray), [object2]); }); test('should work with large arrays of `NaN`', 1, function() { var largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(NaN)); deepEqual(_.difference([1, NaN, 3], largeArray), [1, 3]); }); test('should ignore values that are not arrays or `arguments` objects', 4, function() { var array = [1, null, 3]; deepEqual(_.difference(args, 3, { '0': 1 }), [1, 2, 3]); deepEqual(_.difference(null, array, 1), []); deepEqual(_.difference(array, args, null), [null]); deepEqual(_.difference('abc', array, 'b'), []); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.drop'); (function() { var array = [1, 2, 3]; test('should drop the first two elements', 1, function() { deepEqual(_.drop(array, 2), [3]); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? [2, 3] : array; }); var actual = _.map(falsey, function(n) { return _.drop(array, n); }); deepEqual(actual, expected); }); test('should return all elements when `n` < `1`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.drop(array, n), array); }); }); test('should return an empty array when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.drop(array, n), []); }); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.drop); deepEqual(actual, [[2, 3], [5, 6], [8, 9]]); }); test('should work in a lazy chain sequence', 6, function() { if (!isNpm) { var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], values = [], predicate = function(value) { values.push(value); return value > 2; }, actual = _(array).drop(2).drop().value(); deepEqual(actual, [4, 5, 6, 7, 8, 9, 10]); actual = _(array).filter(predicate).drop(2).drop().value(); deepEqual(actual, [6, 7, 8, 9, 10]); deepEqual(values, array); actual = _(array).drop(2).dropRight().drop().dropRight(2).value(); deepEqual(actual, [4, 5, 6, 7]); values = []; actual = _(array).drop().filter(predicate).drop(2).dropRight().drop().dropRight(2).value(); deepEqual(actual, [6, 7]); deepEqual(values, array.slice(1)); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.dropRight'); (function() { var array = [1, 2, 3]; test('should drop the last two elements', 1, function() { deepEqual(_.dropRight(array, 2), [1]); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? [1, 2] : array; }); var actual = _.map(falsey, function(n) { return _.dropRight(array, n); }); deepEqual(actual, expected); }); test('should return all elements when `n` < `1`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.dropRight(array, n), array); }); }); test('should return an empty array when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.dropRight(array, n), []); }); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.dropRight); deepEqual(actual, [[1, 2], [4, 5], [7, 8]]); }); test('should work in a lazy chain sequence', 6, function() { if (!isNpm) { var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], values = [], predicate = function(value) { values.push(value); return value < 9; }, actual = _(array).dropRight(2).dropRight().value(); deepEqual(actual, [1, 2, 3, 4, 5, 6, 7]); actual = _(array).filter(predicate).dropRight(2).dropRight().value(); deepEqual(actual, [1, 2, 3, 4, 5]); deepEqual(values, array); actual = _(array).dropRight(2).drop().dropRight().drop(2).value(); deepEqual(actual, [4, 5, 6, 7]); values = []; actual = _(array).dropRight().filter(predicate).dropRight(2).drop().dropRight().drop(2).value(); deepEqual(actual, [4, 5]); deepEqual(values, array.slice(0, -1)); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.dropRightWhile'); (function() { var array = [1, 2, 3, 4]; var objects = [ { 'a': 0, 'b': 0 }, { 'a': 1, 'b': 1 }, { 'a': 2, 'b': 2 } ]; test('should drop elements while `predicate` returns truthy', 1, function() { var actual = _.dropRightWhile(array, function(num) { return num > 2; }); deepEqual(actual, [1, 2]); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.dropRightWhile(array, function() { args = slice.call(arguments); }); deepEqual(args, [4, 3, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.dropRightWhile(array, function(num, index) { return this[index] > 2; }, array); deepEqual(actual, [1, 2]); }); test('should work with a "_.matches" style `predicate`', 1, function() { deepEqual(_.dropRightWhile(objects, { 'b': 2 }), objects.slice(0, 2)); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { deepEqual(_.dropRightWhile(objects, 'b', 2), objects.slice(0, 2)); }); test('should work with a "_.property" style `predicate`', 1, function() { deepEqual(_.dropRightWhile(objects, 'b'), objects.slice(0, 1)); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var wrapped = _(array).dropRightWhile(function(num) { return num > 2; }); ok(wrapped instanceof _); deepEqual(wrapped.value(), [1, 2]); } else { skipTest(2); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [16, 3, [1, 4, 9 ,16]]; _(array).dropRightWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, [4, 3, array]); _(array).map(square).dropRightWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).dropRightWhile(function(value, index) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).dropRightWhile(function(value) { args = slice.call(arguments); }).value(); deepEqual(args, [16]); _(array).map(square).dropRightWhile(function() { args = slice.call(arguments); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.dropWhile'); (function() { var array = [1, 2, 3, 4]; var objects = [ { 'a': 2, 'b': 2 }, { 'a': 1, 'b': 1 }, { 'a': 0, 'b': 0 } ]; test('should drop elements while `predicate` returns truthy', 1, function() { var actual = _.dropWhile(array, function(num) { return num < 3; }); deepEqual(actual, [3, 4]); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.dropWhile(array, function() { args = slice.call(arguments); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.dropWhile(array, function(num, index) { return this[index] < 3; }, array); deepEqual(actual, [3, 4]); }); test('should work with a "_.matches" style `predicate`', 1, function() { deepEqual(_.dropWhile(objects, { 'b': 2 }), objects.slice(1)); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { deepEqual(_.dropWhile(objects, 'b', 2), objects.slice(1)); }); test('should work with a "_.property" style `predicate`', 1, function() { deepEqual(_.dropWhile(objects, 'b'), objects.slice(2)); }); test('should work in a lazy chain sequence', 3, function() { if (!isNpm) { var wrapped = _(array).dropWhile(function(num) { return num < 3; }); deepEqual(wrapped.value(), [3, 4]); deepEqual(wrapped.reverse().value(), [4, 3]); strictEqual(wrapped.last(), 4); } else { skipTest(3); } }); test('should work in a lazy chain sequence with `drop`', 1, function() { if (!isNpm) { var actual = _(array) .dropWhile(function(num) { return num == 1; }) .drop() .dropWhile(function(num) { return num == 3; }) .value(); deepEqual(actual, [4]); } else { skipTest(); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [1, 0, [1, 4, 9, 16]]; _(array).dropWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, [1, 0, array]); _(array).map(square).dropWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).dropWhile(function(value, index) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).dropWhile(function(index) { args = slice.call(arguments); }).value(); deepEqual(args, [1]); _(array).map(square).dropWhile(function() { args = slice.call(arguments); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.endsWith'); (function() { var string = 'abc'; test('should return `true` if a string ends with `target`', 1, function() { strictEqual(_.endsWith(string, 'c'), true); }); test('should return `false` if a string does not end with `target`', 1, function() { strictEqual(_.endsWith(string, 'b'), false); }); test('should work with a `position` argument', 1, function() { strictEqual(_.endsWith(string, 'b', 2), true); }); test('should work with `position` >= `string.length`', 4, function() { _.each([3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { strictEqual(_.endsWith(string, 'c', position), true); }); }); test('should treat falsey `position` values, except `undefined`, as `0`', 1, function() { var expected = _.map(falsey, _.constant(true)); var actual = _.map(falsey, function(position) { return _.endsWith(string, position === undefined ? 'c' : '', position); }); deepEqual(actual, expected); }); test('should treat a negative `position` as `0`', 6, function() { _.each([-1, -3, -Infinity], function(position) { ok(_.every(string, function(chr) { return _.endsWith(string, chr, position) === false; })); strictEqual(_.endsWith(string, '', position), true); }); }); test('should return `true` when `target` is an empty string regardless of `position`', 1, function() { ok(_.every([-Infinity, NaN, -3, -1, 0, 1, 2, 3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { return _.endsWith(string, '', position, true); })); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.escape'); (function() { var escaped = '&amp;&lt;&gt;&quot;&#39;&#96;\/', unescaped = '&<>"\'`\/'; escaped += escaped; unescaped += unescaped; test('should escape values', 1, function() { strictEqual(_.escape(unescaped), escaped); }); test('should not escape the "/" character', 1, function() { strictEqual(_.escape('/'), '/'); }); test('should handle strings with nothing to escape', 1, function() { strictEqual(_.escape('abc'), 'abc'); }); test('should escape the same characters unescaped by `_.unescape`', 1, function() { strictEqual(_.escape(_.unescape(escaped)), escaped); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.escapeRegExp'); (function() { var escaped = '\\.\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\/\\\\', unescaped = '.*+?^${}()|[\]\/\\'; escaped += escaped; unescaped += unescaped; test('should escape values', 1, function() { strictEqual(_.escapeRegExp(unescaped), escaped); }); test('should handle strings with nothing to escape', 1, function() { strictEqual(_.escapeRegExp('abc'), 'abc'); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.every'); (function() { test('should return `true` for empty collections', 1, function() { var expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { try { return _.every(value, _.identity); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `true` if `predicate` returns truthy for all elements in the collection', 1, function() { strictEqual(_.every([true, 1, 'a'], _.identity), true); }); test('should return `false` as soon as `predicate` returns falsey', 1, function() { strictEqual(_.every([true, null, true], _.identity), false); }); test('should work with collections of `undefined` values (test in IE < 9)', 1, function() { strictEqual(_.every([undefined, undefined, undefined], _.identity), false); }); test('should work with a "_.property" style `predicate`', 2, function() { var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }]; strictEqual(_.every(objects, 'a'), false); strictEqual(_.every(objects, 'b'), true); }); test('should work with a "_where" style `predicate`', 2, function() { var objects = [{ 'a': 0, 'b': 0 }, { 'a': 0, 'b': 1 }]; strictEqual(_.every(objects, { 'a': 0 }), true); strictEqual(_.every(objects, { 'b': 1 }), false); }); test('should use `_.identity` when `predicate` is nullish', 2, function() { var values = [, null, undefined], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value, index) { var array = [0]; return index ? _.every(array, value) : _.every(array); }); deepEqual(actual, expected); expected = _.map(values, _.constant(true)); actual = _.map(values, function(value, index) { var array = [1]; return index ? _.every(array, value) : _.every(array); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([[1]], _.every); deepEqual(actual, [true]); }); test('should be aliased', 1, function() { strictEqual(_.all, _.every); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('strict mode checks'); _.each(['assign', 'bindAll', 'defaults'], function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` should ' + (isStrict ? '' : 'not ') + 'throw strict mode errors', 1, function() { if (freeze) { var object = { 'a': undefined, 'b': function() {} }, pass = !isStrict; freeze(object); try { if (methodName == 'bindAll') { func(object); } else { func(object, { 'a': 1 }); } } catch(e) { pass = !pass; } ok(pass); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.fill'); (function() { test('should use a default `start` of `0` and a default `end` of `array.length`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a'), ['a', 'a', 'a']); }); test('should use `undefined` for `value` if not provided', 2, function() { var array = [1, 2, 3], actual = _.fill(array); deepEqual(actual, [undefined, undefined, undefined]); ok(_.every(actual, function(value, index) { return index in actual; })); }); test('should work with a positive `start`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 1), [1, 'a', 'a']); }); test('should work with a `start` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(start) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', start), [1, 2, 3]); }); }); test('should treat falsey `start` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(['a', 'a', 'a'])); var actual = _.map(falsey, function(start) { var array = [1, 2, 3]; return _.fill(array, 'a', start); }); deepEqual(actual, expected); }); test('should work with a negative `start`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', -1), [1, 2, 'a']); }); test('should work with a negative `start` <= negative `array.length`', 3, function() { _.each([-3, -4, -Infinity], function(start) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', start), ['a', 'a', 'a']); }); }); test('should work with `start` >= `end`', 2, function() { _.each([2, 3], function(start) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', start, 2), [1, 2, 3]); }); }); test('should work with a positive `end`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 0, 1), ['a', 2, 3]); }); test('should work with a `end` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(end) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 0, end), ['a', 'a', 'a']); }); }); test('should treat falsey `end` values, except `undefined`, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value === undefined ? ['a', 'a', 'a'] : [1, 2, 3]; }); var actual = _.map(falsey, function(end) { var array = [1, 2, 3]; return _.fill(array, 'a', 0, end); }); deepEqual(actual, expected); }); test('should work with a negative `end`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 0, -1), ['a', 'a', 3]); }); test('should work with a negative `end` <= negative `array.length`', 3, function() { _.each([-3, -4, -Infinity], function(end) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 0, end), [1, 2, 3]); }); }); test('should coerce `start` and `end` to integers', 1, function() { var positions = [[0.1, 1.1], ['0', 1], [0, '1'], ['1'], [NaN, 1], [1, NaN]]; var actual = _.map(positions, function(pos) { var array = [1, 2, 3]; return _.fill.apply(_, [array, 'a'].concat(pos)); }); deepEqual(actual, [['a', 2, 3], ['a', 2, 3], ['a', 2, 3], [1, 'a', 'a'], ['a', 2, 3], [1, 2, 3]]); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2], [3, 4]], actual = _.map(array, _.fill); deepEqual(actual, [[0, 0], [1, 1]]); }); test('should return a wrapped value when chaining', 3, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array).fill('a'), actual = wrapped.value(); ok(wrapped instanceof _); deepEqual(actual, ['a', 'a', 'a']); strictEqual(actual, array); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.filter'); (function() { var array = [1, 2, 3]; test('should return elements `predicate` returns truthy for', 1, function() { var actual = _.filter(array, function(num) { return num % 2; }); deepEqual(actual, [1, 3]); }); test('should iterate correctly over an object with numeric keys (test in Mobile Safari 8)', 1, function() { // Trigger a Mobile Safari 8 JIT bug. // See https://github.com/lodash/lodash/issues/799. var counter = 0, object = { '1': 'foo', '8': 'bar', '50': 'baz' }; _.times(1000, function() { _.filter([], _.constant(true)); }); _.filter(object, function() { counter++; return true; }); strictEqual(counter, 3); }); test('should be aliased', 1, function() { strictEqual(_.select, _.filter); }); }()); /*--------------------------------------------------------------------------*/ _.each(['find', 'findLast', 'findIndex', 'findLastIndex', 'findKey', 'findLastKey'], function(methodName) { QUnit.module('lodash.' + methodName); var func = _[methodName]; (function() { var objects = [ { 'a': 0, 'b': 0 }, { 'a': 1, 'b': 1 }, { 'a': 2, 'b': 2 } ]; var expected = ({ 'find': [objects[1], undefined, objects[2], objects[1]], 'findLast': [objects[2], undefined, objects[2], objects[2]], 'findIndex': [1, -1, 2, 1], 'findLastIndex': [2, -1, 2, 2], 'findKey': ['1', undefined, '2', '1'], 'findLastKey': ['2', undefined, '2', '2'] })[methodName]; test('should return the correct value', 1, function() { strictEqual(func(objects, function(object) { return object.a; }), expected[0]); }); test('should work with a `thisArg`', 1, function() { strictEqual(func(objects, function(object, index) { return this[index].a; }, objects), expected[0]); }); test('should return `' + expected[1] + '` if value is not found', 1, function() { strictEqual(func(objects, function(object) { return object.a === 3; }), expected[1]); }); test('should work with a "_.matches" style `predicate`', 1, function() { strictEqual(func(objects, { 'b': 2 }), expected[2]); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { strictEqual(func(objects, 'b', 2), expected[2]); }); test('should work with a "_.property" style `predicate`', 1, function() { strictEqual(func(objects, 'b'), expected[3]); }); test('should return `' + expected[1] + '` for empty collections', 1, function() { var emptyValues = _.endsWith(methodName, 'Index') ? _.reject(empties, _.isPlainObject) : empties, expecting = _.map(emptyValues, _.constant(expected[1])); var actual = _.map(emptyValues, function(value) { try { return func(value, { 'a': 3 }); } catch(e) {} }); deepEqual(actual, expecting); }); }()); (function() { var expected = ({ 'find': 1, 'findLast': 2, 'findKey': 'a', 'findLastKey': 'b' })[methodName]; if (expected != null) { test('should work with an object for `collection`', 1, function() { var actual = func({ 'a': 1, 'b': 2, 'c': 3 }, function(num) { return num < 3; }); strictEqual(actual, expected); }); } }()); (function() { var expected = ({ 'find': 'a', 'findLast': 'b', 'findIndex': 0, 'findLastIndex': 1 })[methodName]; if (expected != null) { test('should work with a string for `collection`', 1, function() { var actual = func('abc', function(chr, index) { return index < 2; }); strictEqual(actual, expected); }); } if (methodName == 'find') { test('should be aliased', 1, function() { strictEqual(_.detect, func); }); } }()); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.findWhere'); (function() { var objects = [ { 'a': 1 }, { 'a': 1 }, { 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }, { 'a': 3 } ]; test('should filter by `source` properties', 6, function() { strictEqual(_.findWhere(objects, { 'a': 1 }), objects[0]); strictEqual(_.findWhere(objects, { 'a': 2 }), objects[3]); strictEqual(_.findWhere(objects, { 'a': 3 }), objects[4]); strictEqual(_.findWhere(objects, { 'b': 1 }), undefined); strictEqual(_.findWhere(objects, { 'b': 2 }), objects[2]); strictEqual(_.findWhere(objects, { 'a': 1, 'b': 2 }), objects[2]); }); test('should work with a function for `source`', 1, function() { function source() {} source.a = 2; strictEqual(_.findWhere(objects, source), objects[3]); }); test('should match all elements when provided an empty `source`', 1, function() { var expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { return _.findWhere(objects, value) === objects[0]; }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.first'); (function() { var array = [1, 2, 3]; test('should return the first element', 1, function() { strictEqual(_.first(array), 1); }); test('should return `undefined` when querying empty arrays', 1, function() { var array = []; array['-1'] = 1; strictEqual(_.first(array), undefined); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.first); deepEqual(actual, [1, 4, 7]); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_(array).first(), 1); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain().first() instanceof _); } else { skipTest(); } }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 3, 4]; var wrapped = _(array).filter(function(value) { return value % 2 == 0; }); strictEqual(wrapped.first(), 2); } else { skipTest(); } }); test('should be aliased', 1, function() { strictEqual(_.head, _.first); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.take'); (function() { var array = [1, 2, 3]; test('should take the first two elements', 1, function() { deepEqual(_.take(array, 2), [1, 2]); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? [1] : []; }); var actual = _.map(falsey, function(n) { return _.take(array, n); }); deepEqual(actual, expected); }); test('should return an empty array when `n` < `1`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.take(array, n), []); }); }); test('should return all elements when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.take(array, n), array); }); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.take); deepEqual(actual, [[1], [4], [7]]); }); test('should work in a lazy chain sequence', 6, function() { if (!isNpm) { var array = [1, 2, 3, 4, 5, 6, 7, 8, 9 , 10], values = [], predicate = function(value) { values.push(value); return value > 2; }, actual = _(array).take(2).take().value(); deepEqual(actual, [1]); actual = _(array).filter(predicate).take(2).take().value(); deepEqual(actual, [3]); deepEqual(values, array.slice(0, 3)); actual = _(array).take(6).takeRight(4).take(2).takeRight().value(); deepEqual(actual, [4]); values = []; actual = _(array).take(array.length - 1).filter(predicate).take(6).takeRight(4).take(2).takeRight().value(); deepEqual(actual, [6]); deepEqual(values, array.slice(0, -2)); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.takeRight'); (function() { var array = [1, 2, 3]; test('should take the last two elements', 1, function() { deepEqual(_.takeRight(array, 2), [2, 3]); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? [3] : []; }); var actual = _.map(falsey, function(n) { return _.takeRight(array, n); }); deepEqual(actual, expected); }); test('should return an empty array when `n` < `1`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.takeRight(array, n), []); }); }); test('should return all elements when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.takeRight(array, n), array); }); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.takeRight); deepEqual(actual, [[3], [6], [9]]); }); test('should work in a lazy chain sequence', 6, function() { if (!isNpm) { var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], values = [], predicate = function(value) { values.push(value); return value < 9; }, actual = _(array).takeRight(2).takeRight().value(); deepEqual(actual, [10]); actual = _(array).filter(predicate).takeRight(2).takeRight().value(); deepEqual(actual, [8]); deepEqual(values, array); actual = _(array).takeRight(6).take(4).takeRight(2).take().value(); deepEqual(actual, [7]); values = []; actual = _(array).filter(predicate).takeRight(6).take(4).takeRight(2).take().value(); deepEqual(actual, [5]); deepEqual(values, array); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.takeRightWhile'); (function() { var array = [1, 2, 3, 4]; var objects = [ { 'a': 0, 'b': 0 }, { 'a': 1, 'b': 1 }, { 'a': 2, 'b': 2 } ]; test('should take elements while `predicate` returns truthy', 1, function() { var actual = _.takeRightWhile(array, function(num) { return num > 2; }); deepEqual(actual, [3, 4]); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.takeRightWhile(array, function() { args = slice.call(arguments); }); deepEqual(args, [4, 3, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.takeRightWhile(array, function(num, index) { return this[index] > 2; }, array); deepEqual(actual, [3, 4]); }); test('should work with a "_.matches" style `predicate`', 1, function() { deepEqual(_.takeRightWhile(objects, { 'b': 2 }), objects.slice(2)); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { deepEqual(_.takeRightWhile(objects, 'b', 2), objects.slice(2)); }); test('should work with a "_.property" style `predicate`', 1, function() { deepEqual(_.takeRightWhile(objects, 'b'), objects.slice(1)); }); test('should work in a lazy chain sequence', 3, function() { if (!isNpm) { var wrapped = _(array).takeRightWhile(function(num) { return num > 2; }); deepEqual(wrapped.value(), [3, 4]); deepEqual(wrapped.reverse().value(), [4, 3]); strictEqual(wrapped.last(), 4); } else { skipTest(3); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [16, 3, [1, 4, 9 , 16]]; _(array).takeRightWhile(function(value, index, array) { args = slice.call(arguments) }).value(); deepEqual(args, [4, 3, array]); _(array).map(square).takeRightWhile(function(value, index, array) { args = slice.call(arguments) }).value(); deepEqual(args, expected); _(array).map(square).takeRightWhile(function(value, index) { args = slice.call(arguments) }).value(); deepEqual(args, expected); _(array).map(square).takeRightWhile(function(index) { args = slice.call(arguments); }).value(); deepEqual(args, [16]); _(array).map(square).takeRightWhile(function() { args = slice.call(arguments); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.takeWhile'); (function() { var array = [1, 2, 3, 4]; var objects = [ { 'a': 2, 'b': 2 }, { 'a': 1, 'b': 1 }, { 'a': 0, 'b': 0 } ]; test('should take elements while `predicate` returns truthy', 1, function() { var actual = _.takeWhile(array, function(num) { return num < 3; }); deepEqual(actual, [1, 2]); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.takeWhile(array, function() { args = slice.call(arguments); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.takeWhile(array, function(num, index) { return this[index] < 3; }, array); deepEqual(actual, [1, 2]); }); test('should work with a "_.matches" style `predicate`', 1, function() { deepEqual(_.takeWhile(objects, { 'b': 2 }), objects.slice(0, 1)); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { deepEqual(_.takeWhile(objects, 'b', 2), objects.slice(0, 1)); }); test('should work with a "_.property" style `predicate`', 1, function() { deepEqual(_.takeWhile(objects, 'b'), objects.slice(0, 2)); }); test('should work in a lazy chain sequence', 3, function() { if (!isNpm) { var wrapped = _(array).takeWhile(function(num) { return num < 3; }); deepEqual(wrapped.value(), [1, 2]); deepEqual(wrapped.reverse().value(), [2, 1]); strictEqual(wrapped.last(), 2); } else { skipTest(3); } }); test('should work in a lazy chain sequence with `take`', 1, function() { if (!isNpm) { var actual = _(array) .takeWhile(function(num) { return num < 4; }) .take(2) .takeWhile(function(num) { return num == 1; }) .value(); deepEqual(actual, [1]); } else { skipTest(); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [1, 0, [1, 4, 9, 16]]; _(array).takeWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, [1, 0, array]); _(array).map(square).takeWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).takeWhile(function(value, index) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).takeWhile(function(value) { args = slice.call(arguments); }).value(); deepEqual(args, [1]); _(array).map(square).takeWhile(function() { args = slice.call(arguments); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('flatten methods'); (function() { var args = arguments; test('should perform a shallow flatten', 1, function() { var array = [[['a']], [['b']]]; deepEqual(_.flatten(array), [['a'], ['b']]); }); test('should work with `isDeep`', 2, function() { var array = [[['a']], [['b']]], expected = ['a', 'b']; deepEqual(_.flatten(array, true), expected); deepEqual(_.flattenDeep(array), expected); }); test('should flatten `arguments` objects', 3, function() { var array = [args, [args]], expected = [1, 2, 3, args]; deepEqual(_.flatten(array), expected); expected = [1, 2, 3, 1, 2, 3]; deepEqual(_.flatten(array, true), expected); deepEqual(_.flattenDeep(array), expected); }); test('should work as an iteratee for `_.map`', 2, function() { var array = [[[['a']]], [[['b']]]]; deepEqual(_.map(array, _.flatten), [[['a']], [['b']]]); deepEqual(_.map(array, _.flattenDeep), [['a'], ['b']]); }); test('should treat sparse arrays as dense', 6, function() { var array = [[1, 2, 3], Array(3)], expected = [1, 2, 3]; expected.push(undefined, undefined, undefined); _.each([_.flatten(array), _.flatten(array, true), _.flattenDeep(array)], function(actual) { deepEqual(actual, expected); ok('4' in actual); }); }); test('should work with extremely large arrays', 3, function() { // Test in modern browsers only to avoid browser hangs. _.times(3, function(index) { if (freeze) { var expected = Array(5e5); try { if (index) { var actual = actual == 1 ? _.flatten([expected], true) : _.flattenDeep([expected]); } else { actual = _.flatten(expected); } deepEqual(actual, expected); } catch(e) { ok(false, e.message); } } else { skipTest(); } }); }); test('should work with empty arrays', 3, function() { var array = [[], [[]], [[], [[[]]]]], expected = [[], [], [[[]]]]; deepEqual(_.flatten(array), expected); expected = []; deepEqual(_.flatten(array, true), expected); deepEqual(_.flattenDeep(array), expected); }); test('should support flattening of nested arrays', 3, function() { var array = [1, [2], [3, [4]]], expected = [1, 2, 3, [4]]; deepEqual(_.flatten(array), expected); expected = [1, 2, 3, 4]; deepEqual(_.flatten(array, true), expected); deepEqual(_.flattenDeep(array), expected); }); test('should return an empty array for non array-like objects', 3, function() { var expected = []; deepEqual(_.flatten({ 'a': 1 }), expected); deepEqual(_.flatten({ 'a': 1 }, true), expected); deepEqual(_.flattenDeep({ 'a': 1 }), expected); }); test('should return a wrapped value when chaining', 6, function() { if (!isNpm) { var wrapped = _([1, [2], [3, [4]]]), actual = wrapped.flatten(), expected = [1, 2, 3, [4]]; ok(actual instanceof _); deepEqual(actual.value(), expected); expected = [1, 2, 3, 4]; actual = wrapped.flatten(true); ok(actual instanceof _); deepEqual(actual.value(), expected); actual = wrapped.flattenDeep(); ok(actual instanceof _); deepEqual(actual.value(), expected); } else { skipTest(6); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.forEach'); (function() { test('should be aliased', 1, function() { strictEqual(_.each, _.forEach); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.forEachRight'); (function() { test('should be aliased', 1, function() { strictEqual(_.eachRight, _.forEachRight); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('forIn methods'); _.each(['forIn', 'forInRight'], function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` iterates over inherited properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var keys = []; func(new Foo, function(value, key) { keys.push(key); }); deepEqual(keys.sort(), ['a', 'b']); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('forOwn methods'); _.each(['forOwn', 'forOwnRight'], function(methodName) { var func = _[methodName]; test('iterates over the `length` property', 1, function() { var object = { '0': 'zero', '1': 'one', 'length': 2 }, props = []; func(object, function(value, prop) { props.push(prop); }); deepEqual(props.sort(), ['0', '1', 'length']); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('iteration methods'); (function() { var methods = [ '_baseEach', 'countBy', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'groupBy', 'indexBy', 'map', 'mapValues', 'max', 'min', 'omit', 'partition', 'pick', 'reject', 'some' ]; var arrayMethods = [ 'findIndex', 'findLastIndex' ]; var collectionMethods = [ '_baseEach', 'countBy', 'every', 'filter', 'find', 'findLast', 'forEach', 'forEachRight', 'groupBy', 'indexBy', 'map', 'max', 'min', 'partition', 'reduce', 'reduceRight', 'reject', 'some' ]; var forInMethods = [ 'forIn', 'forInRight', 'omit', 'pick' ]; var iterationMethods = [ '_baseEach', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight' ] var objectMethods = [ 'findKey', 'findLastKey', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'mapValues', 'omit', 'pick' ]; var rightMethods = [ 'findLast', 'findLastIndex', 'findLastKey', 'forEachRight', 'forInRight', 'forOwnRight' ]; var unwrappedMethods = [ 'every', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'max', 'min', 'some' ]; _.each(methods, function(methodName) { var array = [1, 2, 3], func = _[methodName], isFind = /^find/.test(methodName), isSome = methodName == 'some'; test('`_.' + methodName + '` should provide the correct `iteratee` arguments', 1, function() { if (func) { var args, expected = [1, 0, array]; func(array, function() { args || (args = slice.call(arguments)); }); if (_.includes(rightMethods, methodName)) { expected[0] = 3; expected[1] = 2; } if (_.includes(objectMethods, methodName)) { expected[1] += ''; } deepEqual(args, expected); } else { skipTest(); } }); test('`_.' + methodName + '` should support the `thisArg` argument', 2, function() { if (methodName != '_baseEach') { var actual, callback = function(num, index) { actual = this[index]; }; func([1], callback, [2]); strictEqual(actual, 2); func({ 'a': 1 }, callback, { 'a': 2 }); strictEqual(actual, 2); } else { skipTest(2); } }); test('`_.' + methodName + '` should treat sparse arrays as dense', 1, function() { if (func) { var array = [1]; array[2] = 3; var expected = [[1, 0, array], [undefined, 1, array], [3, 2, array]]; if (_.includes(objectMethods, methodName)) { expected = _.map(expected, function(args) { args[1] += ''; return args; }); } if (_.includes(rightMethods, methodName)) { expected.reverse(); } var argsList = []; func(array, function() { argsList.push(slice.call(arguments)); return !(isFind || isSome); }); deepEqual(argsList, expected); } else { skipTest(); } }); }); _.each(_.difference(methods, objectMethods), function(methodName) { var array = [1, 2, 3], func = _[methodName], isEvery = methodName == 'every'; array.a = 1; test('`_.' + methodName + '` should not iterate custom properties on arrays', 1, function() { if (func) { var keys = []; func(array, function(value, key) { keys.push(key); return isEvery; }); ok(!_.includes(keys, 'a')); } else { skipTest(); } }); }); _.each(_.difference(methods, unwrappedMethods), function(methodName) { var array = [1, 2, 3], func = _[methodName], isBaseEach = methodName == '_baseEach'; test('`_.' + methodName + '` should return a wrapped value when implicitly chaining', 1, function() { if (!(isBaseEach || isNpm)) { var wrapped = _(array)[methodName](_.noop); ok(wrapped instanceof _); } else { skipTest(); } }); }); _.each(unwrappedMethods, function(methodName) { var array = [1, 2, 3], func = _[methodName]; test('`_.' + methodName + '` should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { var wrapped = _(array)[methodName](_.noop); ok(!(wrapped instanceof _)); } else { skipTest(); } }); test('`_.' + methodName + '` should return a wrapped value when implicitly chaining', 1, function() { if (!isNpm) { var wrapped = _(array).chain()[methodName](_.noop); ok(wrapped instanceof _); } else { skipTest(); } }); }); _.each(_.difference(methods, arrayMethods, forInMethods), function(methodName) { var array = [1, 2, 3], func = _[methodName]; test('`_.' + methodName + '` iterates over own properties of objects', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; if (func) { var keys = []; func(new Foo, function(value, key) { keys.push(key); }); deepEqual(keys, ['a']); } else { skipTest(); } }); }); _.each(iterationMethods, function(methodName) { var array = [1, 2, 3], func = _[methodName], isBaseEach = methodName == '_baseEach', isObject = _.includes(objectMethods, methodName), isRight = _.includes(rightMethods, methodName); test('`_.' + methodName + '` should return the collection', 1, function() { if (func) { strictEqual(func(array, Boolean), array); } else { skipTest(); } }); test('`_.' + methodName + '` should not return the existing wrapped value when chaining', 1, function() { if (!(isBaseEach || isNpm)) { var wrapped = _(array); notStrictEqual(wrapped[methodName](_.noop), wrapped); } else { skipTest(); } }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('`_.' + methodName + '` should work with a string ' + key + ' for `collection` (test in IE < 9)', 6, function() { if (func) { var args, values = [], expectedChars = ['a', 'b', 'c']; var expectedArgs = isObject ? (isRight ? ['c', '2', collection] : ['a', '0', collection]) : (isRight ? ['c', 2, collection] : ['a', 0, collection]); var actual = func(collection, function(value) { args || (args = slice.call(arguments)); values.push(value); }); var stringObject = args[2]; ok(_.isString(stringObject)); ok(_.isObject(stringObject)); deepEqual([stringObject[0], stringObject[1], stringObject[2]], expectedChars); deepEqual(args, expectedArgs); deepEqual(values, isRight ? ['c', 'b', 'a'] : expectedChars); strictEqual(actual, collection); } else { skipTest(6); } }); }); }); _.each(collectionMethods, function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` should use `isLength` to determine whether a value is array-like', 2, function() { if (func) { var isIteratedAsObject = function(length) { var result = false; func({ 'length': length }, function() { result = true; }, 0); return result; }; var values = [-1, '1', 1.1, Object(1), MAX_SAFE_INTEGER + 1], expected = _.map(values, _.constant(true)), actual = _.map(values, isIteratedAsObject); deepEqual(actual, expected); ok(!isIteratedAsObject(0)); } else { skipTest(2); } }); }); _.each(methods, function(methodName) { var array = [1, 2, 3], func = _[methodName], isFind = /^find/.test(methodName), isSome = methodName == 'some'; test('`_.' + methodName + '` should ignore changes to `array.length`', 1, function() { if (func) { var count = 0, array = [1]; func(array, function() { if (++count == 1) { array.push(2); } return !(isFind || isSome); }, array); strictEqual(count, 1); } else { skipTest(); } }); }); _.each(_.difference(_.union(methods, collectionMethods), arrayMethods), function(methodName) { var func = _[methodName], isFind = /^find/.test(methodName), isSome = methodName == 'some'; test('`_.' + methodName + '` should ignore added `object` properties', 1, function() { if (func) { var count = 0, object = { 'a': 1 }; func(object, function() { if (++count == 1) { object.b = 2; } return !(isFind || isSome); }, object); strictEqual(count, 1); } else { skipTest(); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('collection iteration bugs'); _.each(['forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight'], function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 1, function() { var props = []; func(shadowObject, function(value, prop) { props.push(prop); }); deepEqual(props.sort(), shadowProps); }); test('`_.' + methodName + '` skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', 2, function() { function Foo() {} Foo.prototype.a = 1; var props = []; function callback(value, prop) { props.push(prop); } func(Foo, callback); deepEqual(props, []); props.length = 0; Foo.prototype = { 'a': 1 }; func(Foo, callback); deepEqual(props, []); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('object assignments'); _.each(['assign', 'defaults', 'merge'], function(methodName) { var func = _[methodName], isDefaults = methodName == 'defaults'; test('`_.' + methodName + '` should pass thru falsey `object` values', 1, function() { var actual = _.map(falsey, function(value, index) { return index ? func(value) : func(); }); deepEqual(actual, falsey); }); test('`_.' + methodName + '` should assign own source properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; deepEqual(func({}, new Foo), { 'a': 1 }); }); test('`_.' + methodName + '` should assign problem JScript properties (test in IE < 9)', 1, function() { var object = { 'constructor': '0', 'hasOwnProperty': '1', 'isPrototypeOf': '2', 'propertyIsEnumerable': undefined, 'toLocaleString': undefined, 'toString': undefined, 'valueOf': undefined }; var source = { 'propertyIsEnumerable': '3', 'toLocaleString': '4', 'toString': '5', 'valueOf': '6' }; deepEqual(func(object, source), shadowObject); }); test('`_.' + methodName + '` skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', 2, function() { function Foo() {} Foo.a = 1; Foo.prototype.b = 2; var expected = { 'a': 1 }; deepEqual(func({}, Foo), expected); Foo.prototype = { 'b': 2 }; deepEqual(func({}, Foo), expected); }); test('`_.' + methodName + '` should not error on nullish sources (test in IE < 9)', 1, function() { try { deepEqual(func({ 'a': 1 }, undefined, { 'b': 2 }, null), { 'a': 1, 'b': 2 }); } catch(e) { ok(false, e.message); } }); test('`_.' + methodName + '` should not error when `object` is nullish and source objects are provided', 1, function() { var expected = _.times(2, _.constant(true)); var actual = _.map([null, undefined], function(value) { try { return _.isEqual(func(value, { 'a': 1 }), value); } catch(e) { return false; } }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should work as an iteratee for `_.reduce`', 1, function() { var array = [{ 'a': 1 }, { 'b': 2 }, { 'c': 3 }], expected = { 'a': 1, 'b': 2, 'c': 3 }; expected.a = isDefaults ? 0 : 1; deepEqual(_.reduce(array, func, { 'a': 0 }), expected); }); test('`_.' + methodName + '` should not return the existing wrapped value when chaining', 1, function() { if (!isNpm) { var wrapped = _({ 'a': 1 }); notStrictEqual(wrapped[methodName]({ 'b': 2 }), wrapped); } else { skipTest(); } }); }); _.each(['assign', 'merge'], function(methodName) { var func = _[methodName], isMerge = methodName == 'merge'; test('`_.' + methodName + '` should provide the correct `customizer` arguments', 3, function() { var args, object = { 'a': 1 }, source = { 'a': 2 }; func(object, source, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 2, 'a', object, source], 'primitive property values'); args = null; object = { 'a': 1 }; source = { 'b': 2 }; func(object, source, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [undefined, 2, 'b', object, source], 'missing destination property'); var argsList = [], objectValue = [1, 2], sourceValue = { 'b': 2 }; object = { 'a': objectValue }; source = { 'a': sourceValue }; func(object, source, function() { argsList.push(slice.call(arguments)); }); var expected = [[objectValue, sourceValue, 'a', object, source]]; if (isMerge) { expected.push([undefined, 2, 'b', sourceValue, sourceValue]); } deepEqual(argsList, expected, 'non-primitive property values'); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func({}, { 'a': 0 }, function(a, b) { return this[b]; }, [2]); deepEqual(actual, { 'a': 2 }); }); test('`_.' + methodName + '` should not treat `object` as `source`', 1, function() { function Foo() {} Foo.prototype.a = 1; var actual = func(new Foo, { 'b': 2 }); ok(!_.has(actual, 'a')); }); test('`_.' + methodName + '` should not treat the second argument as a `customizer` callback', 2, function() { function callback() {} callback.b = 2; var actual = func({ 'a': 1 }, callback); deepEqual(actual, { 'a': 1, 'b': 2 }); actual = func({ 'a': 1 }, callback, { 'c': 3 }); deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 }); }); test('`_.' + methodName + '` should not assign the `customizer` result if it is the same as the destination value', 4, function() { _.each(['a', ['a'], { 'a': 1 }, NaN], function(value) { if (defineProperty) { var object = {}, pass = true; defineProperty(object, 'a', { 'get': _.constant(value), 'set': function() { pass = false; } }); func(object, { 'a': value }, _.identity); ok(pass); } else { skipTest(); } }); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('exit early'); _.each(['_baseEach', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'transform'], function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` can exit early when iterating arrays', 1, function() { if (func) { var array = [1, 2, 3], values = []; func(array, function(value, other) { values.push(_.isArray(value) ? other : value); return false; }); deepEqual(values, [_.endsWith(methodName, 'Right') ? 3 : 1]); } else { skipTest(); } }); test('`_.' + methodName + '` can exit early when iterating objects', 1, function() { if (func) { var object = { 'a': 1, 'b': 2, 'c': 3 }, values = []; func(object, function(value, other) { values.push(_.isArray(value) ? other : value); return false; }); strictEqual(values.length, 1); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('`__proto__` property bugs'); (function() { test('internal data objects should work with the `__proto__` key', 4, function() { var stringLiteral = '__proto__', stringObject = Object(stringLiteral), expected = [stringLiteral, stringObject]; var largeArray = _.times(LARGE_ARRAY_SIZE, function(count) { return count % 2 ? stringObject : stringLiteral; }); deepEqual(_.difference(largeArray, largeArray), []); deepEqual(_.intersection(largeArray, largeArray), expected); deepEqual(_.uniq(largeArray), expected); deepEqual(_.without.apply(_, [largeArray].concat(largeArray)), []); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.functions'); (function() { test('should return the function names of an object', 1, function() { var object = { 'a': 'a', 'b': _.identity, 'c': /x/, 'd': _.each }; deepEqual(_.functions(object).sort(), ['b', 'd']); }); test('should include inherited functions', 1, function() { function Foo() { this.a = _.identity; this.b = 'b'; } Foo.prototype.c = _.noop; deepEqual(_.functions(new Foo).sort(), ['a', 'c']); }); test('should be aliased', 1, function() { strictEqual(_.methods, _.functions); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.groupBy'); (function() { var array = [4.2, 6.1, 6.4]; test('should use `_.identity` when `iteratee` is nullish', 1, function() { var array = [4, 6, 6], values = [, null, undefined], expected = _.map(values, _.constant({ '4': [4], '6': [6, 6] })); var actual = _.map(values, function(value, index) { return index ? _.groupBy(array, value) : _.groupBy(array); }); deepEqual(actual, expected); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.groupBy(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [4.2, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.groupBy(array, function(num) { return this.floor(num); }, Math); deepEqual(actual, { '4': [4.2], '6': [6.1, 6.4] }); }); test('should only add values to own, not inherited, properties', 2, function() { var actual = _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); deepEqual(actual.constructor, [4.2]); deepEqual(actual.hasOwnProperty, [6.1, 6.4]); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.groupBy(['one', 'two', 'three'], 'length'); deepEqual(actual, { '3': ['one', 'two'], '5': ['three'] }); }); test('should work with a number for `iteratee`', 2, function() { var array = [ [1, 'a'], [2, 'a'], [2, 'b'] ]; deepEqual(_.groupBy(array, 0), { '1': [[1, 'a']], '2': [[2, 'a'], [2, 'b']] }); deepEqual(_.groupBy(array, 1), { 'a': [[1, 'a'], [2, 'a']], 'b': [[2, 'b']] }); }); test('should work with an object for `collection`', 1, function() { var actual = _.groupBy({ 'a': 4.2, 'b': 6.1, 'c': 6.4 }, function(num) { return Math.floor(num); }); deepEqual(actual, { '4': [4.2], '6': [6.1, 6.4] }); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 1, 3], iteratee = function(value) { value.push(value[0]); return value; }, predicate = function(value) { return value[0] > 1; }, actual = _(array).groupBy(_.identity).map(iteratee).filter(predicate).take().value(); deepEqual(actual, [[2, 2]]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.has'); (function() { test('should check for own properties', 2, function() { var object = { 'a': 1 }; strictEqual(_.has(object, 'a'), true); strictEqual(_.has(object, 'b'), false); }); test('should not use the `hasOwnProperty` method of the object', 1, function() { var object = { 'hasOwnProperty': null, 'a': 1 }; strictEqual(_.has(object, 'a'), true); }); test('should not check for inherited properties', 1, function() { function Foo() {} Foo.prototype.a = 1; strictEqual(_.has(new Foo, 'a'), false); }); test('should work with functions', 1, function() { function Foo() {} strictEqual(_.has(Foo, 'prototype'), true); }); test('should return `false` for primitives', 1, function() { var values = falsey.concat(true, 1, 'a'), expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.has(value, 'valueOf'); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.identity'); (function() { test('should return the first argument provided', 1, function() { var object = { 'name': 'fred' }; strictEqual(_.identity(object), object); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.includes'); (function() { _.each({ 'an `arguments` object': arguments, 'an array': [1, 2, 3, 4], 'an object': { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, 'a string': '1234' }, function(collection, key) { var values = _.toArray(collection); test('should work with ' + key + ' and return `true` for matched values', 1, function() { strictEqual(_.includes(collection, 3), true); }); test('should work with ' + key + ' and return `false` for unmatched values', 1, function() { strictEqual(_.includes(collection, 5), false); }); test('should work with ' + key + ' and a positive `fromIndex`', 2, function() { strictEqual(_.includes(collection, values[2], 2), true); strictEqual(_.includes(collection, values[1], 2), false); }); test('should work with ' + key + ' and a `fromIndex` >= `collection.length`', 12, function() { _.each([4, 6, Math.pow(2, 32), Infinity], function(fromIndex) { strictEqual(_.includes(collection, 1, fromIndex), false); strictEqual(_.includes(collection, undefined, fromIndex), false); strictEqual(_.includes(collection, '', fromIndex), false); }); }); test('should work with ' + key + ' and treat falsey `fromIndex` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(true)); var actual = _.map(falsey, function(fromIndex) { return _.includes(collection, values[0], fromIndex); }); deepEqual(actual, expected); }); test('should work with ' + key + ' and treat non-number `fromIndex` values as `0`', 1, function() { strictEqual(_.includes(collection, values[0], '1'), true); }); test('should work with ' + key + ' and a negative `fromIndex`', 2, function() { strictEqual(_.includes(collection, values[2], -2), true); strictEqual(_.includes(collection, values[1], -2), false); }); test('should work with ' + key + ' and a negative `fromIndex` <= negative `collection.length`', 3, function() { _.each([-4, -6, -Infinity], function(fromIndex) { strictEqual(_.includes(collection, values[0], fromIndex), true); }); }); test('should work with ' + key + ' and return an unwrapped value implicitly when chaining', 1, function() { if (!isNpm) { strictEqual(_(collection).includes(3), true); } else { skipTest(); } }); test('should work with ' + key + ' and return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(collection).chain().includes(3) instanceof _); } else { skipTest(); } }); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 2, function() { strictEqual(_.includes(collection, 'bc'), true); strictEqual(_.includes(collection, 'd'), false); }); }); test('should return `false` for empty collections', 1, function() { var expected = _.map(empties, _.constant(false)); var actual = _.map(empties, function(value) { try { return _.includes(value); } catch(e) {} }); deepEqual(actual, expected); }); test('should not be possible to perform a binary search', 1, function() { strictEqual(_.includes([3, 2, 1], 3, true), true); }); test('should match `NaN`', 1, function() { strictEqual(_.includes([1, NaN, 3], NaN), true); }); test('should match `-0` as `0`', 1, function() { strictEqual(_.includes([-0], 0), true); }); test('should be aliased', 2, function() { strictEqual(_.contains, _.includes); strictEqual(_.include, _.includes); }); }(1, 2, 3, 4)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.indexBy'); (function() { test('should use `_.identity` when `iteratee` is nullish', 1, function() { var array = [4, 6, 6], values = [, null, undefined], expected = _.map(values, _.constant({ '4': 4, '6': 6 })); var actual = _.map(values, function(value, index) { return index ? _.indexBy(array, value) : _.indexBy(array); }); deepEqual(actual, expected); }); test('should support the `thisArg` argument', 1, function() { var actual = _.indexBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); deepEqual(actual, { '4': 4.2, '6': 6.4 }); }); test('should only add values to own, not inherited, properties', 2, function() { var actual = _.indexBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); deepEqual(actual.constructor, 4.2); deepEqual(actual.hasOwnProperty, 6.4); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.indexBy(['one', 'two', 'three'], 'length'); deepEqual(actual, { '3': 'two', '5': 'three' }); }); test('should work with a number for `iteratee`', 2, function() { var array = [ [1, 'a'], [2, 'a'], [2, 'b'] ]; deepEqual(_.indexBy(array, 0), { '1': [1, 'a'], '2': [2, 'b'] }); deepEqual(_.indexBy(array, 1), { 'a': [2, 'a'], 'b': [2, 'b'] }); }); test('should work with an object for `collection`', 1, function() { var actual = _.indexBy({ 'a': 4.2, 'b': 6.1, 'c': 6.4 }, function(num) { return Math.floor(num); }); deepEqual(actual, { '4': 4.2, '6': 6.4 }); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 1, 3], predicate = function(value) { return value > 2; }, actual = _(array).indexBy(_.identity).map(square).filter(predicate).take().value(); deepEqual(actual, [4]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.indexOf'); (function() { var array = [1, 2, 3, 1, 2, 3]; test('should return the index of the first matched value', 1, function() { strictEqual(_.indexOf(array, 3), 2); }); test('should work with a positive `fromIndex`', 1, function() { strictEqual(_.indexOf(array, 1, 2), 3); }); test('should work with `fromIndex` >= `array.length`', 1, function() { var values = [6, 8, Math.pow(2, 32), Infinity], expected = _.map(values, _.constant([-1, -1, -1])); var actual = _.map(values, function(fromIndex) { return [ _.indexOf(array, undefined, fromIndex), _.indexOf(array, 1, fromIndex), _.indexOf(array, '', fromIndex) ]; }); deepEqual(actual, expected); }); test('should treat falsey `fromIndex` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(0)); var actual = _.map(falsey, function(fromIndex) { return _.indexOf(array, 1, fromIndex); }); deepEqual(actual, expected); }); test('should perform a binary search when `fromIndex` is a non-number truthy value', 1, function() { var sorted = [4, 4, 5, 5, 6, 6], values = [true, '1', {}], expected = _.map(values, _.constant(2)); var actual = _.map(values, function(value) { return _.indexOf(sorted, 5, value); }); deepEqual(actual, expected); }); test('should work with a negative `fromIndex`', 1, function() { strictEqual(_.indexOf(array, 2, -3), 4); }); test('should work with a negative `fromIndex` <= `-array.length`', 1, function() { var values = [-6, -8, -Infinity], expected = _.map(values, _.constant(0)); var actual = _.map(values, function(fromIndex) { return _.indexOf(array, 1, fromIndex); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('custom `_.indexOf` methods'); (function() { function Foo() {} function custom(array, value, fromIndex) { var index = (fromIndex || 0) - 1, length = array.length; while (++index < length) { var other = array[index]; if (other === value || (value instanceof Foo && other instanceof Foo)) { return index; } } return -1; } var array = [1, new Foo, 3, new Foo], indexOf = _.indexOf; var largeArray = _.times(LARGE_ARRAY_SIZE, function() { return new Foo; }); test('`_.includes` should work with a custom `_.indexOf` method', 2, function() { if (!isModularize) { _.indexOf = custom; ok(_.includes(array, new Foo)); ok(_.includes({ 'a': 1, 'b': new Foo, 'c': 3 }, new Foo)); _.indexOf = indexOf; } else { skipTest(2); } }); test('`_.difference` should work with a custom `_.indexOf` method', 2, function() { if (!isModularize) { _.indexOf = custom; deepEqual(_.difference(array, [new Foo]), [1, 3]); deepEqual(_.difference(array, largeArray), [1, 3]); _.indexOf = indexOf; } else { skipTest(2); } }); test('`_.intersection` should work with a custom `_.indexOf` method', 2, function() { if (!isModularize) { _.indexOf = custom; deepEqual(_.intersection(array, [new Foo]), [array[1]]); deepEqual(_.intersection(largeArray, [new Foo]), [array[1]]); _.indexOf = indexOf; } else { skipTest(2); } }); test('`_.uniq` should work with a custom `_.indexOf` method', 6, function() { _.each([false, true, _.identity], function(param) { if (!isModularize) { _.indexOf = custom; deepEqual(_.uniq(array, param), array.slice(0, 3)); deepEqual(_.uniq(largeArray, param), [largeArray[0]]); _.indexOf = indexOf; } else { skipTest(2); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.initial'); (function() { var array = [1, 2, 3]; test('should accept a falsey `array` argument', 1, function() { var expected = _.map(falsey, _.constant([])); var actual = _.map(falsey, function(value, index) { try { return index ? _.initial(value) : _.initial(); } catch(e) {} }); deepEqual(actual, expected); }); test('should exclude last element', 1, function() { deepEqual(_.initial(array), [1, 2]); }); test('should return an empty when querying empty arrays', 1, function() { deepEqual(_.initial([]), []); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.initial); deepEqual(actual, [[1, 2], [4, 5], [7, 8]]); }); test('should work in a lazy chain sequence', 4, function() { if (!isNpm) { var array = [1, 2, 3], values = []; var actual = _(array).initial().filter(function(value) { values.push(value); return false; }) .value(); deepEqual(actual, []); deepEqual(values, [1, 2]); values = []; actual = _(array).filter(function(value) { values.push(value); return value < 3; }) .initial() .value(); deepEqual(actual, [1]); deepEqual(values, array); } else { skipTest(4); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.inRange'); (function() { test('should work with an `end` argument', 3, function() { strictEqual(_.inRange(3, 5), true); strictEqual(_.inRange(5, 5), false); strictEqual(_.inRange(6, 5), false); }); test('should work with `start` and `end` arguments', 4, function() { strictEqual(_.inRange(1, 1, 5), true); strictEqual(_.inRange(3, 1, 5), true); strictEqual(_.inRange(0, 1, 5), false); strictEqual(_.inRange(5, 1, 5), false); }); test('should treat falsey `start` arguments as `0`', 13, function() { _.each(falsey, function(value, index) { if (index) { strictEqual(_.inRange(0, value), false); strictEqual(_.inRange(0, value, 1), true); } else { strictEqual(_.inRange(0), false); } }); }); test('should work with a floating point `n` value', 4, function() { strictEqual(_.inRange(0.5, 5), true); strictEqual(_.inRange(1.2, 1, 5), true); strictEqual(_.inRange(5.2, 5), false); strictEqual(_.inRange(0.5, 1, 5), false); }); test('should coerce arguments to finite numbers', 1, function() { var actual = [_.inRange(0, '0', 1), _.inRange(0, '1'), _.inRange(0, 0, '1'), _.inRange(0, NaN, 1), _.inRange(-1, -1, NaN)], expected = _.map(actual, _.constant(true)); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.intersection'); (function() { var args = arguments; test('should return the intersection of the given arrays', 1, function() { var actual = _.intersection([1, 3, 2], [5, 2, 1, 4], [2, 1]); deepEqual(actual, [1, 2]); }); test('should return an array of unique values', 2, function() { var array = [1, 1, 3, 2, 2]; deepEqual(_.intersection(array, [5, 2, 2, 1, 4], [2, 1, 1]), [1, 2]); deepEqual(_.intersection(array), [1, 3, 2]); }); test('should match `NaN`', 1, function() { deepEqual(_.intersection([1, NaN, 3], [NaN, 5, NaN]), [NaN]); }); test('should work with large arrays of objects', 1, function() { var object = {}, largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object)); deepEqual(_.intersection([object], largeArray), [object]); }); test('should work with large arrays of objects', 2, function() { var object = {}, largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object)); deepEqual(_.intersection([object], largeArray), [object]); deepEqual(_.intersection(_.range(LARGE_ARRAY_SIZE), null, [1]), [1]); }); test('should work with large arrays of `NaN`', 1, function() { var largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(NaN)); deepEqual(_.intersection([1, NaN, 3], largeArray), [NaN]); }); test('should ignore values that are not arrays or `arguments` objects', 3, function() { var array = [0, 1, null, 3]; deepEqual(_.intersection(array, 3, null, { '0': 1 }), array); deepEqual(_.intersection(null, array, null, [2, 1]), [1]); deepEqual(_.intersection(array, null, args, null), [1, 3]); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var wrapped = _([1, 3, 2]).intersection([5, 2, 1, 4]); ok(wrapped instanceof _); deepEqual(wrapped.value(), [1, 2]); } else { skipTest(2); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.invert'); (function() { test('should invert an object', 2, function() { var object = { 'a': 1, 'b': 2 }, actual = _.invert(object); deepEqual(actual, { '1': 'a', '2': 'b' }); deepEqual(_.invert(actual), { 'a': '1', 'b': '2' }); }); test('should work with an object that has a `length` property', 1, function() { var object = { '0': 'a', '1': 'b', 'length': 2 }; deepEqual(_.invert(object), { 'a': '0', 'b': '1', '2': 'length' }); }); test('should accept a `multiValue` flag', 1, function() { var object = { 'a': 1, 'b': 2, 'c': 1 }; deepEqual(_.invert(object, true), { '1': ['a', 'c'], '2': ['b'] }); }); test('should only add multiple values to own, not inherited, properties', 2, function() { var object = { 'a': 'hasOwnProperty', 'b': 'constructor' }; deepEqual(_.invert(object), { 'hasOwnProperty': 'a', 'constructor': 'b' }); ok(_.isEqual(_.invert(object, true), { 'hasOwnProperty': ['a'], 'constructor': ['b'] })); }); test('should work as an iteratee for `_.map`', 2, function() { var regular = { 'a': 1, 'b': 2, 'c': 1 }, inverted = { '1': 'c', '2': 'b' }; var array = [regular, regular, regular], object = { 'a': regular, 'b': regular, 'c': regular }, expected = _.map(array, _.constant(inverted)); _.each([array, object], function(collection) { var actual = _.map(collection, _.invert); deepEqual(actual, expected); }); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var object = { 'a': 1, 'b': 2 }, wrapped = _(object).invert(); ok(wrapped instanceof _); deepEqual(wrapped.value(), { '1': 'a', '2': 'b' }); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.invoke'); (function() { test('should invoke a methods on each element of a collection', 1, function() { var array = ['a', 'b', 'c']; deepEqual(_.invoke(array, 'toUpperCase'), ['A', 'B', 'C']); }); test('should support invoking with arguments', 1, function() { var array = [function() { return slice.call(arguments); }], actual = _.invoke(array, 'call', null, 'a', 'b', 'c'); deepEqual(actual, [['a', 'b', 'c']]); }); test('should work with a function `methodName` argument', 1, function() { var array = ['a', 'b', 'c']; var actual = _.invoke(array, function(left, right) { return left + this.toUpperCase() + right; }, '(', ')'); deepEqual(actual, ['(A)', '(B)', '(C)']); }); test('should work with an object for `collection`', 1, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }; deepEqual(_.invoke(object, 'toFixed', 1), ['1.0', '2.0', '3.0']); }); test('should treat number values for `collection` as empty', 1, function() { deepEqual(_.invoke(1), []); }); test('should not error on nullish elements', 1, function() { var array = ['a', null, undefined, 'd']; try { var actual = _.invoke(array, 'toUpperCase'); } catch(e) {} deepEqual(_.invoke(array, 'toUpperCase'), ['A', undefined, undefined, 'D']); }); test('should not error on elements with missing properties', 1, function() { var objects = _.map(falsey.concat(_.constant(1)), function(value) { return { 'a': value }; }); var expected = _.times(objects.length - 1, _.constant(undefined)).concat(1); try { var actual = _.invoke(objects, 'a'); } catch(e) {} deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isArguments'); (function() { var args = arguments; test('should return `true` for `arguments` objects', 1, function() { strictEqual(_.isArguments(args), true); }); test('should return `false` for non `arguments` objects', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isArguments(value) : _.isArguments(); }); deepEqual(actual, expected); strictEqual(_.isArguments([1, 2, 3]), false); strictEqual(_.isArguments(true), false); strictEqual(_.isArguments(new Date), false); strictEqual(_.isArguments(new Error), false); strictEqual(_.isArguments(_), false); strictEqual(_.isArguments(slice), false); strictEqual(_.isArguments({ '0': 1, 'callee': _.noop, 'length': 1 }), false); strictEqual(_.isArguments(1), false); strictEqual(_.isArguments(NaN), false); strictEqual(_.isArguments(/x/), false); strictEqual(_.isArguments('a'), false); }); test('should work with an `arguments` object from another realm', 1, function() { if (_._object) { strictEqual(_.isArguments(_._arguments), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isArray'); (function() { var args = arguments; test('should return `true` for arrays', 1, function() { strictEqual(_.isArray([1, 2, 3]), true); }); test('should return `false` for non-arrays', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isArray(value) : _.isArray(); }); deepEqual(actual, expected); strictEqual(_.isArray(args), false); strictEqual(_.isArray(true), false); strictEqual(_.isArray(new Date), false); strictEqual(_.isArray(new Error), false); strictEqual(_.isArray(_), false); strictEqual(_.isArray(slice), false); strictEqual(_.isArray({ '0': 1, 'length': 1 }), false); strictEqual(_.isArray(1), false); strictEqual(_.isArray(NaN), false); strictEqual(_.isArray(/x/), false); strictEqual(_.isArray('a'), false); }); test('should work with an array from another realm', 1, function() { if (_._object) { strictEqual(_.isArray(_._array), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isBoolean'); (function() { var args = arguments; test('should return `true` for booleans', 4, function() { strictEqual(_.isBoolean(true), true); strictEqual(_.isBoolean(false), true); strictEqual(_.isBoolean(Object(true)), true); strictEqual(_.isBoolean(Object(false)), true); }); test('should return `false` for non-booleans', 12, function() { var expected = _.map(falsey, function(value) { return value === false; }); var actual = _.map(falsey, function(value, index) { return index ? _.isBoolean(value) : _.isBoolean(); }); deepEqual(actual, expected); strictEqual(_.isBoolean(args), false); strictEqual(_.isBoolean([1, 2, 3]), false); strictEqual(_.isBoolean(new Date), false); strictEqual(_.isBoolean(new Error), false); strictEqual(_.isBoolean(_), false); strictEqual(_.isBoolean(slice), false); strictEqual(_.isBoolean({ 'a': 1 }), false); strictEqual(_.isBoolean(1), false); strictEqual(_.isBoolean(NaN), false); strictEqual(_.isBoolean(/x/), false); strictEqual(_.isBoolean('a'), false); }); test('should work with a boolean from another realm', 1, function() { if (_._object) { strictEqual(_.isBoolean(_._boolean), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isDate'); (function() { var args = arguments; test('should return `true` for dates', 1, function() { strictEqual(_.isDate(new Date), true); }); test('should return `false` for non-dates', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isDate(value) : _.isDate(); }); deepEqual(actual, expected); strictEqual(_.isDate(args), false); strictEqual(_.isDate([1, 2, 3]), false); strictEqual(_.isDate(true), false); strictEqual(_.isDate(new Error), false); strictEqual(_.isDate(_), false); strictEqual(_.isDate(slice), false); strictEqual(_.isDate({ 'a': 1 }), false); strictEqual(_.isDate(1), false); strictEqual(_.isDate(NaN), false); strictEqual(_.isDate(/x/), false); strictEqual(_.isDate('a'), false); }); test('should work with a date object from another realm', 1, function() { if (_._object) { strictEqual(_.isDate(_._date), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isElement'); (function() { var args = arguments; function Element() { this.nodeType = 1; } test('should use robust check', 7, function() { var element = body || new Element; strictEqual(_.isElement(element), true); strictEqual(_.isElement({ 'nodeType': 1 }), false); strictEqual(_.isElement({ 'nodeType': Object(1) }), false); strictEqual(_.isElement({ 'nodeType': true }), false); strictEqual(_.isElement({ 'nodeType': [1] }), false); strictEqual(_.isElement({ 'nodeType': '1' }), false); strictEqual(_.isElement({ 'nodeType': '001' }), false); }); test('should use a stronger check in browsers', 2, function() { var expected = !_.support.dom; strictEqual(_.isElement(new Element), expected); if (lodashBizarro) { expected = !lodashBizarro.support.dom; strictEqual(lodashBizarro.isElement(new Element), expected); } else { skipTest(); } }); test('should return `false` for non DOM elements', 13, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isElement(value) : _.isElement(); }); deepEqual(actual, expected); strictEqual(_.isElement(args), false); strictEqual(_.isElement([1, 2, 3]), false); strictEqual(_.isElement(true), false); strictEqual(_.isElement(new Date), false); strictEqual(_.isElement(new Error), false); strictEqual(_.isElement(_), false); strictEqual(_.isElement(slice), false); strictEqual(_.isElement({ 'a': 1 }), false); strictEqual(_.isElement(1), false); strictEqual(_.isElement(NaN), false); strictEqual(_.isElement(/x/), false); strictEqual(_.isElement('a'), false); }); test('should work with a DOM element from another realm', 1, function() { if (_._element) { strictEqual(_.isElement(_._element), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isEmpty'); (function() { var args = arguments; test('should return `true` for empty values', 7, function() { var expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { return _.isEmpty(value); }); deepEqual(actual, expected); strictEqual(_.isEmpty(true), true); strictEqual(_.isEmpty(slice), true); strictEqual(_.isEmpty(1), true); strictEqual(_.isEmpty(NaN), true); strictEqual(_.isEmpty(/x/), true); strictEqual(_.isEmpty(), true); }); test('should return `false` for non-empty values', 3, function() { strictEqual(_.isEmpty([0]), false); strictEqual(_.isEmpty({ 'a': 0 }), false); strictEqual(_.isEmpty('a'), false); }); test('should work with an object that has a `length` property', 1, function() { strictEqual(_.isEmpty({ 'length': 0 }), false); }); test('should work with `arguments` objects (test in IE < 9)', 1, function() { strictEqual(_.isEmpty(args), false); }); test('should work with jQuery/MooTools DOM query collections', 1, function() { function Foo(elements) { push.apply(this, elements); } Foo.prototype = { 'length': 0, 'splice': arrayProto.splice }; strictEqual(_.isEmpty(new Foo([])), true); }); test('should not treat objects with negative lengths as array-like', 1, function() { function Foo() {} Foo.prototype.length = -1; strictEqual(_.isEmpty(new Foo), true); }); test('should not treat objects with lengths larger than `MAX_SAFE_INTEGER` as array-like', 1, function() { function Foo() {} Foo.prototype.length = MAX_SAFE_INTEGER + 1; strictEqual(_.isEmpty(new Foo), true); }); test('should not treat objects with non-number lengths as array-like', 1, function() { strictEqual(_.isEmpty({ 'length': '0' }), false); }); test('fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 1, function() { strictEqual(_.isEmpty(shadowObject), false); }); test('skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', 2, function() { function Foo() {} Foo.prototype.a = 1; strictEqual(_.isEmpty(Foo), true); Foo.prototype = { 'a': 1 }; strictEqual(_.isEmpty(Foo), true); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_({}).isEmpty(), true); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_({}).chain().isEmpty() instanceof _); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isEqual'); (function() { test('should perform comparisons between primitive values', 1, function() { var pairs = [ [1, 1, true], [1, Object(1), true], [1, '1', false], [1, 2, false], [-0, -0, true], [0, 0, true], [0, Object(0), true], [Object(0), Object(0), true], [-0, 0, false], [0, '0', false], [0, null, false], [NaN, NaN, true], [NaN, Object(NaN), true], [Object(NaN), Object(NaN), true], [NaN, 'a', false], [NaN, Infinity, false], ['a', 'a', true], ['a', Object('a'), true], [Object('a'), Object('a'), true], ['a', 'b', false], ['a', ['a'], false], [true, true, true], [true, Object(true), true], [Object(true), Object(true), true], [true, 1, false], [true, 'a', false], [false, false, true], [false, Object(false), true], [Object(false), Object(false), true], [false, 0, false], [false, '', false], [null, null, true], [null, undefined, false], [null, {}, false], [null, '', false], [undefined, undefined, true], [undefined, null, false], [undefined, '', false] ]; var expected = _.map(pairs, function(pair) { return pair[2]; }); var actual = _.map(pairs, function(pair) { return _.isEqual(pair[0], pair[1]); }); deepEqual(actual, expected); }); test('should perform comparisons between arrays', 6, function() { var array1 = [true, null, 1, 'a', undefined], array2 = [true, null, 1, 'a', undefined]; strictEqual(_.isEqual(array1, array2), true); array1 = [[1, 2, 3], new Date(2012, 4, 23), /x/, { 'e': 1 }]; array2 = [[1, 2, 3], new Date(2012, 4, 23), /x/, { 'e': 1 }]; strictEqual(_.isEqual(array1, array2), true); array1 = [1]; array1[2] = 3; array2 = [1]; array2[1] = undefined; array2[2] = 3; strictEqual(_.isEqual(array1, array2), true); array1 = [Object(1), false, Object('a'), /x/, new Date(2012, 4, 23), ['a', 'b', [Object('c')]], { 'a': 1 }]; array2 = [1, Object(false), 'a', /x/, new Date(2012, 4, 23), ['a', Object('b'), ['c']], { 'a': 1 }]; strictEqual(_.isEqual(array1, array2), true); array1 = [1, 2, 3]; array2 = [3, 2, 1]; strictEqual(_.isEqual(array1, array2), false); array1 = [1, 2]; array2 = [1, 2, 3]; strictEqual(_.isEqual(array1, array2), false); }); test('should treat arrays with identical values but different non-numeric properties as equal', 3, function() { var array1 = [1, 2, 3], array2 = [1, 2, 3]; array1.every = array1.filter = array1.forEach = array1.indexOf = array1.lastIndexOf = array1.map = array1.some = array1.reduce = array1.reduceRight = null; array2.concat = array2.join = array2.pop = array2.reverse = array2.shift = array2.slice = array2.sort = array2.splice = array2.unshift = null; strictEqual(_.isEqual(array1, array2), true); array1 = [1, 2, 3]; array1.a = 1; array2 = [1, 2, 3]; array2.b = 1; strictEqual(_.isEqual(array1, array2), true); array1 = /x/.exec('vwxyz'); array2 = ['x']; strictEqual(_.isEqual(array1, array2), true); }); test('should work with sparse arrays', 3, function() { var array = Array(1); strictEqual(_.isEqual(array, Array(1)), true); strictEqual(_.isEqual(array, [undefined]), true); strictEqual(_.isEqual(array, Array(2)), false); }); test('should perform comparisons between plain objects', 5, function() { var object1 = { 'a': true, 'b': null, 'c': 1, 'd': 'a', 'e': undefined }, object2 = { 'a': true, 'b': null, 'c': 1, 'd': 'a', 'e': undefined }; strictEqual(_.isEqual(object1, object2), true); object1 = { 'a': [1, 2, 3], 'b': new Date(2012, 4, 23), 'c': /x/, 'd': { 'e': 1 } }; object2 = { 'a': [1, 2, 3], 'b': new Date(2012, 4, 23), 'c': /x/, 'd': { 'e': 1 } }; strictEqual(_.isEqual(object1, object2), true); object1 = { 'a': 1, 'b': 2, 'c': 3 }; object2 = { 'a': 3, 'b': 2, 'c': 1 }; strictEqual(_.isEqual(object1, object2), false); object1 = { 'a': 1, 'b': 2, 'c': 3 }; object2 = { 'd': 1, 'e': 2, 'f': 3 }; strictEqual(_.isEqual(object1, object2), false); object1 = { 'a': 1, 'b': 2 }; object2 = { 'a': 1, 'b': 2, 'c': 3 }; strictEqual(_.isEqual(object1, object2), false); }); test('should perform comparisons of nested objects', 1, function() { var object1 = { 'a': [1, 2, 3], 'b': true, 'c': Object(1), 'd': 'a', 'e': { 'f': ['a', Object('b'), 'c'], 'g': Object(false), 'h': new Date(2012, 4, 23), 'i': _.noop, 'j': 'a' } }; var object2 = { 'a': [1, Object(2), 3], 'b': Object(true), 'c': 1, 'd': Object('a'), 'e': { 'f': ['a', 'b', 'c'], 'g': false, 'h': new Date(2012, 4, 23), 'i': _.noop, 'j': 'a' } }; strictEqual(_.isEqual(object1, object2), true); }); test('should perform comparisons between object instances', 4, function() { function Foo() { this.value = 1; } Foo.prototype.value = 1; function Bar() { this.value = 1; } Bar.prototype.value = 2; strictEqual(_.isEqual(new Foo, new Foo), true); strictEqual(_.isEqual(new Foo, new Bar), false); strictEqual(_.isEqual({ 'value': 1 }, new Foo), false); strictEqual(_.isEqual({ 'value': 2 }, new Bar), false); }); test('should perform comparisons between objects with constructor properties', 5, function() { strictEqual(_.isEqual({ 'constructor': 1 }, { 'constructor': 1 }), true); strictEqual(_.isEqual({ 'constructor': 1 }, { 'constructor': '1' }), false); strictEqual(_.isEqual({ 'constructor': [1] }, { 'constructor': [1] }), true); strictEqual(_.isEqual({ 'constructor': [1] }, { 'constructor': ['1'] }), false); strictEqual(_.isEqual({ 'constructor': Object }, {}), false); }); test('should perform comparisons between arrays with circular references', 4, function() { var array1 = [], array2 = []; array1.push(array1); array2.push(array2); strictEqual(_.isEqual(array1, array2), true); array1.push('b'); array2.push('b'); strictEqual(_.isEqual(array1, array2), true); array1.push('c'); array2.push('d'); strictEqual(_.isEqual(array1, array2), false); array1 = ['a', 'b', 'c']; array1[1] = array1; array2 = ['a', ['a', 'b', 'c'], 'c']; strictEqual(_.isEqual(array1, array2), false); }); test('should perform comparisons between objects with circular references', 4, function() { var object1 = {}, object2 = {}; object1.a = object1; object2.a = object2; strictEqual(_.isEqual(object1, object2), true); object1.b = 0; object2.b = Object(0); strictEqual(_.isEqual(object1, object2), true); object1.c = Object(1); object2.c = Object(2); strictEqual(_.isEqual(object1, object2), false); object1 = { 'a': 1, 'b': 2, 'c': 3 }; object1.b = object1; object2 = { 'a': 1, 'b': { 'a': 1, 'b': 2, 'c': 3 }, 'c': 3 }; strictEqual(_.isEqual(object1, object2), false); }); test('should perform comparisons between objects with multiple circular references', 3, function() { var array1 = [{}], array2 = [{}]; (array1[0].a = array1).push(array1); (array2[0].a = array2).push(array2); strictEqual(_.isEqual(array1, array2), true); array1[0].b = 0; array2[0].b = Object(0); strictEqual(_.isEqual(array1, array2), true); array1[0].c = Object(1); array2[0].c = Object(2); strictEqual(_.isEqual(array1, array2), false); }); test('should perform comparisons between objects with complex circular references', 1, function() { var object1 = { 'foo': { 'b': { 'c': { 'd': {} } } }, 'bar': { 'a': 2 } }; var object2 = { 'foo': { 'b': { 'c': { 'd': {} } } }, 'bar': { 'a': 2 } }; object1.foo.b.c.d = object1; object1.bar.b = object1.foo.b; object2.foo.b.c.d = object2; object2.bar.b = object2.foo.b; strictEqual(_.isEqual(object1, object2), true); }); test('should perform comparisons between objects with shared property values', 1, function() { var object1 = { 'a': [1, 2] }; var object2 = { 'a': [1, 2], 'b': [1, 2] }; object1.b = object1.a; strictEqual(_.isEqual(object1, object2), true); }); test('should work with `arguments` objects (test in IE < 9)', 2, function() { var args1 = (function() { return arguments; }(1, 2, 3)), args2 = (function() { return arguments; }(1, 2, 3)), args3 = (function() { return arguments; }(1, 2)); strictEqual(_.isEqual(args1, args2), true); strictEqual(_.isEqual(args1, args3), false); }); test('should treat `arguments` objects like `Object` objects', 4, function() { var args = (function() { return arguments; }(1, 2, 3)), object = { '0': 1, '1': 2, '2': 3 }; function Foo() {} Foo.prototype = object; strictEqual(_.isEqual(args, object), true); strictEqual(_.isEqual(object, args), true); strictEqual(_.isEqual(args, new Foo), false); strictEqual(_.isEqual(new Foo, args), false); }); test('should perform comparisons between date objects', 4, function() { strictEqual(_.isEqual(new Date(2012, 4, 23), new Date(2012, 4, 23)), true); strictEqual(_.isEqual(new Date(2012, 4, 23), new Date(2013, 3, 25)), false); strictEqual(_.isEqual(new Date(2012, 4, 23), { 'getTime': _.constant(1337756400000) }), false); strictEqual(_.isEqual(new Date('a'), new Date('a')), false); }); test('should perform comparisons between error objects', 1, function() { var pairs = _.map([ 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError' ], function(type, index, errorTypes) { var otherType = errorTypes[++index % errorTypes.length], CtorA = root[type], CtorB = root[otherType]; return [new CtorA('a'), new CtorA('a'), new CtorB('a'), new CtorB('b')]; }); var expected = _.times(pairs.length, _.constant([true, false, false])); var actual = _.map(pairs, function(pair) { return [_.isEqual(pair[0], pair[1]), _.isEqual(pair[0], pair[2]), _.isEqual(pair[2], pair[3])]; }); deepEqual(actual, expected); }); test('should perform comparisons between functions', 2, function() { function a() { return 1 + 2; } function b() { return 1 + 2; } strictEqual(_.isEqual(a, a), true); strictEqual(_.isEqual(a, b), false); }); test('should perform comparisons between regexes', 5, function() { strictEqual(_.isEqual(/x/gim, /x/gim), true); strictEqual(_.isEqual(/x/gim, /x/mgi), true); strictEqual(_.isEqual(/x/gi, /x/g), false); strictEqual(_.isEqual(/x/, /y/), false); strictEqual(_.isEqual(/x/g, { 'global': true, 'ignoreCase': false, 'multiline': false, 'source': 'x' }), false); }); test('should perform comparisons between typed arrays', 1, function() { var pairs = _.map(typedArrays, function(type, index) { var otherType = typedArrays[(index + 1) % typedArrays.length], CtorA = root[type] || function(n) { this.n = n; }, CtorB = root[otherType] || function(n) { this.n = n; }, bufferA = root[type] ? new ArrayBuffer(8) : 8, bufferB = root[otherType] ? new ArrayBuffer(8) : 8, bufferC = root[otherType] ? new ArrayBuffer(16) : 16; return [new CtorA(bufferA), new CtorA(bufferA), new CtorB(bufferB), new CtorB(bufferC)]; }); var expected = _.times(pairs.length, _.constant([true, false, false])); var actual = _.map(pairs, function(pair) { return [_.isEqual(pair[0], pair[1]), _.isEqual(pair[0], pair[2]), _.isEqual(pair[2], pair[3])]; }); deepEqual(actual, expected); }); test('should avoid common type coercions', 9, function() { strictEqual(_.isEqual(true, Object(false)), false); strictEqual(_.isEqual(Object(false), Object(0)), false); strictEqual(_.isEqual(false, Object('')), false); strictEqual(_.isEqual(Object(36), Object('36')), false); strictEqual(_.isEqual(0, ''), false); strictEqual(_.isEqual(1, true), false); strictEqual(_.isEqual(1337756400000, new Date(2012, 4, 23)), false); strictEqual(_.isEqual('36', 36), false); strictEqual(_.isEqual(36, '36'), false); }); test('fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 1, function() { strictEqual(_.isEqual(shadowObject, {}), false); }); test('should return `false` for objects with custom `toString` methods', 1, function() { var primitive, object = { 'toString': function() { return primitive; } }, values = [true, null, 1, 'a', undefined], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { primitive = value; return _.isEqual(object, value); }); deepEqual(actual, expected); }); test('should provide the correct `customizer` arguments', 1, function() { var argsList = [], object1 = { 'a': [1, 2], 'b': null }, object2 = { 'a': [1, 2], 'b': null }; object1.b = object2; object2.b = object1; var expected = [ [object1, object2], [object1.a, object2.a, 'a'], [object1.a[0], object2.a[0], 0], [object1.a[1], object2.a[1], 1], [object1.b, object2.b, 'b'], [object1.b.a, object2.b.a, 'a'], [object1.b.a[0], object2.b.a[0], 0], [object1.b.a[1], object2.b.a[1], 1], [object1.b.b, object2.b.b, 'b'] ]; _.isEqual(object1, object2, function() { argsList.push(slice.call(arguments)); }); deepEqual(argsList, expected); }); test('should correctly set the `this` binding', 1, function() { var actual = _.isEqual('a', 'b', function(a, b) { return this[a] == this[b]; }, { 'a': 1, 'b': 1 }); strictEqual(actual, true); }); test('should handle comparisons if `customizer` returns `undefined`', 1, function() { strictEqual(_.isEqual('a', 'a', _.noop), true); }); test('should return a boolean value even if `customizer` does not', 2, function() { var actual = _.isEqual('a', 'a', _.constant('a')); strictEqual(actual, true); var expected = _.map(falsey, _.constant(false)); actual = []; _.each(falsey, function(value) { actual.push(_.isEqual('a', 'b', _.constant(value))); }); deepEqual(actual, expected); }); test('should ensure `customizer` is a function', 1, function() { var array = [1, 2, 3], eq = _.partial(_.isEqual, array), actual = _.map([array, [1, 0, 3]], eq); deepEqual(actual, [true, false]); }); test('should work as an iteratee for `_.every`', 1, function() { var actual = _.every([1, 1, 1], _.partial(_.isEqual, 1)); ok(actual); }); test('should treat objects created by `Object.create(null)` like any other plain object', 2, function() { function Foo() { this.a = 1; } Foo.prototype.constructor = null; var object2 = { 'a': 1 }; strictEqual(_.isEqual(new Foo, object2), false); if (create) { var object1 = create(null); object1.a = 1; strictEqual(_.isEqual(object1, object2), true); } else { skipTest(); } }); test('should return `true` for like-objects from different documents', 4, function() { // Ensure `_._object` is assigned (unassigned in Opera 10.00). if (_._object) { strictEqual(_.isEqual({ 'a': 1, 'b': 2, 'c': 3 }, _._object), true); strictEqual(_.isEqual({ 'a': 1, 'b': 2, 'c': 2 }, _._object), false); strictEqual(_.isEqual([1, 2, 3], _._array), true); strictEqual(_.isEqual([1, 2, 2], _._array), false); } else { skipTest(4); } }); test('should not error on DOM elements', 1, function() { if (document) { var element1 = document.createElement('div'), element2 = element1.cloneNode(true); try { strictEqual(_.isEqual(element1, element2), false); } catch(e) { ok(false, e.message); } } else { skipTest(); } }); test('should perform comparisons between wrapped values', 32, function() { var stamp = +new Date; var values = [ [[1, 2], [1, 2], [1, 2, 3]], [true, true, false], [new Date(stamp), new Date(stamp), new Date(stamp - 100)], [{ 'a': 1, 'b': 2 }, { 'a': 1, 'b': 2 }, { 'a': 1, 'b': 1 }], [1, 1, 2], [NaN, NaN, Infinity], [/x/, /x/, /x/i], ['a', 'a', 'A'] ]; _.each(values, function(vals) { if (!isNpm) { var wrapped1 = _(vals[0]), wrapped2 = _(vals[1]), actual = wrapped1.isEqual(wrapped2); strictEqual(actual, true); strictEqual(_.isEqual(_(actual), _(true)), true); wrapped1 = _(vals[0]); wrapped2 = _(vals[2]); actual = wrapped1.isEqual(wrapped2); strictEqual(actual, false); strictEqual(_.isEqual(_(actual), _(false)), true); } else { skipTest(4); } }); }); test('should perform comparisons between wrapped and non-wrapped values', 4, function() { if (!isNpm) { var object1 = _({ 'a': 1, 'b': 2 }), object2 = { 'a': 1, 'b': 2 }; strictEqual(object1.isEqual(object2), true); strictEqual(_.isEqual(object1, object2), true); object1 = _({ 'a': 1, 'b': 2 }); object2 = { 'a': 1, 'b': 1 }; strictEqual(object1.isEqual(object2), false); strictEqual(_.isEqual(object1, object2), false); } else { skipTest(4); } }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_('a').isEqual('a'), true); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_('a').chain().isEqual('a') instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isError'); (function() { var args = arguments; test('should return `true` for error objects', 1, function() { var expected = _.map(errors, _.constant(true)); var actual = _.map(errors, function(error) { return _.isError(error) === true; }); deepEqual(actual, expected); }); test('should return `false` for non error objects', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isError(value) : _.isError(); }); deepEqual(actual, expected); strictEqual(_.isError(args), false); strictEqual(_.isError([1, 2, 3]), false); strictEqual(_.isError(true), false); strictEqual(_.isError(new Date), false); strictEqual(_.isError(_), false); strictEqual(_.isError(slice), false); strictEqual(_.isError({ 'a': 1 }), false); strictEqual(_.isError(1), false); strictEqual(_.isError(NaN), false); strictEqual(_.isError(/x/), false); strictEqual(_.isError('a'), false); }); test('should work with an error object from another realm', 1, function() { if (_._object) { var expected = _.map(_._errors, _.constant(true)); var actual = _.map(_._errors, function(error) { return _.isError(error) === true; }); deepEqual(actual, expected); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isFinite'); (function() { var args = arguments; test('should return `true` for finite values', 1, function() { var values = [0, 1, 3.14, -1], expected = _.map(values, _.constant(true)); var actual = _.map(values, function(value) { return _.isFinite(value); }); deepEqual(actual, expected); }); test('should return `false` for non-finite values', 9, function() { var values = [NaN, Infinity, -Infinity, Object(1)], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.isFinite(value); }); deepEqual(actual, expected); strictEqual(_.isFinite(args), false); strictEqual(_.isFinite([1, 2, 3]), false); strictEqual(_.isFinite(true), false); strictEqual(_.isFinite(new Date), false); strictEqual(_.isFinite(new Error), false); strictEqual(_.isFinite({ 'a': 1 }), false); strictEqual(_.isFinite(/x/), false); strictEqual(_.isFinite('a'), false); }); test('should return `false` for non-numeric values', 1, function() { var values = [undefined, [], true, new Date, new Error, '', ' ', '2px'], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.isFinite(value); }); deepEqual(actual, expected); }); test('should return `false` for numeric string values', 1, function() { var values = ['2', '0', '08'], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.isFinite(value); }); deepEqual(actual, expected); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isFunction'); (function() { var args = arguments; test('should return `true` for functions', 2, function() { strictEqual(_.isFunction(_), true); strictEqual(_.isFunction(slice), true); }); test('should return `true` for typed array constructors', 1, function() { var expected = _.map(typedArrays, function(type) { return objToString.call(root[type]) == funcTag; }); var actual = _.map(typedArrays, function(type) { return _.isFunction(root[type]); }); deepEqual(actual, expected); }); test('should return `false` for non-functions', 11, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isFunction(value) : _.isFunction(); }); deepEqual(actual, expected); strictEqual(_.isFunction(args), false); strictEqual(_.isFunction([1, 2, 3]), false); strictEqual(_.isFunction(true), false); strictEqual(_.isFunction(new Date), false); strictEqual(_.isFunction(new Error), false); strictEqual(_.isFunction({ 'a': 1 }), false); strictEqual(_.isFunction(1), false); strictEqual(_.isFunction(NaN), false); strictEqual(_.isFunction(/x/), false); strictEqual(_.isFunction('a'), false); }); test('should work using its fallback', 3, function() { if (!isModularize) { // Simulate native `Uint8Array` constructor with a `toStringTag` of // 'Function' and a `typeof` result of 'object'. var lodash = _.runInContext({ 'Function': { 'prototype': { 'toString': function() { return _.has(this, 'toString') ? this.toString() : fnToString.call(this); } } }, 'Object': _.assign(function(value) { return Object(value); }, { 'prototype': { 'toString': _.assign(function() { return _.has(this, '@@toStringTag') ? this['@@toStringTag'] : objToString.call(this); }, { 'toString': function() { return String(toString); } }) } }), 'Uint8Array': { '@@toStringTag': funcTag, 'toString': function() { return String(Uint8Array || Array); } } }); strictEqual(lodash.isFunction(slice), true); strictEqual(lodash.isFunction(/x/), false); strictEqual(lodash.isFunction(Uint8Array), objToString.call(Uint8Array) == funcTag); } else { skipTest(3); } }); test('should work with host objects in IE 8 document mode (test in IE 11)', 2, function() { // Trigger a Chakra JIT bug. // See https://github.com/jashkenas/underscore/issues/1621. _.each([body, xml], function(object) { if (object) { _.times(100, _.isFunction); strictEqual(_.isFunction(object), false); } else { skipTest(); } }); }); test('should work with a function from another realm', 1, function() { if (_._object) { strictEqual(_.isFunction(_._function), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isMatch'); (function() { test('should perform a deep comparison between `object` and `source`', 5, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }; strictEqual(_.isMatch(object, { 'a': 1 }), true); strictEqual(_.isMatch(object, { 'b': 1 }), false); strictEqual(_.isMatch(object, { 'a': 1, 'c': 3 }), true); strictEqual(_.isMatch(object, { 'c': 3, 'd': 4 }), false); object = { 'a': { 'b': { 'c': 1, 'd': 2 }, 'e': 3 }, 'f': 4 }; strictEqual(_.isMatch(object, { 'a': { 'b': { 'c': 1 } } }), true); }); test('should compare a variety of `source` values', 2, function() { var object1 = { 'a': false, 'b': true, 'c': '3', 'd': 4, 'e': [5], 'f': { 'g': 6 } }, object2 = { 'a': 0, 'b': 1, 'c': 3, 'd': '4', 'e': ['5'], 'f': { 'g': '6' } }; strictEqual(_.isMatch(object1, object1), true); strictEqual(_.isMatch(object1, object2), false); }); test('should return `true` when comparing an empty `source`', 1, function() { var object = { 'a': 1 }, expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { return _.isMatch(object, value); }); deepEqual(actual, expected); }); test('should return `true` when comparing a `source` of empty arrays and objects', 1, function() { var objects = [{ 'a': [1], 'b': { 'c': 1 } }, { 'a': [2, 3], 'b': { 'd': 2 } }], source = { 'a': [], 'b': {} }; var actual = _.filter(objects, function(object) { return _.isMatch(object, source); }); deepEqual(actual, objects); }); test('should not error for falsey `object` values', 1, function() { var values = falsey.slice(1), expected = _.map(values, _.constant(false)), source = { 'a': 1 }; var actual = _.map(values, function(value) { try { return _.isMatch(value, source); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `true` when comparing an empty `source` to a falsey `object`', 1, function() { var values = falsey.slice(1), expected = _.map(values, _.constant(true)), source = {}; var actual = _.map(values, function(value) { try { return _.isMatch(value, source); } catch(e) {} }); deepEqual(actual, expected); }); test('should search arrays of `source` for values', 3, function() { var objects = [{ 'a': ['b'] }, { 'a': ['c', 'd'] }], source = { 'a': ['d'] }, predicate = function(object) { return _.isMatch(object, source); }, actual = _.filter(objects, predicate); deepEqual(actual, [objects[1]]); source = { 'a': ['b', 'd'] }; actual = _.filter(objects, predicate); deepEqual(actual, []); source = { 'a': ['d', 'b'] }; actual = _.filter(objects, predicate); deepEqual(actual, []); }); test('should perform a partial comparison of all objects within arrays of `source`', 1, function() { var source = { 'a': [{ 'b': 1 }, { 'b': 4, 'c': 5 }] }; var objects = [ { 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 5, 'd': 6 }] }, { 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 6, 'd': 7 }] } ]; var actual = _.filter(objects, function(object) { return _.isMatch(object, source); }); deepEqual(actual, [objects[0]]); }); test('should handle a `source` with `undefined` values', 2, function() { var objects = [{ 'a': 1 }, { 'a': 1, 'b': 1 }, { 'a': 1, 'b': undefined }], source = { 'b': undefined }, predicate = function(object) { return _.isMatch(object, source); }, actual = _.map(objects, predicate), expected = [false, false, true]; deepEqual(actual, expected); source = { 'a': { 'c': undefined } }; objects = [{ 'a': { 'b': 1 } }, { 'a':{ 'b':1, 'c': 1 } }, { 'a': { 'b': 1, 'c': undefined } }]; actual = _.map(objects, predicate); deepEqual(actual, expected); }); test('should not match by inherited `source` properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var objects = [{ 'a': 1 }, { 'a': 1, 'b': 2 }], source = new Foo, expected = _.map(objects, _.constant(true)); var actual = _.map(objects, function(object) { return _.isMatch(object, source); }); deepEqual(actual, expected); }); test('should work with a function for `source`', 1, function() { function source() {} source.a = 1; source.b = function() {}; source.c = 3; var objects = [{ 'a': 1 }, { 'a': 1, 'b': source.b, 'c': 3 }]; var actual = _.map(objects, function(object) { return _.isMatch(object, source); }); deepEqual(actual, [false, true]); }); test('should match problem JScript properties (test in IE < 9)', 1, function() { var objects = [{}, shadowObject]; var actual = _.map(objects, function(object) { return _.isMatch(object, shadowObject); }); deepEqual(actual, [false, true]); }); test('should provide the correct `customizer` arguments', 1, function() { var argsList = [], object1 = { 'a': [1, 2], 'b': null }, object2 = { 'a': [1, 2], 'b': null }; object1.b = object2; object2.b = object1; var expected = [ [object1.a, object2.a, 'a'], [object1.a[0], object2.a[0], 0], [object1.a[1], object2.a[1], 1], [object1.b, object2.b, 'b'], [object1.b.a, object2.b.a, 'a'], [object1.b.a[0], object2.b.a[0], 0], [object1.b.a[1], object2.b.a[1], 1], [object1.b.b, object2.b.b, 'b'], [object1.b.b.a, object2.b.b.a, 'a'], [object1.b.b.a[0], object2.b.b.a[0], 0], [object1.b.b.a[1], object2.b.b.a[1], 1], [object1.b.b.b, object2.b.b.b, 'b'] ]; _.isMatch(object1, object2, function() { argsList.push(slice.call(arguments)); }); deepEqual(argsList, expected); }); test('should correctly set the `this` binding', 1, function() { var actual = _.isMatch({ 'a': 1 }, { 'a': 2 }, function(a, b) { return this[a] == this[b]; }, { 'a': 1, 'b': 1 }); strictEqual(actual, true); }); test('should handle comparisons if `customizer` returns `undefined`', 1, function() { strictEqual(_.isMatch({ 'a': 1 }, { 'a': 1 }, _.noop), true); }); test('should return a boolean value even if `customizer` does not', 2, function() { var object = { 'a': 1 }, actual = _.isMatch(object, { 'a': 1 }, _.constant('a')); strictEqual(actual, true); var expected = _.map(falsey, _.constant(false)); actual = []; _.each(falsey, function(value) { actual.push(_.isMatch(object, { 'a': 2 }, _.constant(value))); }); deepEqual(actual, expected); }); test('should ensure `customizer` is a function', 1, function() { var object = { 'a': 1 }, matches = _.partial(_.isMatch, object), actual = _.map([object, { 'a': 2 }], matches); deepEqual(actual, [true, false]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isNaN'); (function() { var args = arguments; test('should return `true` for NaNs', 2, function() { strictEqual(_.isNaN(NaN), true); strictEqual(_.isNaN(Object(NaN)), true); }); test('should return `false` for non-NaNs', 12, function() { var expected = _.map(falsey, function(value) { return value !== value; }); var actual = _.map(falsey, function(value, index) { return index ? _.isNaN(value) : _.isNaN(); }); deepEqual(actual, expected); strictEqual(_.isNaN(args), false); strictEqual(_.isNaN([1, 2, 3]), false); strictEqual(_.isNaN(true), false); strictEqual(_.isNaN(new Date), false); strictEqual(_.isNaN(new Error), false); strictEqual(_.isNaN(_), false); strictEqual(_.isNaN(slice), false); strictEqual(_.isNaN({ 'a': 1 }), false); strictEqual(_.isNaN(1), false); strictEqual(_.isNaN(/x/), false); strictEqual(_.isNaN('a'), false); }); test('should work with `NaN` from another realm', 1, function() { if (_._object) { strictEqual(_.isNaN(_._nan), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isNative'); (function() { var args = arguments; test('should return `true` for native methods', 6, function() { _.each([Array, create, root.encodeURI, slice, Uint8Array], function(func) { if (func) { strictEqual(_.isNative(func), true); } else { skipTest(); } }); if (body) { strictEqual(_.isNative(body.cloneNode), true); } else { skipTest(); } }); test('should return `false` for non-native methods', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isNative(value) : _.isNative(); }); deepEqual(actual, expected); strictEqual(_.isNative(args), false); strictEqual(_.isNative([1, 2, 3]), false); strictEqual(_.isNative(true), false); strictEqual(_.isNative(new Date), false); strictEqual(_.isNative(new Error), false); strictEqual(_.isNative(_), false); strictEqual(_.isNative({ 'a': 1 }), false); strictEqual(_.isNative(1), false); strictEqual(_.isNative(NaN), false); strictEqual(_.isNative(/x/), false); strictEqual(_.isNative('a'), false); }); test('should work with native functions from another realm', 2, function() { if (_._element) { strictEqual(_.isNative(_._element.cloneNode), true); } else { skipTest(); } if (_._object) { strictEqual(_.isNative(_._object.valueOf), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isNull'); (function() { var args = arguments; test('should return `true` for nulls', 1, function() { strictEqual(_.isNull(null), true); }); test('should return `false` for non-nulls', 13, function() { var expected = _.map(falsey, function(value) { return value === null; }); var actual = _.map(falsey, function(value, index) { return index ? _.isNull(value) : _.isNull(); }); deepEqual(actual, expected); strictEqual(_.isNull(args), false); strictEqual(_.isNull([1, 2, 3]), false); strictEqual(_.isNull(true), false); strictEqual(_.isNull(new Date), false); strictEqual(_.isNull(new Error), false); strictEqual(_.isNull(_), false); strictEqual(_.isNull(slice), false); strictEqual(_.isNull({ 'a': 1 }), false); strictEqual(_.isNull(1), false); strictEqual(_.isNull(NaN), false); strictEqual(_.isNull(/x/), false); strictEqual(_.isNull('a'), false); }); test('should work with nulls from another realm', 1, function() { if (_._object) { strictEqual(_.isNull(_._null), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isNumber'); (function() { var args = arguments; test('should return `true` for numbers', 3, function() { strictEqual(_.isNumber(0), true); strictEqual(_.isNumber(Object(0)), true); strictEqual(_.isNumber(NaN), true); }); test('should return `false` for non-numbers', 11, function() { var expected = _.map(falsey, function(value) { return typeof value == 'number'; }); var actual = _.map(falsey, function(value, index) { return index ? _.isNumber(value) : _.isNumber(); }); deepEqual(actual, expected); strictEqual(_.isNumber(args), false); strictEqual(_.isNumber([1, 2, 3]), false); strictEqual(_.isNumber(true), false); strictEqual(_.isNumber(new Date), false); strictEqual(_.isNumber(new Error), false); strictEqual(_.isNumber(_), false); strictEqual(_.isNumber(slice), false); strictEqual(_.isNumber({ 'a': 1 }), false); strictEqual(_.isNumber(/x/), false); strictEqual(_.isNumber('a'), false); }); test('should work with numbers from another realm', 1, function() { if (_._object) { strictEqual(_.isNumber(_._number), true); } else { skipTest(); } }); test('should avoid `[xpconnect wrapped native prototype]` in Firefox', 1, function() { strictEqual(_.isNumber(+"2"), true); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isObject'); (function() { var args = arguments; test('should return `true` for objects', 12, function() { strictEqual(_.isObject(args), true); strictEqual(_.isObject([1, 2, 3]), true); strictEqual(_.isObject(Object(false)), true); strictEqual(_.isObject(new Date), true); strictEqual(_.isObject(new Error), true); strictEqual(_.isObject(_), true); strictEqual(_.isObject(slice), true); strictEqual(_.isObject({ 'a': 1 }), true); strictEqual(_.isObject(Object(0)), true); strictEqual(_.isObject(/x/), true); strictEqual(_.isObject(Object('a')), true); if (document) { strictEqual(_.isObject(body), true); } else { skipTest(); } }); test('should return `false` for non-objects', 1, function() { var symbol = (Symbol || noop)(), values = falsey.concat(true, 1, 'a', symbol), expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value, index) { return index ? _.isObject(value) : _.isObject(); }); deepEqual(actual, expected); }); test('should work with objects from another realm', 8, function() { if (_._element) { strictEqual(_.isObject(_._element), true); } else { skipTest(); } if (_._object) { strictEqual(_.isObject(_._object), true); strictEqual(_.isObject(_._boolean), true); strictEqual(_.isObject(_._date), true); strictEqual(_.isObject(_._function), true); strictEqual(_.isObject(_._number), true); strictEqual(_.isObject(_._regexp), true); strictEqual(_.isObject(_._string), true); } else { skipTest(7); } }); test('should avoid V8 bug #2291 (test in Chrome 19-20)', 1, function() { // Trigger a V8 JIT bug. // See https://code.google.com/p/v8/issues/detail?id=2291. var object = {}; // 1: Useless comparison statement, this is half the trigger. object == object; // 2: Initial check with object, this is the other half of the trigger. _.isObject(object); strictEqual(_.isObject('x'), false); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isPlainObject'); (function() { var element = document && document.createElement('div'); test('should detect plain objects', 5, function() { function Foo(a) { this.a = 1; } strictEqual(_.isPlainObject({}), true); strictEqual(_.isPlainObject({ 'a': 1 }), true); strictEqual(_.isPlainObject({ 'constructor': Foo }), true); strictEqual(_.isPlainObject([1, 2, 3]), false); strictEqual(_.isPlainObject(new Foo(1)), false); }); test('should return `true` for objects with a `[[Prototype]]` of `null`', 1, function() { if (create) { strictEqual(_.isPlainObject(create(null)), true); } else { skipTest(); } }); test('should return `true` for plain objects with a custom `valueOf` property', 2, function() { strictEqual(_.isPlainObject({ 'valueOf': 0 }), true); if (element) { var valueOf = element.valueOf; element.valueOf = 0; strictEqual(_.isPlainObject(element), false); element.valueOf = valueOf; } else { skipTest(); } }); test('should return `false` for DOM elements', 1, function() { if (element) { strictEqual(_.isPlainObject(element), false); } else { skipTest(); } }); test('should return `false` for Object objects without a `toStringTag` of "Object"', 3, function() { strictEqual(_.isPlainObject(arguments), false); strictEqual(_.isPlainObject(Error), false); strictEqual(_.isPlainObject(Math), false); }); test('should return `false` for non-objects', 3, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isPlainObject(value) : _.isPlainObject(); }); deepEqual(actual, expected); strictEqual(_.isPlainObject(true), false); strictEqual(_.isPlainObject('a'), false); }); test('should work with objects from another realm', 1, function() { if (_._object) { strictEqual(_.isPlainObject(_._object), true); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isRegExp'); (function() { var args = arguments; test('should return `true` for regexes', 2, function() { strictEqual(_.isRegExp(/x/), true); strictEqual(_.isRegExp(RegExp('x')), true); }); test('should return `false` for non-regexes', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isRegExp(value) : _.isRegExp(); }); deepEqual(actual, expected); strictEqual(_.isRegExp(args), false); strictEqual(_.isRegExp([1, 2, 3]), false); strictEqual(_.isRegExp(true), false); strictEqual(_.isRegExp(new Date), false); strictEqual(_.isRegExp(new Error), false); strictEqual(_.isRegExp(_), false); strictEqual(_.isRegExp(slice), false); strictEqual(_.isRegExp({ 'a': 1 }), false); strictEqual(_.isRegExp(1), false); strictEqual(_.isRegExp(NaN), false); strictEqual(_.isRegExp('a'), false); }); test('should work with regexes from another realm', 1, function() { if (_._object) { strictEqual(_.isRegExp(_._regexp), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isString'); (function() { var args = arguments; test('should return `true` for strings', 2, function() { strictEqual(_.isString('a'), true); strictEqual(_.isString(Object('a')), true); }); test('should return `false` for non-strings', 12, function() { var expected = _.map(falsey, function(value) { return value === ''; }); var actual = _.map(falsey, function(value, index) { return index ? _.isString(value) : _.isString(); }); deepEqual(actual, expected); strictEqual(_.isString(args), false); strictEqual(_.isString([1, 2, 3]), false); strictEqual(_.isString(true), false); strictEqual(_.isString(new Date), false); strictEqual(_.isString(new Error), false); strictEqual(_.isString(_), false); strictEqual(_.isString(slice), false); strictEqual(_.isString({ '0': 1, 'length': 1 }), false); strictEqual(_.isString(1), false); strictEqual(_.isString(NaN), false); strictEqual(_.isString(/x/), false); }); test('should work with strings from another realm', 1, function() { if (_._object) { strictEqual(_.isString(_._string), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isTypedArray'); (function() { var args = arguments; test('should return `true` for typed arrays', 1, function() { var expected = _.map(typedArrays, function(type) { return type in root; }); var actual = _.map(typedArrays, function(type) { var Ctor = root[type]; return Ctor ? _.isTypedArray(new Ctor(new ArrayBuffer(8))) : false; }); deepEqual(actual, expected); }); test('should return `false` for non typed arrays', 13, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isTypedArray(value) : _.isTypedArray(); }); deepEqual(actual, expected); strictEqual(_.isTypedArray(args), false); strictEqual(_.isTypedArray([1, 2, 3]), false); strictEqual(_.isTypedArray(true), false); strictEqual(_.isTypedArray(new Date), false); strictEqual(_.isTypedArray(new Error), false); strictEqual(_.isTypedArray(_), false); strictEqual(_.isTypedArray(slice), false); strictEqual(_.isTypedArray({ 'a': 1 }), false); strictEqual(_.isTypedArray(1), false); strictEqual(_.isTypedArray(NaN), false); strictEqual(_.isTypedArray(/x/), false); strictEqual(_.isTypedArray('a'), false); }); test('should work with typed arrays from another realm', 1, function() { if (_._object) { var props = _.map(typedArrays, function(type) { return '_' + type.toLowerCase(); }); var expected = _.map(props, function(key) { return key in _; }); var actual = _.map(props, function(key) { var value = _[key]; return value ? _.isTypedArray(value) : false; }); deepEqual(actual, expected); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isUndefined'); (function() { var args = arguments; test('should return `true` for `undefined` values', 2, function() { strictEqual(_.isUndefined(), true); strictEqual(_.isUndefined(undefined), true); }); test('should return `false` for non `undefined` values', 13, function() { var expected = _.map(falsey, function(value) { return value === undefined; }); var actual = _.map(falsey, function(value, index) { return index ? _.isUndefined(value) : _.isUndefined(); }); deepEqual(actual, expected); strictEqual(_.isUndefined(args), false); strictEqual(_.isUndefined([1, 2, 3]), false); strictEqual(_.isUndefined(true), false); strictEqual(_.isUndefined(new Date), false); strictEqual(_.isUndefined(new Error), false); strictEqual(_.isUndefined(_), false); strictEqual(_.isUndefined(slice), false); strictEqual(_.isUndefined({ 'a': 1 }), false); strictEqual(_.isUndefined(1), false); strictEqual(_.isUndefined(NaN), false); strictEqual(_.isUndefined(/x/), false); strictEqual(_.isUndefined('a'), false); }); test('should work with `undefined` from another realm', 1, function() { if (_._object) { strictEqual(_.isUndefined(_._undefined), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('isType checks'); (function() { test('should return `false` for subclassed values', 8, function() { var funcs = [ 'isArray', 'isBoolean', 'isDate', 'isError', 'isFunction', 'isNumber', 'isRegExp', 'isString' ]; _.each(funcs, function(methodName) { function Foo() {} Foo.prototype = root[methodName.slice(2)].prototype; var object = new Foo; if (objToString.call(object) == objectTag) { strictEqual(_[methodName](object), false, '`_.' + methodName + '` returns `false`'); } else { skipTest(); } }); }); test('should not error on host objects (test in IE)', 15, function() { var funcs = [ 'isArguments', 'isArray', 'isBoolean', 'isDate', 'isElement', 'isError', 'isFinite', 'isFunction', 'isNaN', 'isNull', 'isNumber', 'isObject', 'isRegExp', 'isString', 'isUndefined' ]; _.each(funcs, function(methodName) { if (xml) { var pass = true; try { _[methodName](xml); } catch(e) { pass = false; } ok(pass, '`_.' + methodName + '` should not error'); } else { skipTest(); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('keys methods'); _.each(['keys', 'keysIn'], function(methodName) { var args = arguments, func = _[methodName], isKeys = methodName == 'keys'; test('`_.' + methodName + '` should return the keys of an object', 1, function() { deepEqual(func({ 'a': 1, 'b': 1 }).sort(), ['a', 'b']); }); test('`_.' + methodName + '` should coerce primitives to objects (test in IE 9)', 2, function() { deepEqual(func('abc').sort(), ['0', '1', '2']); if (!isKeys) { // IE 9 doesn't box numbers in for-in loops. Number.prototype.a = 1; deepEqual(func(0).sort(), ['a']); delete Number.prototype.a; } else { skipTest(); } }); test('`_.' + methodName + '` should treat sparse arrays as dense', 1, function() { var array = [1]; array[2] = 3; deepEqual(func(array).sort(), ['0', '1', '2']); }); test('`_.' + methodName + '` should return an empty array for `null` or `undefined` values', 2, function() { objectProto.a = 1; _.each([null, undefined], function(value) { deepEqual(func(value), []); }); delete objectProto.a; }); test('`_.' + methodName + '` should return keys for custom properties on arrays', 1, function() { var array = [1]; array.a = 1; deepEqual(func(array).sort(), ['0', 'a']); }); test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties of arrays', 1, function() { var expected = isKeys ? ['0'] : ['0', 'a']; arrayProto.a = 1; deepEqual(func([1]).sort(), expected); delete arrayProto.a; }); test('`_.' + methodName + '` should work with `arguments` objects (test in IE < 9)', 1, function() { if (!(isPhantom || isStrict)) { deepEqual(func(args).sort(), ['0', '1', '2']); } else { skipTest(); } }); test('`_.' + methodName + '` should return keys for custom properties on `arguments` objects', 1, function() { if (!(isPhantom || isStrict)) { args.a = 1; deepEqual(func(args).sort(), ['0', '1', '2', 'a']); delete args.a; } else { skipTest(); } }); test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties of `arguments` objects', 1, function() { if (!(isPhantom || isStrict)) { var expected = isKeys ? ['0', '1', '2'] : ['0', '1', '2', 'a']; objectProto.a = 1; deepEqual(func(args).sort(), expected); delete objectProto.a; } else { skipTest(); } }); test('`_.' + methodName + '` should work with string objects (test in IE < 9)', 1, function() { deepEqual(func(Object('abc')).sort(), ['0', '1', '2']); }); test('`_.' + methodName + '` should return keys for custom properties on string objects', 1, function() { var object = Object('a'); object.a = 1; deepEqual(func(object).sort(), ['0', 'a']); }); test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties of string objects', 1, function() { var expected = isKeys ? ['0'] : ['0', 'a']; stringProto.a = 1; deepEqual(func(Object('a')).sort(), expected); delete stringProto.a; }); test('`_.' + methodName + '` fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 3, function() { function Foo() {} Foo.prototype = _.create(shadowObject); deepEqual(func(shadowObject).sort(), shadowProps); var actual = isKeys ? [] : _.without(shadowProps, 'constructor'); deepEqual(func(new Foo).sort(), actual); Foo.prototype.constructor = Foo; deepEqual(func(new Foo).sort(), actual); }); test('`_.' + methodName + '` skips non-enumerable properties (test in IE < 9)', 50, function() { _.forOwn({ 'Array': arrayProto, 'Boolean': Boolean.prototype, 'Date': Date.prototype, 'Error': errorProto, 'Function': funcProto, 'Object': objectProto, 'Number': Number.prototype, 'TypeError': TypeError.prototype, 'RegExp': RegExp.prototype, 'String': stringProto }, function(proto, key) { _.each([proto, _.create(proto)], function(object, index) { var actual = func(proto), isErr = _.endsWith(key, 'Error'), message = 'enumerable properties ' + (index ? 'inherited from' : 'on') + ' `' + key + '.prototype`', props = isErr ? ['constructor', 'toString'] : ['constructor']; actual = isErr ? _.difference(props, actual) : actual; strictEqual(_.isEmpty(actual), !isErr, 'skips non-' + message); proto.a = 1; actual = func(object); delete proto.a; strictEqual(_.includes(actual, 'a'), !(isKeys && index), 'includes ' + message); if (index) { object.constructor = 1; if (isErr) { object.toString = 2; } actual = func(object); ok(_.isEmpty(_.difference(props, actual)), 'includes properties on objects that shadow those on `' + key + '.prototype`'); } }); }); }); test('`_.' + methodName + '` skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', 2, function() { function Foo() {} Foo.a = 1; Foo.prototype.b = 2; var expected = ['a']; deepEqual(func(Foo).sort(), expected); Foo.prototype = { 'b': 2 }; deepEqual(func(Foo).sort(), expected); }); test('`_.' + methodName + '` skips the `constructor` property on prototype objects', 3, function() { function Foo() {} Foo.prototype.a = 1; var expected = ['a']; deepEqual(func(Foo.prototype), expected); Foo.prototype = { 'constructor': Foo, 'a': 1 }; deepEqual(func(Foo.prototype), expected); var Fake = { 'prototype': {} }; Fake.prototype.constructor = Fake; deepEqual(func(Fake.prototype), ['constructor']); }); test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var expected = isKeys ? ['a'] : ['a', 'b']; deepEqual(func(new Foo).sort(), expected); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.last'); (function() { var array = [1, 2, 3]; test('should return the last element', 1, function() { strictEqual(_.last(array), 3); }); test('should return `undefined` when querying empty arrays', 1, function() { var array = []; array['-1'] = 1; strictEqual(_.last([]), undefined); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.last); deepEqual(actual, [3, 6, 9]); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_(array).last(), 3); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain().last() instanceof _); } else { skipTest(); } }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 3, 4]; var wrapped = _(array).filter(function(value) { return value % 2; }); strictEqual(wrapped.last(), 3); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.lastIndexOf'); (function() { var array = [1, 2, 3, 1, 2, 3]; test('should return the index of the last matched value', 1, function() { strictEqual(_.lastIndexOf(array, 3), 5); }); test('should work with a positive `fromIndex`', 1, function() { strictEqual(_.lastIndexOf(array, 1, 2), 0); }); test('should work with `fromIndex` >= `array.length`', 1, function() { var values = [6, 8, Math.pow(2, 32), Infinity], expected = _.map(values, _.constant([-1, 3, -1])); var actual = _.map(values, function(fromIndex) { return [ _.lastIndexOf(array, undefined, fromIndex), _.lastIndexOf(array, 1, fromIndex), _.lastIndexOf(array, '', fromIndex) ]; }); deepEqual(actual, expected); }); test('should treat falsey `fromIndex` values, except `0` and `NaN`, as `array.length`', 1, function() { var expected = _.map(falsey, function(value) { return typeof value == 'number' ? -1 : 5; }); var actual = _.map(falsey, function(fromIndex) { return _.lastIndexOf(array, 3, fromIndex); }); deepEqual(actual, expected); }); test('should perform a binary search when `fromIndex` is a non-number truthy value', 1, function() { var sorted = [4, 4, 5, 5, 6, 6], values = [true, '1', {}], expected = _.map(values, _.constant(3)); var actual = _.map(values, function(value) { return _.lastIndexOf(sorted, 5, value); }); deepEqual(actual, expected); }); test('should work with a negative `fromIndex`', 1, function() { strictEqual(_.lastIndexOf(array, 2, -3), 1); }); test('should work with a negative `fromIndex` <= `-array.length`', 1, function() { var values = [-6, -8, -Infinity], expected = _.map(values, _.constant(0)); var actual = _.map(values, function(fromIndex) { return _.lastIndexOf(array, 1, fromIndex); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('indexOf methods'); _.each(['indexOf', 'lastIndexOf'], function(methodName) { var func = _[methodName], isIndexOf = methodName == 'indexOf'; test('`_.' + methodName + '` should accept a falsey `array` argument', 1, function() { var expected = _.map(falsey, _.constant(-1)); var actual = _.map(falsey, function(value, index) { try { return index ? func(value) : func(); } catch(e) {} }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should return `-1` for an unmatched value', 4, function() { var array = [1, 2, 3], empty = []; strictEqual(func(array, 4), -1); strictEqual(func(array, 4, true), -1); strictEqual(func(empty, undefined), -1); strictEqual(func(empty, undefined, true), -1); }); test('`_.' + methodName + '` should not match values on empty arrays', 2, function() { var array = []; array[-1] = 0; strictEqual(func(array, undefined), -1); strictEqual(func(array, 0, true), -1); }); test('`_.' + methodName + '` should match `NaN`', 4, function() { var array = [1, NaN, 3, NaN, 5, NaN]; strictEqual(func(array, NaN), isIndexOf ? 1 : 5); strictEqual(func(array, NaN, 2), isIndexOf ? 3 : 1); strictEqual(func(array, NaN, -2), isIndexOf ? 5 : 3); strictEqual(func([1, 2, NaN, NaN], NaN, true), isIndexOf ? 2 : 3); }); test('`_.' + methodName + '` should match `-0` as `0`', 1, function() { strictEqual(func([-0], 0), 0); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.map'); (function() { var array = [1, 2, 3]; test('should map values in `collection` to a new array', 2, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }, expected = ['1', '2', '3']; deepEqual(_.map(array, String), expected); deepEqual(_.map(object, String), expected); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.map(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 2, function() { var callback = function(num, index) { return this[index] + num; }, actual = _.map([1], callback, [2]); deepEqual(actual, [3]); actual = _.map({ 'a': 1 }, callback, { 'a': 2 }); deepEqual(actual, [3]); }); test('should work with a "_.property" style `iteratee`', 1, function() { var objects = [{ 'a': 'x' }, { 'a': 'y' }]; deepEqual(_.map(objects, 'a'), ['x', 'y']); }); test('should iterate over own properties of objects', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var actual = _.map(new Foo, function(value, key) { return key; }); deepEqual(actual, ['a']); }); test('should work on an object with no `iteratee`', 1, function() { var actual = _.map({ 'a': 1, 'b': 2, 'c': 3 }); deepEqual(actual, array); }); test('should handle object arguments with non-numeric length properties', 1, function() { var value = { 'value': 'x' }, object = { 'length': { 'value': 'x' } }; deepEqual(_.map(object, _.identity), [value]); }); test('should treat a nodelist as an array-like object', 1, function() { if (document) { var actual = _.map(document.getElementsByTagName('body'), function(element) { return element.nodeName.toLowerCase(); }); deepEqual(actual, ['body']); } else { skipTest(); } }); test('should accept a falsey `collection` argument', 1, function() { var expected = _.map(falsey, _.constant([])); var actual = _.map(falsey, function(value, index) { try { return index ? _.map(value) : _.map(); } catch(e) {} }); deepEqual(actual, expected); }); test('should treat number values for `collection` as empty', 1, function() { deepEqual(_.map(1), []); }); test('should return a wrapped value when chaining', 1, function() { if (!isNpm) { ok(_(array).map(_.noop) instanceof _); } else { skipTest(); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [1, 0, [1, 4, 9]]; _(array).map(function(value, index, array) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, [1, 0, array]); args = null; _(array).map(square).map(function(value, index, array) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); args = null; _(array).map(square).map(function(value, index) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); args = null; _(array).map(square).map(function(value) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, [1]); args = null; _(array).map(square).map(function() { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); test('should be aliased', 1, function() { strictEqual(_.collect, _.map); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.mapValues'); (function() { var array = [1, 2], object = { 'a': 1, 'b': 2, 'c': 3 }; test('should map values in `object` to a new object', 1, function() { var actual = _.mapValues(object, String); deepEqual(actual, { 'a': '1', 'b': '2', 'c': '3' }); }); test('should treat arrays like objects', 1, function() { var actual = _.mapValues(array, String); deepEqual(actual, { '0': '1', '1': '2' }); }); test('should provide the correct `iteratee` arguments', 2, function() { _.each([object, array], function(value, index) { var args; _.mapValues(value, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, index ? '0' : 'a', value]); }); }); test('should support the `thisArg` argument', 2, function() { function callback(num, key) { return this[key] + num; } var actual = _.mapValues({ 'a': 1 }, callback, { 'a': 2 }); deepEqual(actual, { 'a': 3 }); actual = _.mapValues([1], callback, [2]); deepEqual(actual, { '0': 3 }); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.mapValues({ 'a': { 'b': 1 } }, 'b'); deepEqual(actual, { 'a': 1 }); }); test('should iterate over own properties of objects', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var actual = _.mapValues(new Foo, function(value, key) { return key; }); deepEqual(actual, { 'a': 'a' }); }); test('should work on an object with no `iteratee`', 2, function() { var actual = _.mapValues({ 'a': 1, 'b': 2, 'c': 3 }); deepEqual(actual, object); notStrictEqual(actual, object); }); test('should accept a falsey `object` argument', 1, function() { var expected = _.map(falsey, _.constant({})); var actual = _.map(falsey, function(value, index) { try { return index ? _.mapValues(value) : _.mapValues(); } catch(e) {} }); deepEqual(actual, expected); }); test('should return a wrapped value when chaining', 1, function() { if (!isNpm) { ok(_(object).mapValues(_.noop) instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.matches'); (function() { test('should create a function that performs a deep comparison between a given object and `source`', 6, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }, matches = _.matches({ 'a': 1 }); strictEqual(matches.length, 1); strictEqual(matches(object), true); matches = _.matches({ 'b': 1 }); strictEqual(matches(object), false); matches = _.matches({ 'a': 1, 'c': 3 }); strictEqual(matches(object), true); matches = _.matches({ 'c': 3, 'd': 4 }); strictEqual(matches(object), false); object = { 'a': { 'b': { 'c': 1, 'd': 2 }, 'e': 3 }, 'f': 4 }; matches = _.matches({ 'a': { 'b': { 'c': 1 } } }); strictEqual(matches(object), true); }); test('should compare a variety of `source` values', 2, function() { var object1 = { 'a': false, 'b': true, 'c': '3', 'd': 4, 'e': [5], 'f': { 'g': 6 } }, object2 = { 'a': 0, 'b': 1, 'c': 3, 'd': '4', 'e': ['5'], 'f': { 'g': '6' } }, matches = _.matches(object1); strictEqual(matches(object1), true); strictEqual(matches(object2), false); }); test('should not change match behavior if `source` is augmented', 9, function() { _.each([{ 'a': { 'b': 2, 'c': 3 } }, { 'a': 1, 'b': 2 }, { 'a': 1 }], function(source, index) { var object = _.cloneDeep(source), matches = _.matches(source); strictEqual(matches(object), true); if (index) { source.a = 2; source.b = 1; source.c = 3; } else { source.a.b = 1; source.a.c = 2; source.a.d = 3; } strictEqual(matches(object), true); strictEqual(matches(source), false); }); }); test('should return `true` when comparing an empty `source`', 1, function() { var object = { 'a': 1 }, expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { var matches = _.matches(value); return matches(object); }); deepEqual(actual, expected); }); test('should return `true` when comparing a `source` of empty arrays and objects', 1, function() { var objects = [{ 'a': [1], 'b': { 'c': 1 } }, { 'a': [2, 3], 'b': { 'd': 2 } }], matches = _.matches({ 'a': [], 'b': {} }), actual = _.filter(objects, matches); deepEqual(actual, objects); }); test('should not error for falsey `object` values', 1, function() { var expected = _.map(falsey, _.constant(false)), matches = _.matches({ 'a': 1 }); var actual = _.map(falsey, function(value, index) { try { return index ? matches(value) : matches(); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `true` when comparing an empty `source` to a falsey `object`', 1, function() { var expected = _.map(falsey, _.constant(true)), matches = _.matches({}); var actual = _.map(falsey, function(value, index) { try { return index ? matches(value) : matches(); } catch(e) {} }); deepEqual(actual, expected); }); test('should search arrays of `source` for values', 3, function() { var objects = [{ 'a': ['b'] }, { 'a': ['c', 'd'] }], matches = _.matches({ 'a': ['d'] }), actual = _.filter(objects, matches); deepEqual(actual, [objects[1]]); matches = _.matches({ 'a': ['b', 'd'] }); actual = _.filter(objects, matches); deepEqual(actual, []); matches = _.matches({ 'a': ['d', 'b'] }); actual = _.filter(objects, matches); deepEqual(actual, []); }); test('should perform a partial comparison of all objects within arrays of `source`', 1, function() { var objects = [ { 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 5, 'd': 6 }] }, { 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 6, 'd': 7 }] } ]; var matches = _.matches({ 'a': [{ 'b': 1 }, { 'b': 4, 'c': 5 }] }), actual = _.filter(objects, matches); deepEqual(actual, [objects[0]]); }); test('should handle a `source` with `undefined` values', 2, function() { var matches = _.matches({ 'b': undefined }), objects = [{ 'a': 1 }, { 'a': 1, 'b': 1 }, { 'a': 1, 'b': undefined }], actual = _.map(objects, matches), expected = [false, false, true]; deepEqual(actual, expected); matches = _.matches({ 'a': { 'c': undefined } }); objects = [{ 'a': { 'b': 1 } }, { 'a':{ 'b':1, 'c': 1 } }, { 'a': { 'b': 1, 'c': undefined } }]; actual = _.map(objects, matches); deepEqual(actual, expected); }); test('should not match by inherited `source` properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var objects = [{ 'a': 1 }, { 'a': 1, 'b': 2 }], source = new Foo, matches = _.matches(source), actual = _.map(objects, matches), expected = _.map(objects, _.constant(true)); deepEqual(actual, expected); }); test('should work with a function for `source`', 1, function() { function source() {} source.a = 1; source.b = function() {}; source.c = 3; var matches = _.matches(source), objects = [{ 'a': 1 }, { 'a': 1, 'b': source.b, 'c': 3 }], actual = _.map(objects, matches); deepEqual(actual, [false, true]); }); test('should match problem JScript properties (test in IE < 9)', 1, function() { var matches = _.matches(shadowObject), objects = [{}, shadowObject], actual = _.map(objects, matches); deepEqual(actual, [false, true]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.matchesProperty'); (function() { test('should create a function that performs a deep comparison between a property value and `value`', 6, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }, matches = _.matchesProperty('a', 1); strictEqual(matches.length, 1); strictEqual(matches(object), true); matches = _.matchesProperty('b', 3); strictEqual(matches(object), false); matches = _.matchesProperty('a', { 'a': 1, 'c': 3 }); strictEqual(matches({ 'a': object }), true); matches = _.matchesProperty('a', { 'c': 3, 'd': 4 }); strictEqual(matches(object), false); object = { 'a': { 'b': { 'c': 1, 'd': 2 }, 'e': 3 }, 'f': 4 }; matches = _.matchesProperty('a', { 'b': { 'c': 1 } }); strictEqual(matches(object), true); }); test('should compare a variety of values', 2, function() { var object1 = { 'a': false, 'b': true, 'c': '3', 'd': 4, 'e': [5], 'f': { 'g': 6 } }, object2 = { 'a': 0, 'b': 1, 'c': 3, 'd': '4', 'e': ['5'], 'f': { 'g': '6' } }, matches = _.matchesProperty('a', object1); strictEqual(matches({ 'a': object1 }), true); strictEqual(matches({ 'a': object2 }), false); }); test('should not change match behavior if `value` is augmented', 9, function() { _.each([{ 'a': { 'b': 2, 'c': 3 } }, { 'a': 1, 'b': 2 }, { 'a': 1 }], function(source, index) { var object = _.cloneDeep(source), matches = _.matchesProperty('a', source); strictEqual(matches({ 'a': object }), true); if (index) { source.a = 2; source.b = 1; source.c = 3; } else { source.a.b = 1; source.a.c = 2; source.a.d = 3; } strictEqual(matches({ 'a': object }), true); strictEqual(matches({ 'a': source }), false); }); }); test('should return `true` when comparing a `value` of empty arrays and objects', 1, function() { var objects = [{ 'a': [1], 'b': { 'c': 1 } }, { 'a': [2, 3], 'b': { 'd': 2 } }], matches = _.matchesProperty('a', { 'a': [], 'b': {} }); var actual = _.filter(objects, function(object) { return matches({ 'a': object }); }); deepEqual(actual, objects); }); test('should not error for falsey `object` values', 1, function() { var expected = _.map(falsey, _.constant(false)), matches = _.matchesProperty('a', 1); var actual = _.map(falsey, function(value, index) { try { return index ? matches(value) : matches(); } catch(e) {} }); deepEqual(actual, expected); }); test('should search arrays of `value` for values', 3, function() { var objects = [{ 'a': ['b'] }, { 'a': ['c', 'd'] }], matches = _.matchesProperty('a', ['d']), actual = _.filter(objects, matches); deepEqual(actual, [objects[1]]); matches = _.matchesProperty('a', ['b', 'd']); actual = _.filter(objects, matches); deepEqual(actual, []); matches = _.matchesProperty('a', ['d', 'b']); actual = _.filter(objects, matches); deepEqual(actual, []); }); test('should perform a partial comparison of all objects within arrays of `value`', 1, function() { var objects = [ { 'a': [{ 'a': 1, 'b': 2 }, { 'a': 4, 'b': 5, 'c': 6 }] }, { 'a': [{ 'a': 1, 'b': 2 }, { 'a': 4, 'b': 6, 'c': 7 }] } ]; var matches = _.matchesProperty('a', [{ 'a': 1 }, { 'a': 4, 'b': 5 }]), actual = _.filter(objects, matches); deepEqual(actual, [objects[0]]); }); test('should handle a `value` with `undefined` values', 2, function() { var matches = _.matchesProperty('b', undefined), objects = [{ 'a': 1 }, { 'a': 1, 'b': 1 }, { 'a': 1, 'b': undefined }], actual = _.map(objects, matches); deepEqual(actual, [true, false, true]); matches = _.matchesProperty('a', { 'b': undefined }); objects = [{ 'a': { 'a': 1 } }, { 'a': { 'a': 1, 'b': 1 } }, { 'a': { 'a': 1, 'b': undefined } }]; actual = _.map(objects, matches); deepEqual(actual, [false, false, true]); }); test('should not match by inherited `value` properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var objects = [{ 'a': { 'a': 1 } }, { 'a': { 'a': 1, 'b': 2 } }], source = new Foo, matches = _.matchesProperty('a', source), actual = _.map(objects, matches), expected = _.map(objects, _.constant(true)); deepEqual(actual, expected); }); test('should work with a function for `value`', 1, function() { function source() {} source.a = 1; source.b = function() {}; source.c = 3; var matches = _.matchesProperty('a', source), objects = [{ 'a': { 'a': 1 } }, { 'a': { 'a': 1, 'b': source.b, 'c': 3 } }], actual = _.map(objects, matches); deepEqual(actual, [false, true]); }); test('should match problem JScript properties (test in IE < 9)', 1, function() { var matches = _.matchesProperty('a', shadowObject), objects = [{ 'a': {} }, { 'a': shadowObject }], actual = _.map(objects, matches); deepEqual(actual, [false, true]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.max'); (function() { test('should return the largest value from a collection', 1, function() { strictEqual(_.max([1, 2, 3]), 3); }); test('should return `-Infinity` for empty collections', 1, function() { var expected = _.map(empties, _.constant(-Infinity)); var actual = _.map(empties, function(value) { try { return _.max(value); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `-Infinity` for non-numeric collection values', 1, function() { var collections = [['a', 'b'], { 'a': 'a', 'b': 'b' }], expected = _.map(collections, _.constant(-Infinity)); var actual = _.map(collections, function(value) { try { return _.max(value); } catch(e) {} }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.memoize'); (function() { test('should memoize results based on the first argument provided', 2, function() { var memoized = _.memoize(function(a, b, c) { return a + b + c; }); strictEqual(memoized(1, 2, 3), 6); strictEqual(memoized(1, 3, 5), 6); }); test('should support a `resolver` argument', 2, function() { var fn = function(a, b, c) { return a + b + c; }, memoized = _.memoize(fn, fn); strictEqual(memoized(1, 2, 3), 6); strictEqual(memoized(1, 3, 5), 9); }); test('should not set a `this` binding', 2, function() { var memoized = _.memoize(function(a, b, c) { return a + this.b + this.c; }); var object = { 'b': 2, 'c': 3, 'memoized': memoized }; strictEqual(object.memoized(1), 6); strictEqual(object.memoized(2), 7); }); test('should throw a TypeError if `resolve` is truthy and not a function', function() { raises(function() { _.memoize(_.noop, {}); }, TypeError); }); test('should not error if `resolve` is falsey', function() { var expected = _.map(falsey, _.constant(true)); var actual = _.map(falsey, function(value, index) { try { return _.isFunction(index ? _.memoize(_.noop, value) : _.memoize(_.noop)); } catch(e) {} }); deepEqual(actual, expected); }); test('should check cache for own properties', 1, function() { var actual = [], memoized = _.memoize(_.identity); _.each(shadowProps, function(value) { actual.push(memoized(value)); }); deepEqual(actual, shadowProps); }); test('should expose a `cache` object on the `memoized` function which implements `Map` interface', 18, function() { _.times(2, function(index) { var resolver = index ? _.identity : null, memoized = _.memoize(function(value) { return 'value:' + value; }, resolver), cache = memoized.cache; memoized('a'); strictEqual(cache.has('a'), true); strictEqual(cache.get('a'), 'value:a'); strictEqual(cache['delete']('a'), true); strictEqual(cache['delete']('b'), false); strictEqual(cache.set('b', 'value:b'), cache); strictEqual(cache.has('b'), true); strictEqual(cache.get('b'), 'value:b'); strictEqual(cache['delete']('b'), true); strictEqual(cache['delete']('a'), false); }); }); test('should skip the `__proto__` key', 8, function() { _.times(2, function(index) { var count = 0, key = '__proto__', resolver = index && _.identity; var memoized = _.memoize(function() { count++; return []; }, resolver); var cache = memoized.cache; memoized(key); memoized(key); strictEqual(count, 2); strictEqual(cache.get(key), undefined); strictEqual(cache['delete'](key), false); ok(!(cache.__data__ instanceof Array)); }); }); test('should allow `_.memoize.Cache` to be customized', 4, function() { var oldCache = _.memoize.Cache function Cache() { this.__data__ = []; } Cache.prototype = { 'delete': function(key) { var data = this.__data__; var index = _.findIndex(data, function(entry) { return key === entry.key; }); if (index < 0) { return false; } data.splice(index, 1); return true; }, 'get': function(key) { return _.find(this.__data__, function(entry) { return key === entry.key; }).value; }, 'has': function(key) { return _.some(this.__data__, function(entry) { return key === entry.key; }); }, 'set': function(key, value) { this.__data__.push({ 'key': key, 'value': value }); } }; _.memoize.Cache = Cache; var memoized = _.memoize(function(object) { return '`id` is "' + object.id + '"'; }); var actual = memoized({ 'id': 'a' }); strictEqual(actual, '`id` is "a"'); var key = { 'id': 'b' }; actual = memoized(key); strictEqual(actual, '`id` is "b"'); var cache = memoized.cache; strictEqual(cache.has(key), true); cache['delete'](key); strictEqual(cache.has(key), false); _.memoize.Cache = oldCache; }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.merge'); (function() { var args = arguments; test('should merge `source` into the destination object', 1, function() { var names = { 'characters': [ { 'name': 'barney' }, { 'name': 'fred' } ] }; var ages = { 'characters': [ { 'age': 36 }, { 'age': 40 } ] }; var heights = { 'characters': [ { 'height': '5\'4"' }, { 'height': '5\'5"' } ] }; var expected = { 'characters': [ { 'name': 'barney', 'age': 36, 'height': '5\'4"' }, { 'name': 'fred', 'age': 40, 'height': '5\'5"' } ] }; deepEqual(_.merge(names, ages, heights), expected); }); test('should merge sources containing circular references', 1, function() { var object = { 'foo': { 'a': 1 }, 'bar': { 'a': 2 } }; var source = { 'foo': { 'b': { 'c': { 'd': {} } } }, 'bar': {} }; source.foo.b.c.d = source; source.bar.b = source.foo.b; var actual = _.merge(object, source); ok(actual.bar.b === actual.foo.b && actual.foo.b.c.d === actual.foo.b.c.d.foo.b.c.d); }); test('should treat sources that are sparse arrays as dense', 2, function() { var array = Array(3); array[0] = 1; array[2] = 3; var actual = _.merge([], array), expected = array.slice(); expected[1] = undefined; ok('1' in actual); deepEqual(actual, expected); }); test('should merge `arguments` objects', 3, function() { var object1 = { 'value': args }, object2 = { 'value': { '3': 4 } }, expected = { '0': 1, '1': 2, '2': 3, '3': 4 }, actual = _.merge(object1, object2); ok(!_.isArguments(actual.value)); deepEqual(actual.value, expected); delete object1.value[3]; actual = _.merge(object2, object1); deepEqual(actual.value, expected); }); test('should merge typed arrays', 4, function() { var array1 = [0], array2 = [0, 0], array3 = [0, 0, 0, 0], array4 = _.range(0, 8, 0); var arrays = [array2, array1, array4, array3, array2, array4, array4, array3, array2], buffer = ArrayBuffer && new ArrayBuffer(8); // juggle for `Float64Array` shim if (root.Float64Array && (new Float64Array(buffer)).length == 8) { arrays[1] = array4; } var expected = _.map(typedArrays, function(type, index) { var array = arrays[index].slice(); array[0] = 1; return root[type] ? { 'value': array } : false; }); var actual = _.map(typedArrays, function(type) { var Ctor = root[type]; return Ctor ? _.merge({ 'value': new Ctor(buffer) }, { 'value': [1] }) : false; }); ok(_.isArray(actual)); deepEqual(actual, expected); expected = _.map(typedArrays, function(type, index) { var array = arrays[index].slice(); array.push(1); return root[type] ? { 'value': array } : false; }); actual = _.map(typedArrays, function(type, index) { var Ctor = root[type], array = _.range(arrays[index].length); array.push(1); return Ctor ? _.merge({ 'value': array }, { 'value': new Ctor(buffer) }) : false; }); ok(_.isArray(actual)); deepEqual(actual, expected); }); test('should work with four arguments', 1, function() { var expected = { 'a': 4 }; deepEqual(_.merge({ 'a': 1 }, { 'a': 2 }, { 'a': 3 }, expected), expected); }); test('should assign `null` values', 1, function() { var actual = _.merge({ 'a': 1 }, { 'a': null }); strictEqual(actual.a, null); }); test('should not assign `undefined` values', 1, function() { var actual = _.merge({ 'a': 1 }, { 'a': undefined, 'b': undefined }); deepEqual(actual, { 'a': 1 }); }); test('should not not error on DOM elements', 1, function() { var object1 = { 'el': document && document.createElement('div') }, object2 = { 'el': document && document.createElement('div') }, pairs = [[{}, object1], [object1, object2]], expected = _.map(pairs, _.constant(true)); var actual = _.map(pairs, function(pair) { try { return _.merge(pair[0], pair[1]).el === pair[1].el; } catch(e) {} }); deepEqual(actual, expected); }); test('should assign non array/plain-object values directly', 1, function() { function Foo() {} var values = [new Foo, new Boolean, new Date, Foo, new Number, new String, new RegExp], expected = _.map(values, _.constant(true)); var actual = _.map(values, function(value) { var object = _.merge({}, { 'a': value }); return object.a === value; }); deepEqual(actual, expected); }); test('should work with a function `object` value', 2, function() { function Foo() {} var source = { 'a': 1 }, actual = _.merge(Foo, source); strictEqual(actual, Foo); strictEqual(Foo.a, 1); }); test('should work with a non-plain `object` value', 2, function() { function Foo() {} var object = new Foo, source = { 'a': 1 }, actual = _.merge(object, source); strictEqual(actual, object); strictEqual(object.a, 1); }); test('should pass thru primitive `object` values', 1, function() { var values = [true, 1, '1']; var actual = _.map(values, function(value) { return _.merge(value, { 'a': 1 }); }); deepEqual(actual, values); }); test('should handle merging if `customizer` returns `undefined`', 2, function() { var actual = _.merge({ 'a': { 'b': [1, 1] } }, { 'a': { 'b': [0] } }, _.noop); deepEqual(actual, { 'a': { 'b': [0, 1] } }); actual = _.merge([], [undefined], _.identity); deepEqual(actual, [undefined]); }); test('should defer to `customizer` when it returns a value other than `undefined`', 1, function() { var actual = _.merge({ 'a': { 'b': [0, 1] } }, { 'a': { 'b': [2] } }, function(a, b) { return _.isArray(a) ? a.concat(b) : undefined; }); deepEqual(actual, { 'a': { 'b': [0, 1, 2] } }); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.min'); (function() { test('should return the smallest value from a collection', 1, function() { strictEqual(_.min([1, 2, 3]), 1); }); test('should return `Infinity` for empty collections', 1, function() { var expected = _.map(empties, _.constant(Infinity)); var actual = _.map(empties, function(value) { try { return _.min(value); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `Infinity` for non-numeric collection values', 1, function() { var collections = [['a', 'b'], { 'a': 'a', 'b': 'b' }], expected = _.map(collections, _.constant(Infinity)); var actual = _.map(collections, function(value) { try { return _.min(value); } catch(e) {} }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('extremum methods'); _.each(['max', 'min'], function(methodName) { var array = [1, 2, 3], func = _[methodName], isMax = methodName == 'max'; test('`_.' + methodName + '` should work with Date objects', 1, function() { var curr = new Date, past = new Date(0); strictEqual(func([curr, past]), isMax ? curr : past); }); test('`_.' + methodName + '` should work with an `iteratee` argument', 1, function() { var actual = func(array, function(num) { return -num; }); strictEqual(actual, isMax ? 1 : 3); }); test('`_.' + methodName + '` should provide the correct `iteratee` arguments when iterating an array', 1, function() { var args; func(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 0, array]); }); test('`_.' + methodName + '` should provide the correct `iteratee` arguments when iterating an object', 1, function() { var args, object = { 'a': 1, 'b': 2 }, firstKey = _.first(_.keys(object)); var expected = firstKey == 'a' ? [1, 'a', object] : [2, 'b', object]; func(object, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, expected); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func(array, function(num, index) { return -this[index]; }, array); strictEqual(actual, isMax ? 1 : 3); }); test('should work with a "_.property" style `iteratee`', 2, function() { var objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }], actual = func(objects, 'a'); deepEqual(actual, objects[isMax ? 1 : 2]); var arrays = [[2], [3], [1]]; actual = func(arrays, 0); deepEqual(actual, arrays[isMax ? 1 : 2]); }); test('`_.' + methodName + '` should work when `iteratee` returns +/-Infinity', 1, function() { var value = isMax ? -Infinity : Infinity, object = { 'a': value }; var actual = func([object, { 'a': value }], function(object) { return object.a; }); strictEqual(actual, object); }); test('`_.' + methodName + '` should iterate an object', 1, function() { var actual = func({ 'a': 1, 'b': 2, 'c': 3 }); strictEqual(actual, isMax ? 3 : 1); }); test('`_.' + methodName + '` should iterate a string', 2, function() { _.each(['abc', Object('abc')], function(value) { var actual = func(value); strictEqual(actual, isMax ? 'c' : 'a'); }); }); test('`_.' + methodName + '` should work with extremely large arrays', 1, function() { var array = _.range(0, 5e5); strictEqual(func(array), isMax ? 499999 : 0); }); test('`_.' + methodName + '` should work as an iteratee for `_.map`', 3, function() { var arrays = [[2, 1], [5, 4], [7, 8]], objects = [{ 'a': 2, 'b': 1 }, { 'a': 5, 'b': 4 }, { 'a': 7, 'b': 8 }], expected = isMax ? [2, 5, 8] : [1, 4, 7]; deepEqual(_.map(arrays, func), expected); deepEqual(_.map(objects, func), expected); deepEqual(_.map('abc', func), ['a', 'b', 'c']); }); test('`_.' + methodName + '` should work when chaining on an array with only one value', 1, function() { if (!isNpm) { var actual = _([40])[methodName](); strictEqual(actual, 40); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.mixin'); (function() { function Wrapper(value) { if (!(this instanceof Wrapper)) { return new Wrapper(value); } if (_.has(value, '__wrapped__')) { var actions = _.slice(value.__actions__), chain = value.__chain__; value = value.__wrapped__; } this.__actions__ = actions || []; this.__chain__ = chain || false; this.__wrapped__ = value; } Wrapper.prototype.value = function() { return getUnwrappedValue(this); }; var array = ['a'], source = { 'a': function(array) { return array[0]; }, 'b': 'B' }; test('should mixin `source` methods into lodash', 4, function() { if (!isNpm) { _.mixin(source); strictEqual(_.a(array), 'a'); strictEqual(_(array).a().value(), 'a'); delete _.a; delete _.prototype.a; ok(!('b' in _)); ok(!('b' in _.prototype)); delete _.b; delete _.prototype.b; } else { skipTest(4); } }); test('should mixin chaining methods by reference', 2, function() { if (!isNpm) { _.mixin(source); _.a = _.constant('b'); strictEqual(_.a(array), 'b'); strictEqual(_(array).a().value(), 'a'); delete _.a; delete _.prototype.a; } else { skipTest(2); } }); test('should use `this` as the default `object` value', 3, function() { var object = _.create(_); object.mixin(source); strictEqual(object.a(array), 'a'); ok(!('a' in _)); ok(!('a' in _.prototype)); delete Wrapper.a; delete Wrapper.prototype.a; delete Wrapper.b; delete Wrapper.prototype.b; }); test('should accept an `object` argument', 1, function() { var object = {}; _.mixin(object, source); strictEqual(object.a(array), 'a'); }); test('should return `object`', 2, function() { var object = {}; strictEqual(_.mixin(object, source), object); strictEqual(_.mixin(), _); }); test('should work with a function for `object`', 2, function() { _.mixin(Wrapper, source); var wrapped = Wrapper(array), actual = wrapped.a(); strictEqual(actual.value(), 'a'); ok(actual instanceof Wrapper); delete Wrapper.a; delete Wrapper.prototype.a; delete Wrapper.b; delete Wrapper.prototype.b; }); test('should not assign inherited `source` properties', 1, function() { function Foo() {} Foo.prototype.a = _.noop; deepEqual(_.mixin({}, new Foo, {}), {}); }); test('should accept an `options` argument', 16, function() { function message(func, chain) { return (func === _ ? 'lodash' : 'provided') + ' function should ' + (chain ? '' : 'not ') + 'chain'; } _.each([_, Wrapper], function(func) { _.each([false, true, { 'chain': false }, { 'chain': true }], function(options) { if (!isNpm) { if (func === _) { _.mixin(source, options); } else { _.mixin(func, source, options); } var wrapped = func(array), actual = wrapped.a(); if (options === true || (options && options.chain)) { strictEqual(actual.value(), 'a', message(func, true)); ok(actual instanceof func, message(func, true)); } else { strictEqual(actual, 'a', message(func, false)); ok(!(actual instanceof func), message(func, false)); } delete func.a; delete func.prototype.a; delete func.b; delete func.prototype.b; } else { skipTest(2); } }); }); }); test('should not extend lodash when an `object` is provided with an empty `options` object', 1, function() { _.mixin({ 'a': _.noop }, {}); ok(!('a' in _)); delete _.a; }); test('should not error for non-object `options` values', 2, function() { var pass = true; try { _.mixin({}, source, 1); } catch(e) { pass = false; } ok(pass); pass = true; try { _.mixin(source, 1); } catch(e) { pass = false; } delete _.a; delete _.prototype.a; delete _.b; delete _.prototype.b; ok(pass); }); test('should not return the existing wrapped value when chaining', 2, function() { _.each([_, Wrapper], function(func) { if (!isNpm) { if (func === _) { var wrapped = _(source), actual = wrapped.mixin(); strictEqual(actual.value(), _); } else { wrapped = _(func); actual = wrapped.mixin(source); notStrictEqual(actual, wrapped); } delete func.a; delete func.prototype.a; delete func.b; delete func.prototype.b; } else { skipTest(); } }); }); test('should produce methods that work in a lazy chain sequence', 1, function() { if (!isNpm) { _.mixin({ 'a': _.countBy, 'b': _.filter }); var predicate = function(value) { return value > 2; }, actual = _([1, 2, 1, 3]).a(_.identity).map(square).b(predicate).take().value(); deepEqual(actual, [4]); delete _.a; delete _.prototype.a; delete _.b; delete _.prototype.b; } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.negate'); (function() { test('should create a function that negates the result of `func`', 2, function() { var negate = _.negate(function(n) { return n % 2 == 0; }); strictEqual(negate(1), true); strictEqual(negate(2), false); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.noop'); (function() { test('should return `undefined`', 1, function() { var values = empties.concat(true, new Date, _, 1, /x/, 'a'), expected = _.map(values, _.constant()); var actual = _.map(values, function(value, index) { return index ? _.noop(value) : _.noop(); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.noConflict'); (function() { test('should return the `lodash` function', 1, function() { if (!isModularize) { var oldDash = root._; strictEqual(_.noConflict(), _); root._ = oldDash; } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.now'); (function() { asyncTest('should return the number of milliseconds that have elapsed since the Unix epoch', 2, function() { var stamp = +new Date, actual = _.now(); ok(actual >= stamp); if (!(isRhino && isModularize)) { setTimeout(function() { ok(_.now() > actual); QUnit.start(); }, 32); } else { skipTest(); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.omit'); (function() { var args = arguments, object = { 'a': 1, 'b': 2, 'c': 3 }, expected = { 'b': 2 }; test('should create an object with omitted properties', 2, function() { deepEqual(_.omit(object, 'a'), { 'b': 2, 'c': 3 }); deepEqual(_.omit(object, 'a', 'c'), expected); }); test('should support picking an array of properties', 1, function() { deepEqual(_.omit(object, ['a', 'c']), expected); }); test('should support picking an array of properties and individual properties', 1, function() { deepEqual(_.omit(object, ['a'], 'c'), expected); }); test('should iterate over inherited properties', 1, function() { function Foo() {} Foo.prototype = object; deepEqual(_.omit(new Foo, 'a', 'c'), expected); }); test('should return an empty object when `object` is `null` or `undefined`', 2, function() { objectProto.a = 1; _.each([null, undefined], function(value) { deepEqual(_.omit(value, 'valueOf'), {}); }); delete objectProto.a; }); test('should work with `arguments` objects as secondary arguments', 1, function() { deepEqual(_.omit(object, args), expected); }); test('should work with an array `object` argument', 1, function() { deepEqual(_.omit([1, 2, 3], '0', '2'), { '1': 2 }); }); test('should work with a primitive `object` argument', 1, function() { stringProto.a = 1; stringProto.b = 2; deepEqual(_.omit('', 'b'), { 'a': 1 }); delete stringProto.a; delete stringProto.b; }); test('should work with a `predicate` argument', 1, function() { var actual = _.omit(object, function(num) { return num != 2; }); deepEqual(actual, expected); }); test('should provide the correct `predicate` arguments', 1, function() { var args, object = { 'a': 1, 'b': 2 }, lastKey = _.keys(object).pop(); var expected = lastKey == 'b' ? [1, 'a', object] : [2, 'b', object]; _.omit(object, function() { args || (args = slice.call(arguments)); }); deepEqual(args, expected); }); test('should correctly set the `this` binding', 1, function() { var actual = _.omit(object, function(num) { return num != this.b; }, { 'b': 2 }); deepEqual(actual, expected); }); test('should coerce property names to strings', 1, function() { deepEqual(_.omit({ '0': 'a' }, 0), {}); }); }('a', 'c')); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.once'); (function() { test('should invoke `func` once', 2, function() { var count = 0, once = _.once(function() { return ++count; }); once(); strictEqual(once(), 1); strictEqual(count, 1); }); test('should not set a `this` binding', 2, function() { var once = _.once(function() { return ++this.count; }), object = { 'count': 0, 'once': once }; object.once(); strictEqual(object.once(), 1); strictEqual(object.count, 1); }); test('should ignore recursive calls', 2, function() { var count = 0; var once = _.once(function() { once(); return ++count; }); strictEqual(once(), 1); strictEqual(count, 1); }); test('should not throw more than once', 2, function() { var pass = true; var once = _.once(function() { throw new Error; }); raises(function() { once(); }, Error); try { once(); } catch(e) { pass = false; } ok(pass); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pad'); (function() { test('should pad a string to a given length', 1, function() { strictEqual(_.pad('abc', 9), ' abc '); }); test('should truncate pad characters to fit the pad length', 2, function() { strictEqual(_.pad('abc', 8), ' abc '); strictEqual(_.pad('abc', 8, '_-'), '_-abc_-_'); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.pad(Object('abc'), 4), 'abc '); strictEqual(_.pad({ 'toString': _.constant('abc') }, 5), ' abc '); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.padLeft'); (function() { test('should pad a string to a given length', 1, function() { strictEqual(_.padLeft('abc', 6), ' abc'); }); test('should truncate pad characters to fit the pad length', 1, function() { strictEqual(_.padLeft('abc', 6, '_-'), '_-_abc'); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.padLeft(Object('abc'), 4), ' abc'); strictEqual(_.padLeft({ 'toString': _.constant('abc') }, 5), ' abc'); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.padRight'); (function() { test('should pad a string to a given length', 1, function() { strictEqual(_.padRight('abc', 6), 'abc '); }); test('should truncate pad characters to fit the pad length', 1, function() { strictEqual(_.padRight('abc', 6, '_-'), 'abc_-_'); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.padRight(Object('abc'), 4), 'abc '); strictEqual(_.padRight({ 'toString': _.constant('abc') }, 5), 'abc '); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('pad methods'); _.each(['pad', 'padLeft', 'padRight'], function(methodName) { var func = _[methodName], isPadLeft = methodName == 'padLeft'; test('`_.' + methodName + '` should not pad is string is >= `length`', 2, function() { strictEqual(func('abc', 2), 'abc'); strictEqual(func('abc', 3), 'abc'); }); test('`_.' + methodName + '` should treat negative `length` as `0`', 2, function() { _.each([0, -2], function(length) { strictEqual(func('abc', length), 'abc'); }); }); test('`_.' + methodName + '` should coerce `length` to a number', 2, function() { _.each(['', '4'], function(length) { var actual = length ? (isPadLeft ? ' abc' : 'abc ') : 'abc'; strictEqual(func('abc', length), actual); }); }); test('`_.' + methodName + '` should return an empty string when provided `null`, `undefined`, or empty string and `chars`', 6, function() { _.each([null, '_-'], function(chars) { strictEqual(func(null, 0, chars), ''); strictEqual(func(undefined, 0, chars), ''); strictEqual(func('', 0, chars), ''); }); }); test('`_.' + methodName + '` should work with `null`, `undefined`, or empty string for `chars`', 3, function() { notStrictEqual(func('abc', 6, null), 'abc'); notStrictEqual(func('abc', 6, undefined), 'abc'); strictEqual(func('abc', 6, ''), 'abc'); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pairs'); (function() { test('should create a two dimensional array of key-value pairs', 1, function() { var object = { 'a': 1, 'b': 2 }; deepEqual(_.pairs(object), [['a', 1], ['b', 2]]); }); test('should work with an object that has a `length` property', 1, function() { var object = { '0': 'a', '1': 'b', 'length': 2 }; deepEqual(_.pairs(object), [['0', 'a'], ['1', 'b'], ['length', 2]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.parseInt'); (function() { test('should accept a `radix` argument', 1, function() { var expected = _.range(2, 37); var actual = _.map(expected, function(radix) { return _.parseInt('10', radix); }); deepEqual(actual, expected); }); test('should use a radix of `10`, for non-hexadecimals, if `radix` is `undefined` or `0`', 4, function() { strictEqual(_.parseInt('10'), 10); strictEqual(_.parseInt('10', 0), 10); strictEqual(_.parseInt('10', 10), 10); strictEqual(_.parseInt('10', undefined), 10); }); test('should use a radix of `16`, for hexadecimals, if `radix` is `undefined` or `0`', 8, function() { _.each(['0x20', '0X20'], function(string) { strictEqual(_.parseInt(string), 32); strictEqual(_.parseInt(string, 0), 32); strictEqual(_.parseInt(string, 16), 32); strictEqual(_.parseInt(string, undefined), 32); }); }); test('should use a radix of `10` for string with leading zeros', 2, function() { strictEqual(_.parseInt('08'), 8); strictEqual(_.parseInt('08', 10), 8); }); test('should parse strings with leading whitespace (test in Chrome, Firefox, and Opera)', 2, function() { var expected = [8, 8, 10, 10, 32, 32, 32, 32]; _.times(2, function(index) { var actual = [], func = (index ? (lodashBizarro || {}) : _).parseInt; if (func) { _.times(2, function(otherIndex) { var string = otherIndex ? '10' : '08'; actual.push( func(whitespace + string, 10), func(whitespace + string) ); }); _.each(['0x20', '0X20'], function(string) { actual.push( func(whitespace + string), func(whitespace + string, 16) ); }); deepEqual(actual, expected); } else { skipTest(); } }); }); test('should coerce `radix` to a number', 2, function() { var object = { 'valueOf': _.constant(0) }; strictEqual(_.parseInt('08', object), 8); strictEqual(_.parseInt('0x20', object), 32); }); test('should work as an iteratee for `_.map`', 2, function() { var strings = _.map(['6', '08', '10'], Object), actual = _.map(strings, _.parseInt); deepEqual(actual, [6, 8, 10]); actual = _.map('123', _.parseInt); deepEqual(actual, [1, 2, 3]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('partial methods'); _.each(['partial', 'partialRight'], function(methodName) { var func = _[methodName], isPartial = methodName == 'partial', ph = func.placeholder; test('`_.' + methodName + '` partially applies arguments', 1, function() { var par = func(_.identity, 'a'); strictEqual(par(), 'a'); }); test('`_.' + methodName + '` creates a function that can be invoked with additional arguments', 1, function() { var fn = function(a, b) { return [a, b]; }, par = func(fn, 'a'), expected = ['a', 'b']; deepEqual(par('b'), isPartial ? expected : expected.reverse()); }); test('`_.' + methodName + '` works when there are no partially applied arguments and the created function is invoked without additional arguments', 1, function() { var fn = function() { return arguments.length; }, par = func(fn); strictEqual(par(), 0); }); test('`_.' + methodName + '` works when there are no partially applied arguments and the created function is invoked with additional arguments', 1, function() { var par = func(_.identity); strictEqual(par('a'), 'a'); }); test('`_.' + methodName + '` should support placeholders', 4, function() { var fn = function() { return slice.call(arguments); }, par = func(fn, ph, 'b', ph); deepEqual(par('a', 'c'), ['a', 'b', 'c']); deepEqual(par('a'), ['a', 'b', undefined]); deepEqual(par(), [undefined, 'b', undefined]); if (isPartial) { deepEqual(par('a', 'c', 'd'), ['a', 'b', 'c', 'd']); } else { par = func(fn, ph, 'c', ph); deepEqual(par('a', 'b', 'd'), ['a', 'b', 'c', 'd']); } }); test('`_.' + methodName + '` should not set a `this` binding', 3, function() { var fn = function() { return this.a; }, object = { 'a': 1 }; var par = func(_.bind(fn, object)); strictEqual(par(), object.a); par = _.bind(func(fn), object); strictEqual(par(), object.a); object.par = func(fn); strictEqual(object.par(), object.a); }); test('`_.' + methodName + '` creates a function with a `length` of `0`', 1, function() { var fn = function(a, b, c) {}, par = func(fn, 'a'); strictEqual(par.length, 0); }); test('`_.' + methodName + '` ensure `new partialed` is an instance of `func`', 2, function() { function Foo(value) { return value && object; } var object = {}, par = func(Foo); ok(new par instanceof Foo); strictEqual(new par(true), object); }); test('`_.' + methodName + '` should clone metadata for created functions', 3, function() { function greet(greeting, name) { return greeting + ' ' + name; } var par1 = func(greet, 'hi'), par2 = func(par1, 'barney'), par3 = func(par1, 'pebbles'); strictEqual(par1('fred'), isPartial ? 'hi fred' : 'fred hi'); strictEqual(par2(), isPartial ? 'hi barney' : 'barney hi'); strictEqual(par3(), isPartial ? 'hi pebbles' : 'pebbles hi'); }); test('`_.' + methodName + '` should work with curried methods', 2, function() { var fn = function(a, b, c) { return a + b + c; }, curried = _.curry(func(fn, 1), 2); strictEqual(curried(2, 3), 6); strictEqual(curried(2)(3), 6); }); test('should work with placeholders and curried methods', 1, function() { var fn = function() { return slice.call(arguments); }, curried = _.curry(fn), par = func(curried, ph, 'b', ph, 'd'); deepEqual(par('a', 'c'), ['a', 'b', 'c', 'd']); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.partialRight'); (function() { test('should work as a deep `_.defaults`', 1, function() { var object = { 'a': { 'b': 1 } }, source = { 'a': { 'b': 2, 'c': 3 } }, expected = { 'a': { 'b': 1, 'c': 3 } }; var defaultsDeep = _.partialRight(_.merge, function deep(value, other) { return _.merge(value, other, deep); }); deepEqual(defaultsDeep(object, source), expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('methods using `createWrapper`'); (function() { var ph1 = _.bind.placeholder, ph2 = _.bindKey.placeholder, ph3 = _.partial.placeholder, ph4 = _.partialRight.placeholder; test('combinations of partial functions should work', 1, function() { function fn() { return slice.call(arguments); } var a = _.partial(fn), b = _.partialRight(a, 3), c = _.partial(b, 1); deepEqual(c(2), [1, 2, 3]); }); test('combinations of bound and partial functions should work', 3, function() { function fn() { var result = [this.a]; push.apply(result, arguments); return result; } var expected = [1, 2, 3, 4], object = { 'a': 1, 'fn': fn }; var a = _.bindKey(object, 'fn'), b = _.partialRight(a, 4), c = _.partial(b, 2); deepEqual(c(3), expected); a = _.bind(fn, object); b = _.partialRight(a, 4); c = _.partial(b, 2); deepEqual(c(3), expected); a = _.partial(fn, 2); b = _.bind(a, object); c = _.partialRight(b, 4); deepEqual(c(3), expected); }); test('combinations of functions with placeholders should work', 3, function() { function fn() { return slice.call(arguments); } var expected = [1, 2, 3, 4, 5, 6], object = { 'fn': fn }; var a = _.bindKey(object, 'fn', ph2, 2), b = _.partialRight(a, ph4, 6), c = _.partial(b, 1, ph3, 4); deepEqual(c(3, 5), expected); a = _.bind(fn, object, ph1, 2); b = _.partialRight(a, ph4, 6); c = _.partial(b, 1, ph3, 4); deepEqual(c(3, 5), expected); a = _.partial(fn, ph3, 2); b = _.bind(a, object, 1, ph1, 4); c = _.partialRight(b, ph4, 6); deepEqual(c(3, 5), expected); }); test('combinations of functions with overlaping placeholders should work', 3, function() { function fn() { return slice.call(arguments); } var expected = [1, 2, 3, 4], object = { 'fn': fn }; var a = _.bindKey(object, 'fn', ph2, 2), b = _.partialRight(a, ph4, 4), c = _.partial(b, ph3, 3); deepEqual(c(1), expected); a = _.bind(fn, object, ph1, 2); b = _.partialRight(a, ph4, 4); c = _.partial(b, ph3, 3); deepEqual(c(1), expected); a = _.partial(fn, ph3, 2); b = _.bind(a, object, ph1, 3); c = _.partialRight(b, ph4, 4); deepEqual(c(1), expected); }); test('recursively bound functions should work', 1, function() { function fn() { return this.a; } var a = _.bind(fn, { 'a': 1 }), b = _.bind(a, { 'a': 2 }), c = _.bind(b, { 'a': 3 }); strictEqual(c(), 1); }); test('should work when hot', 12, function() { _.times(2, function(index) { var fn = function() { var result = [this]; push.apply(result, arguments); return result; }; var object = {}, bound1 = index ? _.bind(fn, object, 1) : _.bind(fn, object), expected = [object, 1, 2, 3]; var actual = _.last(_.times(HOT_COUNT, function() { var bound2 = index ? _.bind(bound1, null, 2) : _.bind(bound1); return index ? bound2(3) : bound2(1, 2, 3); })); deepEqual(actual, expected); actual = _.last(_.times(HOT_COUNT, function() { var bound1 = index ? _.bind(fn, object, 1) : _.bind(fn, object), bound2 = index ? _.bind(bound1, null, 2) : _.bind(bound1); return index ? bound2(3) : bound2(1, 2, 3); })); deepEqual(actual, expected); }); _.each(['curry', 'curryRight'], function(methodName, index) { var fn = function(a, b, c) { return [a, b, c]; }, curried = _[methodName](fn), expected = index ? [3, 2, 1] : [1, 2, 3]; var actual = _.last(_.times(HOT_COUNT, function() { return curried(1)(2)(3); })); deepEqual(actual, expected); actual = _.last(_.times(HOT_COUNT, function() { var curried = _[methodName](fn); return curried(1)(2)(3); })); deepEqual(actual, expected); }); _.each(['partial', 'partialRight'], function(methodName, index) { var func = _[methodName], fn = function() { return slice.call(arguments); }, par1 = func(fn, 1), expected = index ? [3, 2, 1] : [1, 2, 3]; var actual = _.last(_.times(HOT_COUNT, function() { var par2 = func(par1, 2); return par2(3); })); deepEqual(actual, expected); actual = _.last(_.times(HOT_COUNT, function() { var par1 = func(fn, 1), par2 = func(par1, 2); return par2(3); })); deepEqual(actual, expected); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.partition'); (function() { var array = [1, 0, 1]; test('should return two groups of elements', 3, function() { deepEqual(_.partition([], _.identity), [[], []]); deepEqual(_.partition(array, _.constant(true)), [array, []]); deepEqual(_.partition(array, _.constant(false)), [[], array]); }); test('should use `_.identity` when `predicate` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant([[1, 1], [0]])); var actual = _.map(values, function(value, index) { return index ? _.partition(array, value) : _.partition(array); }); deepEqual(actual, expected); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.partition(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.partition([1.1, 0.2, 1.3], function(num) { return this.floor(num); }, Math); deepEqual(actual, [[1.1, 1.3], [0.2]]); }); test('should work with a "_.property" style `predicate`', 1, function() { var objects = [{ 'a': 1 }, { 'a': 1 }, { 'b': 2 }], actual = _.partition(objects, 'a'); deepEqual(actual, [objects.slice(0, 2), objects.slice(2)]); }); test('should work with a number for `predicate`', 2, function() { var array = [ [1, 0], [0, 1], [1, 0] ]; deepEqual(_.partition(array, 0), [[array[0], array[2]], [array[1]]]); deepEqual(_.partition(array, 1), [[array[1]], [array[0], array[2]]]); }); test('should work with an object for `collection`', 1, function() { var actual = _.partition({ 'a': 1.1, 'b': 0.2, 'c': 1.3 }, function(num) { return Math.floor(num); }); deepEqual(actual, [[1.1, 1.3], [0.2]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pick'); (function() { var args = arguments, object = { 'a': 1, 'b': 2, 'c': 3 }, expected = { 'a': 1, 'c': 3 }; test('should create an object of picked properties', 2, function() { deepEqual(_.pick(object, 'a'), { 'a': 1 }); deepEqual(_.pick(object, 'a', 'c'), expected); }); test('should support picking an array of properties', 1, function() { deepEqual(_.pick(object, ['a', 'c']), expected); }); test('should support picking an array of properties and individual properties', 1, function() { deepEqual(_.pick(object, ['a'], 'c'), expected); }); test('should iterate over inherited properties', 1, function() { function Foo() {} Foo.prototype = object; deepEqual(_.pick(new Foo, 'a', 'c'), expected); }); test('should return an empty object when `object` is `null` or `undefined`', 2, function() { _.each([null, undefined], function(value) { deepEqual(_.pick(value, 'valueOf'), {}); }); }); test('should work with `arguments` objects as secondary arguments', 1, function() { deepEqual(_.pick(object, args), expected); }); test('should work with an array `object` argument', 1, function() { deepEqual(_.pick([1, 2, 3], '1'), { '1': 2 }); }); test('should work with a primitive `object` argument', 1, function() { deepEqual(_.pick('', 'slice'), { 'slice': ''.slice }); }); test('should work with a `predicate` argument', 1, function() { var actual = _.pick(object, function(num) { return num != 2; }); deepEqual(actual, expected); }); test('should provide the correct `predicate` arguments', 1, function() { var args, object = { 'a': 1, 'b': 2 }, lastKey = _.keys(object).pop(); var expected = lastKey == 'b' ? [1, 'a', object] : [2, 'b', object]; _.pick(object, function() { args || (args = slice.call(arguments)); }); deepEqual(args, expected); }); test('should correctly set the `this` binding', 1, function() { var actual = _.pick(object, function(num) { return num != this.b; }, { 'b': 2 }); deepEqual(actual, expected); }); test('should coerce property names to strings', 1, function() { deepEqual(_.pick({ '0': 'a', '1': 'b' }, 0), { '0': 'a' }); }); }('a', 'c')); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pluck'); (function() { test('should return an array of property values from each element of a collection', 1, function() { var objects = [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; deepEqual(_.pluck(objects, 'name'), ['barney', 'fred']); }); test('should pluck inherited property values', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; deepEqual(_.pluck([new Foo], 'b'), [2]); }); test('should work with an object for `collection`', 1, function() { var object = { 'a': [1], 'b': [1, 2], 'c': [1, 2, 3] }; deepEqual(_.pluck(object, 'length'), [1, 2, 3]); }); test('should return `undefined` for undefined properties', 1, function() { var array = [{ 'a': 1 }], actual = [_.pluck(array, 'b'), _.pluck(array, 'c')]; deepEqual(actual, [[undefined], [undefined]]); }); test('should work with nullish elements', 1, function() { var objects = [{ 'a': 1 }, null, undefined, { 'a': 4 }]; deepEqual(_.pluck(objects, 'a'), [1, undefined, undefined, 4]); }); test('should coerce `key` to a string', 1, function() { function fn() {} fn.toString = _.constant('fn'); var objects = [{ 'null': 1 }, { 'undefined': 2 }, { 'fn': 3 }, { '[object Object]': 4 }], values = [null, undefined, fn, {}] var actual = _.map(objects, function(object, index) { return _.pluck([object], values[index]); }); deepEqual(actual, [[1], [2], [3], [4]]); }); test('should work in a lazy chain sequence', 2, function() { if (!isNpm) { var array = [{ 'a': 1 }, null, { 'a': 3 }, { 'a': 4 }], actual = _(array).pluck('a').value(); deepEqual(actual, [1, undefined, 3, 4]); actual = _(array).filter(Boolean).pluck('a').value(); deepEqual(actual, [1, 3, 4]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.property'); (function() { test('should create a function that plucks a property value of a given object', 3, function() { var object = { 'a': 1, 'b': 2 }, prop = _.property('a'); strictEqual(prop.length, 1); strictEqual(prop(object), 1); prop = _.property('b'); strictEqual(prop(object), 2); }); test('should work with non-string `prop` arguments', 1, function() { var prop = _.property(1); strictEqual(prop([1, 2, 3]), 2); }); test('should coerce key to a string', 1, function() { function fn() {} fn.toString = _.constant('fn'); var objects = [{ 'null': 1 }, { 'undefined': 2 }, { 'fn': 3 }, { '[object Object]': 4 }], values = [null, undefined, fn, {}] var actual = _.map(objects, function(object, index) { var prop = _.property(values[index]); return prop(object); }); deepEqual(actual, [1, 2, 3, 4]); }); test('should pluck inherited property values', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var prop = _.property('b'); strictEqual(prop(new Foo), 2); }); test('should work when `object` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant(undefined)); var actual = _.map(values, function(value, index) { var prop = _.property('a'); return index ? prop(value) : prop(); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.propertyOf'); (function() { test('should create a function that plucks a property value of a given key', 3, function() { var object = { 'a': 1, 'b': 2 }, propOf = _.propertyOf(object); strictEqual(propOf.length, 1); strictEqual(propOf('a'), 1); strictEqual(propOf('b'), 2); }); test('should pluck inherited property values', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var propOf = _.propertyOf(new Foo); strictEqual(propOf('b'), 2); }); test('should work when `object` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant(undefined)); var actual = _.map(values, function(value, index) { var propOf = index ? _.propertyOf(value) : _.propertyOf(); return propOf('a'); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pull'); (function() { test('should modify and return the array', 2, function() { var array = [1, 2, 3], actual = _.pull(array, 1, 3); deepEqual(array, [2]); ok(actual === array); }); test('should preserve holes in arrays', 2, function() { var array = [1, 2, 3, 4]; delete array[1]; delete array[3]; _.pull(array, 1); ok(!('0' in array)); ok(!('2' in array)); }); test('should treat holes as `undefined`', 1, function() { var array = [1, 2, 3]; delete array[1]; _.pull(array, undefined); deepEqual(array, [1, 3]); }); test('should match `NaN`', 1, function() { var array = [1, NaN, 3, NaN]; _.pull(array, NaN); deepEqual(array, [1, 3]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pullAt'); (function() { test('should modify the array and return removed elements', 2, function() { var array = [1, 2, 3], actual = _.pullAt(array, [0, 1]); deepEqual(array, [3]); deepEqual(actual, [1, 2]); }); test('should work with unsorted indexes', 2, function() { var array = [1, 2, 3, 4], actual = _.pullAt(array, [1, 3, 0]); deepEqual(array, [3]); deepEqual(actual, [2, 4, 1]); }); test('should work with repeated indexes', 2, function() { var array = [1, 2, 3, 4], actual = _.pullAt(array, [0, 2, 0, 1, 0, 2]); deepEqual(array, [4]); deepEqual(actual, [1, 3, 1, 2, 1, 3]); }); test('should use `undefined` for nonexistent indexes', 2, function() { var array = ['a', 'b', 'c'], actual = _.pullAt(array, [2, 4, 0]); deepEqual(array, ['b']); deepEqual(actual, ['c', undefined, 'a']); }); test('should ignore non-index keys', 2, function() { var array = ['a', 'b', 'c'], clone = array.slice(); array['1.1'] = array['-1'] = 1; var values = _.reject(empties, function(value) { return value === 0 || _.isArray(value); }).concat(-1, 1.1); var expected = _.map(values, _.constant(undefined)), actual = _.pullAt(array, values); deepEqual(actual, expected); deepEqual(array, clone); }); test('should return an empty array when no indexes are provided', 4, function() { var array = ['a', 'b', 'c'], actual = _.pullAt(array); deepEqual(array, ['a', 'b', 'c']); deepEqual(actual, []); actual = _.pullAt(array, [], []); deepEqual(array, ['a', 'b', 'c']); deepEqual(actual, []); }); test('should accept multiple index arguments', 2, function() { var array = ['a', 'b', 'c', 'd'], actual = _.pullAt(array, 3, 0, 2); deepEqual(array, ['b']); deepEqual(actual, ['d', 'a', 'c']); }); test('should accept multiple arrays of indexes', 2, function() { var array = ['a', 'b', 'c', 'd'], actual = _.pullAt(array, [3], [0, 2]); deepEqual(array, ['b']); deepEqual(actual, ['d', 'a', 'c']); }); test('should work with a falsey `array` argument when keys are provided', 1, function() { var expected = _.map(falsey, _.constant([undefined, undefined])); var actual = _.map(falsey, function(value) { try { return _.pullAt(value, 0, 1); } catch(e) {} }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.random'); (function() { var array = Array(1000); test('should return `0` or `1` when arguments are not provided', 1, function() { var actual = _.map(array, function() { return _.random(); }); deepEqual(_.uniq(actual).sort(), [0, 1]); }); test('should support a `min` and `max` argument', 1, function() { var min = 5, max = 10; ok(_.some(array, function() { var result = _.random(min, max); return result >= min && result <= max; })); }); test('should support not providing a `max` argument', 1, function() { var min = 0, max = 5; ok(_.some(array, function() { var result = _.random(max); return result >= min && result <= max; })); }); test('should support large integer values', 2, function() { var min = Math.pow(2, 31), max = Math.pow(2, 62); ok(_.every(array, function() { var result = _.random(min, max); return result >= min && result <= max; })); ok(_.some(array, function() { return _.random(Number.MAX_VALUE) > 0; })); }); test('should coerce arguments to numbers', 1, function() { strictEqual(_.random('1', '1'), 1); }); test('should support floats', 2, function() { var min = 1.5, max = 1.6, actual = _.random(min, max); ok(actual % 1); ok(actual >= min && actual <= max); }); test('should support providing a `floating` argument', 3, function() { var actual = _.random(true); ok(actual % 1 && actual >= 0 && actual <= 1); actual = _.random(2, true); ok(actual % 1 && actual >= 0 && actual <= 2); actual = _.random(2, 4, true); ok(actual % 1 && actual >= 2 && actual <= 4); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [1, 2, 3], expected = _.map(array, _.constant(true)), randoms = _.map(array, _.random); var actual = _.map(randoms, function(result, index) { return result >= 0 && result <= array[index] && (result % 1) == 0; }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.range'); (function() { test('should work with an `end` argument', 1, function() { deepEqual(_.range(4), [0, 1, 2, 3]); }); test('should work with `start` and `end` arguments', 1, function() { deepEqual(_.range(1, 5), [1, 2, 3, 4]); }); test('should work with `start`, `end`, and `step` arguments', 1, function() { deepEqual(_.range(0, 20, 5), [0, 5, 10, 15]); }); test('should support a `step` of `0`', 1, function() { deepEqual(_.range(1, 4, 0), [1, 1, 1]); }); test('should work with a `step` larger than `end`', 1, function() { deepEqual(_.range(1, 5, 20), [1]); }); test('should work with a negative `step` argument', 2, function() { deepEqual(_.range(0, -4, -1), [0, -1, -2, -3]); deepEqual(_.range(21, 10, -3), [21, 18, 15, 12]); }); test('should treat falsey `start` arguments as `0`', 13, function() { _.each(falsey, function(value, index) { if (index) { deepEqual(_.range(value), []); deepEqual(_.range(value, 1), [0]); } else { deepEqual(_.range(), []); } }); }); test('should coerce arguments to finite numbers', 1, function() { var actual = [_.range('0', 1), _.range('1'), _.range(0, 1, '1'), _.range(NaN), _.range(NaN, NaN)]; deepEqual(actual, [[0], [0], [0], [], []]); }); test('should work as an iteratee for `_.map`', 2, function() { var array = [1, 2, 3], object = { 'a': 1, 'b': 2, 'c': 3 }, expected = [[0], [0, 1], [0, 1, 2]]; _.each([array, object], function(collection) { var actual = _.map(collection, _.range); deepEqual(actual, expected); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.rearg'); (function() { function fn() { return slice.call(arguments); } test('should reorder arguments provided to `func`', 1, function() { var rearged = _.rearg(fn, [2, 0, 1]); deepEqual(rearged('b', 'c', 'a'), ['a', 'b', 'c']); }); test('should work with repeated indexes', 1, function() { var rearged = _.rearg(fn, [1, 1, 1]); deepEqual(rearged('c', 'a', 'b'), ['a', 'a', 'a']); }); test('should use `undefined` for nonexistent indexes', 1, function() { var rearged = _.rearg(fn, [1, 4]); deepEqual(rearged('b', 'a', 'c'), ['a', undefined, 'c']); }); test('should use `undefined` for non-index values', 1, function() { var values = _.reject(empties, function(value) { return value === 0 || _.isArray(value); }).concat(-1, 1.1); var expected = _.map(values, _.constant([undefined, 'b', 'c'])); var actual = _.map(values, function(value) { var rearged = _.rearg(fn, [value]); return rearged('a', 'b', 'c'); }); deepEqual(actual, expected); }); test('should not rearrange arguments when no indexes are provided', 2, function() { var rearged = _.rearg(fn); deepEqual(rearged('a', 'b', 'c'), ['a', 'b', 'c']); rearged = _.rearg(fn, [], []); deepEqual(rearged('a', 'b', 'c'), ['a', 'b', 'c']); }); test('should accept multiple index arguments', 1, function() { var rearged = _.rearg(fn, 2, 0, 1); deepEqual(rearged('b', 'c', 'a'), ['a', 'b', 'c']); }); test('should accept multiple arrays of indexes', 1, function() { var rearged = _.rearg(fn, [2], [0, 1]); deepEqual(rearged('b', 'c', 'a'), ['a', 'b', 'c']); }); test('should work with fewer indexes than arguments', 1, function() { var rearged = _.rearg(fn, [1, 0]); deepEqual(rearged('b', 'a', 'c'), ['a', 'b', 'c']); }); test('should work on functions that have been rearged', 1, function() { var rearged1 = _.rearg(fn, 2, 1, 0), rearged2 = _.rearg(rearged1, 1, 0, 2); deepEqual(rearged2('b', 'c', 'a'), ['a', 'b', 'c']); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.reduce'); (function() { var array = [1, 2, 3]; test('should use the first element of a collection as the default `accumulator`', 1, function() { strictEqual(_.reduce(array), 1); }); test('should provide the correct `iteratee` arguments when iterating an array', 2, function() { var args; _.reduce(array, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, [0, 1, 0, array]); args = null; _.reduce(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 2, 1, array]); }); test('should provide the correct `iteratee` arguments when iterating an object', 2, function() { var args, object = { 'a': 1, 'b': 2 }, firstKey = _.first(_.keys(object)); var expected = firstKey == 'a' ? [0, 1, 'a', object] : [0, 2, 'b', object]; _.reduce(object, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, expected); args = null; expected = firstKey == 'a' ? [1, 2, 'b', object] : [2, 1, 'a', object]; _.reduce(object, function() { args || (args = slice.call(arguments)); }); deepEqual(args, expected); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection` (test in IE < 9)', 2, function() { var args; var actual = _.reduce(collection, function(accumulator, value) { args || (args = slice.call(arguments)); return accumulator + value; }); deepEqual(args, ['a', 'b', 1, collection]); strictEqual(actual, 'abc'); }); }); test('should be aliased', 2, function() { strictEqual(_.foldl, _.reduce); strictEqual(_.inject, _.reduce); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.reduceRight'); (function() { var array = [1, 2, 3]; test('should use the last element of a collection as the default `accumulator`', 1, function() { strictEqual(_.reduceRight(array), 3); }); test('should provide the correct `iteratee` arguments when iterating an array', 2, function() { var args; _.reduceRight(array, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, [0, 3, 2, array]); args = null; _.reduceRight(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [3, 2, 1, array]); }); test('should provide the correct `iteratee` arguments when iterating an object', 2, function() { var args, object = { 'a': 1, 'b': 2 }, lastKey = _.last(_.keys(object)); var expected = lastKey == 'b' ? [0, 2, 'b', object] : [0, 1, 'a', object]; _.reduceRight(object, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, expected); args = null; expected = lastKey == 'b' ? [2, 1, 'a', object] : [1, 2, 'b', object]; _.reduceRight(object, function() { args || (args = slice.call(arguments)); }); deepEqual(args, expected); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection` (test in IE < 9)', 2, function() { var args; var actual = _.reduceRight(collection, function(accumulator, value) { args || (args = slice.call(arguments)); return accumulator + value; }); deepEqual(args, ['c', 'b', 1, collection]); strictEqual(actual, 'cba'); }); }); test('should be aliased', 1, function() { strictEqual(_.foldr, _.reduceRight); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('reduce methods'); _.each(['reduce', 'reduceRight'], function(methodName) { var func = _[methodName], array = [1, 2, 3], isReduce = methodName == 'reduce'; test('`_.' + methodName + '` should reduce a collection to a single value', 1, function() { var actual = func(['a', 'b', 'c'], function(accumulator, value) { return accumulator + value; }, ''); strictEqual(actual, isReduce ? 'abc' : 'cba'); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func(array, function(sum, num, index) { return sum + this[index]; }, 0, array); deepEqual(actual, 6); }); test('`_.' + methodName + '` should support empty collections without an initial `accumulator` value', 1, function() { var actual = [], expected = _.map(empties, _.constant()); _.each(empties, function(value) { try { actual.push(func(value, _.noop)); } catch(e) {} }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should support empty collections with an initial `accumulator` value', 1, function() { var expected = _.map(empties, _.constant('x')); var actual = _.map(empties, function(value) { try { return func(value, _.noop, 'x'); } catch(e) {} }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should handle an initial `accumulator` value of `undefined`', 1, function() { var actual = func([], _.noop, undefined); strictEqual(actual, undefined); }); test('`_.' + methodName + '` should return `undefined` for empty collections when no `accumulator` is provided (test in IE > 9 and modern browsers)', 2, function() { var array = [], object = { '0': 1, 'length': 0 }; if ('__proto__' in array) { array.__proto__ = object; strictEqual(_.reduce(array, _.noop), undefined); } else { skipTest(); } strictEqual(_.reduce(object, _.noop), undefined); }); test('`_.' + methodName + '` should return an unwrapped value when implicityly chaining', 1, function() { if (!isNpm) { strictEqual(_(array)[methodName](add), 6); } else { skipTest(); } }); test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain()[methodName](add) instanceof _); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.reject'); (function() { var array = [1, 2, 3]; test('should return elements the `predicate` returns falsey for', 1, function() { var actual = _.reject(array, function(num) { return num % 2; }); deepEqual(actual, [2]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('filter methods'); _.each(['filter', 'reject'], function(methodName) { var array = [1, 2, 3, 4], func = _[methodName], isFilter = methodName == 'filter', objects = [{ 'a': 0 }, { 'a': 1 }]; test('`_.' + methodName + '` should not modify the resulting value from within `predicate`', 1, function() { var actual = func([0], function(num, index, array) { array[index] = 1; return isFilter; }); deepEqual(actual, [0]); }); test('`_.' + methodName + '` should work with a "_.property" style `predicate`', 1, function() { deepEqual(func(objects, 'a'), [objects[isFilter ? 1 : 0]]); }); test('`_.' + methodName + '` should work with a "_where" style `predicate`', 1, function() { deepEqual(func(objects, objects[1]), [objects[isFilter ? 1 : 0]]); }); test('`_.' + methodName + '` should not modify wrapped values', 2, function() { if (!isNpm) { var wrapped = _(array); var actual = wrapped[methodName](function(num) { return num < 3; }); deepEqual(actual.value(), isFilter ? [1, 2] : [3, 4]); actual = wrapped[methodName](function(num) { return num > 2; }); deepEqual(actual.value(), isFilter ? [3, 4] : [1, 2]); } else { skipTest(2); } }); test('`_.' + methodName + '` should work in a lazy chain sequence', 2, function() { if (!isNpm) { var object = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, predicate = function(value) { return isFilter ? (value > 6) : (value < 6); }; var expected = [9, 16], actual = _(array).map(square)[methodName](predicate).value(); deepEqual(actual, expected); actual = _(object).mapValues(square)[methodName](predicate).value(); deepEqual(actual, expected); } else { skipTest(2); } }); test('`_.' + methodName + '` should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [1, 0, [1, 4, 9, 16]]; _(array)[methodName](function(value, index, array) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, [1, 0, array]); args = null; _(array).map(square)[methodName](function(value, index, array) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); args = null; _(array).map(square)[methodName](function(value, index) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); args = null; _(array).map(square)[methodName](function(value) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, [1]); args = null; _(array).map(square)[methodName](function() { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.remove'); (function() { test('should modify the array and return removed elements', 2, function() { var array = [1, 2, 3]; var actual = _.remove(array, function(num) { return num < 3; }); deepEqual(array, [3]); deepEqual(actual, [1, 2]); }); test('should provide the correct `predicate` arguments', 1, function() { var args, array = [1, 2, 3]; _.remove(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var array = [1, 2, 3]; var actual = _.remove(array, function(num, index) { return this[index] < 3; }, array); deepEqual(actual, [1, 2]); }); test('should work with a "_.matches" style `predicate`', 1, function() { var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }]; _.remove(objects, { 'a': 1 }); deepEqual(objects, [{ 'a': 0, 'b': 1 }]); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }]; _.remove(objects, 'a', 1); deepEqual(objects, [{ 'a': 0, 'b': 1 }]); }); test('should work with a "_.property" style `predicate`', 1, function() { var objects = [{ 'a': 0 }, { 'a': 1 }]; _.remove(objects, 'a'); deepEqual(objects, [{ 'a': 0 }]); }); test('should preserve holes in arrays', 2, function() { var array = [1, 2, 3, 4]; delete array[1]; delete array[3]; _.remove(array, function(num) { return num === 1; }); ok(!('0' in array)); ok(!('2' in array)); }); test('should treat holes as `undefined`', 1, function() { var array = [1, 2, 3]; delete array[1]; _.remove(array, function(num) { return num == null; }); deepEqual(array, [1, 3]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.repeat'); (function() { test('should repeat a string `n` times', 2, function() { strictEqual(_.repeat('*', 3), '***'); strictEqual(_.repeat('abc', 2), 'abcabc'); }); test('should return an empty string for negative `n` or `n` of `0`', 2, function() { strictEqual(_.repeat('abc', 0), ''); strictEqual(_.repeat('abc', -2), ''); }); test('should coerce `n` to a number', 3, function() { strictEqual(_.repeat('abc'), ''); strictEqual(_.repeat('abc', '2'), 'abcabc'); strictEqual(_.repeat('*', { 'valueOf': _.constant(3) }), '***'); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.repeat(Object('abc'), 2), 'abcabc'); strictEqual(_.repeat({ 'toString': _.constant('*') }, 3), '***'); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.result'); (function() { var object = { 'a': 1, 'b': null, 'c': function() { return this.a; } }; test('should resolve property values', 4, function() { strictEqual(_.result(object, 'a'), 1); strictEqual(_.result(object, 'b'), null); strictEqual(_.result(object, 'c'), 1); strictEqual(_.result(object, 'd'), undefined); }); test('should return `undefined` when `object` is nullish', 2, function() { strictEqual(_.result(null, 'a'), undefined); strictEqual(_.result(undefined, 'a'), undefined); }); test('should return the specified default value for undefined properties', 1, function() { var values = empties.concat(true, new Date, 1, /x/, 'a'); var expected = _.transform(values, function(result, value) { result.push(value, value); }); var actual = _.transform(values, function(result, value) { result.push( _.result(object, 'd', value), _.result(null, 'd', value) ); }); deepEqual(actual, expected); }); test('should execute default function values', 1, function() { var actual = _.result(object, 'd', object.c); strictEqual(actual, 1); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.rest'); (function() { var array = [1, 2, 3]; test('should accept a falsey `array` argument', 1, function() { var expected = _.map(falsey, _.constant([])); var actual = _.map(falsey, function(value, index) { try { return index ? _.rest(value) : _.rest(); } catch(e) {} }); deepEqual(actual, expected); }); test('should exclude the first element', 1, function() { deepEqual(_.rest(array), [2, 3]); }); test('should return an empty when querying empty arrays', 1, function() { deepEqual(_.rest([]), []); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.rest); deepEqual(actual, [[2, 3], [5, 6], [8, 9]]); }); test('should work in a lazy chain sequence', 4, function() { if (!isNpm) { var array = [1, 2, 3], values = []; var actual = _(array).rest().filter(function(value) { values.push(value); return false; }) .value(); deepEqual(actual, []); deepEqual(values, [2, 3]); values = []; actual = _(array).filter(function(value) { values.push(value); return value > 1; }) .rest() .value(); deepEqual(actual, [3]); deepEqual(values, array); } else { skipTest(4); } }); test('should not execute subsequent iteratees on an empty array in a lazy chain sequence', 4, function() { if (!isNpm) { var array = [1], iteratee = function() { pass = false }, pass = true, actual = _(array).rest().map(iteratee).value(); ok(pass); deepEqual(actual, []); pass = true; actual = _(array).filter(_.identity).rest().map(iteratee).value(); ok(pass); deepEqual(actual, []); } else { skipTest(4); } }); test('should be aliased', 1, function() { strictEqual(_.tail, _.rest); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.runInContext'); (function() { test('should not require a fully populated `context` object', 1, function() { if (!isModularize) { var lodash = _.runInContext({ 'setTimeout': function(callback) { callback(); } }); var pass = false; lodash.delay(function() { pass = true; }, 32); ok(pass); } else { skipTest(); } }); test('should use a zeroed `_.uniqueId` counter', 3, function() { if (!isModularize) { var oldId = (_.uniqueId(), _.uniqueId()), lodash = _.runInContext(); ok(_.uniqueId() > oldId); var id = lodash.uniqueId(); strictEqual(id, '1'); ok(id < oldId); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.sample'); (function() { var array = [1, 2, 3]; test('should return a random element', 1, function() { var actual = _.sample(array); ok(_.includes(array, actual)); }); test('should return two random elements', 1, function() { var actual = _.sample(array, 2); ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(array, actual[0]) && _.includes(array, actual[1])); }); test('should contain elements of the collection', 1, function() { var actual = _.sample(array, array.length); deepEqual(actual.sort(), array); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? 1 : []; }); var actual = _.map(falsey, function(n) { return _.sample([1], n); }); deepEqual(actual, expected); }); test('should return an empty array when `n` < `1` or `NaN`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.sample(array, n), []); }); }); test('should return all elements when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.sample(array, n).sort(), array); }); }); test('should return `undefined` when sampling an empty array', 1, function() { strictEqual(_.sample([]), undefined); }); test('should return an empty array for empty collections', 1, function() { var expected = _.transform(empties, function(result) { result.push(undefined, []); }); var actual = []; _.each(empties, function(value) { try { actual.push(_.sample(value), _.sample(value, 1)); } catch(e) {} }); deepEqual(actual, expected); }); test('should sample an object', 2, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }, actual = _.sample(object); ok(_.includes(array, actual)); actual = _.sample(object, 2); ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(array, actual[0]) && _.includes(array, actual[1])); }); test('should work as an iteratee for `_.map`', 2, function() { var array1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array2 = ['abc', 'def', 'ghi']; _.each([array1, array2], function(values) { var a = values[0], b = values[1], c = values[2], actual = _.map(values, _.sample); ok(_.includes(a, actual[0]) && _.includes(b, actual[1]) && _.includes(c, actual[2])); }); }); test('should return a wrapped value when chaining and `n` is provided', 2, function() { if (!isNpm) { var wrapped = _(array).sample(2), actual = wrapped.value(); ok(wrapped instanceof _); ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(array, actual[0]) && _.includes(array, actual[1])); } else { skipTest(2); } }); test('should return an unwrapped value when chaining and `n` is not provided', 1, function() { if (!isNpm) { var actual = _(array).sample(); ok(_.includes(array, actual)); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain().sample() instanceof _); } else { skipTest(); } }); test('should use a stored reference to `_.sample` when chaining', 2, function() { if (!isNpm) { var sample = _.sample; _.sample = _.noop; var wrapped = _(array); notStrictEqual(wrapped.sample(), undefined); notStrictEqual(wrapped.sample(2).value(), undefined); _.sample = sample; } else { skipTest(2); } }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 2, function() { var actual = _.sample(collection); ok(_.includes(collection, actual)); actual = _.sample(collection, 2); ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(collection, actual[0]) && _.includes(collection, actual[1])); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.shuffle'); (function() { var array = [1, 2, 3], object = { 'a': 1, 'b': 2, 'c': 3 }; test('should return a new array', 1, function() { notStrictEqual(_.shuffle(array), array); }); test('should contain the same elements after a collection is shuffled', 2, function() { deepEqual(_.shuffle(array).sort(), array); deepEqual(_.shuffle(object).sort(), array); }); test('should shuffle small collections', 1, function() { var actual = _.times(1000, function() { return _.shuffle([1, 2]); }); deepEqual(_.sortBy(_.uniq(actual, String), '0'), [[1, 2], [2, 1]]); }); test('should treat number values for `collection` as empty', 1, function() { deepEqual(_.shuffle(1), []); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 1, function() { var actual = _.shuffle(collection); deepEqual(actual.sort(), ['a','b', 'c']); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.size'); (function() { var args = arguments, array = [1, 2, 3]; test('should return the number of own enumerable properties of an object', 1, function() { strictEqual(_.size({ 'one': 1, 'two': 2, 'three': 3 }), 3); }); test('should return the length of an array', 1, function() { strictEqual(_.size(array), 3); }); test('should accept a falsey `object` argument', 1, function() { var expected = _.map(falsey, _.constant(0)); var actual = _.map(falsey, function(value, index) { try { return index ? _.size(value) : _.size(); } catch(e) {} }); deepEqual(actual, expected); }); test('should work with `arguments` objects (test in IE < 9)', 1, function() { strictEqual(_.size(args), 3); }); test('should work with jQuery/MooTools DOM query collections', 1, function() { function Foo(elements) { push.apply(this, elements); } Foo.prototype = { 'length': 0, 'splice': arrayProto.splice }; strictEqual(_.size(new Foo(array)), 3); }); test('should not treat objects with negative lengths as array-like', 1, function() { strictEqual(_.size({ 'length': -1 }), 1); }); test('should not treat objects with lengths larger than `MAX_SAFE_INTEGER` as array-like', 1, function() { strictEqual(_.size({ 'length': MAX_SAFE_INTEGER + 1 }), 1); }); test('should not treat objects with non-number lengths as array-like', 1, function() { strictEqual(_.size({ 'length': '0' }), 1); }); test('fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 1, function() { strictEqual(_.size(shadowObject), 7); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 1, function() { deepEqual(_.size(collection), 3); }); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.slice'); (function() { var array = [1, 2, 3]; test('should use a default `start` of `0` and a default `end` of `array.length`', 2, function() { var actual = _.slice(array); deepEqual(actual, array); notStrictEqual(actual, array); }); test('should work with a positive `start`', 2, function() { deepEqual(_.slice(array, 1), [2, 3]); deepEqual(_.slice(array, 1, 3), [2, 3]); }); test('should work with a `start` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(start) { deepEqual(_.slice(array, start), []); }); }); test('should treat falsey `start` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(array)); var actual = _.map(falsey, function(start) { return _.slice(array, start); }); deepEqual(actual, expected); }); test('should work with a negative `start`', 1, function() { deepEqual(_.slice(array, -1), [3]); }); test('should work with a negative `start` <= negative `array.length`', 3, function() { _.each([-3, -4, -Infinity], function(start) { deepEqual(_.slice(array, start), array); }); }); test('should work with `start` >= `end`', 2, function() { _.each([2, 3], function(start) { deepEqual(_.slice(array, start, 2), []); }); }); test('should work with a positive `end`', 1, function() { deepEqual(_.slice(array, 0, 1), [1]); }); test('should work with a `end` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(end) { deepEqual(_.slice(array, 0, end), array); }); }); test('should treat falsey `end` values, except `undefined`, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value === undefined ? array : []; }); var actual = _.map(falsey, function(end) { return _.slice(array, 0, end); }); deepEqual(actual, expected); }); test('should work with a negative `end`', 1, function() { deepEqual(_.slice(array, 0, -1), [1, 2]); }); test('should work with a negative `end` <= negative `array.length`', 3, function() { _.each([-3, -4, -Infinity], function(end) { deepEqual(_.slice(array, 0, end), []); }); }); test('should coerce `start` and `end` to integers', 1, function() { var positions = [[0.1, 1.1], ['0', 1], [0, '1'], ['1'], [NaN, 1], [1, NaN]]; var actual = _.map(positions, function(pos) { return _.slice.apply(_, [array].concat(pos)); }); deepEqual(actual, [[1], [1], [1], [2, 3], [1], []]); }); test('should work as an iteratee for `_.map`', 2, function() { var array = [[1], [2, 3]], actual = _.map(array, _.slice); deepEqual(actual, array); notStrictEqual(actual, array); }); test('should work in a lazy chain sequence', 38, function() { if (!isNpm) { var wrapped = _(array); _.each(['map', 'filter'], function(methodName) { deepEqual(wrapped[methodName]().slice(0, -1).value(), [1, 2]); deepEqual(wrapped[methodName]().slice(1).value(), [2, 3]); deepEqual(wrapped[methodName]().slice(1, 3).value(), [2, 3]); deepEqual(wrapped[methodName]().slice(-1).value(), [3]); deepEqual(wrapped[methodName]().slice(4).value(), []); deepEqual(wrapped[methodName]().slice(3, 2).value(), []); deepEqual(wrapped[methodName]().slice(0, -4).value(), []); deepEqual(wrapped[methodName]().slice(0, null).value(), []); deepEqual(wrapped[methodName]().slice(0, 4).value(), array); deepEqual(wrapped[methodName]().slice(-4).value(), array); deepEqual(wrapped[methodName]().slice(null).value(), array); deepEqual(wrapped[methodName]().slice(0, 1).value(), [1]); deepEqual(wrapped[methodName]().slice(NaN, '1').value(), [1]); deepEqual(wrapped[methodName]().slice(0.1, 1.1).value(), [1]); deepEqual(wrapped[methodName]().slice('0', 1).value(), [1]); deepEqual(wrapped[methodName]().slice(0, '1').value(), [1]); deepEqual(wrapped[methodName]().slice('1').value(), [2, 3]); deepEqual(wrapped[methodName]().slice(NaN, 1).value(), [1]); deepEqual(wrapped[methodName]().slice(1, NaN).value(), []); }); } else { skipTest(38); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.some'); (function() { test('should return `false` for empty collections', 1, function() { var expected = _.map(empties, _.constant(false)); var actual = _.map(empties, function(value) { try { return _.some(value, _.identity); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `true` if `predicate` returns truthy for any element in the collection', 2, function() { strictEqual(_.some([false, 1, ''], _.identity), true); strictEqual(_.some([null, 'x', 0], _.identity), true); }); test('should return `false` if `predicate` returns falsey for all elements in the collection', 2, function() { strictEqual(_.some([false, false, false], _.identity), false); strictEqual(_.some([null, 0, ''], _.identity), false); }); test('should return `true` as soon as `predicate` returns truthy', 1, function() { strictEqual(_.some([null, true, null], _.identity), true); }); test('should work with a "_.property" style `predicate`', 2, function() { var objects = [{ 'a': 0, 'b': 0 }, { 'a': 0, 'b': 1 }]; strictEqual(_.some(objects, 'a'), false); strictEqual(_.some(objects, 'b'), true); }); test('should work with a "_where" style `predicate`', 2, function() { var objects = [{ 'a': 0, 'b': 0 }, { 'a': 1, 'b': 1}]; strictEqual(_.some(objects, { 'a': 0 }), true); strictEqual(_.some(objects, { 'b': 2 }), false); }); test('should use `_.identity` when `predicate` is nullish', 2, function() { var values = [, null, undefined], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value, index) { var array = [0, 0]; return index ? _.some(array, value) : _.some(array); }); deepEqual(actual, expected); expected = _.map(values, _.constant(true)); actual = _.map(values, function(value, index) { var array = [0, 1]; return index ? _.some(array, value) : _.some(array); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([[1]], _.some); deepEqual(actual, [true]); }); test('should be aliased', 1, function() { strictEqual(_.any, _.some); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.sortBy'); (function() { function Pair(a, b, c) { this.a = a; this.b = b; this.c = c; } var objects = [ { 'a': 'x', 'b': 3 }, { 'a': 'y', 'b': 4 }, { 'a': 'x', 'b': 1 }, { 'a': 'y', 'b': 2 } ]; var stableOrder = [ new Pair(1, 1, 1), new Pair(1, 2, 1), new Pair(1, 1, 1), new Pair(1, 2, 1), new Pair(1, 3, 1), new Pair(1, 4, 1), new Pair(1, 5, 1), new Pair(1, 6, 1), new Pair(2, 1, 2), new Pair(2, 2, 2), new Pair(2, 3, 2), new Pair(2, 4, 2), new Pair(2, 5, 2), new Pair(2, 6, 2), new Pair(undefined, 1, 1), new Pair(undefined, 2, 1), new Pair(undefined, 3, 1), new Pair(undefined, 4, 1), new Pair(undefined, 5, 1), new Pair(undefined, 6, 1) ]; test('should sort in ascending order', 1, function() { var actual = _.pluck(_.sortBy(objects, function(object) { return object.b; }), 'b'); deepEqual(actual, [1, 2, 3, 4]); }); test('should perform a stable sort (test in V8)', 1, function() { var actual = _.sortBy(stableOrder, function(pair) { return pair.a; }); deepEqual(actual, stableOrder); }); test('should use `_.identity` when `iteratee` is nullish', 1, function() { var array = [3, 2, 1], values = [, null, undefined], expected = _.map(values, _.constant([1, 2, 3])); var actual = _.map(values, function(value, index) { return index ? _.sortBy(array, value) : _.sortBy(array); }); deepEqual(actual, expected); }); test('should move `undefined` and `NaN` values to the end', 1, function() { var array = [NaN, undefined, 4, 1, undefined, 3, NaN, 2]; deepEqual(_.sortBy(array), [1, 2, 3, 4, undefined, undefined, NaN, NaN]); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.sortBy(objects, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [objects[0], 0, objects]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); deepEqual(actual, [3, 1, 2]); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.pluck(_.sortBy(objects.concat(undefined), 'b'), 'b'); deepEqual(actual, [1, 2, 3, 4, undefined]); }); test('should work with an object for `collection`', 1, function() { var actual = _.sortBy({ 'a': 1, 'b': 2, 'c': 3 }, function(num) { return Math.sin(num); }); deepEqual(actual, [3, 1, 2]); }); test('should treat number values for `collection` as empty', 1, function() { deepEqual(_.sortBy(1), []); }); test('should coerce arrays returned from `iteratee`', 1, function() { var actual = _.sortBy(objects, function(object) { var result = [object.a, object.b]; result.toString = function() { return String(this[0]); }; return result; }); deepEqual(actual, [objects[0], objects[2], objects[1], objects[3]]); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([[2, 1, 3], [3, 2, 1]], _.sortBy); deepEqual(actual, [[1, 2, 3], [1, 2, 3]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.sortByOrder'); (function() { var objects = [ { 'a': 'x', 'b': 3 }, { 'a': 'y', 'b': 4 }, { 'a': 'x', 'b': 1 }, { 'a': 'y', 'b': 2 } ]; test('should sort multiple properties by specified orders', 1, function() { var actual = _.sortByOrder(objects, ['a', 'b'], [false, true]); deepEqual(actual, [objects[3], objects[1], objects[2], objects[0]]); }); test('should sort a property in ascending order when its order is not specified', 1, function() { var actual = _.sortByOrder(objects, ['a', 'b'], [false]); deepEqual(actual, [objects[3], objects[1], objects[2], objects[0]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('sortBy methods'); _.each(['sortByAll', 'sortByOrder'], function(methodName) { var func = _[methodName]; function Pair(a, b, c) { this.a = a; this.b = b; this.c = c; } var objects = [ { 'a': 'x', 'b': 3 }, { 'a': 'y', 'b': 4 }, { 'a': 'x', 'b': 1 }, { 'a': 'y', 'b': 2 } ]; var stableOrder = [ new Pair(1, 1, 1), new Pair(1, 2, 1), new Pair(1, 1, 1), new Pair(1, 2, 1), new Pair(1, 3, 1), new Pair(1, 4, 1), new Pair(1, 5, 1), new Pair(1, 6, 1), new Pair(2, 1, 2), new Pair(2, 2, 2), new Pair(2, 3, 2), new Pair(2, 4, 2), new Pair(2, 5, 2), new Pair(2, 6, 2), new Pair(undefined, 1, 1), new Pair(undefined, 2, 1), new Pair(undefined, 3, 1), new Pair(undefined, 4, 1), new Pair(undefined, 5, 1), new Pair(undefined, 6, 1) ]; test('`_.' + methodName + '` should sort mutliple properties in ascending order', 1, function() { var actual = func(objects, ['a', 'b']); deepEqual(actual, [objects[2], objects[0], objects[3], objects[1]]); }); test('`_.' + methodName + '` should perform a stable sort (test in IE > 8, Opera, and V8)', 1, function() { var actual = func(stableOrder, ['a', 'c']); deepEqual(actual, stableOrder); }); test('`_.' + methodName + '` should not error on nullish elements', 1, function() { try { var actual = func(objects.concat(undefined), ['a', 'b']); } catch(e) {} deepEqual(actual, [objects[2], objects[0], objects[3], objects[1], undefined]); }); test('`_.' + methodName + '` should work as an iteratee for `_.reduce`', 1, function() { var objects = [ { 'a': 'x', '0': 3 }, { 'a': 'y', '0': 4 }, { 'a': 'x', '0': 1 }, { 'a': 'y', '0': 2 } ]; var funcs = [func, _.partialRight(func, 'bogus')], expected = _.map(funcs, _.constant([objects[0], objects[2], objects[1], objects[3]])); var actual = _.map(funcs, function(func) { return _.reduce([['a']], func, objects); }); deepEqual(actual, expected); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('sortedIndex methods'); _.each(['sortedIndex', 'sortedLastIndex'], function(methodName) { var array = [30, 50], func = _[methodName], isSortedIndex = methodName == 'sortedIndex', objects = [{ 'x': 30 }, { 'x': 50 }]; test('`_.' + methodName + '` should return the correct insert index', 1, function() { var array = [30, 50], values = [30, 40, 50], expected = isSortedIndex ? [0, 1, 1] : [1, 1, 2]; var actual = _.map(values, function(value) { return func(array, value); }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should work with an array of strings', 1, function() { var array = ['a', 'c'], values = ['a', 'b', 'c'], expected = isSortedIndex ? [0, 1, 1] : [1, 1, 2]; var actual = _.map(values, function(value) { return func(array, value); }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should accept a falsey `array` argument and a `value`', 1, function() { var expected = _.map(falsey, _.constant([0, 0, 0])); var actual = _.map(falsey, function(array) { return [func(array, 1), func(array, undefined), func(array, NaN)]; }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should provide the correct `iteratee` arguments', 1, function() { var args; func(array, 40, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [40]); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func(array, 40, function(num) { return this[num]; }, { '30': 30, '40': 40, '50': 50 }); strictEqual(actual, 1); }); test('`_.' + methodName + '` should work with a "_.property" style `iteratee`', 1, function() { var actual = func(objects, { 'x': 40 }, 'x'); strictEqual(actual, 1); }); test('`_.' + methodName + '` should align with `_.sortBy`', 8, function() { var expected = [1, '2', {}, undefined, NaN, NaN]; _.each([ [NaN, 1, '2', {}, NaN, undefined], ['2', 1, NaN, {}, NaN, undefined] ], function(array) { deepEqual(_.sortBy(array), expected); strictEqual(func(expected, 3), 2); strictEqual(func(expected, undefined), isSortedIndex ? 3 : 4); strictEqual(func(expected, NaN), isSortedIndex ? 4 : 6); }); }); test('`_.' + methodName + '` should support arrays larger than `MAX_ARRAY_LENGTH / 2`', 12, function() { _.each([Math.ceil(MAX_ARRAY_LENGTH / 2), MAX_ARRAY_LENGTH], function(length) { var array = [], values = [MAX_ARRAY_LENGTH, NaN, undefined]; array.length = length; _.each(values, function(value) { var steps = 0, actual = func(array, value, function(value) { steps++; return value; }); var expected = (isSortedIndex ? !_.isNaN(value) : _.isFinite(value)) ? 0 : Math.min(length, MAX_ARRAY_INDEX); // Avoid false fails in older Firefox. if (array.length == length) { ok(steps == 32 || steps == 33); strictEqual(actual, expected); } else { skipTest(2); } }); }); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.spread'); (function() { test('should spread arguments to `func`', 1, function() { var spread = _.spread(add); strictEqual(spread([4, 2]), 6); }); test('should throw a TypeError when receiving a non-array `array` argument', 1, function() { raises(function() { _.spread(4, 2); }, TypeError); }); test('should provide the correct `func` arguments', 1, function() { var args; var spread = _.spread(function() { args = slice.call(arguments); }); spread([4, 2], 'ignored'); deepEqual(args, [4, 2]); }); test('should not set a `this` binding', 1, function() { var spread = _.spread(function(x, y) { return this[x] + this[y]; }); var object = { 'spread': spread, 'x': 4, 'y': 2 }; strictEqual(object.spread(['x', 'y']), 6); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.startsWith'); (function() { var string = 'abc'; test('should return `true` if a string starts with `target`', 1, function() { strictEqual(_.startsWith(string, 'a'), true); }); test('should return `false` if a string does not start with `target`', 1, function() { strictEqual(_.startsWith(string, 'b'), false); }); test('should work with a `position` argument', 1, function() { strictEqual(_.startsWith(string, 'b', 1), true); }); test('should work with `position` >= `string.length`', 4, function() { _.each([3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { strictEqual(_.startsWith(string, 'a', position), false); }); }); test('should treat falsey `position` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(true)); var actual = _.map(falsey, function(position) { return _.startsWith(string, 'a', position); }); deepEqual(actual, expected); }); test('should treat a negative `position` as `0`', 6, function() { _.each([-1, -3, -Infinity], function(position) { strictEqual(_.startsWith(string, 'a', position), true); strictEqual(_.startsWith(string, 'b', position), false); }); }); test('should return `true` when `target` is an empty string regardless of `position`', 1, function() { ok(_.every([-Infinity, NaN, -3, -1, 0, 1, 2, 3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { return _.startsWith(string, '', position, true); })); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.startsWith and lodash.endsWith'); _.each(['startsWith', 'endsWith'], function(methodName) { var func = _[methodName], isStartsWith = methodName == 'startsWith'; var string = 'abc', chr = isStartsWith ? 'a' : 'c'; test('`_.' + methodName + '` should coerce `string` to a string', 2, function() { strictEqual(func(Object(string), chr), true); strictEqual(func({ 'toString': _.constant(string) }, chr), true); }); test('`_.' + methodName + '` should coerce `target` to a string', 2, function() { strictEqual(func(string, Object(chr)), true); strictEqual(func(string, { 'toString': _.constant(chr) }), true); }); test('`_.' + methodName + '` should coerce `position` to a number', 2, function() { var position = isStartsWith ? 1 : 2; strictEqual(func(string, 'b', Object(position)), true); strictEqual(func(string, 'b', { 'toString': _.constant(String(position)) }), true); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.sum'); (function() { test('should return the sum of an array of numbers', 1, function() { strictEqual(_.sum([6, 4, 2]), 12); }); test('should return `0` when passing empty `array` values', 1, function() { var expected = _.map(empties, _.constant(0)); var actual = _.map(empties, function(value) { return _.sum(value); }); deepEqual(actual, expected); }); test('should coerce values to numbers and `NaN` to `0`', 1, function() { strictEqual(_.sum(['1', NaN, '2']), 3); }); test('should iterate an object', 1, function() { strictEqual(_.sum({ 'a': 1, 'b': 2, 'c': 3 }), 6); }); test('should iterate a string', 2, function() { _.each(['123', Object('123')], function(value) { strictEqual(_.sum(value), 6); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.support'); (function() { test('should contain properties with boolean values', 1, function() { ok(_.every(_.values(_.support), function(value) { return value === true || value === false; })); }); test('should not contain minified properties (test production builds)', 1, function() { var props = [ 'argsTag', 'argsObject', 'dom', 'enumErrorProps', 'enumPrototypes', 'fastBind', 'funcDecomp', 'funcNames', 'hostObject', 'nodeTag', 'nonEnumArgs', 'nonEnumShadows', 'nonEnumStrings', 'ownLast', 'spliceObjects', 'unindexedChars' ]; ok(_.isEmpty(_.difference(_.keys(_.support), props))); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.tap'); (function() { test('should intercept and return the given value', 2, function() { if (!isNpm) { var intercepted, array = [1, 2, 3]; var actual = _.tap(array, function(value) { intercepted = value; }); strictEqual(actual, array); strictEqual(intercepted, array); } else { skipTest(2); } }); test('should intercept unwrapped values and return wrapped values when chaining', 2, function() { if (!isNpm) { var intercepted, array = [1, 2, 3]; var wrapped = _(array).tap(function(value) { intercepted = value; value.pop(); }); ok(wrapped instanceof _); wrapped.value(); strictEqual(intercepted, array); } else { skipTest(2); } }); test('should support the `thisArg` argument', 1, function() { if (!isNpm) { var array = [1, 2]; var wrapped = _(array.slice()).tap(function(value) { value.push(this[0]); }, array); deepEqual(wrapped.value(), [1, 2, 1]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.template'); (function() { test('should escape values in "escape" delimiters', 1, function() { var strings = ['<p><%- value %></p>', '<p><%-value%></p>', '<p><%-\nvalue\n%></p>'], expected = _.map(strings, _.constant('<p>&amp;&lt;&gt;&quot;&#39;&#96;\/</p>')), data = { 'value': '&<>"\'`\/' }; var actual = _.map(strings, function(string) { return _.template(string)(data); }); deepEqual(actual, expected); }); test('should evaluate JavaScript in "evaluate" delimiters', 1, function() { var compiled = _.template( '<ul><%\ for (var key in collection) {\ %><li><%= collection[key] %></li><%\ } %></ul>' ); var data = { 'collection': { 'a': 'A', 'b': 'B' } }, actual = compiled(data); strictEqual(actual, '<ul><li>A</li><li>B</li></ul>'); }); test('should interpolate data object properties', 1, function() { var strings = ['<%= a %>BC', '<%=a%>BC', '<%=\na\n%>BC'], expected = _.map(strings, _.constant('ABC')), data = { 'a': 'A' }; var actual = _.map(strings, function(string) { return _.template(string)(data); }); deepEqual(actual, expected); }); test('should support escaped values in "interpolation" delimiters', 1, function() { var compiled = _.template('<%= a ? "a=\\"A\\"" : "" %>'), data = { 'a': true }; strictEqual(compiled(data), 'a="A"'); }); test('should work with "interpolate" delimiters containing ternary operators', 1, function() { var compiled = _.template('<%= value ? value : "b" %>'), data = { 'value': 'a' }; strictEqual(compiled(data), 'a'); }); test('should work with "interpolate" delimiters containing global values', 1, function() { var compiled = _.template('<%= typeof Math.abs %>'); try { var actual = compiled(); } catch(e) {} strictEqual(actual, 'function'); }); test('should work with complex "interpolate" delimiters', 22, function() { _.each({ '<%= a + b %>': '3', '<%= b - a %>': '1', '<%= a = b %>': '2', '<%= !a %>': 'false', '<%= ~a %>': '-2', '<%= a * b %>': '2', '<%= a / b %>': '0.5', '<%= a % b %>': '1', '<%= a >> b %>': '0', '<%= a << b %>': '4', '<%= a & b %>': '0', '<%= a ^ b %>': '3', '<%= a | b %>': '3', '<%= {}.toString.call(0) %>': numberTag, '<%= a.toFixed(2) %>': '1.00', '<%= obj["a"] %>': '1', '<%= delete a %>': 'true', '<%= "a" in obj %>': 'true', '<%= obj instanceof Object %>': 'true', '<%= new Boolean %>': 'false', '<%= typeof a %>': 'number', '<%= void a %>': '' }, function(value, key) { var compiled = _.template(key), data = { 'a': 1, 'b': 2 }; strictEqual(compiled(data), value, key); }); }); test('should parse ES6 template delimiters', 2, function() { var data = { 'value': 2 }; strictEqual(_.template('1${value}3')(data), '123'); strictEqual(_.template('${"{" + value + "\\}"}')(data), '{2}'); }); test('should not reference `_.escape` when "escape" delimiters are not used', 1, function() { var compiled = _.template('<%= typeof __e %>'); strictEqual(compiled({}), 'undefined'); }); test('should allow referencing variables declared in "evaluate" delimiters from other delimiters', 1, function() { var compiled = _.template('<% var b = a; %><%= b.value %>'), data = { 'a': { 'value': 1 } }; strictEqual(compiled(data), '1'); }); test('should support single line comments in "evaluate" delimiters (test production builds)', 1, function() { var compiled = _.template('<% // A code comment. %><% if (value) { %>yap<% } else { %>nope<% } %>'), data = { 'value': true }; strictEqual(compiled(data), 'yap'); }); test('should work with custom delimiters', 2, function() { _.times(2, function(index) { var settingsClone = _.clone(_.templateSettings); var settings = _.assign(index ? _.templateSettings : {}, { 'escape': /\{\{-([\s\S]+?)\}\}/g, 'evaluate': /\{\{([\s\S]+?)\}\}/g, 'interpolate': /\{\{=([\s\S]+?)\}\}/g }); var compiled = _.template('<ul>{{ _.each(collection, function(value, index) {}}<li>{{= index }}: {{- value }}</li>{{}); }}</ul>', index ? null : settings), expected = '<ul><li>0: a &amp; A</li><li>1: b &amp; B</li></ul>', data = { 'collection': ['a & A', 'b & B'] }; strictEqual(compiled(data), expected); _.assign(_.templateSettings, settingsClone); }); }); test('should work with custom delimiters containing special characters', 2, function() { _.times(2, function(index) { var settingsClone = _.clone(_.templateSettings); var settings = _.assign(index ? _.templateSettings : {}, { 'escape': /<\?-([\s\S]+?)\?>/g, 'evaluate': /<\?([\s\S]+?)\?>/g, 'interpolate': /<\?=([\s\S]+?)\?>/g }); var compiled = _.template('<ul><? _.each(collection, function(value, index) { ?><li><?= index ?>: <?- value ?></li><? }); ?></ul>', index ? null : settings), expected = '<ul><li>0: a &amp; A</li><li>1: b &amp; B</li></ul>', data = { 'collection': ['a & A', 'b & B'] }; strictEqual(compiled(data), expected); _.assign(_.templateSettings, settingsClone); }); }); test('should work with strings without delimiters', 1, function() { var expected = 'abc'; strictEqual(_.template(expected)({}), expected); }); test('should support the "imports" option', 1, function() { var compiled = _.template('<%= a %>', { 'imports': { 'a': 1 } }); strictEqual(compiled({}), '1'); }); test('should support the "variable" options', 1, function() { var compiled = _.template( '<% _.each( data.a, function( value ) { %>' + '<%= value.valueOf() %>' + '<% }) %>', { 'variable': 'data' } ); var data = { 'a': [1, 2, 3] }; try { strictEqual(compiled(data), '123'); } catch(e) { ok(false, e.message); } }); test('should support the legacy `options` param signature', 1, function() { var compiled = _.template('<%= data.a %>', null, { 'variable': 'data' }), data = { 'a': 1 }; strictEqual(compiled(data), '1'); }); test('should use a `with` statement by default', 1, function() { var compiled = _.template('<%= index %><%= collection[index] %><% _.each(collection, function(value, index) { %><%= index %><% }); %>'), actual = compiled({ 'index': 1, 'collection': ['a', 'b', 'c'] }); strictEqual(actual, '1b012'); }); test('should work correctly with `this` references', 2, function() { var compiled = _.template('a<%= this.String("b") %>c'); strictEqual(compiled(), 'abc'); var object = { 'b': 'B' }; object.compiled = _.template('A<%= this.b %>C', { 'variable': 'obj' }); strictEqual(object.compiled(), 'ABC'); }); test('should work with backslashes', 1, function() { var compiled = _.template('<%= a %> \\b'), data = { 'a': 'A' }; strictEqual(compiled(data), 'A \\b'); }); test('should work with escaped characters in string literals', 2, function() { var compiled = _.template('<% print("\'\\n\\r\\t\\u2028\\u2029\\\\") %>'); strictEqual(compiled(), "'\n\r\t\u2028\u2029\\"); var data = { 'a': 'A' }; compiled = _.template('\'\n\r\t<%= a %>\u2028\u2029\\"'); strictEqual(compiled(data), '\'\n\r\tA\u2028\u2029\\"'); }); test('should handle \\u2028 & \\u2029 characters', 1, function() { var compiled = _.template('\u2028<%= "\\u2028\\u2029" %>\u2029'); strictEqual(compiled(), '\u2028\u2028\u2029\u2029'); }); test('should work with statements containing quotes', 1, function() { var compiled = _.template("<%\ if (a == 'A' || a == \"a\") {\ %>'a',\"A\"<%\ } %>" ); var data = { 'a': 'A' }; strictEqual(compiled(data), "'a',\"A\""); }); test('should work with templates containing newlines and comments', 1, function() { var compiled = _.template('<%\n\ // A code comment.\n\ if (value) { value += 3; }\n\ %><p><%= value %></p>' ); strictEqual(compiled({ 'value': 3 }), '<p>6</p>'); }); test('should not error with IE conditional comments enabled (test with development build)', 1, function() { var compiled = _.template(''), pass = true; /*@cc_on @*/ try { compiled(); } catch(e) { pass = false; } ok(pass); }); test('should tokenize delimiters', 1, function() { var compiled = _.template('<span class="icon-<%= type %>2"></span>'), data = { 'type': 1 }; strictEqual(compiled(data), '<span class="icon-12"></span>'); }); test('should evaluate delimiters once', 1, function() { var actual = [], compiled = _.template('<%= func("a") %><%- func("b") %><% func("c") %>'), data = { 'func': function(value) { actual.push(value); } }; compiled(data); deepEqual(actual, ['a', 'b', 'c']); }); test('should match delimiters before escaping text', 1, function() { var compiled = _.template('<<\n a \n>>', { 'evaluate': /<<(.*?)>>/g }); strictEqual(compiled(), '<<\n a \n>>'); }); test('should resolve `null` and `undefined` values to an empty string', 3, function() { var compiled = _.template('<%= a %><%- a %>'), data = { 'a': null }; strictEqual(compiled(data), ''); data = { 'a': undefined }; strictEqual(compiled(data), ''); data = { 'a': {} }; compiled = _.template('<%= a.b %><%- a.b %>'); strictEqual(compiled(data), ''); }); test('should parse delimiters without newlines', 1, function() { var expected = '<<\nprint("<p>" + (value ? "yes" : "no") + "</p>")\n>>', compiled = _.template(expected, { 'evaluate': /<<(.+?)>>/g }), data = { 'value': true }; strictEqual(compiled(data), expected); }); test('should support recursive calls', 1, function() { var compiled = _.template('<%= a %><% a = _.template(c)(obj) %><%= a %>'), data = { 'a': 'A', 'b': 'B', 'c': '<%= b %>' }; strictEqual(compiled(data), 'AB'); }); test('should coerce `text` argument to a string', 1, function() { var object = { 'toString': _.constant('<%= a %>') }, data = { 'a': 1 }; strictEqual(_.template(object)(data), '1'); }); test('should not augment the `options` object', 1, function() { var options = {}; _.template('', options); deepEqual(options, {}); }); test('should not modify `_.templateSettings` when `options` are provided', 2, function() { var data = { 'a': 1 }; ok(!('a' in _.templateSettings)); _.template('', {}, data); ok(!('a' in _.templateSettings)); delete _.templateSettings.a; }); test('should not error for non-object `data` and `options` values', 2, function() { var pass = true; try { _.template('')(1); } catch(e) { pass = false; } ok(pass); pass = true; try { _.template('', 1)(1); } catch(e) { pass = false; } ok(pass); }); test('should expose the source for compiled templates', 1, function() { var compiled = _.template('x'), values = [String(compiled), compiled.source], expected = _.map(values, _.constant(true)); var actual = _.map(values, function(value) { return _.includes(value, '__p'); }); deepEqual(actual, expected); }); test('should expose the source when a SyntaxError occurs', 1, function() { try { _.template('<% if x %>'); } catch(e) { var source = e.source; } ok(_.includes(source, '__p')); }); test('should not include sourceURLs in the source', 1, function() { var options = { 'sourceURL': '/a/b/c' }, compiled = _.template('x', options), values = [compiled.source, undefined]; try { _.template('<% if x %>', options); } catch(e) { values[1] = e.source; } var expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.includes(value, 'sourceURL'); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var array = ['<%= a %>', '<%- b %>', '<% print(c) %>'], compiles = _.map(array, _.template), data = { 'a': 'one', 'b': '`two`', 'c': 'three' }; var actual = _.map(compiles, function(compiled) { return compiled(data); }); deepEqual(actual, ['one', '&#96;two&#96;', 'three']); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.trunc'); (function() { var string = 'hi-diddly-ho there, neighborino'; test('should truncate to a length of `30` by default', 1, function() { strictEqual(_.trunc(string), 'hi-diddly-ho there, neighbo...'); }); test('should not truncate if `string` is <= `length`', 2, function() { strictEqual(_.trunc(string, string.length), string); strictEqual(_.trunc(string, string.length + 2), string); }); test('should truncate string the given length', 1, function() { strictEqual(_.trunc(string, 24), 'hi-diddly-ho there, n...'); }); test('should support a `omission` option', 1, function() { strictEqual(_.trunc(string, { 'omission': ' [...]' }), 'hi-diddly-ho there, neig [...]'); }); test('should support a `length` option', 1, function() { strictEqual(_.trunc(string, { 'length': 4 }), 'h...'); }); test('should support a `separator` option', 2, function() { strictEqual(_.trunc(string, { 'length': 24, 'separator': ' ' }), 'hi-diddly-ho there,...'); strictEqual(_.trunc(string, { 'length': 24, 'separator': /,? +/ }), 'hi-diddly-ho there...'); }); test('should treat negative `length` as `0`', 4, function() { _.each([0, -2], function(length) { strictEqual(_.trunc(string, length), '...'); strictEqual(_.trunc(string, { 'length': length }), '...'); }); }); test('should coerce `length` to an integer', 8, function() { _.each(['', NaN, 4.5, '4'], function(length, index) { var actual = index > 1 ? 'h...' : '...'; strictEqual(_.trunc(string, length), actual); strictEqual(_.trunc(string, { 'length': { 'valueOf': _.constant(length) } }), actual); }); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.trunc(Object(string), 4), 'h...'); strictEqual(_.trunc({ 'toString': _.constant(string) }, 5), 'hi...'); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([string, string, string], _.trunc), truncated = 'hi-diddly-ho there, neighbo...'; deepEqual(actual, [truncated, truncated, truncated]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.throttle'); (function() { asyncTest('should throttle a function', 2, function() { if (!(isRhino && isModularize)) { var callCount = 0, throttled = _.throttle(function() { callCount++; }, 32); throttled(); throttled(); throttled(); var lastCount = callCount; ok(callCount > 0); setTimeout(function() { ok(callCount > lastCount); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); asyncTest('subsequent calls should return the result of the first call', 5, function() { if (!(isRhino && isModularize)) { var throttled = _.throttle(_.identity, 32), result = [throttled('a'), throttled('b')]; deepEqual(result, ['a', 'a']); setTimeout(function() { var result = [throttled('x'), throttled('y')]; notEqual(result[0], 'a'); notStrictEqual(result[0], undefined); notEqual(result[1], 'y'); notStrictEqual(result[1], undefined); QUnit.start(); }, 64); } else { skipTest(5); QUnit.start(); } }); asyncTest('should clear timeout when `func` is called', 1, function() { if (!isModularize) { var callCount = 0, dateCount = 0; var getTime = function() { return ++dateCount == 5 ? Infinity : +new Date; }; var lodash = _.runInContext(_.assign({}, root, { 'Date': function() { return { 'getTime': getTime }; } })); var throttled = lodash.throttle(function() { callCount++; }, 32); throttled(); throttled(); throttled(); setTimeout(function() { strictEqual(callCount, 2); QUnit.start(); }, 64); } else { skipTest(); QUnit.start(); } }); asyncTest('should not trigger a trailing call when invoked once', 2, function() { if (!(isRhino && isModularize)) { var callCount = 0, throttled = _.throttle(function() { callCount++; }, 32); throttled(); strictEqual(callCount, 1); setTimeout(function() { strictEqual(callCount, 1); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); _.times(2, function(index) { asyncTest('should trigger a call when invoked repeatedly' + (index ? ' and `leading` is `false`' : ''), 1, function() { if (!(isRhino && isModularize)) { var callCount = 0, limit = (argv || isPhantom) ? 1000 : 320, options = index ? { 'leading': false } : {}; var throttled = _.throttle(function() { callCount++; }, 32, options); var start = +new Date; while ((new Date - start) < limit) { throttled(); } var actual = callCount > 1; setTimeout(function() { ok(actual); QUnit.start(); }, 1); } else { skipTest(); QUnit.start(); } }); }); asyncTest('should apply default options correctly', 3, function() { if (!(isRhino && isModularize)) { var callCount = 0; var throttled = _.throttle(function(value) { callCount++; return value; }, 32, {}); strictEqual(throttled('a'), 'a'); strictEqual(throttled('b'), 'a'); setTimeout(function() { strictEqual(callCount, 2); QUnit.start(); }, 256); } else { skipTest(3); QUnit.start(); } }); test('should support a `leading` option', 4, function() { _.each([true, { 'leading': true }], function(options) { if (!(isRhino && isModularize)) { var withLeading = _.throttle(_.identity, 32, options); strictEqual(withLeading('a'), 'a'); } else { skipTest(); } }); _.each([false, { 'leading': false }], function(options) { if (!(isRhino && isModularize)) { var withoutLeading = _.throttle(_.identity, 32, options); strictEqual(withoutLeading('a'), undefined); } else { skipTest(); } }); }); asyncTest('should support a `trailing` option', 6, function() { if (!(isRhino && isModularize)) { var withCount = 0, withoutCount = 0; var withTrailing = _.throttle(function(value) { withCount++; return value; }, 64, { 'trailing': true }); var withoutTrailing = _.throttle(function(value) { withoutCount++; return value; }, 64, { 'trailing': false }); strictEqual(withTrailing('a'), 'a'); strictEqual(withTrailing('b'), 'a'); strictEqual(withoutTrailing('a'), 'a'); strictEqual(withoutTrailing('b'), 'a'); setTimeout(function() { strictEqual(withCount, 2); strictEqual(withoutCount, 1); QUnit.start(); }, 256); } else { skipTest(6); QUnit.start(); } }); asyncTest('should not update `lastCalled`, at the end of the timeout, when `trailing` is `false`', 1, function() { if (!(isRhino && isModularize)) { var callCount = 0; var throttled = _.throttle(function() { callCount++; }, 64, { 'trailing': false }); throttled(); throttled(); setTimeout(function() { throttled(); throttled(); }, 96); setTimeout(function() { ok(callCount > 1); QUnit.start(); }, 192); } else { skipTest(); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.debounce and lodash.throttle'); _.each(['debounce', 'throttle'], function(methodName) { var func = _[methodName], isDebounce = methodName == 'debounce'; test('_.' + methodName + ' should not error for non-object `options` values', 1, function() { var pass = true; try { func(_.noop, 32, 1); } catch(e) { pass = false; } ok(pass); }); asyncTest('_.' + methodName + ' should have a default `wait` of `0`', 1, function() { if (!(isRhino && isModularize)) { var callCount = 0; var funced = func(function() { callCount++; }); funced(); setTimeout(function() { funced(); strictEqual(callCount, isDebounce ? 1 : 2); QUnit.start(); }, 32); } else { skipTest(); QUnit.start(); } }); asyncTest('_.' + methodName + ' should call `func` with the correct `this` binding', 1, function() { if (!(isRhino && isModularize)) { var object = { 'funced': func(function() { actual.push(this); }, 32) }; var actual = [], expected = _.times(isDebounce ? 1 : 2, _.constant(object)); object.funced(); if (!isDebounce) { object.funced(); } setTimeout(function() { deepEqual(actual, expected); QUnit.start(); }, 64); } else { skipTest(); QUnit.start(); } }); asyncTest('_.' + methodName + ' supports recursive calls', 2, function() { if (!(isRhino && isModularize)) { var actual = [], args = _.map(['a', 'b', 'c'], function(chr) { return [{}, chr]; }), length = isDebounce ? 1 : 2, expected = args.slice(0, length), queue = args.slice(); var funced = func(function() { var current = [this]; push.apply(current, arguments); actual.push(current); var next = queue.shift(); if (next) { funced.call(next[0], next[1]); } }, 64); var next = queue.shift(); funced.call(next[0], next[1]); deepEqual(actual, expected.slice(0, length - 1)); setTimeout(function() { deepEqual(actual, expected); QUnit.start(); }, 96); } else { skipTest(2); QUnit.start(); } }); asyncTest('_.' + methodName + ' should work if the system time is set backwards', 1, function() { if (!isModularize) { var callCount = 0, dateCount = 0; var getTime = function() { return ++dateCount === 4 ? +new Date(2012, 3, 23, 23, 27, 18) : +new Date; }; var lodash = _.runInContext(_.assign({}, root, { 'Date': function() { return { 'getTime': getTime, 'valueOf': getTime }; } })); var funced = lodash[methodName](function() { callCount++; }, 32); funced(); setTimeout(function() { funced(); strictEqual(callCount, isDebounce ? 1 : 2); QUnit.start(); }, 64); } else { skipTest(); QUnit.start(); } }); asyncTest('_.' + methodName + ' should support cancelling delayed calls', 1, function() { if (!(isRhino && isModularize)) { var callCount = 0; var funced = func(function() { callCount++; }, 32, { 'leading': false }); funced(); funced.cancel(); setTimeout(function() { strictEqual(callCount, 0); QUnit.start(); }, 64); } else { skipTest(); QUnit.start(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.times'); (function() { test('should coerce non-finite `n` values to `0`', 3, function() { _.each([-Infinity, NaN, Infinity], function(n) { deepEqual(_.times(n), []); }); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.times(1, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [0]); }); test('should support the `thisArg` argument', 1, function() { var expect = [1, 2, 3]; var actual = _.times(3, function(num) { return this[num]; }, expect); deepEqual(actual, expect); }); test('should use `_.identity` when `iteratee` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant([0, 1, 2])); var actual = _.map(values, function(value, index) { return index ? _.times(3, value) : _.times(3); }); deepEqual(actual, expected); }); test('should return an array of the results of each `iteratee` execution', 1, function() { deepEqual(_.times(3, function(n) { return n * 2; }), [0, 2, 4]); }); test('should return an empty array for falsey and negative `n` arguments', 1, function() { var values = falsey.concat(-1, -Infinity), expected = _.map(values, _.constant([])); var actual = _.map(values, function(value, index) { return index ? _.times(value) : _.times(); }); deepEqual(actual, expected); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var wrapped = _(3).times(); ok(wrapped instanceof _); deepEqual(wrapped.value(), [0, 1, 2]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.toArray'); (function() { test('should return the values of objects', 1, function() { var array = [1, 2], object = { 'a': 1, 'b': 2 }; deepEqual(_.toArray(object), array); }); test('should work with a string for `collection` (test in Opera < 10.52)', 2, function() { deepEqual(_.toArray('ab'), ['a', 'b']); deepEqual(_.toArray(Object('ab')), ['a', 'b']); }); test('should work in a lazy chain sequence', 2, function() { if (!isNpm) { var actual = _([1, 2]).map(String).toArray().value(); deepEqual(actual, ['1', '2']); actual = _({ 'a': 1, 'b': 2 }).toArray().map(String).value(); deepEqual(actual, ['1', '2']); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.slice and lodash.toArray'); _.each(['slice', 'toArray'], function(methodName) { var args = (function() { return arguments; }(1, 2, 3)), array = [1, 2, 3], func = _[methodName]; test('should return a dense array', 3, function() { var sparse = Array(3); sparse[1] = 2; var actual = func(sparse); ok('0' in actual); ok('2' in actual); deepEqual(actual, sparse); }); test('should treat array-like objects like arrays', 2, function() { var object = { '0': 'a', '1': 'b', '2': 'c', 'length': 3 }; deepEqual(func(object), ['a', 'b', 'c']); deepEqual(func(args), array); }); test('should return a shallow clone of arrays', 2, function() { var actual = func(array); deepEqual(actual, array); notStrictEqual(actual, array); }); test('should work with a node list for `collection` (test in IE < 9)', 1, function() { if (document) { try { var nodeList = document.getElementsByTagName('body'), actual = func(nodeList); } catch(e) {} deepEqual(actual, [body]); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.toPlainObject'); (function() { var args = arguments; test('should flatten inherited properties', 1, function() { function Foo() { this.b = 2; } Foo.prototype.c = 3; var actual = _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 }); }); test('should convert `arguments` objects to plain objects', 1, function() { var actual = _.toPlainObject(args), expected = { '0': 1, '1': 2, '2': 3 }; deepEqual(actual, expected); }); test('should convert arrays to plain objects', 1, function() { var actual = _.toPlainObject(['a', 'b', 'c']), expected = { '0': 'a', '1': 'b', '2': 'c' }; deepEqual(actual, expected); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.transform'); (function() { function Foo() { this.a = 1; this.b = 2; this.c = 3; } test('should create an object with the same `[[Prototype]]` as `object` when `accumulator` is `null` or `undefined`', 4, function() { var accumulators = [, null, undefined], expected = _.map(accumulators, _.constant(true)), object = new Foo; var iteratee = function(result, value, key) { result[key] = value * value; }; var mapper = function(accumulator, index) { return index ? _.transform(object, iteratee, accumulator) : _.transform(object, iteratee); }; var results = _.map(accumulators, mapper); var actual = _.map(results, function(result) { return result instanceof Foo; }); deepEqual(actual, expected); expected = _.map(accumulators, _.constant({ 'a': 1, 'b': 4, 'c': 9 })); actual = _.map(results, _.clone); deepEqual(actual, expected); object = { 'a': 1, 'b': 2, 'c': 3 }; actual = _.map(accumulators, mapper); deepEqual(actual, expected); object = [1, 2, 3]; expected = _.map(accumulators, _.constant([1, 4, 9])); actual = _.map(accumulators, mapper); deepEqual(actual, expected); }); test('should support an `accumulator` value', 4, function() { var values = [new Foo, [1, 2, 3], { 'a': 1, 'b': 2, 'c': 3 }], expected = _.map(values, _.constant([0, 1, 4, 9])); var actual = _.map(values, function(value) { return _.transform(value, function(result, value) { result.push(value * value); }, [0]); }); deepEqual(actual, expected); var object = { '_': 0, 'a': 1, 'b': 4, 'c': 9 }; expected = [object, { '_': 0, '0': 1, '1': 4, '2': 9 }, object]; actual = _.map(values, function(value) { return _.transform(value, function(result, value, key) { result[key] = value * value; }, { '_': 0 }); }); deepEqual(actual, expected); object = {}; expected = _.map(values, _.constant(object)); actual = _.map(values, function(value) { return _.transform(value, _.noop, object); }); deepEqual(actual, expected); actual = _.map(values, function(value) { return _.transform(null, null, object); }); deepEqual(actual, expected); }); test('should treat sparse arrays as dense', 1, function() { var actual = _.transform(Array(1), function(result, value, index) { result[index] = String(value); }); deepEqual(actual, ['undefined']); }); test('should work without an `iteratee` argument', 1, function() { ok(_.transform(new Foo) instanceof Foo); }); test('should check that `object` is an object before using its `[[Prototype]]`', 2, function() { var Ctors = [Boolean, Boolean, Number, Number, Number, String, String], values = [true, false, 0, 1, NaN, '', 'a'], expected = _.map(values, _.constant({})); var results = _.map(values, function(value) { return _.transform(value); }); deepEqual(results, expected); expected = _.map(values, _.constant(false)); var actual = _.map(results, function(value, index) { return value instanceof Ctors[index]; }); deepEqual(actual, expected); }); test('should create an empty object when provided a falsey `object` argument', 1, function() { var expected = _.map(falsey, _.constant({})); var actual = _.map(falsey, function(value, index) { return index ? _.transform(value) : _.transform(); }); deepEqual(actual, expected); }); _.each({ 'array': [1, 2, 3], 'object': { 'a': 1, 'b': 2, 'c': 3 } }, function(object, key) { test('should provide the correct `iteratee` arguments when transforming an ' + key, 2, function() { var args; _.transform(object, function() { args || (args = slice.call(arguments)); }); var first = args[0]; if (key == 'array') { ok(first !== object && _.isArray(first)); deepEqual(args, [first, 1, 0, object]); } else { ok(first !== object && _.isPlainObject(first)); deepEqual(args, [first, 1, 'a', object]); } }); test('should support the `thisArg` argument when transforming an ' + key, 2, function() { var actual = _.transform(object, function(result, value, key) { result[key] = this[key]; }, null, object); deepEqual(actual, object); notStrictEqual(actual, object); }); }); test('should create an object from the same realm as `object`', 1, function() { var objects = _.transform(_, function(result, value, key) { if (_.startsWith(key, '_') && _.isObject(value) && !_.isElement(value)) { result.push(value); } }, []); var expected = _.times(objects.length, _.constant(true)); var actual = _.map(objects, function(object) { var Ctor = object.constructor, result = _.transform(object); if (result === object) { return false; } if (_.isTypedArray(object)) { return result instanceof Array; } return result instanceof Ctor || !(new Ctor instanceof Ctor); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('trim methods'); _.each(['trim', 'trimLeft', 'trimRight'], function(methodName, index) { var func = _[methodName]; var parts = []; if (index != 2) { parts.push('leading'); } if (index != 1) { parts.push('trailing'); } parts = parts.join(' and '); test('`_.' + methodName + '` should remove ' + parts + ' whitespace', 1, function() { var string = whitespace + 'a b c' + whitespace, expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''); strictEqual(func(string), expected); }); test('`_.' + methodName + '` should not remove non-whitespace characters', 1, function() { // Zero-width space (zws), next line character (nel), and non-character (bom) are not whitespace. var problemChars = '\x85\u200b\ufffe', string = problemChars + 'a b c' + problemChars; strictEqual(func(string), string); }); test('`_.' + methodName + '` should coerce `string` to a string', 1, function() { var object = { 'toString': _.constant(whitespace + 'a b c' + whitespace) }, expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''); strictEqual(func(object), expected); }); test('`_.' + methodName + '` should remove ' + parts + ' `chars`', 1, function() { var string = '-_-a-b-c-_-', expected = (index == 2 ? '-_-' : '') + 'a-b-c' + (index == 1 ? '-_-' : ''); strictEqual(func(string, '_-'), expected); }); test('`_.' + methodName + '` should coerce `chars` to a string', 1, function() { var object = { 'toString': _.constant('_-') }, string = '-_-a-b-c-_-', expected = (index == 2 ? '-_-' : '') + 'a-b-c' + (index == 1 ? '-_-' : ''); strictEqual(func(string, object), expected); }); test('`_.' + methodName + '` should return an empty string when provided `null`, `undefined`, or empty string and `chars`', 6, function() { _.each([null, '_-'], function(chars) { strictEqual(func(null, chars), ''); strictEqual(func(undefined, chars), ''); strictEqual(func('', chars), ''); }); }); test('`_.' + methodName + '` should work with `null`, `undefined`, or empty string for `chars`', 3, function() { var string = whitespace + 'a b c' + whitespace, expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''); strictEqual(func(string, null), expected); strictEqual(func(string, undefined), expected); strictEqual(func(string, ''), string); }); test('`_.' + methodName + '` should work as an iteratee for `_.map`', 1, function() { var string = Object(whitespace + 'a b c' + whitespace), trimmed = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''), actual = _.map([string, string, string], func); deepEqual(actual, [trimmed, trimmed, trimmed]); }); test('`_.' + methodName + '` should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { var string = whitespace + 'a b c' + whitespace, expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''); strictEqual(_(string)[methodName](), expected); } else { skipTest(); } }); test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { var string = whitespace + 'a b c' + whitespace; ok(_(string).chain()[methodName]() instanceof _); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.unescape'); (function() { var escaped = '&amp;&lt;&gt;&quot;&#39;\/', unescaped = '&<>"\'\/'; escaped += escaped; unescaped += unescaped; test('should unescape entities in the correct order', 1, function() { strictEqual(_.unescape('&amp;lt;'), '&lt;'); }); test('should unescape the proper entities', 1, function() { strictEqual(_.unescape(escaped), unescaped); }); test('should not unescape the "&#x2F;" entity', 1, function() { strictEqual(_.unescape('&#x2F;'), '&#x2F;'); }); test('should handle strings with nothing to unescape', 1, function() { strictEqual(_.unescape('abc'), 'abc'); }); test('should unescape the same characters escaped by `_.escape`', 1, function() { strictEqual(_.unescape(_.escape(unescaped)), unescaped); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.union'); (function() { var args = arguments; test('should return the union of the given arrays', 1, function() { var actual = _.union([1, 3, 2], [5, 2, 1, 4], [2, 1]); deepEqual(actual, [1, 3, 2, 5, 4]); }); test('should not flatten nested arrays', 1, function() { var actual = _.union([1, 3, 2], [1, [5]], [2, [4]]); deepEqual(actual, [1, 3, 2, [5], [4]]); }); test('should ignore values that are not arrays or `arguments` objects', 3, function() { var array = [0]; deepEqual(_.union(array, 3, null, { '0': 1 }), array); deepEqual(_.union(null, array, null, [2, 1]), [0, 2, 1]); deepEqual(_.union(array, null, args, null), [0, 1, 2, 3]); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.uniq'); (function() { var objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }, { 'a': 2 }, { 'a': 3 }, { 'a': 1 }]; test('should return unique values of an unsorted array', 1, function() { var array = [2, 3, 1, 2, 3, 1]; deepEqual(_.uniq(array), [2, 3, 1]); }); test('should return unique values of a sorted array', 1, function() { var array = [1, 1, 2, 2, 3]; deepEqual(_.uniq(array), [1, 2, 3]); }); test('should treat object instances as unique', 1, function() { deepEqual(_.uniq(objects), objects); }); test('should not treat `NaN` as unique', 1, function() { deepEqual(_.uniq([1, NaN, 3, NaN]), [1, NaN, 3]); }); test('should work with `isSorted`', 3, function() { var expected = [1, 2, 3]; deepEqual(_.uniq([1, 2, 3], true), expected); deepEqual(_.uniq([1, 1, 2, 2, 3], true), expected); deepEqual(_.uniq([1, 2, 3, 3, 3, 3, 3], true), expected); }); test('should work with an `iteratee` argument', 2, function() { _.each([objects, _.sortBy(objects, 'a')], function(array, index) { var isSorted = !!index, expected = isSorted ? [objects[2], objects[0], objects[1]] : objects.slice(0, 3); var actual = _.uniq(array, isSorted, function(object) { return object.a; }); deepEqual(actual, expected); }); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.uniq(objects, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [objects[0], 0, objects]); }); test('should work with `iteratee` without specifying `isSorted`', 1, function() { var actual = _.uniq(objects, function(object) { return object.a; }); deepEqual(actual, objects.slice(0, 3)); }); test('should support the `thisArg` argument', 1, function() { var actual = _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); deepEqual(actual, [1, 2, 3]); }); test('should work with a "_.property" style `iteratee`', 2, function() { var actual = _.uniq(objects, 'a'); deepEqual(actual, objects.slice(0, 3)); var arrays = [[2], [3], [1], [2], [3], [1]]; actual = _.uniq(arrays, 0); deepEqual(actual, arrays.slice(0, 3)); }); test('should perform an unsorted uniq when used as an iteratee for `_.map`', 1, function() { var array = [[2, 1, 2], [1, 2, 1]], actual = _.map(array, _.uniq); deepEqual(actual, [[2, 1], [1, 2]]); }); test('should work with large arrays', 1, function() { var largeArray = [], expected = [0, 'a', {}], count = Math.ceil(LARGE_ARRAY_SIZE / expected.length); _.times(count, function() { push.apply(largeArray, expected); }); deepEqual(_.uniq(largeArray), expected); }); test('should work with large arrays of boolean, `NaN`, `null`, and `undefined` values', 1, function() { var largeArray = [], expected = [true, false, NaN, null, undefined], count = Math.ceil(LARGE_ARRAY_SIZE / expected.length); _.times(count, function() { push.apply(largeArray, expected); }); deepEqual(_.uniq(largeArray), expected); }); test('should work with large arrays of symbols', 1, function() { if (Symbol) { var largeArray = _.times(LARGE_ARRAY_SIZE, function() { return Symbol(); }); deepEqual(_.uniq(largeArray), largeArray); } else { skipTest(); } }); test('should distinguish between numbers and numeric strings', 1, function() { var array = [], expected = ['2', 2, Object('2'), Object(2)], count = Math.ceil(LARGE_ARRAY_SIZE / expected.length); _.times(count, function() { push.apply(array, expected); }); deepEqual(_.uniq(array), expected); }); _.each({ 'an object': ['a'], 'a number': 0, 'a string': '0' }, function(callback, key) { test('should work with ' + key + ' for `iteratee`', 1, function() { var actual = _.uniq([['a'], ['b'], ['a']], callback); deepEqual(actual, [['a'], ['b']]); }); }); test('should be aliased', 1, function() { strictEqual(_.unique, _.uniq); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.uniqueId'); (function() { test('should generate unique ids', 1, function() { var actual = _.times(1000, function() { return _.uniqueId(); }); strictEqual(_.uniq(actual).length, actual.length); }); test('should return a string value when not providing a prefix argument', 1, function() { strictEqual(typeof _.uniqueId(), 'string'); }); test('should coerce the prefix argument to a string', 1, function() { var actual = [_.uniqueId(3), _.uniqueId(2), _.uniqueId(1)]; ok(/3\d+,2\d+,1\d+/.test(actual)); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.values'); (function() { test('should get the values of an object', 1, function() { var object = { 'a': 1, 'b': 2 }; deepEqual(_.values(object), [1, 2]); }); test('should work with an object that has a `length` property', 1, function() { var object = { '0': 'a', '1': 'b', 'length': 2 }; deepEqual(_.values(object), ['a', 'b', 2]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.where'); (function() { test('should filter by `source` properties', 12, function() { var objects = [ { 'a': 1 }, { 'a': 1 }, { 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }, { 'a': 3 } ]; var pairs = [ [{ 'a': 1 }, [{ 'a': 1 }, { 'a': 1 }, { 'a': 1, 'b': 2 }]], [{ 'a': 2 }, [{ 'a': 2, 'b': 2 }]], [{ 'a': 3 }, [{ 'a': 3 }]], [{ 'b': 1 }, []], [{ 'b': 2 }, [{ 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }]], [{ 'a': 1, 'b': 2 }, [{ 'a': 1, 'b': 2 }]] ]; _.each(pairs, function(pair) { var actual = _.where(objects, pair[0]); deepEqual(actual, pair[1]); ok(_.isEmpty(_.difference(actual, objects))); }); }); test('should work with an object for `collection`', 1, function() { var object = { 'x': { 'a': 1 }, 'y': { 'a': 3 }, 'z': { 'a': 1, 'b': 2 } }; var actual = _.where(object, { 'a': 1 }); deepEqual(actual, [object.x, object.z]); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [ { 'a': 1 }, { 'a': 3 }, { 'a': 1, 'b': 2 } ]; var actual = _(array).where({ 'a': 1 }).value(); deepEqual(actual, [array[0], array[2]]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.without'); (function() { test('should use strict equality to determine the values to reject', 2, function() { var object1 = { 'a': 1 }, object2 = { 'b': 2 }, array = [object1, object2]; deepEqual(_.without(array, { 'a': 1 }), array); deepEqual(_.without(array, object1), [object2]); }); test('should remove all occurrences of each value from an array', 1, function() { var array = [1, 2, 3, 1, 2, 3]; deepEqual(_.without(array, 1, 2), [3, 3]); }); test('should treat string values for `array` as empty', 1, function() { deepEqual(_.without('abc', 'b'), []); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.words'); (function() { test('should treat latin-1 supplementary letters as words', 1, function() { var expected = _.map(burredLetters, function(letter) { return [letter]; }); var actual = _.map(burredLetters, function(letter) { return _.words(letter); }); deepEqual(actual, expected); }); test('should not treat mathematical operators as words', 1, function() { var operators = ['\xd7', '\xf7'], expected = _.map(operators, _.constant([])), actual = _.map(operators, _.words); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var strings = _.map(['a', 'b', 'c'], Object), actual = _.map(strings, _.words); deepEqual(actual, [['a'], ['b'], ['c']]); }); test('should work with compound words', 6, function() { deepEqual(_.words('aeiouAreVowels'), ['aeiou', 'Are', 'Vowels']); deepEqual(_.words('enable 24h format'), ['enable', '24', 'h', 'format']); deepEqual(_.words('LETTERSAeiouAreVowels'), ['LETTERS', 'Aeiou', 'Are', 'Vowels']); deepEqual(_.words('tooLegit2Quit'), ['too', 'Legit', '2', 'Quit']); deepEqual(_.words('walk500Miles'), ['walk', '500', 'Miles']); deepEqual(_.words('xhr2Request'), ['xhr', '2', 'Request']); }); test('should work with compound words containing diacritical marks', 3, function() { deepEqual(_.words('LETTERSÆiouAreVowels'), ['LETTERS', 'Æiou', 'Are', 'Vowels']); deepEqual(_.words('æiouAreVowels'), ['æiou', 'Are', 'Vowels']); deepEqual(_.words('æiou2Consonants'), ['æiou', '2', 'Consonants']); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.wrap'); (function() { test('should create a wrapped function', 1, function() { var p = _.wrap(_.escape, function(func, text) { return '<p>' + func(text) + '</p>'; }); strictEqual(p('fred, barney, & pebbles'), '<p>fred, barney, &amp; pebbles</p>'); }); test('should provide the correct `wrapper` arguments', 1, function() { var args; var wrapped = _.wrap(_.noop, function() { args || (args = slice.call(arguments)); }); wrapped(1, 2, 3); deepEqual(args, [_.noop, 1, 2, 3]); }); test('should not set a `this` binding', 1, function() { var p = _.wrap(_.escape, function(func) { return '<p>' + func(this.text) + '</p>'; }); var object = { 'p': p, 'text': 'fred, barney, & pebbles' }; strictEqual(object.p(), '<p>fred, barney, &amp; pebbles</p>'); }); test('should use `_.identity` when `wrapper` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant('a')); var actual = _.map(values, function(value, index) { var wrapped = index ? _.wrap('a', value) : _.wrap('a'); return wrapped('b', 'c'); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.xor'); (function() { var args = arguments; test('should return the symmetric difference of the given arrays', 1, function() { var actual = _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); deepEqual(actual, [1, 4, 5]); }); test('should return an array of unique values', 2, function() { var actual = _.xor([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]); deepEqual(actual, [1, 4, 5]); actual = _.xor([1, 1]); deepEqual(actual, [1]); }); test('should return a new array when a single array is provided', 1, function() { var array = [1]; notStrictEqual(_.xor(array), array); }); test('should ignore individual secondary arguments', 1, function() { var array = [0]; deepEqual(_.xor(array, 3, null, { '0': 1 }), array); }); test('should ignore values that are not arrays or `arguments` objects', 3, function() { var array = [1, 2]; deepEqual(_.xor(array, 3, null, { '0': 1 }), array); deepEqual(_.xor(null, array, null, [2, 3]), [1, 3]); deepEqual(_.xor(array, null, args, null), [3]); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var wrapped = _([1, 2, 3]).xor([5, 2, 1, 4]); ok(wrapped instanceof _); deepEqual(wrapped.value(), [3, 5, 4]); } else { skipTest(2); } }); test('should work when in a lazy chain sequence before `first` or `last`', 1, function() { if (!isNpm) { var wrapped = _([1, 2]).slice().xor([2, 3]); var actual = _.map(['first', 'last'], function(methodName) { return wrapped[methodName](); }); deepEqual(actual, [1, 3]); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.unzip and lodash.zip'); _.each(['unzip', 'zip'], function(methodName, index) { var func = _[methodName]; func = _.bind(index ? func.apply : func.call, func, null); var object = { 'an empty array': [ [], [] ], '0-tuples': [ [[], []], [] ], '2-tuples': [ [['barney', 'fred'], [36, 40]], [['barney', 36], ['fred', 40]] ], '3-tuples': [ [['barney', 'fred'], [36, 40], [true, false]], [['barney', 36, true], ['fred', 40, false]] ] }; _.forOwn(object, function(pair, key) { test('`_.' + methodName + '` should work with ' + key, 2, function() { var actual = func(pair[0]); deepEqual(actual, pair[1]); deepEqual(func(actual), actual.length ? pair[0] : []); }); }); test('`_.' + methodName + '` should work with tuples of different lengths', 4, function() { var pair = [ [['barney', 36], ['fred', 40, false]], [['barney', 'fred'], [36, 40], [undefined, false]] ]; var actual = func(pair[0]); ok('0' in actual[2]); deepEqual(actual, pair[1]); actual = func(actual); ok('2' in actual[0]); deepEqual(actual, [['barney', 36, undefined], ['fred', 40, false]]); }); test('`_.' + methodName + '` should treat falsey values as empty arrays', 1, function() { var expected = _.map(falsey, _.constant([])); var actual = _.map(falsey, function(value) { return func([value, value, value]); }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should support consuming its return value', 1, function() { var expected = [['barney', 'fred'], [36, 40]]; deepEqual(func(func(func(func(expected)))), expected); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.zipObject'); (function() { var object = { 'barney': 36, 'fred': 40 }, array = [['barney', 36], ['fred', 40]]; test('should skip falsey elements in a given two dimensional array', 1, function() { var actual = _.zipObject(array.concat(falsey)); deepEqual(actual, object); }); test('should zip together key/value arrays into an object', 1, function() { var actual = _.zipObject(['barney', 'fred'], [36, 40]); deepEqual(actual, object); }); test('should ignore extra `values`', 1, function() { deepEqual(_.zipObject(['a'], [1, 2]), { 'a': 1 }); }); test('should accept a two dimensional array', 1, function() { var actual = _.zipObject(array); deepEqual(actual, object); }); test('should not assume `keys` is two dimensional if `values` is not provided', 1, function() { var actual = _.zipObject(['barney', 'fred']); deepEqual(actual, { 'barney': undefined, 'fred': undefined }); }); test('should accept a falsey `array` argument', 1, function() { var expected = _.map(falsey, _.constant({})); var actual = _.map(falsey, function(value, index) { try { return index ? _.zipObject(value) : _.zipObject(); } catch(e) {} }); deepEqual(actual, expected); }); test('should support consuming the return value of `_.pairs`', 1, function() { deepEqual(_.zipObject(_.pairs(object)), object); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [['a', 1], ['b', 2]], predicate = function(value) { return value > 2; }, actual = _(array).zipObject().map(square).filter(predicate).take().value(); deepEqual(actual, [4]); } else { skipTest(); } }); test('should be aliased', 1, function() { strictEqual(_.object, _.zipObject); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).commit'); (function() { test('should execute the chained sequence and returns the wrapped result', 4, function() { if (!isNpm) { var array = [1], wrapped = _(array).push(2).push(3); deepEqual(array, [1]); var otherWrapper = wrapped.commit(); ok(otherWrapper instanceof _); deepEqual(otherWrapper.value(), [1, 2, 3]); deepEqual(wrapped.value(), [1, 2, 3, 2, 3]); } else { skipTest(4); } }); test('should track the `__chain__` value of a wrapper', 2, function() { if (!isNpm) { var wrapper = _([1]).chain().commit().first(); ok(wrapper instanceof _); strictEqual(wrapper.value(), 1); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).concat'); (function() { test('should return a new wrapped array', 3, function() { if (!isNpm) { var array = [1], wrapped = _(array).concat([2, 3]), actual = wrapped.value(); deepEqual(array, [1]); deepEqual(actual, [1, 2, 3]); notStrictEqual(actual, array); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).join'); (function() { var array = [1, 2, 3]; test('should return join all array elements into a string', 2, function() { if (!isNpm) { var wrapped = _(array); strictEqual(wrapped.join('.'), '1.2.3'); strictEqual(wrapped.value(), array); } else { skipTest(2); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain().join('.') instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).plant'); (function() { test('should clone the chained sequence planting `value` as the wrapped value', 2, function() { if (!isNpm) { var array1 = [5, null, 3, null, 1], array2 = [10, null, 8, null, 6], wrapper1 = _(array1).thru(_.compact).map(square).takeRight(2).sort(), wrapper2 = wrapper1.plant(array2); deepEqual(wrapper2.value(), [36, 64]); deepEqual(wrapper1.value(), [1, 9]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).pop'); (function() { test('should remove elements from the end of `array`', 5, function() { if (!isNpm) { var array = [1, 2], wrapped = _(array); strictEqual(wrapped.pop(), 2); deepEqual(wrapped.value(), [1]); strictEqual(wrapped.pop(), 1); var actual = wrapped.value(); deepEqual(actual, []); strictEqual(actual, array); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).push'); (function() { test('should append elements to `array`', 2, function() { if (!isNpm) { var array = [1], wrapped = _(array).push(2, 3), actual = wrapped.value(); strictEqual(actual, array); deepEqual(actual, [1, 2, 3]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).replace'); (function() { test('should replace the matched pattern', 2, function() { if (!isNpm) { var wrapped = _('abcdef'); strictEqual(wrapped.replace('def', '123'), 'abc123'); strictEqual(wrapped.replace(/[bdf]/g, '-'), 'a-c-e-'); } else { skipTest(2); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_('abc').chain().replace('b', '_') instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).reverse'); (function() { test('should return the wrapped reversed `array`', 3, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array).reverse(), actual = wrapped.value(); ok(wrapped instanceof _); strictEqual(actual, array); deepEqual(actual, [3, 2, 1]); } else { skipTest(3); } }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var actual = _([1, 2, 3, null]).map(_.identity).reverse().value(); deepEqual(actual, [null, 3, 2, 1]); } else { skipTest(); } }); test('should be lazy when in a lazy chain sequence', 2, function() { if (!isNpm) { var spy = { 'toString': function() { throw new Error('spy was revealed'); } }; try { var wrapped = _(['a', spy]).map(String).reverse(), actual = wrapped.last(); } catch(e) {} ok(wrapped instanceof _); strictEqual(actual, 'a'); } else { skipTest(2); } }); test('should work in a hybrid chain sequence', 4, function() { if (!isNpm) { var array = [1, 2, 3, null]; _.each(['map', 'filter'], function(methodName) { var actual = _(array)[methodName](_.identity).thru(_.compact).reverse().value(); deepEqual(actual, [3, 2, 1]); actual = _(array).thru(_.compact)[methodName](_.identity).pull(1).push(4).reverse().value(); deepEqual(actual, [4, 3, 2]); }); } else { skipTest(4); } }); test('should track the `__chain__` value of a wrapper', 2, function() { if (!isNpm) { var wrapper = _([1, 2, 3]).chain().reverse().first(); ok(wrapper instanceof _); strictEqual(wrapper.value(), 3); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).shift'); (function() { test('should remove elements from the front of `array`', 5, function() { if (!isNpm) { var array = [1, 2], wrapped = _(array); strictEqual(wrapped.shift(), 1); deepEqual(wrapped.value(), [2]); strictEqual(wrapped.shift(), 2); var actual = wrapped.value(); deepEqual(actual, []); strictEqual(actual, array); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).slice'); (function() { test('should return a slice of `array`', 3, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array).slice(0, 2), actual = wrapped.value(); deepEqual(array, [1, 2, 3]); deepEqual(actual, [1, 2]); notStrictEqual(actual, array); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).sort'); (function() { test('should return the wrapped sorted `array`', 2, function() { if (!isNpm) { var array = [3, 1, 2], wrapped = _(array).sort(), actual = wrapped.value(); strictEqual(actual, array); deepEqual(actual, [1, 2, 3]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).splice'); (function() { test('should support removing and inserting elements', 5, function() { if (!isNpm) { var array = [1, 2], wrapped = _(array); deepEqual(wrapped.splice(1, 1, 3).value(), [2]); deepEqual(wrapped.value(), [1, 3]); deepEqual(wrapped.splice(0, 2).value(), [1, 3]); var actual = wrapped.value(); deepEqual(actual, []); strictEqual(actual, array); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).split'); (function() { test('should support string split', 2, function() { if (!isNpm) { var wrapped = _('abcde'); deepEqual(wrapped.split('c').value(), ['ab', 'de']); deepEqual(wrapped.split(/[bd]/).value(), ['a', 'c', 'e']); } else { skipTest(2); } }); test('should allow mixed string and array prototype methods', 1, function() { if (!isNpm) { var wrapped = _('abc'); strictEqual(wrapped.split('b').join(','), 'a,c'); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).unshift'); (function() { test('should prepend elements to `array`', 2, function() { if (!isNpm) { var array = [3], wrapped = _(array).unshift(1, 2), actual = wrapped.value(); strictEqual(actual, array); deepEqual(actual, [1, 2, 3]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('splice objects'); _.each(['pop', 'shift', 'splice'], function(methodName) { test('`_(...).' + methodName + '` should remove the value at index `0` when length is `0` (test in IE 8 compatibility mode)', 2, function() { if (!isNpm) { var wrapped = _({ '0': 1, 'length': 1 }); if (methodName == 'splice') { wrapped.splice(0, 1).value(); } else { wrapped[methodName](); } deepEqual(wrapped.keys().value(), ['length']); strictEqual(wrapped.first(), undefined); } else { skipTest(2); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).toString'); (function() { test('should return the `toString` result of the wrapped value', 1, function() { if (!isNpm) { var wrapped = _([1, 2, 3]); strictEqual(String(wrapped), '1,2,3'); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).value'); (function() { test('should execute the chained sequence and extract the unwrapped value', 4, function() { if (!isNpm) { var array = [1], wrapped = _(array).push(2).push(3); deepEqual(array, [1]); deepEqual(wrapped.value(), [1, 2, 3]); deepEqual(wrapped.value(), [1, 2, 3, 2, 3]); deepEqual(array, [1, 2, 3, 2, 3]); } else { skipTest(4); } }); test('should return the `valueOf` result of the wrapped value', 1, function() { if (!isNpm) { var wrapped = _(123); strictEqual(Number(wrapped), 123); } else { skipTest(); } }); test('should stringify the wrapped value when used by `JSON.stringify`', 1, function() { if (!isNpm && JSON) { var wrapped = _([1, 2, 3]); strictEqual(JSON.stringify(wrapped), '[1,2,3]'); } else { skipTest(); } }); test('should be aliased', 3, function() { if (!isNpm) { var expected = _.prototype.value; strictEqual(_.prototype.run, expected); strictEqual(_.prototype.toJSON, expected); strictEqual(_.prototype.valueOf, expected); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...) methods that return the wrapped modified array'); (function() { var funcs = [ 'push', 'reverse', 'sort', 'unshift' ]; _.each(funcs, function(methodName) { test('`_(...).' + methodName + '` should return a new wrapper', 2, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array), actual = wrapped[methodName](); ok(actual instanceof _); notStrictEqual(actual, wrapped); } else { skipTest(2); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...) methods that return new wrapped values'); (function() { var funcs = [ 'concat', 'slice', 'splice' ]; _.each(funcs, function(methodName) { test('`_(...).' + methodName + '` should return a new wrapped value', 2, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array), actual = wrapped[methodName](); ok(actual instanceof _); notStrictEqual(actual, wrapped); } else { skipTest(2); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...) methods that return unwrapped values'); (function() { var funcs = [ 'clone', 'contains', 'every', 'find', 'first', 'has', 'isArguments', 'isArray', 'isBoolean', 'isDate', 'isElement', 'isEmpty', 'isEqual', 'isError', 'isFinite', 'isFunction', 'isNaN', 'isNull', 'isNumber', 'isObject', 'isPlainObject', 'isRegExp', 'isString', 'isUndefined', 'join', 'last', 'max', 'min', 'parseInt', 'pop', 'shift', 'sum', 'random', 'reduce', 'reduceRight', 'some' ]; _.each(funcs, function(methodName) { test('`_(...).' + methodName + '` should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { var array = [1, 2, 3], actual = _(array)[methodName](); ok(!(actual instanceof _)); } else { skipTest(); } }); test('`_(...).' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { var array = [1, 2, 3], actual = _(array).chain()[methodName](); ok(actual instanceof _); } else { skipTest(); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('"Arrays" category methods'); (function() { var args = arguments, array = [1, 2, 3, 4, 5, 6]; test('should work with `arguments` objects', 29, function() { function message(methodName) { return '`_.' + methodName + '` should work with `arguments` objects'; } deepEqual(_.difference(args, [null]), [1, [3], 5], message('difference')); deepEqual(_.difference(array, args), [2, 3, 4, 6], '_.difference should work with `arguments` objects as secondary arguments'); deepEqual(_.union(args, [null, 6]), [1, null, [3], 5, 6], message('union')); deepEqual(_.union(array, args), array.concat([null, [3]]), '_.union should work with `arguments` objects as secondary arguments'); deepEqual(_.compact(args), [1, [3], 5], message('compact')); deepEqual(_.drop(args, 3), [null, 5], message('drop')); deepEqual(_.dropRight(args, 3), [1, null], message('dropRight')); deepEqual(_.dropRightWhile(args,_.identity), [1, null, [3], null], message('dropRightWhile')); deepEqual(_.dropWhile(args,_.identity), [ null, [3], null, 5], message('dropWhile')); deepEqual(_.findIndex(args, _.identity), 0, message('findIndex')); deepEqual(_.findLastIndex(args, _.identity), 4, message('findLastIndex')); deepEqual(_.first(args), 1, message('first')); deepEqual(_.flatten(args), [1, null, 3, null, 5], message('flatten')); deepEqual(_.indexOf(args, 5), 4, message('indexOf')); deepEqual(_.initial(args), [1, null, [3], null], message('initial')); deepEqual(_.intersection(args, [1]), [1], message('intersection')); deepEqual(_.last(args), 5, message('last')); deepEqual(_.lastIndexOf(args, 1), 0, message('lastIndexOf')); deepEqual(_.rest(args, 4), [null, [3], null, 5], message('rest')); deepEqual(_.sortedIndex(args, 6), 5, message('sortedIndex')); deepEqual(_.take(args, 2), [1, null], message('take')); deepEqual(_.takeRight(args, 1), [5], message('takeRight')); deepEqual(_.takeRightWhile(args, _.identity), [5], message('takeRightWhile')); deepEqual(_.takeWhile(args, _.identity), [1], message('takeWhile')); deepEqual(_.uniq(args), [1, null, [3], 5], message('uniq')); deepEqual(_.without(args, null), [1, [3], 5], message('without')); deepEqual(_.zip(args, args), [[1, 1], [null, null], [[3], [3]], [null, null], [5, 5]], message('zip')); if (_.support.argsTag && _.support.argsObject && !_.support.nonEnumArgs) { _.pull(args, null); deepEqual([args[0], args[1], args[2]], [1, [3], 5], message('pull')); _.remove(args, function(value) { return typeof value == 'number'; }); ok(args.length === 1 && _.isEqual(args[0], [3]), message('remove')); } else { skipTest(2); } }); test('should accept falsey primary arguments', 4, function() { function message(methodName) { return '`_.' + methodName + '` should accept falsey primary arguments'; } deepEqual(_.difference(null, array), [], message('difference')); deepEqual(_.intersection(null, array), array, message('intersection')); deepEqual(_.union(null, array), array, message('union')); deepEqual(_.xor(null, array), array, message('xor')); }); test('should accept falsey secondary arguments', 3, function() { function message(methodName) { return '`_.' + methodName + '` should accept falsey secondary arguments'; } deepEqual(_.difference(array, null), array, message('difference')); deepEqual(_.intersection(array, null), array, message('intersection')); deepEqual(_.union(array, null), array, message('union')); }); }(1, null, [3], null, 5)); /*--------------------------------------------------------------------------*/ QUnit.module('"Strings" category methods'); (function() { var stringMethods = [ 'camelCase', 'capitalize', 'escape', 'escapeRegExp', 'kebabCase', 'pad', 'padLeft', 'padRight', 'repeat', 'snakeCase', 'trim', 'trimLeft', 'trimRight', 'trunc', 'unescape' ]; _.each(stringMethods, function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` should return an empty string when provided `null`, `undefined`, or empty string', 3, function() { strictEqual(func(null), ''); strictEqual(func(undefined), ''); strictEqual(func(''), ''); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash methods'); (function() { var allMethods = _.reject(_.functions(_).sort(), function(methodName) { return _.startsWith(methodName, '_'); }); var checkFuncs = [ 'after', 'ary', 'before', 'bind', 'curry', 'curryRight', 'debounce', 'defer', 'delay', 'memoize', 'negate', 'once', 'partial', 'partialRight', 'rearg', 'spread', 'throttle' ]; var rejectFalsey = [ 'backflow', 'compose', 'flow', 'flowRight', 'tap', 'thru' ].concat(checkFuncs); var returnArrays = [ 'at', 'chunk', 'compact', 'difference', 'drop', 'filter', 'flatten', 'functions', 'initial', 'intersection', 'invoke', 'keys', 'map', 'pairs', 'pluck', 'pull', 'pullAt', 'range', 'reject', 'remove', 'rest', 'sample', 'shuffle', 'sortBy', 'sortByAll', 'sortByOrder', 'take', 'times', 'toArray', 'union', 'uniq', 'values', 'where', 'without', 'xor', 'zip' ]; var acceptFalsey = _.difference(allMethods, rejectFalsey); test('should accept falsey arguments', 213, function() { var emptyArrays = _.map(falsey, _.constant([])), isExposed = '_' in root, oldDash = root._; _.each(acceptFalsey, function(methodName) { var expected = emptyArrays, func = _[methodName], pass = true; var actual = _.map(falsey, function(value, index) { try { return index ? func(value) : func(); } catch(e) { pass = false; } }); if (methodName == 'noConflict') { if (isExposed) { root._ = oldDash; } else { delete root._; } } else if (methodName == 'pull') { expected = falsey; } if (_.includes(returnArrays, methodName) && methodName != 'sample') { deepEqual(actual, expected, '_.' + methodName + ' returns an array'); } ok(pass, '`_.' + methodName + '` accepts falsey arguments'); }); // Skip tests for missing methods of modularized builds. _.each(['chain', 'noConflict', 'runInContext'], function(methodName) { if (!_[methodName]) { skipTest(); } }); }); test('should return an array', 72, function() { var array = [1, 2, 3]; _.each(returnArrays, function(methodName) { var actual, func = _[methodName]; switch (methodName) { case 'invoke': actual = func(array, 'toFixed'); break; case 'sample': actual = func(array, 1); break; default: actual = func(array); } ok(_.isArray(actual), '_.' + methodName + ' returns an array'); var isPull = methodName == 'pull'; strictEqual(actual === array, isPull, '_.' + methodName + ' should ' + (isPull ? '' : 'not ') + 'return the provided array'); }); }); test('should throw an error for falsey arguments', 23, function() { _.each(rejectFalsey, function(methodName) { var expected = _.map(falsey, _.constant(true)), func = _[methodName]; var actual = _.map(falsey, function(value, index) { var pass = !index && /^(?:backflow|compose|flow(Right)?)$/.test(methodName); try { index ? func(value) : func(); } catch(e) { pass = _.includes(checkFuncs, methodName) ? e.message == FUNC_ERROR_TEXT : !pass; } return pass; }); deepEqual(actual, expected, '`_.' + methodName + '` rejects falsey arguments'); }); }); test('should handle `null` `thisArg` arguments', 44, function() { var expected = (function() { return this; }).call(null); var funcs = [ 'assign', 'clone', 'cloneDeep', 'countBy', 'dropWhile', 'dropRightWhile', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'groupBy', 'isEqual', 'map', 'mapValues', 'max', 'merge', 'min', 'omit', 'partition', 'pick', 'reduce', 'reduceRight', 'reject', 'remove', 'some', 'sortBy', 'sortedIndex', 'takeWhile', 'takeRightWhile', 'tap', 'times', 'transform', 'thru', 'uniq' ]; _.each(funcs, function(methodName) { var actual, array = ['a'], callback = function() { actual = this; }, func = _[methodName], message = '`_.' + methodName + '` handles `null` `thisArg` arguments'; if (func) { if (_.startsWith(methodName, 'reduce') || methodName == 'transform') { func(array, callback, 0, null); } else if (_.includes(['assign', 'merge'], methodName)) { func(array, array, callback, null); } else if (_.includes(['isEqual', 'sortedIndex'], methodName)) { func(array, 'a', callback, null); } else if (methodName == 'times') { func(1, callback, null); } else { func(array, callback, null); } strictEqual(actual, expected, message); } else { skipTest(); } }); }); test('should not contain minified method names (test production builds)', 1, function() { ok(_.every(_.functions(_), function(methodName) { return methodName.length > 2 || methodName === 'at'; })); }); }()); /*--------------------------------------------------------------------------*/ QUnit.config.asyncRetries = 10; QUnit.config.hidepassed = true; if (!document) { QUnit.config.noglobals = true; QUnit.load(); } }.call(this));
test/test.js
;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used to detect when a function becomes hot. */ var HOT_COUNT = 150; /** Used as the size to cover large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used as references for the max length and index of an array. */ var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1; /** Used as the maximum length an array-like object. */ var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; /** `Object#toString` result references. */ var funcTag = '[object Function]', numberTag = '[object Number]', objectTag = '[object Object]'; /** Used as a reference to the global object. */ var root = (typeof global == 'object' && global) || this; /** Used to store lodash to test for bad extensions/shims. */ var lodashBizarro = root.lodashBizarro; /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, funcProto = Function.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Method and object shortcuts. */ var phantom = root.phantom, amd = root.define && define.amd, argv = root.process && process.argv, ArrayBuffer = root.ArrayBuffer, document = !phantom && root.document, body = root.document && root.document.body, create = Object.create, fnToString = funcProto.toString, freeze = Object.freeze, hasOwnProperty = objectProto.hasOwnProperty, JSON = root.JSON, objToString = objectProto.toString, noop = function() {}, params = root.arguments, push = arrayProto.push, slice = arrayProto.slice, Symbol = root.Symbol, system = root.system, Uint8Array = root.Uint8Array; /** Math helpers. */ var add = function(x, y) { return x + y; }, square = function(n) { return n * n; }; /** Used to set property descriptors. */ var defineProperty = (function() { try { var o = {}, func = Object.defineProperty, result = func(o, o, o) && func; } catch(e) {} return result; }()); /** The file path of the lodash file to test. */ var filePath = (function() { var min = 0, result = []; if (phantom) { result = params = phantom.args; } else if (system) { min = 1; result = params = system.args; } else if (argv) { min = 2; result = params = argv; } else if (params) { result = params; } var last = result[result.length - 1]; result = (result.length > min && !/test(?:\.js)?$/.test(last)) ? last : '../lodash.src.js'; if (!amd) { try { result = require('fs').realpathSync(result); } catch(e) {} try { result = require.resolve(result); } catch(e) {} } return result; }()); /** The `ui` object. */ var ui = root.ui || (root.ui = { 'buildPath': filePath, 'loaderPath': '', 'isModularize': /\b(?:amd|commonjs|es6?|node|npm|(index|main)\.js)\b/.test(filePath), 'isStrict': /\bes6?\b/.test(filePath), 'urlParams': {} }); /** The basename of the lodash file to test. */ var basename = /[\w.-]+$/.exec(filePath)[0]; /** Detect if in a Java environment. */ var isJava = !document && !!root.java; /** Used to indicate testing a modularized build. */ var isModularize = ui.isModularize; /** Detect if testing `npm` modules. */ var isNpm = isModularize && /\bnpm\b/.test([ui.buildPath, ui.urlParams.build]); /** Detect if running in PhantomJS. */ var isPhantom = phantom || typeof callPhantom == 'function'; /** Detect if running in Rhino. */ var isRhino = isJava && typeof global == 'function' && global().Array === root.Array; /** Detect if lodash is in strict mode. */ var isStrict = ui.isStrict; /** Used to test Web Workers. */ var Worker = !(ui.isForeign || ui.isSauceLabs || isModularize) && document && root.Worker; /** Used to test host objects in IE. */ try { var xml = new ActiveXObject('Microsoft.XMLDOM'); } catch(e) {} /** Use a single "load" function. */ var load = (typeof require == 'function' && !amd) ? require : (isJava ? root.load : noop); /** The unit testing framework. */ var QUnit = root.QUnit || (root.QUnit = ( QUnit = load('../node_modules/qunitjs/qunit/qunit.js') || root.QUnit, QUnit = QUnit.QUnit || QUnit )); /** Load QUnit Extras and ES6 Set/WeakMap shims. */ (function() { var paths = [ './asset/set.js', './asset/weakmap.js', '../node_modules/qunit-extras/qunit-extras.js' ]; var index = -1, length = paths.length; while (++index < length) { var object = load(paths[index]); if (object) { object.runInContext(root); } } }()); /*--------------------------------------------------------------------------*/ // Log params provided to `test.js`. if (params) { console.log('test.js invoked with arguments: ' + JSON.stringify(slice.call(params))); } // Exit early if going to run tests in a PhantomJS web page. if (phantom && isModularize) { var page = require('webpage').create(); page.open(filePath, function(status) { if (status != 'success') { console.log('PhantomJS failed to load page: ' + filePath); phantom.exit(1); } }); page.onCallback = function(details) { var coverage = details.coverage; if (coverage) { var fs = require('fs'), cwd = fs.workingDirectory, sep = fs.separator; fs.write([cwd, 'coverage', 'coverage.json'].join(sep), JSON.stringify(coverage)); } phantom.exit(details.failed ? 1 : 0); }; page.onConsoleMessage = function(message) { console.log(message); }; page.onInitialized = function() { page.evaluate(function() { document.addEventListener('DOMContentLoaded', function() { QUnit.done(function(details) { details.coverage = window.__coverage__; callPhantom(details); }); }); }); }; return; } /*--------------------------------------------------------------------------*/ /** The `lodash` function to test. */ var _ = root._ || (root._ = ( _ = load(filePath) || root._, _ = _._ || (isStrict = ui.isStrict = isStrict || 'default' in _, _['default']) || _, (_.runInContext ? _.runInContext(root) : _) )); /** List of latin-1 supplementary letters to basic latin letters. */ var burredLetters = [ '\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7', '\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf', '\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf', '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef', '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff' ]; /** List of `burredLetters` translated to basic latin letters. */ var deburredLetters = [ 'A', 'A', 'A', 'A', 'A', 'A', 'Ae', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'Th', 'ss', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'd', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'th', 'y' ]; /** Used to provide falsey values to methods. */ var falsey = [, '', 0, false, NaN, null, undefined]; /** Used to provide empty values to methods. */ var empties = [[], {}].concat(falsey.slice(1)); /** Used to test error objects. */ var errors = [ new Error, new EvalError, new RangeError, new ReferenceError, new SyntaxError, new TypeError, new URIError ]; /** Used to check problem JScript properties (a.k.a. the `[[DontEnum]]` bug). */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used to check problem JScript properties too. */ var shadowObject = _.invert(shadowProps); /** Used to check whether methods support typed arrays. */ var typedArrays = [ 'Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array' ]; /** * Used to check for problems removing whitespace. For a whitespace reference * see V8's unit test https://code.google.com/p/v8/source/browse/branches/bleeding_edge/test/mjsunit/whitespaces.js. */ var whitespace = ' \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'; /** * Extracts the unwrapped value from its wrapper. * * @private * @param {Object} wrapper The wrapper to unwrap. * @returns {*} Returns the unwrapped value. */ function getUnwrappedValue(wrapper) { var index = -1, actions = wrapper.__actions__, length = actions.length, result = wrapper.__wrapped__; while (++index < length) { var args = [result], action = actions[index]; push.apply(args, action.args); result = action.func.apply(action.thisArg, args); } return result; } /** * Removes all own enumerable properties from a given object. * * @private * @param {Object} object The object to empty. */ function emptyObject(object) { _.forOwn(object, function(value, key, object) { delete object[key]; }); } /** * Sets a non-enumerable property value on `object`. * * Note: This function is used to avoid a bug in older versions of V8 where * overwriting non-enumerable built-ins makes them enumerable. * See https://code.google.com/p/v8/issues/detail?id=1623 * * @private * @param {Object} object The object augment. * @param {string} key The name of the property to set. * @param {*} value The property value. */ function setProperty(object, key, value) { try { defineProperty(object, key, { 'configurable': true, 'enumerable': false, 'writable': true, 'value': value }); } catch(e) { object[key] = value; } } /** * Skips a given number of tests with a passing result. * * @private * @param {number} [count=1] The number of tests to skip. */ function skipTest(count) { count || (count = 1); while (count--) { ok(true, 'test skipped'); } } /*--------------------------------------------------------------------------*/ // Setup values for Node.js. (function() { if (amd) { return; } try { // Add values from a different realm. _.extend(_, require('vm').runInNewContext([ '(function() {', ' var object = {', " '_arguments': (function() { return arguments; }(1, 2, 3)),", " '_array': [1, 2, 3],", " '_boolean': Object(false),", " '_date': new Date,", " '_errors': [new Error, new EvalError, new RangeError, new ReferenceError, new SyntaxError, new TypeError, new URIError],", " '_function': function() {},", " '_nan': NaN,", " '_null': null,", " '_number': Object(0),", " '_object': { 'a': 1, 'b': 2, 'c': 3 },", " '_regexp': /x/,", " '_string': Object('a'),", " '_undefined': undefined", ' };', '', " ['" + typedArrays.join("', '") + "'].forEach(function(type) {", " var Ctor = Function('return typeof ' + type + \" != 'undefined' && \" + type)()", ' if (Ctor) {', " object['_' + type.toLowerCase()] = new Ctor(new ArrayBuffer(24));", ' }', " });", '', ' return object;', '}())' ].join('\n'))); } catch(e) { if (!phantom) { return; } } var nativeString = fnToString.call(toString), reToString = /toString/g; function createToString(funcName) { return _.constant(nativeString.replace(reToString, funcName)); } // Expose internal modules for better code coverage. if (isModularize && !isNpm) { _.each(['baseEach', 'isIndex', 'isIterateeCall', 'isLength'], function(funcName) { var path = require('path'), func = require(path.join(path.dirname(filePath), 'internal', funcName + '.js')); _['_' + funcName] = func[funcName] || func['default'] || func; }); } // Allow bypassing native checks. setProperty(funcProto, 'toString', function wrapper() { setProperty(funcProto, 'toString', fnToString); var result = _.has(this, 'toString') ? this.toString() : fnToString.call(this); setProperty(funcProto, 'toString', wrapper); return result; }); // Add built-in prototype extensions. funcProto._method = _.noop; // Set bad shims. var _isArray = Array.isArray; setProperty(Array, 'isArray', _.noop); var _now = Date.now; setProperty(Date, 'now', _.noop); var _getPrototypeOf = Object.getPrototypeOf; setProperty(Object, 'getPrototypeOf', _.noop); var _keys = Object.keys; setProperty(Object, 'keys', _.noop); var _propertyIsEnumerable = objectProto.propertyIsEnumerable; setProperty(objectProto, 'propertyIsEnumerable', function(key) { if (key == '1' && _.isArguments(this) && _.isEqual(_.values(this), [0, 0])) { throw new Error; } return _.has(this, key); }); var _isFinite = Number.isFinite; setProperty(Number, 'isFinite', _.noop); var _ArrayBuffer = ArrayBuffer; setProperty(root, 'ArrayBuffer', (function() { function ArrayBuffer(byteLength) { var buffer = new _ArrayBuffer(byteLength); if (!byteLength) { setProperty(buffer, 'slice', buffer.slice ? null : bufferSlice); } return buffer; } function bufferSlice() { var newBuffer = new _ArrayBuffer(this.byteLength), view = new Uint8Array(newBuffer); view.set(new Uint8Array(this)); return newBuffer; } setProperty(ArrayBuffer, 'toString', createToString('ArrayBuffer')); setProperty(bufferSlice, 'toString', createToString('slice')); return ArrayBuffer; }())); if (!root.Float64Array) { setProperty(root, 'Float64Array', (function() { function Float64Array(buffer, byteOffset, length) { return arguments.length == 1 ? new Uint8Array(buffer) : new Uint8Array(buffer, byteOffset || 0, length || buffer.byteLength); } setProperty(Float64Array, 'BYTES_PER_ELEMENT', 8); setProperty(Float64Array, 'toString', createToString('Float64Array')); return Float64Array; }())); } var _parseInt = parseInt; setProperty(root, 'parseInt', (function() { var checkStr = whitespace + '08', isFaked = _parseInt(checkStr) != 8, reHexPrefix = /^0[xX]/, reTrim = RegExp('^[' + whitespace + ']+|[' + whitespace + ']+$'); return function(value, radix) { if (value == checkStr && !isFaked) { isFaked = true; return 0; } value = String(value == null ? '' : value).replace(reTrim, ''); return _parseInt(value, +radix || (reHexPrefix.test(value) ? 16 : 10)); }; }())); var _Set = root.Set; setProperty(root, 'Set', _.noop); var _WeakMap = root.WeakMap; setProperty(root, 'WeakMap', _.noop); // Fake the DOM. setProperty(root, 'window', {}); setProperty(root.window, 'document', {}); setProperty(root.window.document, 'createDocumentFragment', function() { return { 'nodeType': 11 }; }); // Fake `WinRTError`. setProperty(root, 'WinRTError', Error); // Clear cache so lodash can be reloaded. emptyObject(require.cache); // Load lodash and expose it to the bad extensions/shims. lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro; // Restore built-in methods. setProperty(Array, 'isArray', _isArray); setProperty(Date, 'now', _now); setProperty(Object, 'getPrototypeOf', _getPrototypeOf); setProperty(Object, 'keys', _keys); setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable); setProperty(root, 'parseInt', _parseInt); if (_isFinite) { setProperty(Number, 'isFinite', _isFinite); } else { delete Number.isFinite; } if (_ArrayBuffer) { setProperty(root, 'ArrayBuffer', _ArrayBuffer); } else { delete root.ArrayBuffer; } if (_Set) { setProperty(root, 'Set', Set); } else { delete root.Set; } if (_WeakMap) { setProperty(root, 'WeakMap', WeakMap); } else { delete root.WeakMap; } delete root.WinRTError; delete root.window; delete funcProto._method; }()); // Add values from an iframe. (function() { if (_._object || !document) { return; } var iframe = document.createElement('iframe'); iframe.frameBorder = iframe.height = iframe.width = 0; body.appendChild(iframe); var idoc = (idoc = iframe.contentDocument || iframe.contentWindow).document || idoc; idoc.write([ '<script>', 'parent._._arguments = (function() { return arguments; }(1, 2, 3));', 'parent._._array = [1, 2, 3];', 'parent._._boolean = Object(false);', 'parent._._date = new Date;', "parent._._element = document.createElement('div');", 'parent._._errors = [new Error, new EvalError, new RangeError, new ReferenceError, new SyntaxError, new TypeError, new URIError];', 'parent._._function = function() {};', 'parent._._nan = NaN;', 'parent._._null = null;', 'parent._._number = Object(0);', "parent._._object = { 'a': 1, 'b': 2, 'c': 3 };", 'parent._._regexp = /x/;', "parent._._string = Object('a');", 'parent._._undefined = undefined;', '', 'var root = this;', "parent._.each(['" + typedArrays.join("', '") + "'], function(type) {", ' var Ctor = root[type];', ' if (Ctor) {', " parent._['_' + type.toLowerCase()] = new Ctor(new ArrayBuffer(24));", ' }', '});', '<\/script>' ].join('\n')); idoc.close(); }()); // Add a web worker. (function() { if (!Worker) { return; } var worker = new Worker('./asset/worker.js?t=' + (+new Date)); worker.addEventListener('message', function(e) { _._VERSION = e.data || ''; }, false); worker.postMessage(ui.buildPath); }()); /*--------------------------------------------------------------------------*/ QUnit.module(basename); (function() { test('should support loading ' + basename + ' as the "lodash" module', 1, function() { if (amd) { strictEqual((lodashModule || {}).moduleName, 'lodash'); } else { skipTest(); } }); test('should support loading ' + basename + ' with the Require.js "shim" configuration option', 1, function() { if (amd && _.includes(ui.loaderPath, 'requirejs')) { strictEqual((shimmedModule || {}).moduleName, 'shimmed'); } else { skipTest(); } }); test('should support loading ' + basename + ' as the "underscore" module', 1, function() { if (amd) { strictEqual((underscoreModule || {}).moduleName, 'underscore'); } else { skipTest(); } }); asyncTest('should support loading ' + basename + ' in a web worker', 1, function() { if (Worker) { var limit = 30000 / QUnit.config.asyncRetries, start = +new Date; var attempt = function() { var actual = _._VERSION; if ((new Date - start) < limit && typeof actual != 'string') { setTimeout(attempt, 16); return; } strictEqual(actual, _.VERSION); QUnit.start(); }; attempt(); } else { skipTest(); QUnit.start(); } }); test('should not add `Function.prototype` extensions to lodash', 1, function() { if (lodashBizarro) { ok(!('_method' in lodashBizarro)); } else { skipTest(); } }); test('should avoid overwritten native methods', 12, function() { function Foo() {} function message(lodashMethod, nativeMethod) { return '`' + lodashMethod + '` should avoid overwritten native `' + nativeMethod + '`'; } var object = { 'a': 1 }, otherObject = { 'b': 2 }, largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object)); if (lodashBizarro) { try { var actual = [lodashBizarro.isArray([]), lodashBizarro.isArray({ 'length': 0 })]; } catch(e) { actual = null; } deepEqual(actual, [true, false], message('_.isArray', 'Array.isArray')); try { actual = lodashBizarro.now(); } catch(e) { actual = null; } ok(typeof actual == 'number', message('_.now', 'Date.now')); try { actual = [lodashBizarro.isPlainObject({}), lodashBizarro.isPlainObject([])]; } catch(e) { actual = null; } deepEqual(actual, [true, false], message('_.isPlainObject', 'Object.getPrototypeOf')); try { actual = [lodashBizarro.keys(object), lodashBizarro.keys()]; } catch(e) { actual = null; } deepEqual(actual, [['a'], []], message('_.keys', 'Object.keys')); try { actual = [lodashBizarro.isFinite(1), lodashBizarro.isFinite(NaN)]; } catch(e) { actual = null; } deepEqual(actual, [true, false], message('_.isFinite', 'Number.isFinite')); try { actual = [ lodashBizarro.difference([object, otherObject], largeArray), lodashBizarro.intersection(largeArray, [object]), lodashBizarro.uniq(largeArray) ]; } catch(e) { actual = null; } deepEqual(actual, [[otherObject], [object], [object]], message('_.difference`, `_.intersection`, and `_.uniq', 'Set')); try { actual = _.map(['6', '08', '10'], lodashBizarro.parseInt); } catch(e) { actual = null; } deepEqual(actual, [6, 8, 10], '`_.parseInt` should work in its bizarro form'); if (ArrayBuffer) { try { var buffer = new ArrayBuffer(10); actual = lodashBizarro.clone(buffer); } catch(e) { actual = null; } deepEqual(actual, buffer, message('_.clone', 'ArrayBuffer#slice')); notStrictEqual(actual, buffer, message('_.clone', 'ArrayBuffer#slice')); } else { skipTest(2); } if (ArrayBuffer && Uint8Array) { try { var array = new Uint8Array(new ArrayBuffer(10)); actual = lodashBizarro.cloneDeep(array); } catch(e) { actual = null; } deepEqual(actual, array, message('_.cloneDeep', 'Float64Array')); notStrictEqual(actual && actual.buffer, array.buffer, message('_.cloneDeep', 'Float64Array')); notStrictEqual(actual, array, message('_.cloneDeep', 'Float64Array')); } else { skipTest(3); } } else { skipTest(12); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('isIndex'); (function() { var func = _._isIndex; test('should return `true` for indexes', 4, function() { if (func) { strictEqual(func(0), true); strictEqual(func('1'), true); strictEqual(func(3, 4), true); strictEqual(func(MAX_SAFE_INTEGER - 1), true); } else { skipTest(4); } }); test('should return `false` for non-indexes', 4, function() { if (func) { strictEqual(func(-1), false); strictEqual(func(3, 3), false); strictEqual(func(1.1), false); strictEqual(func(MAX_SAFE_INTEGER), false); } else { skipTest(4); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('isIterateeCall'); (function() { var array = [1], func = _._isIterateeCall, object = { 'a': 1 }; test('should return `true` for iteratee calls', 3, function() { function Foo() {} Foo.prototype.a = 1; if (func) { strictEqual(func(1, 0, array), true); strictEqual(func(1, 'a', object), true); strictEqual(func(1, 'a', new Foo), true); } else { skipTest(3); } }); test('should return `false` for non-iteratee calls', 4, function() { if (func) { strictEqual(func(2, 0, array), false); strictEqual(func(1, 1.1, array), false); strictEqual(func(1, 0, { 'length': MAX_SAFE_INTEGER + 1 }), false); strictEqual(func(1, 'b', object), false); } else { skipTest(4); } }); test('should work with `NaN` values', 2, function() { if (func) { strictEqual(func(NaN, 0, [NaN]), true); strictEqual(func(NaN, 'a', { 'a': NaN }), true); } else { skipTest(2); } }); test('should not error when `index` is an object without a `toString` method', 1, function() { if (func) { try { var actual = func(1, { 'toString': null }, [1]); } catch(e) { var message = e.message; } strictEqual(actual, false, message || ''); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('isLength'); (function() { var func = _._isLength; test('should return `true` for lengths', 3, function() { if (func) { strictEqual(func(0), true); strictEqual(func(3), true); strictEqual(func(MAX_SAFE_INTEGER), true); } else { skipTest(3); } }); test('should return `false` for non-lengths', 4, function() { if (func) { strictEqual(func(-1), false); strictEqual(func('1'), false); strictEqual(func(1.1), false); strictEqual(func(MAX_SAFE_INTEGER + 1), false); } else { skipTest(4); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash constructor'); (function() { var values = empties.concat(true, 1, 'a'), expected = _.map(values, _.constant(true)); test('creates a new instance when called without the `new` operator', 1, function() { if (!isNpm) { var actual = _.map(values, function(value) { return _(value) instanceof _; }); deepEqual(actual, expected); } else { skipTest(); } }); test('should return provided `lodash` instances', 1, function() { if (!isNpm) { var actual = _.map(values, function(value) { var wrapped = _(value); return _(wrapped) === wrapped; }); deepEqual(actual, expected); } else { skipTest(); } }); test('should convert foreign wrapped values to `lodash` instances', 1, function() { if (!isNpm && lodashBizarro) { var actual = _.map(values, function(value) { var wrapped = _(lodashBizarro(value)), unwrapped = wrapped.value(); return wrapped instanceof _ && (unwrapped === value || (_.isNaN(unwrapped) && _.isNaN(value))); }); deepEqual(actual, expected); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.add'); (function() { test('should add two numbers together', 1, function() { equal(_.add(6, 4), 10); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_(1).add(2), 3); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(1).chain().add(2) instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.after'); (function() { function after(n, times) { var count = 0; _.times(times, _.after(n, function() { count++; })); return count; } test('should create a function that invokes `func` after `n` calls', 4, function() { strictEqual(after(5, 5), 1, 'after(n) should invoke `func` after being called `n` times'); strictEqual(after(5, 4), 0, 'after(n) should not invoke `func` before being called `n` times'); strictEqual(after(0, 0), 0, 'after(0) should not invoke `func` immediately'); strictEqual(after(0, 1), 1, 'after(0) should invoke `func` when called once'); }); test('should coerce non-finite `n` values to `0`', 1, function() { var values = [-Infinity, NaN, Infinity], expected = _.map(values, _.constant(1)); var actual = _.map(values, function(n) { return after(n, 1); }); deepEqual(actual, expected); }); test('should allow `func` as the first argument', 1, function() { var count = 0; try { var after = _.after(function() { count++; }, 1); after(); after(); } catch(e) {} strictEqual(count, 2); }); test('should not set a `this` binding', 2, function() { var after = _.after(1, function() { return ++this.count; }), object = { 'count': 0, 'after': after }; object.after(); strictEqual(object.after(), 2); strictEqual(object.count, 2); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.ary'); (function() { function fn(a, b, c) { return slice.call(arguments); } test('should cap the numer of params provided to `func`', 2, function() { var actual = _.map(['6', '8', '10'], _.ary(parseInt, 1)); deepEqual(actual, [6, 8, 10]); var capped = _.ary(fn, 2); deepEqual(capped('a', 'b', 'c', 'd'), ['a', 'b']); }); test('should use `func.length` if `n` is not provided', 1, function() { var capped = _.ary(fn); deepEqual(capped('a', 'b', 'c', 'd'), ['a', 'b', 'c']); }); test('should treat a negative `n` as `0`', 1, function() { var capped = _.ary(fn, -1); try { var actual = capped('a'); } catch(e) {} deepEqual(actual, []); }); test('should work when provided less than the capped numer of arguments', 1, function() { var capped = _.ary(fn, 3); deepEqual(capped('a'), ['a']); }); test('should work as an iteratee for `_.map`', 1, function() { var funcs = _.map([fn], _.ary), actual = funcs[0]('a', 'b', 'c'); deepEqual(actual, ['a', 'b', 'c']); }); test('should work when combined with other methods that use metadata', 2, function() { var array = ['a', 'b', 'c'], includes = _.curry(_.rearg(_.ary(_.includes, 2), 1, 0), 2); strictEqual(includes('b')(array, 2), true); if (!isNpm) { includes = _(_.includes).ary(2).rearg(1, 0).curry(2).value(); strictEqual(includes('b')(array, 2), true); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.assign'); (function() { test('should assign properties of a source object to the destination object', 1, function() { deepEqual(_.assign({ 'a': 1 }, { 'b': 2 }), { 'a': 1, 'b': 2 }); }); test('should accept multiple source objects', 2, function() { var expected = { 'a': 1, 'b': 2, 'c': 3 }; deepEqual(_.assign({ 'a': 1 }, { 'b': 2 }, { 'c': 3 }), expected); deepEqual(_.assign({ 'a': 1 }, { 'b': 2, 'c': 2 }, { 'c': 3 }), expected); }); test('should overwrite destination properties', 1, function() { var expected = { 'a': 3, 'b': 2, 'c': 1 }; deepEqual(_.assign({ 'a': 1, 'b': 2 }, expected), expected); }); test('should assign source properties with `null` and `undefined` values', 1, function() { var expected = { 'a': null, 'b': undefined, 'c': null }; deepEqual(_.assign({ 'a': 1, 'b': 2 }, expected), expected); }); test('should work with a `customizer` callback', 1, function() { var actual = _.assign({ 'a': 1, 'b': 2 }, { 'a': 3, 'c': 3 }, function(a, b) { return typeof a == 'undefined' ? b : a; }); deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 }); }); test('should work with a `customizer` that returns `undefined`', 1, function() { var expected = { 'a': undefined }; deepEqual(_.assign({}, expected, _.identity), expected); }); test('should be aliased', 1, function() { strictEqual(_.extend, _.assign); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.at'); (function() { var args = arguments, array = ['a', 'b', 'c']; array['1.1'] = array['-1'] = 1; test('should return the elements corresponding to the specified keys', 1, function() { var actual = _.at(array, [0, 2]); deepEqual(actual, ['a', 'c']); }); test('should return `undefined` for nonexistent keys', 1, function() { var actual = _.at(array, [2, 4, 0]); deepEqual(actual, ['c', undefined, 'a']); }); test('should use `undefined` for non-index keys on array-like values', 1, function() { var values = _.reject(empties, function(value) { return value === 0 || _.isArray(value); }).concat(-1, 1.1); var expected = _.map(values, _.constant(undefined)), actual = _.at(array, values); deepEqual(actual, expected); }); test('should return an empty array when no keys are provided', 2, function() { deepEqual(_.at(array), []); deepEqual(_.at(array, [], []), []); }); test('should accept multiple key arguments', 1, function() { var actual = _.at(['a', 'b', 'c', 'd'], 3, 0, 2); deepEqual(actual, ['d', 'a', 'c']); }); test('should work with a falsey `collection` argument when keys are provided', 1, function() { var expected = _.map(falsey, _.constant([undefined, undefined])); var actual = _.map(falsey, function(value) { try { return _.at(value, 0, 1); } catch(e) {} }); deepEqual(actual, expected); }); test('should work with an `arguments` object for `collection`', 1, function() { var actual = _.at(args, [2, 0]); deepEqual(actual, [3, 1]); }); test('should work with `arguments` object as secondary arguments', 1, function() { var actual = _.at([1, 2, 3, 4, 5], args); deepEqual(actual, [2, 3, 4]); }); test('should work with an object for `collection`', 1, function() { var actual = _.at({ 'a': 1, 'b': 2, 'c': 3 }, ['c', 'a']); deepEqual(actual, [3, 1]); }); test('should pluck inherited property values', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var actual = _.at(new Foo, 'b'); deepEqual(actual, [2]); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 1, function() { deepEqual(_.at(collection, [2, 0]), ['c', 'a']); }); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.attempt'); (function() { test('should return the result of `func`', 1, function() { strictEqual(_.attempt(_.constant('x')), 'x'); }); test('should provide additional arguments to `func`', 1, function() { var actual = _.attempt(function() { return slice.call(arguments); }, 1, 2); deepEqual(actual, [1, 2]); }); test('should return the caught error', 1, function() { var expected = _.map(errors, _.constant(true)); var actual = _.map(errors, function(error) { return _.attempt(function() { throw error; }) === error; }); deepEqual(actual, expected); }); test('should coerce errors to error objects', 1, function() { var actual = _.attempt(function() { throw 'x'; }); ok(_.isEqual(actual, Error('x'))); }); test('should work with an error object from another realm', 1, function() { if (_._object) { var expected = _.map(_._errors, _.constant(true)); var actual = _.map(_._errors, function(error) { return _.attempt(function() { throw error; }) === error; }); deepEqual(actual, expected); } else { skipTest(); } }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_(_.constant('x')).attempt(), 'x'); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(_.constant('x')).chain().attempt() instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.before'); (function() { function before(n, times) { var count = 0; _.times(times, _.before(n, function() { count++; })); return count; } test('should create a function that invokes `func` after `n` calls', 4, function() { strictEqual(before(5, 4), 4, 'before(n) should invoke `func` before being called `n` times'); strictEqual(before(5, 6), 4, 'before(n) should not invoke `func` after being called `n - 1` times'); strictEqual(before(0, 0), 0, 'before(0) should not invoke `func` immediately'); strictEqual(before(0, 1), 0, 'before(0) should not invoke `func` when called'); }); test('should coerce non-finite `n` values to `0`', 1, function() { var values = [-Infinity, NaN, Infinity], expected = _.map(values, _.constant(0)); var actual = _.map(values, function(n) { return before(n); }); deepEqual(actual, expected); }); test('should allow `func` as the first argument', 1, function() { var count = 0; try { var before = _.before(function() { count++; }, 2); before(); before(); } catch(e) {} strictEqual(count, 1); }); test('should not set a `this` binding', 2, function() { var before = _.before(2, function() { return ++this.count; }), object = { 'count': 0, 'before': before }; object.before(); strictEqual(object.before(), 1); strictEqual(object.count, 1); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.bind'); (function() { function fn() { var result = [this]; push.apply(result, arguments); return result; } test('should bind a function to an object', 1, function() { var object = {}, bound = _.bind(fn, object); deepEqual(bound('a'), [object, 'a']); }); test('should accept a falsey `thisArg` argument', 1, function() { var values = _.reject(falsey.slice(1), function(value) { return value == null; }), expected = _.map(values, function(value) { return [value]; }); var actual = _.map(values, function(value) { try { var bound = _.bind(fn, value); return bound(); } catch(e) {} }); ok(_.every(actual, function(value, index) { return _.isEqual(value, expected[index]); })); }); test('should bind a function to `null` or `undefined`', 6, function() { var bound = _.bind(fn, null), actual = bound('a'); ok(actual[0] === null || actual[0] && actual[0].Array); strictEqual(actual[1], 'a'); _.times(2, function(index) { bound = index ? _.bind(fn, undefined) : _.bind(fn); actual = bound('b'); ok(actual[0] === undefined || actual[0] && actual[0].Array); strictEqual(actual[1], 'b'); }); }); test('should partially apply arguments ', 4, function() { var object = {}, bound = _.bind(fn, object, 'a'); deepEqual(bound(), [object, 'a']); bound = _.bind(fn, object, 'a'); deepEqual(bound('b'), [object, 'a', 'b']); bound = _.bind(fn, object, 'a', 'b'); deepEqual(bound(), [object, 'a', 'b']); deepEqual(bound('c', 'd'), [object, 'a', 'b', 'c', 'd']); }); test('should support placeholders', 4, function() { var object = {}, ph = _.bind.placeholder, bound = _.bind(fn, object, ph, 'b', ph); deepEqual(bound('a', 'c'), [object, 'a', 'b', 'c']); deepEqual(bound('a'), [object, 'a', 'b', undefined]); deepEqual(bound('a', 'c', 'd'), [object, 'a', 'b', 'c', 'd']); deepEqual(bound(), [object, undefined, 'b', undefined]); }); test('should create a function with a `length` of `0`', 2, function() { var fn = function(a, b, c) {}, bound = _.bind(fn, {}); strictEqual(bound.length, 0); bound = _.bind(fn, {}, 1); strictEqual(bound.length, 0); }); test('should ignore binding when called with the `new` operator', 3, function() { function Foo() { return this; } var bound = _.bind(Foo, { 'a': 1 }), newBound = new bound; strictEqual(newBound.a, undefined); strictEqual(bound().a, 1); ok(newBound instanceof Foo); }); test('ensure `new bound` is an instance of `func`', 2, function() { function Foo(value) { return value && object; } var bound = _.bind(Foo), object = {}; ok(new bound instanceof Foo); strictEqual(new bound(true), object); }); test('should append array arguments to partially applied arguments (test in IE < 9)', 1, function() { var object = {}, bound = _.bind(fn, object, 'a'); deepEqual(bound(['b'], 'c'), [object, 'a', ['b'], 'c']); }); test('should rebind functions correctly', 3, function() { var object1 = {}, object2 = {}, object3 = {}; var bound1 = _.bind(fn, object1), bound2 = _.bind(bound1, object2, 'a'), bound3 = _.bind(bound1, object3, 'b'); deepEqual(bound1(), [object1]); deepEqual(bound2(), [object1, 'a']); deepEqual(bound3(), [object1, 'b']); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var object = {}, bound = _(fn).bind({}, 'a', 'b'); ok(bound instanceof _); var actual = bound.value()('c'); deepEqual(actual, [object, 'a', 'b', 'c']); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.bindAll'); (function() { var args = arguments; test('should bind all methods of `object`', 1, function() { function Foo() { this._a = 1; this._b = 2; this.a = function() { return this._a; }; } Foo.prototype.b = function() { return this._b; }; var object = new Foo; _.bindAll(object); var actual = _.map(_.functions(object).sort(), function(methodName) { return object[methodName].call({}); }); deepEqual(actual, [1, 2]); }); test('should accept individual method names', 1, function() { var object = { '_a': 1, '_b': 2, '_c': 3, 'a': function() { return this._a; }, 'b': function() { return this._b; }, 'c': function() { return this._c; } }; _.bindAll(object, 'a', 'b'); var actual = _.map(_.functions(object).sort(), function(methodName) { return object[methodName].call({}); }); deepEqual(actual, [1, 2, undefined]); }); test('should accept arrays of method names', 1, function() { var object = { '_a': 1, '_b': 2, '_c': 3, '_d': 4, 'a': function() { return this._a; }, 'b': function() { return this._b; }, 'c': function() { return this._c; }, 'd': function() { return this._d; } }; _.bindAll(object, ['a', 'b'], ['c']); var actual = _.map(_.functions(object).sort(), function(methodName) { return object[methodName].call({}); }); deepEqual(actual, [1, 2, 3, undefined]); }); test('should work with an array `object` argument', 1, function() { var array = ['push', 'pop']; _.bindAll(array); strictEqual(array.pop, arrayProto.pop); }); test('should work with `arguments` objects as secondary arguments', 1, function() { var object = { '_a': 1, 'a': function() { return this._a; } }; _.bindAll(object, args); var actual = _.map(_.functions(object).sort(), function(methodName) { return object[methodName].call({}); }); deepEqual(actual, [1]); }); }('a')); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.bindKey'); (function() { test('should work when the target function is overwritten', 2, function() { var object = { 'user': 'fred', 'greet': function(greeting) { return this.user + ' says: ' + greeting; } }; var bound = _.bindKey(object, 'greet', 'hi'); strictEqual(bound(), 'fred says: hi'); object.greet = function(greeting) { return this.user + ' says: ' + greeting + '!'; }; strictEqual(bound(), 'fred says: hi!'); }); test('should support placeholders', 4, function() { var object = { 'fn': function() { return slice.call(arguments); } }; var ph = _.bindKey.placeholder, bound = _.bindKey(object, 'fn', ph, 'b', ph); deepEqual(bound('a', 'c'), ['a', 'b', 'c']); deepEqual(bound('a'), ['a', 'b', undefined]); deepEqual(bound('a', 'c', 'd'), ['a', 'b', 'c', 'd']); deepEqual(bound(), [undefined, 'b', undefined]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('case methods'); _.each(['camel', 'kebab', 'snake', 'start'], function(caseName) { var methodName = caseName + 'Case', func = _[methodName]; var strings = [ 'foo bar', 'Foo bar', 'foo Bar', 'Foo Bar', 'FOO BAR', 'fooBar', '--foo-bar', '__foo_bar__' ]; var converted = (function() { switch (caseName) { case 'camel': return 'fooBar'; case 'kebab': return 'foo-bar'; case 'snake': return 'foo_bar'; case 'start': return 'Foo Bar'; } }()); test('`_.' + methodName + '` should convert `string` to ' + caseName + ' case', 1, function() { var actual = _.map(strings, function(string) { var expected = (caseName === 'start' && string === 'FOO BAR') ? string : converted; return func(string) === expected; }); deepEqual(actual, _.map(strings, _.constant(true))); }); test('`_.' + methodName + '` should handle double-converting strings', 1, function() { var actual = _.map(strings, function(string) { var expected = (caseName === 'start' && string === 'FOO BAR') ? string : converted; return func(func(string)) === expected; }); deepEqual(actual, _.map(strings, _.constant(true))); }); test('`_.' + methodName + '` should deburr letters', 1, function() { var actual = _.map(burredLetters, function(burred, index) { var letter = deburredLetters[index]; letter = caseName == 'start' ? _.capitalize(letter) : letter.toLowerCase(); return func(burred) === letter; }); deepEqual(actual, _.map(burredLetters, _.constant(true))); }); test('`_.' + methodName + '` should trim latin-1 mathematical operators', 1, function() { var actual = _.map(['\xd7', '\xf7'], func); deepEqual(actual, ['', '']); }); test('`_.' + methodName + '` should coerce `string` to a string', 2, function() { var string = 'foo bar'; strictEqual(func(Object(string)), converted); strictEqual(func({ 'toString': _.constant(string) }), converted); }); test('`_.' + methodName + '` should return an unwrapped value implicitly when chaining', 1, function() { if (!isNpm) { strictEqual(_('foo bar')[methodName](), converted); } else { skipTest(); } }); test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_('foo bar').chain()[methodName]() instanceof _); } else { skipTest(); } }); }); (function() { test('should get the original value after cycling through all case methods', 1, function() { var funcs = [_.camelCase, _.kebabCase, _.snakeCase, _.startCase, _.camelCase]; var actual = _.reduce(funcs, function(result, func) { return func(result); }, 'enable 24h format'); strictEqual(actual, 'enable24HFormat'); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.camelCase'); (function() { test('should work with numbers', 4, function() { strictEqual(_.camelCase('enable 24h format'), 'enable24HFormat'); strictEqual(_.camelCase('too legit 2 quit'), 'tooLegit2Quit'); strictEqual(_.camelCase('walk 500 miles'), 'walk500Miles'); strictEqual(_.camelCase('xhr2 request'), 'xhr2Request'); }); test('should handle acronyms', 6, function() { _.each(['safe HTML', 'safeHTML'], function(string) { strictEqual(_.camelCase(string), 'safeHtml'); }); _.each(['escape HTML entities', 'escapeHTMLEntities'], function(string) { strictEqual(_.camelCase(string), 'escapeHtmlEntities'); }); _.each(['XMLHttpRequest', 'XmlHTTPRequest'], function(string) { strictEqual(_.camelCase(string), 'xmlHttpRequest'); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.capitalize'); (function() { test('should capitalize the first character of a string', 3, function() { strictEqual(_.capitalize('fred'), 'Fred'); strictEqual(_.capitalize('Fred'), 'Fred'); strictEqual(_.capitalize(' fred'), ' fred'); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_('fred').capitalize(), 'Fred'); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_('fred').chain().capitalize() instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.chain'); (function() { test('should return a wrapped value', 1, function() { if (!isNpm) { var actual = _.chain({ 'a': 0 }); ok(actual instanceof _); } else { skipTest(); } }); test('should return existing wrapped values', 2, function() { if (!isNpm) { var wrapped = _({ 'a': 0 }); strictEqual(_.chain(wrapped), wrapped); strictEqual(wrapped.chain(), wrapped); } else { skipTest(2); } }); test('should enable chaining of methods that return unwrapped values by default', 6, function() { if (!isNpm) { var array = ['c', 'b', 'a']; ok(_.chain(array).first() instanceof _); ok(_(array).chain().first() instanceof _); ok(_.chain(array).isArray() instanceof _); ok(_(array).chain().isArray() instanceof _); ok(_.chain(array).sortBy().first() instanceof _); ok(_(array).chain().sortBy().first() instanceof _); } else { skipTest(6); } }); test('should chain multiple methods', 6, function() { if (!isNpm) { _.times(2, function(index) { var array = ['one two three four', 'five six seven eight', 'nine ten eleven twelve'], expected = { ' ': 9, 'e': 14, 'f': 2, 'g': 1, 'h': 2, 'i': 4, 'l': 2, 'n': 6, 'o': 3, 'r': 2, 's': 2, 't': 5, 'u': 1, 'v': 4, 'w': 2, 'x': 1 }, wrapped = index ? _(array).chain() : _.chain(array); var actual = wrapped .chain() .map(function(value) { return value.split(''); }) .flatten() .reduce(function(object, chr) { object[chr] || (object[chr] = 0); object[chr]++; return object; }, {}) .value(); deepEqual(actual, expected); array = [1, 2, 3, 4, 5, 6]; wrapped = index ? _(array).chain() : _.chain(array); actual = wrapped .chain() .filter(function(n) { return n % 2; }) .reject(function(n) { return n % 3 == 0; }) .sortBy(function(n) { return -n; }) .value(); deepEqual(actual, [5, 1]); array = [3, 4]; wrapped = index ? _(array).chain() : _.chain(array); actual = wrapped .reverse() .concat([2, 1]) .unshift(5) .tap(function(value) { value.pop(); }) .map(square) .value(); deepEqual(actual,[25, 16, 9, 4]); }); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.chunk'); (function() { var array = [0, 1, 2, 3, 4, 5]; test('should return chunked arrays', 1, function() { var actual = _.chunk(array, 3); deepEqual(actual, [[0, 1, 2], [3, 4, 5]]); }); test('should return the last chunk as remaining elements', 1, function() { var actual = _.chunk(array, 4); deepEqual(actual, [[0, 1, 2, 3], [4, 5]]); }); test('should ensure the minimum `chunkSize` is `1`', 1, function() { var values = falsey.concat(-1, -Infinity), expected = _.map(values, _.constant([[0], [1], [2], [3], [4], [5]])); var actual = _.map(values, function(value, index) { return index ? _.chunk(array, value) : _.chunk(array); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([[1, 2], [3, 4]], _.chunk); deepEqual(actual, [[[1], [2]], [[3], [4]]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('clone methods'); (function() { function Foo() { this.a = 1; } Foo.prototype = { 'b': 1 }; Foo.c = function() {}; var objects = { '`arguments` objects': arguments, 'arrays': ['a', ''], 'array-like-objects': { '0': 'a', '1': '', 'length': 3 }, 'booleans': false, 'boolean objects': Object(false), 'Foo instances': new Foo, 'objects': { 'a': 0, 'b': 1, 'c': 3 }, 'objects with object values': { 'a': /a/, 'b': ['B'], 'c': { 'C': 1 } }, 'objects from another document': _._object || {}, 'null values': null, 'numbers': 3, 'number objects': Object(3), 'regexes': /a/gim, 'strings': 'a', 'string objects': Object('a'), 'undefined values': undefined }; objects['arrays'].length = 3; var uncloneable = { 'DOM elements': body, 'functions': Foo }; _.each(errors, function(error) { uncloneable[error.name + 's'] = error; }); test('`_.clone` should perform a shallow clone', 2, function() { var array = [{ 'a': 0 }, { 'b': 1 }], actual = _.clone(array); deepEqual(actual, array); ok(actual !== array && actual[0] === array[0]); }); test('`_.clone` should work with `isDeep`', 8, function() { var array = [{ 'a': 0 }, { 'b': 1 }], values = [true, 1, {}, '1']; _.each(values, function(isDeep) { var actual = _.clone(array, isDeep); deepEqual(actual, array); ok(actual !== array && actual[0] !== array[0]); }); }); test('`_.cloneDeep` should deep clone objects with circular references', 1, function() { var object = { 'foo': { 'b': { 'c': { 'd': {} } } }, 'bar': {} }; object.foo.b.c.d = object; object.bar.b = object.foo.b; var actual = _.cloneDeep(object); ok(actual.bar.b === actual.foo.b && actual === actual.foo.b.c.d && actual !== object); }); _.each(['clone', 'cloneDeep'], function(methodName) { var func = _[methodName], isDeep = methodName == 'cloneDeep'; _.forOwn(objects, function(object, key) { test('`_.' + methodName + '` should clone ' + key, 2, function() { var actual = func(object); ok(_.isEqual(actual, object)); if (_.isObject(object)) { notStrictEqual(actual, object); } else { strictEqual(actual, object); } }); }); _.forOwn(uncloneable, function(value, key) { test('`_.' + methodName + '` should not clone ' + key, 3, function() { var object = { 'a': value, 'b': { 'c': value } }, actual = func(object); deepEqual(actual, object); notStrictEqual(actual, object); var expected = typeof value == 'function' ? { 'c': Foo.c } : (value && {}); deepEqual(func(value), expected); }); test('`_.' + methodName + '` should work with a `customizer` callback and ' + key, 4, function() { var customizer = function(value) { return _.isPlainObject(value) ? undefined : value; }; var actual = func(value, customizer); deepEqual(actual, value); strictEqual(actual, value); var object = { 'a': value, 'b': { 'c': value } }; actual = func(object, customizer); deepEqual(actual, object); notStrictEqual(actual, object); }); }); test('`_.' + methodName + '` should clone array buffers', 2, function() { if (ArrayBuffer) { var buffer = new ArrayBuffer(10), actual = func(buffer); strictEqual(actual.byteLength, buffer.byteLength); notStrictEqual(actual, buffer); } else { skipTest(2); } }); _.each(typedArrays, function(type) { test('`_.' + methodName + '` should clone ' + type + ' arrays', 10, function() { var Ctor = root[type]; _.times(2, function(index) { if (Ctor) { var buffer = new ArrayBuffer(24), array = index ? new Ctor(buffer, 8, 1) : new Ctor(buffer), actual = func(array); deepEqual(actual, array); notStrictEqual(actual, array); strictEqual(actual.buffer === array.buffer, !isDeep); strictEqual(actual.byteOffset, array.byteOffset); strictEqual(actual.length, array.length); } else { skipTest(5); } }); }); }); test('`_.' + methodName + '` should clone problem JScript properties (test in IE < 9)', 2, function() { var actual = func(shadowObject); deepEqual(actual, shadowObject); notStrictEqual(actual, shadowObject); }); test('`_.' + methodName + '` should provide the correct `customizer` arguments', 1, function() { var argsList = [], foo = new Foo; func(foo, function() { argsList.push(slice.call(arguments)); }); deepEqual(argsList, isDeep ? [[foo], [1, 'a', foo]] : [[foo]]); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func('a', function(value) { return this[value]; }, { 'a': 'A' }); strictEqual(actual, 'A'); }); test('`_.' + methodName + '` should handle cloning if `customizer` returns `undefined`', 1, function() { var actual = func({ 'a': { 'b': 'c' } }, _.noop); deepEqual(actual, { 'a': { 'b': 'c' } }); }); test('`_.' + methodName + '` should clone `index` and `input` array properties', 2, function() { var array = /x/.exec('vwxyz'), actual = func(array); strictEqual(actual.index, 2); strictEqual(actual.input, 'vwxyz'); }); test('`_.' + methodName + '` should clone `lastIndex` regexp property', 1, function() { // Avoid a regexp literal for older Opera and use `exec` for older Safari. var regexp = RegExp('x', 'g'); regexp.exec('vwxyz'); var actual = func(regexp); strictEqual(actual.lastIndex, 3); }); test('`_.' + methodName + '` should not error on DOM elements', 1, function() { if (document) { var element = document.createElement('div'); try { deepEqual(func(element), {}); } catch(e) { ok(false, e.message); } } else { skipTest(); } }); test('`_.' + methodName + '` should perform a ' + (isDeep ? 'deep' : 'shallow') + ' clone when used as an iteratee for `_.map`', 3, function() { var expected = [{ 'a': [0] }, { 'b': [1] }], actual = _.map(expected, func); deepEqual(actual, expected); if (isDeep) { ok(actual[0] !== expected[0] && actual[0].a !== expected[0].a && actual[1].b !== expected[1].b); } else { ok(actual[0] !== expected[0] && actual[0].a === expected[0].a && actual[1].b === expected[1].b); } actual = _.map(isDeep ? Object('abc') : 'abc', func); deepEqual(actual, ['a', 'b', 'c']); }); test('`_.' + methodName + '` should create an object from the same realm as `value`', 1, function() { var props = []; var objects = _.transform(_, function(result, value, key) { if (_.startsWith(key, '_') && _.isObject(value) && !_.isArguments(value) && !_.isElement(value) && !_.isFunction(value)) { props.push(_.capitalize(_.camelCase(key))); result.push(value); } }, []); var expected = _.times(objects.length, _.constant(true)); var actual = _.map(objects, function(object) { var Ctor = object.constructor, result = func(object); return result !== object && (result instanceof Ctor || !(new Ctor instanceof Ctor)); }); deepEqual(actual, expected, props.join(', ')); }); test('`_.' + methodName + '` should return a unwrapped value when chaining', 2, function() { if (!isNpm) { var object = objects['objects'], actual = _(object)[methodName](); deepEqual(actual, object); notStrictEqual(actual, object); } else { skipTest(2); } }); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.compact'); (function() { test('should filter falsey values', 1, function() { var array = ['0', '1', '2']; deepEqual(_.compact(falsey.concat(array)), array); }); test('should work when in between lazy operators', 2, function() { if (!isNpm) { var actual = _(falsey).thru(_.slice).compact().thru(_.slice).value(); deepEqual(actual, []); actual = _(falsey).thru(_.slice).push(true, 1).compact().push('a').value(); deepEqual(actual, [true, 1, 'a']); } else { skipTest(2); } }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, null, 3], actual = _(array).map(square).compact().reverse().take().value(); deepEqual(actual, [9]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.flowRight'); (function() { test('should be aliased', 2, function() { strictEqual(_.backflow, _.flowRight); strictEqual(_.compose, _.flowRight); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('flow methods'); _.each(['flow', 'flowRight'], function(methodName) { var func = _[methodName], isFlow = methodName == 'flow'; test('`_.' + methodName + '` should supply each function with the return value of the previous', 1, function() { var fixed = function(n) { return n.toFixed(1); }, combined = isFlow ? func(add, square, fixed) : func(fixed, square, add); strictEqual(combined(1, 2), '9.0'); }); test('`_.' + methodName + '` should return a new function', 1, function() { notStrictEqual(func(_.noop), _.noop); }); test('`_.' + methodName + '` should return an identity function when no arguments are provided', 2, function() { var combined = func(); try { strictEqual(combined('a'), 'a'); } catch(e) { ok(false, e.message); } notStrictEqual(combined, _.identity); }); test('`_.' + methodName + '` should return a wrapped value when chaining', 1, function() { if (!isNpm) { var wrapped = _(_.noop)[methodName](); ok(wrapped instanceof _); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.constant'); (function() { test('should create a function that returns `value`', 1, function() { var object = { 'a': 1 }, values = Array(2).concat(empties, true, 1, 'a'), constant = _.constant(object), expected = _.map(values, function() { return true; }); var actual = _.map(values, function(value, index) { if (index == 0) { var result = constant(); } else if (index == 1) { result = constant.call({}); } else { result = constant(value); } return result === object; }); deepEqual(actual, expected); }); test('should work with falsey values', 1, function() { var expected = _.map(falsey, function() { return true; }); var actual = _.map(falsey, function(value, index) { var constant = index ? _.constant(value) : _.constant(), result = constant(); return result === value || (_.isNaN(result) && _.isNaN(value)); }); deepEqual(actual, expected); }); test('should return a wrapped value when chaining', 1, function() { if (!isNpm) { var wrapped = _(true).constant(); ok(wrapped instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.countBy'); (function() { var array = [4.2, 6.1, 6.4]; test('should work with an iteratee', 1, function() { var actual = _.countBy(array, function(num) { return Math.floor(num); }, Math); deepEqual(actual, { '4': 1, '6': 2 }); }); test('should use `_.identity` when `iteratee` is nullish', 1, function() { var array = [4, 6, 6], values = [, null, undefined], expected = _.map(values, _.constant({ '4': 1, '6': 2 })); var actual = _.map(values, function(value, index) { return index ? _.countBy(array, value) : _.countBy(array); }); deepEqual(actual, expected); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.countBy(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [4.2, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.countBy(array, function(num) { return this.floor(num); }, Math); deepEqual(actual, { '4': 1, '6': 2 }); }); test('should only add values to own, not inherited, properties', 2, function() { var actual = _.countBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); deepEqual(actual.constructor, 1); deepEqual(actual.hasOwnProperty, 2); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.countBy(['one', 'two', 'three'], 'length'); deepEqual(actual, { '3': 2, '5': 1 }); }); test('should work with a number for `iteratee`', 2, function() { var array = [ [1, 'a'], [2, 'a'], [2, 'b'] ]; deepEqual(_.countBy(array, 0), { '1': 1, '2': 2 }); deepEqual(_.countBy(array, 1), { 'a': 2, 'b': 1 }); }); test('should work with an object for `collection`', 1, function() { var actual = _.countBy({ 'a': 4.2, 'b': 6.1, 'c': 6.4 }, function(num) { return Math.floor(num); }); deepEqual(actual, { '4': 1, '6': 2 }); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 1, 3], predicate = function(value) { return value > 2; }, actual = _(array).countBy(_.identity).map(square).filter(predicate).take().value(); deepEqual(actual, [4]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.create'); (function() { function Shape() { this.x = 0; this.y = 0; } function Circle() { Shape.call(this); } test('should create an object that inherits from the given `prototype` object', 3, function() { Circle.prototype = _.create(Shape.prototype); Circle.prototype.constructor = Circle; var actual = new Circle; ok(actual instanceof Circle); ok(actual instanceof Shape); notStrictEqual(Circle.prototype, Shape.prototype); }); test('should assign `properties` to the created object', 3, function() { var expected = { 'constructor': Circle, 'radius': 0 }; Circle.prototype = _.create(Shape.prototype, expected); var actual = new Circle; ok(actual instanceof Circle); ok(actual instanceof Shape); deepEqual(Circle.prototype, expected); }); test('should assign own properties', 1, function() { function Foo() { this.a = 1; this.c = 3; } Foo.prototype.b = 2; deepEqual(_.create({}, new Foo), { 'a': 1, 'c': 3 }); }); test('should accept a falsey `prototype` argument', 1, function() { var expected = _.map(falsey, _.constant({})); var actual = _.map(falsey, function(value, index) { return index ? _.create(value) : _.create(); }); deepEqual(actual, expected); }); test('should ignore primitive `prototype` arguments and use an empty object instead', 1, function() { var primitives = [true, null, 1, 'a', undefined], expected = _.map(primitives, _.constant(true)); var actual = _.map(primitives, function(value, index) { return _.isPlainObject(index ? _.create(value) : _.create()); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [{ 'a': 1 }, { 'a': 1 }, { 'a': 1 }], expected = _.map(array, _.constant(true)), objects = _.map(array, _.create); var actual = _.map(objects, function(object) { return object.a === 1 && !_.keys(object).length; }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.callback'); (function() { test('should provide arguments to `func`', 3, function() { function fn() { var result = [this]; push.apply(result, arguments); return result; } var callback = _.callback(fn), actual = callback('a', 'b', 'c', 'd', 'e', 'f'); ok(actual[0] === null || actual[0] && actual[0].Array); deepEqual(actual.slice(1), ['a', 'b', 'c', 'd', 'e', 'f']); var object = {}; callback = _.callback(fn, object); actual = callback('a', 'b'); deepEqual(actual, [object, 'a', 'b']); }); test('should return `_.identity` when `func` is nullish', 1, function() { var object = {}, values = [, null, undefined], expected = _.map(values, _.constant(object)); var actual = _.map(values, function(value, index) { var callback = index ? _.callback(value) : _.callback(); return callback(object); }); deepEqual(actual, expected); }); test('should not error when `func` is nullish and a `thisArg` is provided', 2, function() { var object = {}; _.each([null, undefined], function(value) { try { var callback = _.callback(value, {}); strictEqual(callback(object), object); } catch(e) { ok(false, e.message); } }); }); test('should create a callback with a falsey `thisArg`', 1, function() { var fn = function() { return this; }, object = {}; var expected = _.map(falsey, function(value) { var result = fn.call(value); return (result && result.Array) ? object : result; }); var actual = _.map(falsey, function(value) { var callback = _.callback(fn, value), result = callback(); return (result && result.Array) ? object : result; }); ok(_.isEqual(actual, expected)); }); test('should return a callback created by `_.matches` when `func` is an object', 2, function() { var callback = _.callback({ 'a': 1 }); strictEqual(callback({ 'a': 1, 'b': 2 }), true); strictEqual(callback({}), false); }); test('should return a callback created by `_.matchesProperty` when `func` is a number or string and `thisArg` is not `undefined`', 3, function() { var array = ['a'], callback = _.callback(0, 'a'); strictEqual(callback(array), true); callback = _.callback('0', 'a'); strictEqual(callback(array), true); callback = _.callback(1, undefined); strictEqual(callback(array), undefined); }); test('should return a callback created by `_.property` when `func` is a number or string', 2, function() { var array = ['a'], callback = _.callback(0); strictEqual(callback(array), 'a'); callback = _.callback('0'); strictEqual(callback(array), 'a'); }); test('should work with functions created by `_.partial` and `_.partialRight`', 2, function() { function fn() { var result = [this.a]; push.apply(result, arguments); return result; } var expected = [1, 2, 3], object = { 'a': 1 }, callback = _.callback(_.partial(fn, 2), object); deepEqual(callback(3), expected); callback = _.callback(_.partialRight(fn, 3), object); deepEqual(callback(2), expected); }); test('should support binding built-in methods', 2, function() { var fn = function() {}, object = { 'a': 1 }, bound = fn.bind && fn.bind(object), callback = _.callback(hasOwnProperty, object); strictEqual(callback('a'), true); if (bound) { callback = _.callback(bound, object); notStrictEqual(callback, bound); } else { skipTest(); } }); test('should return the function provided when there is no `this` reference', 2, function() { function a() {} function b() { return this.b; } var object = {}; if (_.support.funcDecomp) { strictEqual(_.callback(a, object), a); notStrictEqual(_.callback(b, object), b); } else { skipTest(2); } }); test('should work with bizarro `_.support.funcNames`', 6, function() { function a() {} var b = function() {}; function c() { return this; } var object = {}, supportBizarro = lodashBizarro ? lodashBizarro.support : {}, funcDecomp = supportBizarro.funcDecomp, funcNames = supportBizarro.funcNames; supportBizarro.funcNames = !supportBizarro.funcNames; supportBizarro.funcDecomp = true; _.each([a, b, c], function(fn) { if (lodashBizarro && _.support.funcDecomp) { var callback = lodashBizarro.callback(fn, object); strictEqual(callback(), fn === c ? object : undefined); strictEqual(callback === fn, _.support.funcNames && fn === a); } else { skipTest(2); } }); supportBizarro.funcDecomp = funcDecomp; supportBizarro.funcNames = funcNames; }); test('should work as an iteratee for `_.map`', 1, function() { var fn = function() { return this instanceof Number; }, array = [fn, fn, fn], callbacks = _.map(array, _.callback), expected = _.map(array, _.constant(false)); var actual = _.map(callbacks, function(callback) { return callback(); }); deepEqual(actual, expected); }); test('should be aliased', 1, function() { strictEqual(_.iteratee, _.callback); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('custom `_.callback` methods'); (function() { var array = ['one', 'two', 'three'], callback = _.callback, getPropA = _.partial(_.property, 'a'), getPropB = _.partial(_.property, 'b'), getLength = _.partial(_.property, 'length'); var getSum = function() { return function(result, object) { return result + object.a; }; }; var objects = [ { 'a': 0, 'b': 0 }, { 'a': 1, 'b': 0 }, { 'a': 1, 'b': 1 } ]; test('`_.countBy` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getLength; deepEqual(_.countBy(array), { '3': 2, '5': 1 }); _.callback = callback; } else { skipTest(); } }); test('`_.dropRightWhile` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.dropRightWhile(objects), objects.slice(0, 2)); _.callback = callback; } else { skipTest(); } }); test('`_.dropWhile` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.dropWhile(objects.reverse()).reverse(), objects.reverse().slice(0, 2)); _.callback = callback; } else { skipTest(); } }); test('`_.every` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.every(objects.slice(1)), true); _.callback = callback; } else { skipTest(); } }); test('`_.filter` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 0 }, { 'a': 1 }]; _.callback = getPropA; deepEqual(_.filter(objects), [objects[1]]); _.callback = callback; } else { skipTest(); } }); test('`_.find` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.find(objects), objects[1]); _.callback = callback; } else { skipTest(); } }); test('`_.findIndex` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.findIndex(objects), 1); _.callback = callback; } else { skipTest(); } }); test('`_.findLast` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.findLast(objects), objects[2]); _.callback = callback; } else { skipTest(); } }); test('`_.findLastIndex` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; strictEqual(_.findLastIndex(objects), 2); _.callback = callback; } else { skipTest(); } }); test('`_.findLastKey` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; strictEqual(_.findKey(objects), '2'); _.callback = callback; } else { skipTest(); } }); test('`_.findKey` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; strictEqual(_.findLastKey(objects), '2'); _.callback = callback; } else { skipTest(); } }); test('`_.groupBy` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getLength; deepEqual(_.groupBy(array), { '3': ['one', 'two'], '5': ['three'] }); _.callback = callback; } else { skipTest(); } }); test('`_.indexBy` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getLength; deepEqual(_.indexBy(array), { '3': 'two', '5': 'three' }); _.callback = callback; } else { skipTest(); } }); test('`_.map` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; deepEqual(_.map(objects), [0, 1, 1]); _.callback = callback; } else { skipTest(); } }); test('`_.mapValues` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.mapValues({ 'a': { 'b': 1 } }), { 'a': 1 }); _.callback = callback; } else { skipTest(); } }); test('`_.max` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.max(objects), objects[2]); _.callback = callback; } else { skipTest(); } }); test('`_.min` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.min(objects), objects[0]); _.callback = callback; } else { skipTest(); } }); test('`_.partition` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 1 }, { 'a': 1 }, { 'b': 2 }]; _.callback = getPropA; deepEqual(_.partition(objects), [objects.slice(0, 2), objects.slice(2)]); _.callback = callback; } else { skipTest(); } }); test('`_.reduce` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getSum; strictEqual(_.reduce(objects, undefined, 0), 2); _.callback = callback; } else { skipTest(); } }); test('`_.reduceRight` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getSum; strictEqual(_.reduceRight(objects, undefined, 0), 2); _.callback = callback; } else { skipTest(); } }); test('`_.reject` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 0 }, { 'a': 1 }]; _.callback = getPropA; deepEqual(_.reject(objects), [objects[0]]); _.callback = callback; } else { skipTest(); } }); test('`_.remove` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 0 }, { 'a': 1 }]; _.callback = getPropA; _.remove(objects); deepEqual(objects, [{ 'a': 0 }]); _.callback = callback; } else { skipTest(); } }); test('`_.some` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; strictEqual(_.some(objects), true); _.callback = callback; } else { skipTest(); } }); test('`_.sortBy` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropA; deepEqual(_.sortBy(objects.slice().reverse()), [objects[0], objects[2], objects[1]]); _.callback = callback; } else { skipTest(); } }); test('`_.sortedIndex` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 30 }, { 'a': 50 }]; _.callback = getPropA; strictEqual(_.sortedIndex(objects, { 'a': 40 }), 1); _.callback = callback; } else { skipTest(); } }); test('`_.sortedLastIndex` should use `_.callback` internally', 1, function() { if (!isModularize) { var objects = [{ 'a': 30 }, { 'a': 50 }]; _.callback = getPropA; strictEqual(_.sortedLastIndex(objects, { 'a': 40 }), 1); _.callback = callback; } else { skipTest(); } }); test('`_.takeRightWhile` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.takeRightWhile(objects), objects.slice(2)); _.callback = callback; } else { skipTest(); } }); test('`_.takeWhile` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.takeWhile(objects.reverse()), objects.reverse().slice(2)); _.callback = callback; } else { skipTest(); } }); test('`_.transform` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = function() { return function(result, object) { result.sum += object.a; }; }; deepEqual(_.transform(objects, undefined, { 'sum': 0 }), { 'sum': 2 }); _.callback = callback; } else { skipTest(); } }); test('`_.uniq` should use `_.callback` internally', 1, function() { if (!isModularize) { _.callback = getPropB; deepEqual(_.uniq(objects), [objects[0], objects[2]]); _.callback = callback; } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.curry'); (function() { function fn(a, b, c, d) { return slice.call(arguments); } test('should curry based on the number of arguments provided', 3, function() { var curried = _.curry(fn), expected = [1, 2, 3, 4]; deepEqual(curried(1)(2)(3)(4), expected); deepEqual(curried(1, 2)(3, 4), expected); deepEqual(curried(1, 2, 3, 4), expected); }); test('should allow specifying `arity`', 3, function() { var curried = _.curry(fn, 3), expected = [1, 2, 3]; deepEqual(curried(1)(2, 3), expected); deepEqual(curried(1, 2)(3), expected); deepEqual(curried(1, 2, 3), expected); }); test('should coerce `arity` to a number', 2, function() { var values = ['0', 'xyz'], expected = _.map(values, _.constant([])); var actual = _.map(values, function(arity) { return _.curry(fn, arity)(); }); deepEqual(actual, expected); deepEqual(_.curry(fn, '2')(1)(2), [1, 2]); }); test('should support placeholders', 4, function() { var curried = _.curry(fn), ph = curried.placeholder; deepEqual(curried(1)(ph, 3)(ph, 4)(2), [1, 2, 3, 4]); deepEqual(curried(ph, 2)(1)(ph, 4)(3), [1, 2, 3, 4]); deepEqual(curried(ph, ph, 3)(ph, 2)(ph, 4)(1), [1, 2, 3, 4]); deepEqual(curried(ph, ph, ph, 4)(ph, ph, 3)(ph, 2)(1), [1, 2, 3, 4]); }); test('should work with partialed methods', 2, function() { var curried = _.curry(fn), expected = [1, 2, 3, 4]; var a = _.partial(curried, 1), b = _.bind(a, null, 2), c = _.partialRight(b, 4), d = _.partialRight(b(3), 4); deepEqual(c(3), expected); deepEqual(d(), expected); }); test('should provide additional arguments after reaching the target arity', 3, function() { var curried = _.curry(fn, 3); deepEqual(curried(1)(2, 3, 4), [1, 2, 3, 4]); deepEqual(curried(1, 2)(3, 4, 5), [1, 2, 3, 4, 5]); deepEqual(curried(1, 2, 3, 4, 5, 6), [1, 2, 3, 4, 5, 6]); }); test('should return a function with a `length` of `0`', 6, function() { _.times(2, function(index) { var curried = index ? _.curry(fn, 4) : _.curry(fn); strictEqual(curried.length, 0); strictEqual(curried(1).length, 0); strictEqual(curried(1, 2).length, 0); }); }); test('ensure `new curried` is an instance of `func`', 2, function() { var Foo = function(value) { return value && object; }; var curried = _.curry(Foo), object = {}; ok(new curried(false) instanceof Foo); strictEqual(new curried(true), object); }); test('should not set a `this` binding', 9, function() { var fn = function(a, b, c) { var value = this || {}; return [value[a], value[b], value[c]]; }; var object = { 'a': 1, 'b': 2, 'c': 3 }, expected = [1, 2, 3]; deepEqual(_.curry(_.bind(fn, object), 3)('a')('b')('c'), expected); deepEqual(_.curry(_.bind(fn, object), 3)('a', 'b')('c'), expected); deepEqual(_.curry(_.bind(fn, object), 3)('a', 'b', 'c'), expected); deepEqual(_.bind(_.curry(fn), object)('a')('b')('c'), Array(3)); deepEqual(_.bind(_.curry(fn), object)('a', 'b')('c'), Array(3)); deepEqual(_.bind(_.curry(fn), object)('a', 'b', 'c'), expected); object.curried = _.curry(fn); deepEqual(object.curried('a')('b')('c'), Array(3)); deepEqual(object.curried('a', 'b')('c'), Array(3)); deepEqual(object.curried('a', 'b', 'c'), expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.curryRight'); (function() { function fn(a, b, c, d) { return slice.call(arguments); } test('should curry based on the number of arguments provided', 3, function() { var curried = _.curryRight(fn), expected = [1, 2, 3, 4]; deepEqual(curried(4)(3)(2)(1), expected); deepEqual(curried(3, 4)(1, 2), expected); deepEqual(curried(1, 2, 3, 4), expected); }); test('should allow specifying `arity`', 3, function() { var curried = _.curryRight(fn, 3), expected = [1, 2, 3]; deepEqual(curried(3)(1, 2), expected); deepEqual(curried(2, 3)(1), expected); deepEqual(curried(1, 2, 3), expected); }); test('should work with partialed methods', 2, function() { var curried = _.curryRight(fn), expected = [1, 2, 3, 4]; var a = _.partialRight(curried, 4), b = _.partialRight(a, 3), c = _.bind(b, null, 1), d = _.partial(b(2), 1); deepEqual(c(2), expected); deepEqual(d(), expected); }); test('should support placeholders', 4, function() { var curried = _.curryRight(fn), expected = [1, 2, 3, 4], ph = curried.placeholder; deepEqual(curried(4)(2, ph)(1, ph)(3), expected); deepEqual(curried(3, ph)(4)(1, ph)(2), expected); deepEqual(curried(ph, ph, 4)(ph, 3)(ph, 2)(1), expected); deepEqual(curried(ph, ph, ph, 4)(ph, ph, 3)(ph, 2)(1), expected); }); test('should provide additional arguments after reaching the target arity', 3, function() { var curried = _.curryRight(fn, 3); deepEqual(curried(4)(1, 2, 3), [1, 2, 3, 4]); deepEqual(curried(4, 5)(1, 2, 3), [1, 2, 3, 4, 5]); deepEqual(curried(1, 2, 3, 4, 5, 6), [1, 2, 3, 4, 5, 6]); }); test('should return a function with a `length` of `0`', 6, function() { _.times(2, function(index) { var curried = index ? _.curryRight(fn, 4) : _.curryRight(fn); strictEqual(curried.length, 0); strictEqual(curried(4).length, 0); strictEqual(curried(3, 4).length, 0); }); }); test('ensure `new curried` is an instance of `func`', 2, function() { var Foo = function(value) { return value && object; }; var curried = _.curryRight(Foo), object = {}; ok(new curried(false) instanceof Foo); strictEqual(new curried(true), object); }); test('should not set a `this` binding', 9, function() { var fn = function(a, b, c) { var value = this || {}; return [value[a], value[b], value[c]]; }; var object = { 'a': 1, 'b': 2, 'c': 3 }, expected = [1, 2, 3]; deepEqual(_.curryRight(_.bind(fn, object), 3)('c')('b')('a'), expected); deepEqual(_.curryRight(_.bind(fn, object), 3)('b', 'c')('a'), expected); deepEqual(_.curryRight(_.bind(fn, object), 3)('a', 'b', 'c'), expected); deepEqual(_.bind(_.curryRight(fn), object)('c')('b')('a'), Array(3)); deepEqual(_.bind(_.curryRight(fn), object)('b', 'c')('a'), Array(3)); deepEqual(_.bind(_.curryRight(fn), object)('a', 'b', 'c'), expected); object.curried = _.curryRight(fn); deepEqual(object.curried('c')('b')('a'), Array(3)); deepEqual(object.curried('b', 'c')('a'), Array(3)); deepEqual(object.curried('a', 'b', 'c'), expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('curry methods'); _.each(['curry', 'curryRight'], function(methodName) { var func = _[methodName], fn = function(a, b) { return slice.call(arguments); }, isCurry = methodName == 'curry'; test('`_.' + methodName + '` should work as an iteratee for `_.map`', 2, function() { var array = [fn, fn, fn], object = { 'a': fn, 'b': fn, 'c': fn }; _.each([array, object], function(collection) { var curries = _.map(collection, func), expected = _.map(collection, _.constant(isCurry ? ['a', 'b'] : ['b', 'a'])); var actual = _.map(curries, function(curried) { return curried('a')('b'); }); deepEqual(actual, expected); }); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.debounce'); (function() { asyncTest('should debounce a function', 2, function() { if (!(isRhino && isModularize)) { var callCount = 0, debounced = _.debounce(function() { callCount++; }, 32); debounced(); debounced(); debounced(); strictEqual(callCount, 0); setTimeout(function() { strictEqual(callCount, 1); QUnit.start(); }, 96); } else { skipTest(2); QUnit.start(); } }); asyncTest('subsequent debounced calls return the last `func` result', 2, function() { if (!(isRhino && isModularize)) { var debounced = _.debounce(_.identity, 32); debounced('x'); setTimeout(function() { notEqual(debounced('y'), 'y'); }, 64); setTimeout(function() { notEqual(debounced('z'), 'z'); QUnit.start(); }, 128); } else { skipTest(2); QUnit.start(); } }); asyncTest('subsequent "immediate" debounced calls return the last `func` result', 2, function() { if (!(isRhino && isModularize)) { var debounced = _.debounce(_.identity, 32, true), result = [debounced('x'), debounced('y')]; deepEqual(result, ['x', 'x']); setTimeout(function() { var result = [debounced('a'), debounced('b')]; deepEqual(result, ['a', 'a']); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); asyncTest('should apply default options correctly', 2, function() { if (!(isRhino && isModularize)) { var callCount = 0; var debounced = _.debounce(function(value) { callCount++; return value; }, 32, {}); strictEqual(debounced('x'), undefined); setTimeout(function() { strictEqual(callCount, 1); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); asyncTest('should support a `leading` option', 7, function() { if (!(isRhino && isModularize)) { var withLeading, callCounts = [0, 0, 0]; _.each([true, { 'leading': true }], function(options, index) { var debounced = _.debounce(function(value) { callCounts[index]++; return value; }, 32, options); if (index == 1) { withLeading = debounced; } strictEqual(debounced('x'), 'x'); }); _.each([false, { 'leading': false }], function(options) { var withoutLeading = _.debounce(_.identity, 32, options); strictEqual(withoutLeading('x'), undefined); }); var withLeadingAndTrailing = _.debounce(function() { callCounts[2]++; }, 32, { 'leading': true }); withLeadingAndTrailing(); withLeadingAndTrailing(); strictEqual(callCounts[2], 1); setTimeout(function() { deepEqual(callCounts, [1, 1, 2]); withLeading('x'); strictEqual(callCounts[1], 2); QUnit.start(); }, 64); } else { skipTest(7); QUnit.start(); } }); asyncTest('should support a `trailing` option', 4, function() { if (!(isRhino && isModularize)) { var withCount = 0, withoutCount = 0; var withTrailing = _.debounce(function(value) { withCount++; return value; }, 32, { 'trailing': true }); var withoutTrailing = _.debounce(function(value) { withoutCount++; return value; }, 32, { 'trailing': false }); strictEqual(withTrailing('x'), undefined); strictEqual(withoutTrailing('x'), undefined); setTimeout(function() { strictEqual(withCount, 1); strictEqual(withoutCount, 0); QUnit.start(); }, 64); } else { skipTest(4); QUnit.start(); } }); asyncTest('should support a `maxWait` option', 1, function() { if (!(isRhino && isModularize)) { var limit = (argv || isPhantom) ? 1000 : 320, withCount = 0, withoutCount = 0; var withMaxWait = _.debounce(function() { withCount++; }, 64, { 'maxWait': 128 }); var withoutMaxWait = _.debounce(function() { withoutCount++; }, 96); var start = +new Date; while ((new Date - start) < limit) { withMaxWait(); withoutMaxWait(); } var actual = [Boolean(withCount), Boolean(withoutCount)]; setTimeout(function() { deepEqual(actual, [true, false]); QUnit.start(); }, 1); } else { skipTest(); QUnit.start(); } }); asyncTest('should cancel `maxDelayed` when `delayed` is invoked', 1, function() { if (!(isRhino && isModularize)) { var callCount = 0; var debounced = _.debounce(function() { callCount++; }, 32, { 'maxWait': 64 }); debounced(); setTimeout(function() { strictEqual(callCount, 1); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); asyncTest('should invoke the `trailing` call with the correct arguments and `this` binding', 2, function() { if (!(isRhino && isModularize)) { var actual, callCount = 0, object = {}; var debounced = _.debounce(function(value) { actual = [this]; push.apply(actual, arguments); return ++callCount != 2; }, 32, { 'leading': true, 'maxWait': 64 }); while (true) { if (!debounced.call(object, 'a')) { break; } } setTimeout(function() { strictEqual(callCount, 2); deepEqual(actual, [object, 'a']); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.deburr'); (function() { test('should convert latin-1 supplementary letters to basic latin', 1, function() { var actual = _.map(burredLetters, _.deburr); deepEqual(actual, deburredLetters); }); test('should not deburr latin-1 mathematical operators', 1, function() { var operators = ['\xd7', '\xf7'], actual = _.map(operators, _.deburr); deepEqual(actual, operators); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.defaults'); (function() { test('should assign properties of a source object if missing on the destination object', 1, function() { deepEqual(_.defaults({ 'a': 1 }, { 'a': 2, 'b': 2 }), { 'a': 1, 'b': 2 }); }); test('should accept multiple source objects', 2, function() { var expected = { 'a': 1, 'b': 2, 'c': 3 }; deepEqual(_.defaults({ 'a': 1, 'b': 2 }, { 'b': 3 }, { 'c': 3 }), expected); deepEqual(_.defaults({ 'a': 1, 'b': 2 }, { 'b': 3, 'c': 3 }, { 'c': 2 }), expected); }); test('should not overwrite `null` values', 1, function() { var actual = _.defaults({ 'a': null }, { 'a': 1 }); strictEqual(actual.a, null); }); test('should overwrite `undefined` values', 1, function() { var actual = _.defaults({ 'a': undefined }, { 'a': 1 }); strictEqual(actual.a, 1); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.defer'); (function() { asyncTest('should defer `func` execution', 1, function() { if (!(isRhino && isModularize)) { var pass = false; _.defer(function() { pass = true; }); setTimeout(function() { ok(pass); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); asyncTest('should provide additional arguments to `func`', 1, function() { if (!(isRhino && isModularize)) { var args; _.defer(function() { args = slice.call(arguments); }, 1, 2); setTimeout(function() { deepEqual(args, [1, 2]); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); asyncTest('should be cancelable', 1, function() { if (!(isRhino && isModularize)) { var pass = true; var timerId = _.defer(function() { pass = false; }); clearTimeout(timerId); setTimeout(function() { ok(pass); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.delay'); (function() { asyncTest('should delay `func` execution', 2, function() { if (!(isRhino && isModularize)) { var pass = false; _.delay(function() { pass = true; }, 96); setTimeout(function() { ok(!pass); }, 32); setTimeout(function() { ok(pass); QUnit.start(); }, 160); } else { skipTest(2); QUnit.start(); } }); asyncTest('should provide additional arguments to `func`', 1, function() { if (!(isRhino && isModularize)) { var args; _.delay(function() { args = slice.call(arguments); }, 32, 1, 2); setTimeout(function() { deepEqual(args, [1, 2]); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); asyncTest('should be cancelable', 1, function() { if (!(isRhino && isModularize)) { var pass = true; var timerId = _.delay(function() { pass = false; }, 32); clearTimeout(timerId); setTimeout(function() { ok(pass); QUnit.start(); }, 128); } else { skipTest(); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.difference'); (function() { var args = arguments; test('should return the difference of the given arrays', 2, function() { var actual = _.difference([1, 2, 3, 4, 5], [5, 2, 10]); deepEqual(actual, [1, 3, 4]); actual = _.difference([1, 2, 3, 4, 5], [5, 2, 10], [8, 4]); deepEqual(actual, [1, 3]); }); test('should match `NaN`', 1, function() { deepEqual(_.difference([1, NaN, 3], [NaN, 5, NaN]), [1, 3]); }); test('should work with large arrays', 1, function() { var array1 = _.range(LARGE_ARRAY_SIZE + 1), array2 = _.range(LARGE_ARRAY_SIZE), a = {}, b = {}, c = {}; array1.push(a, b, c); array2.push(b, c, a); deepEqual(_.difference(array1, array2), [LARGE_ARRAY_SIZE]); }); test('should work with large arrays of objects', 1, function() { var object1 = {}, object2 = {}, largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object1)); deepEqual(_.difference([object1, object2], largeArray), [object2]); }); test('should work with large arrays of `NaN`', 1, function() { var largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(NaN)); deepEqual(_.difference([1, NaN, 3], largeArray), [1, 3]); }); test('should ignore values that are not arrays or `arguments` objects', 4, function() { var array = [1, null, 3]; deepEqual(_.difference(args, 3, { '0': 1 }), [1, 2, 3]); deepEqual(_.difference(null, array, 1), []); deepEqual(_.difference(array, args, null), [null]); deepEqual(_.difference('abc', array, 'b'), []); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.drop'); (function() { var array = [1, 2, 3]; test('should drop the first two elements', 1, function() { deepEqual(_.drop(array, 2), [3]); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? [2, 3] : array; }); var actual = _.map(falsey, function(n) { return _.drop(array, n); }); deepEqual(actual, expected); }); test('should return all elements when `n` < `1`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.drop(array, n), array); }); }); test('should return an empty array when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.drop(array, n), []); }); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.drop); deepEqual(actual, [[2, 3], [5, 6], [8, 9]]); }); test('should work in a lazy chain sequence', 6, function() { if (!isNpm) { var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], values = [], predicate = function(value) { values.push(value); return value > 2; }, actual = _(array).drop(2).drop().value(); deepEqual(actual, [4, 5, 6, 7, 8, 9, 10]); actual = _(array).filter(predicate).drop(2).drop().value(); deepEqual(actual, [6, 7, 8, 9, 10]); deepEqual(values, array); actual = _(array).drop(2).dropRight().drop().dropRight(2).value(); deepEqual(actual, [4, 5, 6, 7]); values = []; actual = _(array).drop().filter(predicate).drop(2).dropRight().drop().dropRight(2).value(); deepEqual(actual, [6, 7]); deepEqual(values, array.slice(1)); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.dropRight'); (function() { var array = [1, 2, 3]; test('should drop the last two elements', 1, function() { deepEqual(_.dropRight(array, 2), [1]); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? [1, 2] : array; }); var actual = _.map(falsey, function(n) { return _.dropRight(array, n); }); deepEqual(actual, expected); }); test('should return all elements when `n` < `1`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.dropRight(array, n), array); }); }); test('should return an empty array when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.dropRight(array, n), []); }); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.dropRight); deepEqual(actual, [[1, 2], [4, 5], [7, 8]]); }); test('should work in a lazy chain sequence', 6, function() { if (!isNpm) { var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], values = [], predicate = function(value) { values.push(value); return value < 9; }, actual = _(array).dropRight(2).dropRight().value(); deepEqual(actual, [1, 2, 3, 4, 5, 6, 7]); actual = _(array).filter(predicate).dropRight(2).dropRight().value(); deepEqual(actual, [1, 2, 3, 4, 5]); deepEqual(values, array); actual = _(array).dropRight(2).drop().dropRight().drop(2).value(); deepEqual(actual, [4, 5, 6, 7]); values = []; actual = _(array).dropRight().filter(predicate).dropRight(2).drop().dropRight().drop(2).value(); deepEqual(actual, [4, 5]); deepEqual(values, array.slice(0, -1)); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.dropRightWhile'); (function() { var array = [1, 2, 3, 4]; var objects = [ { 'a': 0, 'b': 0 }, { 'a': 1, 'b': 1 }, { 'a': 2, 'b': 2 } ]; test('should drop elements while `predicate` returns truthy', 1, function() { var actual = _.dropRightWhile(array, function(num) { return num > 2; }); deepEqual(actual, [1, 2]); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.dropRightWhile(array, function() { args = slice.call(arguments); }); deepEqual(args, [4, 3, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.dropRightWhile(array, function(num, index) { return this[index] > 2; }, array); deepEqual(actual, [1, 2]); }); test('should work with a "_.matches" style `predicate`', 1, function() { deepEqual(_.dropRightWhile(objects, { 'b': 2 }), objects.slice(0, 2)); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { deepEqual(_.dropRightWhile(objects, 'b', 2), objects.slice(0, 2)); }); test('should work with a "_.property" style `predicate`', 1, function() { deepEqual(_.dropRightWhile(objects, 'b'), objects.slice(0, 1)); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var wrapped = _(array).dropRightWhile(function(num) { return num > 2; }); ok(wrapped instanceof _); deepEqual(wrapped.value(), [1, 2]); } else { skipTest(2); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [16, 3, [1, 4, 9 ,16]]; _(array).dropRightWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, [4, 3, array]); _(array).map(square).dropRightWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).dropRightWhile(function(value, index) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).dropRightWhile(function(value) { args = slice.call(arguments); }).value(); deepEqual(args, [16]); _(array).map(square).dropRightWhile(function() { args = slice.call(arguments); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.dropWhile'); (function() { var array = [1, 2, 3, 4]; var objects = [ { 'a': 2, 'b': 2 }, { 'a': 1, 'b': 1 }, { 'a': 0, 'b': 0 } ]; test('should drop elements while `predicate` returns truthy', 1, function() { var actual = _.dropWhile(array, function(num) { return num < 3; }); deepEqual(actual, [3, 4]); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.dropWhile(array, function() { args = slice.call(arguments); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.dropWhile(array, function(num, index) { return this[index] < 3; }, array); deepEqual(actual, [3, 4]); }); test('should work with a "_.matches" style `predicate`', 1, function() { deepEqual(_.dropWhile(objects, { 'b': 2 }), objects.slice(1)); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { deepEqual(_.dropWhile(objects, 'b', 2), objects.slice(1)); }); test('should work with a "_.property" style `predicate`', 1, function() { deepEqual(_.dropWhile(objects, 'b'), objects.slice(2)); }); test('should work in a lazy chain sequence', 3, function() { if (!isNpm) { var wrapped = _(array).dropWhile(function(num) { return num < 3; }); deepEqual(wrapped.value(), [3, 4]); deepEqual(wrapped.reverse().value(), [4, 3]); strictEqual(wrapped.last(), 4); } else { skipTest(3); } }); test('should work in a lazy chain sequence with `drop`', 1, function() { if (!isNpm) { var actual = _(array) .dropWhile(function(num) { return num == 1; }) .drop() .dropWhile(function(num) { return num == 3; }) .value(); deepEqual(actual, [4]); } else { skipTest(); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [1, 0, [1, 4, 9, 16]]; _(array).dropWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, [1, 0, array]); _(array).map(square).dropWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).dropWhile(function(value, index) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).dropWhile(function(index) { args = slice.call(arguments); }).value(); deepEqual(args, [1]); _(array).map(square).dropWhile(function() { args = slice.call(arguments); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.endsWith'); (function() { var string = 'abc'; test('should return `true` if a string ends with `target`', 1, function() { strictEqual(_.endsWith(string, 'c'), true); }); test('should return `false` if a string does not end with `target`', 1, function() { strictEqual(_.endsWith(string, 'b'), false); }); test('should work with a `position` argument', 1, function() { strictEqual(_.endsWith(string, 'b', 2), true); }); test('should work with `position` >= `string.length`', 4, function() { _.each([3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { strictEqual(_.endsWith(string, 'c', position), true); }); }); test('should treat falsey `position` values, except `undefined`, as `0`', 1, function() { var expected = _.map(falsey, _.constant(true)); var actual = _.map(falsey, function(position) { return _.endsWith(string, position === undefined ? 'c' : '', position); }); deepEqual(actual, expected); }); test('should treat a negative `position` as `0`', 6, function() { _.each([-1, -3, -Infinity], function(position) { ok(_.every(string, function(chr) { return _.endsWith(string, chr, position) === false; })); strictEqual(_.endsWith(string, '', position), true); }); }); test('should return `true` when `target` is an empty string regardless of `position`', 1, function() { ok(_.every([-Infinity, NaN, -3, -1, 0, 1, 2, 3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { return _.endsWith(string, '', position, true); })); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.escape'); (function() { var escaped = '&amp;&lt;&gt;&quot;&#39;&#96;\/', unescaped = '&<>"\'`\/'; escaped += escaped; unescaped += unescaped; test('should escape values', 1, function() { strictEqual(_.escape(unescaped), escaped); }); test('should not escape the "/" character', 1, function() { strictEqual(_.escape('/'), '/'); }); test('should handle strings with nothing to escape', 1, function() { strictEqual(_.escape('abc'), 'abc'); }); test('should escape the same characters unescaped by `_.unescape`', 1, function() { strictEqual(_.escape(_.unescape(escaped)), escaped); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.escapeRegExp'); (function() { var escaped = '\\.\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\/\\\\', unescaped = '.*+?^${}()|[\]\/\\'; escaped += escaped; unescaped += unescaped; test('should escape values', 1, function() { strictEqual(_.escapeRegExp(unescaped), escaped); }); test('should handle strings with nothing to escape', 1, function() { strictEqual(_.escapeRegExp('abc'), 'abc'); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.every'); (function() { test('should return `true` for empty collections', 1, function() { var expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { try { return _.every(value, _.identity); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `true` if `predicate` returns truthy for all elements in the collection', 1, function() { strictEqual(_.every([true, 1, 'a'], _.identity), true); }); test('should return `false` as soon as `predicate` returns falsey', 1, function() { strictEqual(_.every([true, null, true], _.identity), false); }); test('should work with collections of `undefined` values (test in IE < 9)', 1, function() { strictEqual(_.every([undefined, undefined, undefined], _.identity), false); }); test('should work with a "_.property" style `predicate`', 2, function() { var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }]; strictEqual(_.every(objects, 'a'), false); strictEqual(_.every(objects, 'b'), true); }); test('should work with a "_where" style `predicate`', 2, function() { var objects = [{ 'a': 0, 'b': 0 }, { 'a': 0, 'b': 1 }]; strictEqual(_.every(objects, { 'a': 0 }), true); strictEqual(_.every(objects, { 'b': 1 }), false); }); test('should use `_.identity` when `predicate` is nullish', 2, function() { var values = [, null, undefined], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value, index) { var array = [0]; return index ? _.every(array, value) : _.every(array); }); deepEqual(actual, expected); expected = _.map(values, _.constant(true)); actual = _.map(values, function(value, index) { var array = [1]; return index ? _.every(array, value) : _.every(array); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([[1]], _.every); deepEqual(actual, [true]); }); test('should be aliased', 1, function() { strictEqual(_.all, _.every); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('strict mode checks'); _.each(['assign', 'bindAll', 'defaults'], function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` should ' + (isStrict ? '' : 'not ') + 'throw strict mode errors', 1, function() { if (freeze) { var object = { 'a': undefined, 'b': function() {} }, pass = !isStrict; freeze(object); try { if (methodName == 'bindAll') { func(object); } else { func(object, { 'a': 1 }); } } catch(e) { pass = !pass; } ok(pass); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.fill'); (function() { test('should use a default `start` of `0` and a default `end` of `array.length`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a'), ['a', 'a', 'a']); }); test('should use `undefined` for `value` if not provided', 2, function() { var array = [1, 2, 3], actual = _.fill(array); deepEqual(actual, [undefined, undefined, undefined]); ok(_.every(actual, function(value, index) { return index in actual; })); }); test('should work with a positive `start`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 1), [1, 'a', 'a']); }); test('should work with a `start` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(start) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', start), [1, 2, 3]); }); }); test('should treat falsey `start` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(['a', 'a', 'a'])); var actual = _.map(falsey, function(start) { var array = [1, 2, 3]; return _.fill(array, 'a', start); }); deepEqual(actual, expected); }); test('should work with a negative `start`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', -1), [1, 2, 'a']); }); test('should work with a negative `start` <= negative `array.length`', 3, function() { _.each([-3, -4, -Infinity], function(start) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', start), ['a', 'a', 'a']); }); }); test('should work with `start` >= `end`', 2, function() { _.each([2, 3], function(start) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', start, 2), [1, 2, 3]); }); }); test('should work with a positive `end`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 0, 1), ['a', 2, 3]); }); test('should work with a `end` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(end) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 0, end), ['a', 'a', 'a']); }); }); test('should treat falsey `end` values, except `undefined`, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value === undefined ? ['a', 'a', 'a'] : [1, 2, 3]; }); var actual = _.map(falsey, function(end) { var array = [1, 2, 3]; return _.fill(array, 'a', 0, end); }); deepEqual(actual, expected); }); test('should work with a negative `end`', 1, function() { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 0, -1), ['a', 'a', 3]); }); test('should work with a negative `end` <= negative `array.length`', 3, function() { _.each([-3, -4, -Infinity], function(end) { var array = [1, 2, 3]; deepEqual(_.fill(array, 'a', 0, end), [1, 2, 3]); }); }); test('should coerce `start` and `end` to integers', 1, function() { var positions = [[0.1, 1.1], ['0', 1], [0, '1'], ['1'], [NaN, 1], [1, NaN]]; var actual = _.map(positions, function(pos) { var array = [1, 2, 3]; return _.fill.apply(_, [array, 'a'].concat(pos)); }); deepEqual(actual, [['a', 2, 3], ['a', 2, 3], ['a', 2, 3], [1, 'a', 'a'], ['a', 2, 3], [1, 2, 3]]); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2], [3, 4]], actual = _.map(array, _.fill); deepEqual(actual, [[0, 0], [1, 1]]); }); test('should return a wrapped value when chaining', 3, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array).fill('a'), actual = wrapped.value(); ok(wrapped instanceof _); deepEqual(actual, ['a', 'a', 'a']); strictEqual(actual, array); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.filter'); (function() { var array = [1, 2, 3]; test('should return elements `predicate` returns truthy for', 1, function() { var actual = _.filter(array, function(num) { return num % 2; }); deepEqual(actual, [1, 3]); }); test('should iterate correctly over an object with numeric keys (test in Mobile Safari 8)', 1, function() { // Trigger a Mobile Safari 8 JIT bug. // See https://github.com/lodash/lodash/issues/799. var counter = 0, object = { '1': 'foo', '8': 'bar', '50': 'baz' }; _.times(1000, function() { _.filter([], _.constant(true)); }); _.filter(object, function() { counter++; return true; }); strictEqual(counter, 3); }); test('should be aliased', 1, function() { strictEqual(_.select, _.filter); }); }()); /*--------------------------------------------------------------------------*/ _.each(['find', 'findLast', 'findIndex', 'findLastIndex', 'findKey', 'findLastKey'], function(methodName) { QUnit.module('lodash.' + methodName); var func = _[methodName]; (function() { var objects = [ { 'a': 0, 'b': 0 }, { 'a': 1, 'b': 1 }, { 'a': 2, 'b': 2 } ]; var expected = ({ 'find': [objects[1], undefined, objects[2], objects[1]], 'findLast': [objects[2], undefined, objects[2], objects[2]], 'findIndex': [1, -1, 2, 1], 'findLastIndex': [2, -1, 2, 2], 'findKey': ['1', undefined, '2', '1'], 'findLastKey': ['2', undefined, '2', '2'] })[methodName]; test('should return the correct value', 1, function() { strictEqual(func(objects, function(object) { return object.a; }), expected[0]); }); test('should work with a `thisArg`', 1, function() { strictEqual(func(objects, function(object, index) { return this[index].a; }, objects), expected[0]); }); test('should return `' + expected[1] + '` if value is not found', 1, function() { strictEqual(func(objects, function(object) { return object.a === 3; }), expected[1]); }); test('should work with a "_.matches" style `predicate`', 1, function() { strictEqual(func(objects, { 'b': 2 }), expected[2]); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { strictEqual(func(objects, 'b', 2), expected[2]); }); test('should work with a "_.property" style `predicate`', 1, function() { strictEqual(func(objects, 'b'), expected[3]); }); test('should return `' + expected[1] + '` for empty collections', 1, function() { var emptyValues = _.endsWith(methodName, 'Index') ? _.reject(empties, _.isPlainObject) : empties, expecting = _.map(emptyValues, _.constant(expected[1])); var actual = _.map(emptyValues, function(value) { try { return func(value, { 'a': 3 }); } catch(e) {} }); deepEqual(actual, expecting); }); }()); (function() { var expected = ({ 'find': 1, 'findLast': 2, 'findKey': 'a', 'findLastKey': 'b' })[methodName]; if (expected != null) { test('should work with an object for `collection`', 1, function() { var actual = func({ 'a': 1, 'b': 2, 'c': 3 }, function(num) { return num < 3; }); strictEqual(actual, expected); }); } }()); (function() { var expected = ({ 'find': 'a', 'findLast': 'b', 'findIndex': 0, 'findLastIndex': 1 })[methodName]; if (expected != null) { test('should work with a string for `collection`', 1, function() { var actual = func('abc', function(chr, index) { return index < 2; }); strictEqual(actual, expected); }); } if (methodName == 'find') { test('should be aliased', 1, function() { strictEqual(_.detect, func); }); } }()); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.findWhere'); (function() { var objects = [ { 'a': 1 }, { 'a': 1 }, { 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }, { 'a': 3 } ]; test('should filter by `source` properties', 6, function() { strictEqual(_.findWhere(objects, { 'a': 1 }), objects[0]); strictEqual(_.findWhere(objects, { 'a': 2 }), objects[3]); strictEqual(_.findWhere(objects, { 'a': 3 }), objects[4]); strictEqual(_.findWhere(objects, { 'b': 1 }), undefined); strictEqual(_.findWhere(objects, { 'b': 2 }), objects[2]); strictEqual(_.findWhere(objects, { 'a': 1, 'b': 2 }), objects[2]); }); test('should work with a function for `source`', 1, function() { function source() {} source.a = 2; strictEqual(_.findWhere(objects, source), objects[3]); }); test('should match all elements when provided an empty `source`', 1, function() { var expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { return _.findWhere(objects, value) === objects[0]; }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.first'); (function() { var array = [1, 2, 3]; test('should return the first element', 1, function() { strictEqual(_.first(array), 1); }); test('should return `undefined` when querying empty arrays', 1, function() { var array = []; array['-1'] = 1; strictEqual(_.first(array), undefined); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.first); deepEqual(actual, [1, 4, 7]); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_(array).first(), 1); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain().first() instanceof _); } else { skipTest(); } }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 3, 4]; var wrapped = _(array).filter(function(value) { return value % 2 == 0; }); strictEqual(wrapped.first(), 2); } else { skipTest(); } }); test('should be aliased', 1, function() { strictEqual(_.head, _.first); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.take'); (function() { var array = [1, 2, 3]; test('should take the first two elements', 1, function() { deepEqual(_.take(array, 2), [1, 2]); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? [1] : []; }); var actual = _.map(falsey, function(n) { return _.take(array, n); }); deepEqual(actual, expected); }); test('should return an empty array when `n` < `1`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.take(array, n), []); }); }); test('should return all elements when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.take(array, n), array); }); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.take); deepEqual(actual, [[1], [4], [7]]); }); test('should work in a lazy chain sequence', 6, function() { if (!isNpm) { var array = [1, 2, 3, 4, 5, 6, 7, 8, 9 , 10], values = [], predicate = function(value) { values.push(value); return value > 2; }, actual = _(array).take(2).take().value(); deepEqual(actual, [1]); actual = _(array).filter(predicate).take(2).take().value(); deepEqual(actual, [3]); deepEqual(values, array.slice(0, 3)); actual = _(array).take(6).takeRight(4).take(2).takeRight().value(); deepEqual(actual, [4]); values = []; actual = _(array).take(array.length - 1).filter(predicate).take(6).takeRight(4).take(2).takeRight().value(); deepEqual(actual, [6]); deepEqual(values, array.slice(0, -2)); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.takeRight'); (function() { var array = [1, 2, 3]; test('should take the last two elements', 1, function() { deepEqual(_.takeRight(array, 2), [2, 3]); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? [3] : []; }); var actual = _.map(falsey, function(n) { return _.takeRight(array, n); }); deepEqual(actual, expected); }); test('should return an empty array when `n` < `1`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.takeRight(array, n), []); }); }); test('should return all elements when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.takeRight(array, n), array); }); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.takeRight); deepEqual(actual, [[3], [6], [9]]); }); test('should work in a lazy chain sequence', 6, function() { if (!isNpm) { var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], values = [], predicate = function(value) { values.push(value); return value < 9; }, actual = _(array).takeRight(2).takeRight().value(); deepEqual(actual, [10]); actual = _(array).filter(predicate).takeRight(2).takeRight().value(); deepEqual(actual, [8]); deepEqual(values, array); actual = _(array).takeRight(6).take(4).takeRight(2).take().value(); deepEqual(actual, [7]); values = []; actual = _(array).filter(predicate).takeRight(6).take(4).takeRight(2).take().value(); deepEqual(actual, [5]); deepEqual(values, array); } else { skipTest(6); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.takeRightWhile'); (function() { var array = [1, 2, 3, 4]; var objects = [ { 'a': 0, 'b': 0 }, { 'a': 1, 'b': 1 }, { 'a': 2, 'b': 2 } ]; test('should take elements while `predicate` returns truthy', 1, function() { var actual = _.takeRightWhile(array, function(num) { return num > 2; }); deepEqual(actual, [3, 4]); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.takeRightWhile(array, function() { args = slice.call(arguments); }); deepEqual(args, [4, 3, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.takeRightWhile(array, function(num, index) { return this[index] > 2; }, array); deepEqual(actual, [3, 4]); }); test('should work with a "_.matches" style `predicate`', 1, function() { deepEqual(_.takeRightWhile(objects, { 'b': 2 }), objects.slice(2)); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { deepEqual(_.takeRightWhile(objects, 'b', 2), objects.slice(2)); }); test('should work with a "_.property" style `predicate`', 1, function() { deepEqual(_.takeRightWhile(objects, 'b'), objects.slice(1)); }); test('should work in a lazy chain sequence', 3, function() { if (!isNpm) { var wrapped = _(array).takeRightWhile(function(num) { return num > 2; }); deepEqual(wrapped.value(), [3, 4]); deepEqual(wrapped.reverse().value(), [4, 3]); strictEqual(wrapped.last(), 4); } else { skipTest(3); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [16, 3, [1, 4, 9 , 16]]; _(array).takeRightWhile(function(value, index, array) { args = slice.call(arguments) }).value(); deepEqual(args, [4, 3, array]); _(array).map(square).takeRightWhile(function(value, index, array) { args = slice.call(arguments) }).value(); deepEqual(args, expected); _(array).map(square).takeRightWhile(function(value, index) { args = slice.call(arguments) }).value(); deepEqual(args, expected); _(array).map(square).takeRightWhile(function(index) { args = slice.call(arguments); }).value(); deepEqual(args, [16]); _(array).map(square).takeRightWhile(function() { args = slice.call(arguments); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.takeWhile'); (function() { var array = [1, 2, 3, 4]; var objects = [ { 'a': 2, 'b': 2 }, { 'a': 1, 'b': 1 }, { 'a': 0, 'b': 0 } ]; test('should take elements while `predicate` returns truthy', 1, function() { var actual = _.takeWhile(array, function(num) { return num < 3; }); deepEqual(actual, [1, 2]); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.takeWhile(array, function() { args = slice.call(arguments); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.takeWhile(array, function(num, index) { return this[index] < 3; }, array); deepEqual(actual, [1, 2]); }); test('should work with a "_.matches" style `predicate`', 1, function() { deepEqual(_.takeWhile(objects, { 'b': 2 }), objects.slice(0, 1)); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { deepEqual(_.takeWhile(objects, 'b', 2), objects.slice(0, 1)); }); test('should work with a "_.property" style `predicate`', 1, function() { deepEqual(_.takeWhile(objects, 'b'), objects.slice(0, 2)); }); test('should work in a lazy chain sequence', 3, function() { if (!isNpm) { var wrapped = _(array).takeWhile(function(num) { return num < 3; }); deepEqual(wrapped.value(), [1, 2]); deepEqual(wrapped.reverse().value(), [2, 1]); strictEqual(wrapped.last(), 2); } else { skipTest(3); } }); test('should work in a lazy chain sequence with `take`', 1, function() { if (!isNpm) { var actual = _(array) .takeWhile(function(num) { return num < 4; }) .take(2) .takeWhile(function(num) { return num == 1; }) .value(); deepEqual(actual, [1]); } else { skipTest(); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [1, 0, [1, 4, 9, 16]]; _(array).takeWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, [1, 0, array]); _(array).map(square).takeWhile(function(value, index, array) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).takeWhile(function(value, index) { args = slice.call(arguments); }).value(); deepEqual(args, expected); _(array).map(square).takeWhile(function(value) { args = slice.call(arguments); }).value(); deepEqual(args, [1]); _(array).map(square).takeWhile(function() { args = slice.call(arguments); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('flatten methods'); (function() { var args = arguments; test('should perform a shallow flatten', 1, function() { var array = [[['a']], [['b']]]; deepEqual(_.flatten(array), [['a'], ['b']]); }); test('should work with `isDeep`', 2, function() { var array = [[['a']], [['b']]], expected = ['a', 'b']; deepEqual(_.flatten(array, true), expected); deepEqual(_.flattenDeep(array), expected); }); test('should flatten `arguments` objects', 3, function() { var array = [args, [args]], expected = [1, 2, 3, args]; deepEqual(_.flatten(array), expected); expected = [1, 2, 3, 1, 2, 3]; deepEqual(_.flatten(array, true), expected); deepEqual(_.flattenDeep(array), expected); }); test('should work as an iteratee for `_.map`', 2, function() { var array = [[[['a']]], [[['b']]]]; deepEqual(_.map(array, _.flatten), [[['a']], [['b']]]); deepEqual(_.map(array, _.flattenDeep), [['a'], ['b']]); }); test('should treat sparse arrays as dense', 6, function() { var array = [[1, 2, 3], Array(3)], expected = [1, 2, 3]; expected.push(undefined, undefined, undefined); _.each([_.flatten(array), _.flatten(array, true), _.flattenDeep(array)], function(actual) { deepEqual(actual, expected); ok('4' in actual); }); }); test('should work with extremely large arrays', 3, function() { // Test in modern browsers only to avoid browser hangs. _.times(3, function(index) { if (freeze) { var expected = Array(5e5); try { if (index) { var actual = actual == 1 ? _.flatten([expected], true) : _.flattenDeep([expected]); } else { actual = _.flatten(expected); } deepEqual(actual, expected); } catch(e) { ok(false, e.message); } } else { skipTest(); } }); }); test('should work with empty arrays', 3, function() { var array = [[], [[]], [[], [[[]]]]], expected = [[], [], [[[]]]]; deepEqual(_.flatten(array), expected); expected = []; deepEqual(_.flatten(array, true), expected); deepEqual(_.flattenDeep(array), expected); }); test('should support flattening of nested arrays', 3, function() { var array = [1, [2], [3, [4]]], expected = [1, 2, 3, [4]]; deepEqual(_.flatten(array), expected); expected = [1, 2, 3, 4]; deepEqual(_.flatten(array, true), expected); deepEqual(_.flattenDeep(array), expected); }); test('should return an empty array for non array-like objects', 3, function() { var expected = []; deepEqual(_.flatten({ 'a': 1 }), expected); deepEqual(_.flatten({ 'a': 1 }, true), expected); deepEqual(_.flattenDeep({ 'a': 1 }), expected); }); test('should return a wrapped value when chaining', 6, function() { if (!isNpm) { var wrapped = _([1, [2], [3, [4]]]), actual = wrapped.flatten(), expected = [1, 2, 3, [4]]; ok(actual instanceof _); deepEqual(actual.value(), expected); expected = [1, 2, 3, 4]; actual = wrapped.flatten(true); ok(actual instanceof _); deepEqual(actual.value(), expected); actual = wrapped.flattenDeep(); ok(actual instanceof _); deepEqual(actual.value(), expected); } else { skipTest(6); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.forEach'); (function() { test('should be aliased', 1, function() { strictEqual(_.each, _.forEach); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.forEachRight'); (function() { test('should be aliased', 1, function() { strictEqual(_.eachRight, _.forEachRight); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('forIn methods'); _.each(['forIn', 'forInRight'], function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` iterates over inherited properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var keys = []; func(new Foo, function(value, key) { keys.push(key); }); deepEqual(keys.sort(), ['a', 'b']); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('forOwn methods'); _.each(['forOwn', 'forOwnRight'], function(methodName) { var func = _[methodName]; test('iterates over the `length` property', 1, function() { var object = { '0': 'zero', '1': 'one', 'length': 2 }, props = []; func(object, function(value, prop) { props.push(prop); }); deepEqual(props.sort(), ['0', '1', 'length']); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('iteration methods'); (function() { var methods = [ '_baseEach', 'countBy', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'groupBy', 'indexBy', 'map', 'mapValues', 'max', 'min', 'omit', 'partition', 'pick', 'reject', 'some' ]; var arrayMethods = [ 'findIndex', 'findLastIndex' ]; var collectionMethods = [ '_baseEach', 'countBy', 'every', 'filter', 'find', 'findLast', 'forEach', 'forEachRight', 'groupBy', 'indexBy', 'map', 'max', 'min', 'partition', 'reduce', 'reduceRight', 'reject', 'some' ]; var forInMethods = [ 'forIn', 'forInRight', 'omit', 'pick' ]; var iterationMethods = [ '_baseEach', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight' ] var objectMethods = [ 'findKey', 'findLastKey', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'mapValues', 'omit', 'pick' ]; var rightMethods = [ 'findLast', 'findLastIndex', 'findLastKey', 'forEachRight', 'forInRight', 'forOwnRight' ]; var unwrappedMethods = [ 'every', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'max', 'min', 'some' ]; _.each(methods, function(methodName) { var array = [1, 2, 3], func = _[methodName], isFind = /^find/.test(methodName), isSome = methodName == 'some'; test('`_.' + methodName + '` should provide the correct `iteratee` arguments', 1, function() { if (func) { var args, expected = [1, 0, array]; func(array, function() { args || (args = slice.call(arguments)); }); if (_.includes(rightMethods, methodName)) { expected[0] = 3; expected[1] = 2; } if (_.includes(objectMethods, methodName)) { expected[1] += ''; } deepEqual(args, expected); } else { skipTest(); } }); test('`_.' + methodName + '` should support the `thisArg` argument', 2, function() { if (methodName != '_baseEach') { var actual, callback = function(num, index) { actual = this[index]; }; func([1], callback, [2]); strictEqual(actual, 2); func({ 'a': 1 }, callback, { 'a': 2 }); strictEqual(actual, 2); } else { skipTest(2); } }); test('`_.' + methodName + '` should treat sparse arrays as dense', 1, function() { if (func) { var array = [1]; array[2] = 3; var expected = [[1, 0, array], [undefined, 1, array], [3, 2, array]]; if (_.includes(objectMethods, methodName)) { expected = _.map(expected, function(args) { args[1] += ''; return args; }); } if (_.includes(rightMethods, methodName)) { expected.reverse(); } var argsList = []; func(array, function() { argsList.push(slice.call(arguments)); return !(isFind || isSome); }); deepEqual(argsList, expected); } else { skipTest(); } }); }); _.each(_.difference(methods, objectMethods), function(methodName) { var array = [1, 2, 3], func = _[methodName], isEvery = methodName == 'every'; array.a = 1; test('`_.' + methodName + '` should not iterate custom properties on arrays', 1, function() { if (func) { var keys = []; func(array, function(value, key) { keys.push(key); return isEvery; }); ok(!_.includes(keys, 'a')); } else { skipTest(); } }); }); _.each(_.difference(methods, unwrappedMethods), function(methodName) { var array = [1, 2, 3], func = _[methodName], isBaseEach = methodName == '_baseEach'; test('`_.' + methodName + '` should return a wrapped value when implicitly chaining', 1, function() { if (!(isBaseEach || isNpm)) { var wrapped = _(array)[methodName](_.noop); ok(wrapped instanceof _); } else { skipTest(); } }); }); _.each(unwrappedMethods, function(methodName) { var array = [1, 2, 3], func = _[methodName]; test('`_.' + methodName + '` should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { var wrapped = _(array)[methodName](_.noop); ok(!(wrapped instanceof _)); } else { skipTest(); } }); test('`_.' + methodName + '` should return a wrapped value when implicitly chaining', 1, function() { if (!isNpm) { var wrapped = _(array).chain()[methodName](_.noop); ok(wrapped instanceof _); } else { skipTest(); } }); }); _.each(_.difference(methods, arrayMethods, forInMethods), function(methodName) { var array = [1, 2, 3], func = _[methodName]; test('`_.' + methodName + '` iterates over own properties of objects', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; if (func) { var keys = []; func(new Foo, function(value, key) { keys.push(key); }); deepEqual(keys, ['a']); } else { skipTest(); } }); }); _.each(iterationMethods, function(methodName) { var array = [1, 2, 3], func = _[methodName], isBaseEach = methodName == '_baseEach', isObject = _.includes(objectMethods, methodName), isRight = _.includes(rightMethods, methodName); test('`_.' + methodName + '` should return the collection', 1, function() { if (func) { strictEqual(func(array, Boolean), array); } else { skipTest(); } }); test('`_.' + methodName + '` should not return the existing wrapped value when chaining', 1, function() { if (!(isBaseEach || isNpm)) { var wrapped = _(array); notStrictEqual(wrapped[methodName](_.noop), wrapped); } else { skipTest(); } }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('`_.' + methodName + '` should work with a string ' + key + ' for `collection` (test in IE < 9)', 6, function() { if (func) { var args, values = [], expectedChars = ['a', 'b', 'c']; var expectedArgs = isObject ? (isRight ? ['c', '2', collection] : ['a', '0', collection]) : (isRight ? ['c', 2, collection] : ['a', 0, collection]); var actual = func(collection, function(value) { args || (args = slice.call(arguments)); values.push(value); }); var stringObject = args[2]; ok(_.isString(stringObject)); ok(_.isObject(stringObject)); deepEqual([stringObject[0], stringObject[1], stringObject[2]], expectedChars); deepEqual(args, expectedArgs); deepEqual(values, isRight ? ['c', 'b', 'a'] : expectedChars); strictEqual(actual, collection); } else { skipTest(6); } }); }); }); _.each(collectionMethods, function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` should use `isLength` to determine whether a value is array-like', 2, function() { if (func) { var isIteratedAsObject = function(length) { var result = false; func({ 'length': length }, function() { result = true; }, 0); return result; }; var values = [-1, '1', 1.1, Object(1), MAX_SAFE_INTEGER + 1], expected = _.map(values, _.constant(true)), actual = _.map(values, isIteratedAsObject); deepEqual(actual, expected); ok(!isIteratedAsObject(0)); } else { skipTest(2); } }); }); _.each(methods, function(methodName) { var array = [1, 2, 3], func = _[methodName], isFind = /^find/.test(methodName), isSome = methodName == 'some'; test('`_.' + methodName + '` should ignore changes to `array.length`', 1, function() { if (func) { var count = 0, array = [1]; func(array, function() { if (++count == 1) { array.push(2); } return !(isFind || isSome); }, array); strictEqual(count, 1); } else { skipTest(); } }); }); _.each(_.difference(_.union(methods, collectionMethods), arrayMethods), function(methodName) { var func = _[methodName], isFind = /^find/.test(methodName), isSome = methodName == 'some'; test('`_.' + methodName + '` should ignore added `object` properties', 1, function() { if (func) { var count = 0, object = { 'a': 1 }; func(object, function() { if (++count == 1) { object.b = 2; } return !(isFind || isSome); }, object); strictEqual(count, 1); } else { skipTest(); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('collection iteration bugs'); _.each(['forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight'], function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 1, function() { var props = []; func(shadowObject, function(value, prop) { props.push(prop); }); deepEqual(props.sort(), shadowProps); }); test('`_.' + methodName + '` skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', 2, function() { function Foo() {} Foo.prototype.a = 1; var props = []; function callback(value, prop) { props.push(prop); } func(Foo, callback); deepEqual(props, []); props.length = 0; Foo.prototype = { 'a': 1 }; func(Foo, callback); deepEqual(props, []); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('object assignments'); _.each(['assign', 'defaults', 'merge'], function(methodName) { var func = _[methodName], isDefaults = methodName == 'defaults'; test('`_.' + methodName + '` should pass thru falsey `object` values', 1, function() { var actual = _.map(falsey, function(value, index) { return index ? func(value) : func(); }); deepEqual(actual, falsey); }); test('`_.' + methodName + '` should assign own source properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; deepEqual(func({}, new Foo), { 'a': 1 }); }); test('`_.' + methodName + '` should assign problem JScript properties (test in IE < 9)', 1, function() { var object = { 'constructor': '0', 'hasOwnProperty': '1', 'isPrototypeOf': '2', 'propertyIsEnumerable': undefined, 'toLocaleString': undefined, 'toString': undefined, 'valueOf': undefined }; var source = { 'propertyIsEnumerable': '3', 'toLocaleString': '4', 'toString': '5', 'valueOf': '6' }; deepEqual(func(object, source), shadowObject); }); test('`_.' + methodName + '` skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', 2, function() { function Foo() {} Foo.a = 1; Foo.prototype.b = 2; var expected = { 'a': 1 }; deepEqual(func({}, Foo), expected); Foo.prototype = { 'b': 2 }; deepEqual(func({}, Foo), expected); }); test('`_.' + methodName + '` should not error on nullish sources (test in IE < 9)', 1, function() { try { deepEqual(func({ 'a': 1 }, undefined, { 'b': 2 }, null), { 'a': 1, 'b': 2 }); } catch(e) { ok(false, e.message); } }); test('`_.' + methodName + '` should not error when `object` is nullish and source objects are provided', 1, function() { var expected = _.times(2, _.constant(true)); var actual = _.map([null, undefined], function(value) { try { return _.isEqual(func(value, { 'a': 1 }), value); } catch(e) { return false; } }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should work as an iteratee for `_.reduce`', 1, function() { var array = [{ 'a': 1 }, { 'b': 2 }, { 'c': 3 }], expected = { 'a': 1, 'b': 2, 'c': 3 }; expected.a = isDefaults ? 0 : 1; deepEqual(_.reduce(array, func, { 'a': 0 }), expected); }); test('`_.' + methodName + '` should not return the existing wrapped value when chaining', 1, function() { if (!isNpm) { var wrapped = _({ 'a': 1 }); notStrictEqual(wrapped[methodName]({ 'b': 2 }), wrapped); } else { skipTest(); } }); }); _.each(['assign', 'merge'], function(methodName) { var func = _[methodName], isMerge = methodName == 'merge'; test('`_.' + methodName + '` should provide the correct `customizer` arguments', 3, function() { var args, object = { 'a': 1 }, source = { 'a': 2 }; func(object, source, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 2, 'a', object, source], 'primitive property values'); args = null; object = { 'a': 1 }; source = { 'b': 2 }; func(object, source, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [undefined, 2, 'b', object, source], 'missing destination property'); var argsList = [], objectValue = [1, 2], sourceValue = { 'b': 2 }; object = { 'a': objectValue }; source = { 'a': sourceValue }; func(object, source, function() { argsList.push(slice.call(arguments)); }); var expected = [[objectValue, sourceValue, 'a', object, source]]; if (isMerge) { expected.push([undefined, 2, 'b', sourceValue, sourceValue]); } deepEqual(argsList, expected, 'non-primitive property values'); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func({}, { 'a': 0 }, function(a, b) { return this[b]; }, [2]); deepEqual(actual, { 'a': 2 }); }); test('`_.' + methodName + '` should not treat `object` as `source`', 1, function() { function Foo() {} Foo.prototype.a = 1; var actual = func(new Foo, { 'b': 2 }); ok(!_.has(actual, 'a')); }); test('`_.' + methodName + '` should not treat the second argument as a `customizer` callback', 2, function() { function callback() {} callback.b = 2; var actual = func({ 'a': 1 }, callback); deepEqual(actual, { 'a': 1, 'b': 2 }); actual = func({ 'a': 1 }, callback, { 'c': 3 }); deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 }); }); test('`_.' + methodName + '` should not assign the `customizer` result if it is the same as the destination value', 4, function() { _.each(['a', ['a'], { 'a': 1 }, NaN], function(value) { if (defineProperty) { var object = {}, pass = true; defineProperty(object, 'a', { 'get': _.constant(value), 'set': function() { pass = false; } }); func(object, { 'a': value }, _.identity); ok(pass); } else { skipTest(); } }); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('exit early'); _.each(['_baseEach', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'transform'], function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` can exit early when iterating arrays', 1, function() { if (func) { var array = [1, 2, 3], values = []; func(array, function(value, other) { values.push(_.isArray(value) ? other : value); return false; }); deepEqual(values, [_.endsWith(methodName, 'Right') ? 3 : 1]); } else { skipTest(); } }); test('`_.' + methodName + '` can exit early when iterating objects', 1, function() { if (func) { var object = { 'a': 1, 'b': 2, 'c': 3 }, values = []; func(object, function(value, other) { values.push(_.isArray(value) ? other : value); return false; }); strictEqual(values.length, 1); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('`__proto__` property bugs'); (function() { test('internal data objects should work with the `__proto__` key', 4, function() { var stringLiteral = '__proto__', stringObject = Object(stringLiteral), expected = [stringLiteral, stringObject]; var largeArray = _.times(LARGE_ARRAY_SIZE, function(count) { return count % 2 ? stringObject : stringLiteral; }); deepEqual(_.difference(largeArray, largeArray), []); deepEqual(_.intersection(largeArray, largeArray), expected); deepEqual(_.uniq(largeArray), expected); deepEqual(_.without.apply(_, [largeArray].concat(largeArray)), []); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.functions'); (function() { test('should return the function names of an object', 1, function() { var object = { 'a': 'a', 'b': _.identity, 'c': /x/, 'd': _.each }; deepEqual(_.functions(object).sort(), ['b', 'd']); }); test('should include inherited functions', 1, function() { function Foo() { this.a = _.identity; this.b = 'b'; } Foo.prototype.c = _.noop; deepEqual(_.functions(new Foo).sort(), ['a', 'c']); }); test('should be aliased', 1, function() { strictEqual(_.methods, _.functions); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.groupBy'); (function() { var array = [4.2, 6.1, 6.4]; test('should use `_.identity` when `iteratee` is nullish', 1, function() { var array = [4, 6, 6], values = [, null, undefined], expected = _.map(values, _.constant({ '4': [4], '6': [6, 6] })); var actual = _.map(values, function(value, index) { return index ? _.groupBy(array, value) : _.groupBy(array); }); deepEqual(actual, expected); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.groupBy(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [4.2, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.groupBy(array, function(num) { return this.floor(num); }, Math); deepEqual(actual, { '4': [4.2], '6': [6.1, 6.4] }); }); test('should only add values to own, not inherited, properties', 2, function() { var actual = _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); deepEqual(actual.constructor, [4.2]); deepEqual(actual.hasOwnProperty, [6.1, 6.4]); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.groupBy(['one', 'two', 'three'], 'length'); deepEqual(actual, { '3': ['one', 'two'], '5': ['three'] }); }); test('should work with a number for `iteratee`', 2, function() { var array = [ [1, 'a'], [2, 'a'], [2, 'b'] ]; deepEqual(_.groupBy(array, 0), { '1': [[1, 'a']], '2': [[2, 'a'], [2, 'b']] }); deepEqual(_.groupBy(array, 1), { 'a': [[1, 'a'], [2, 'a']], 'b': [[2, 'b']] }); }); test('should work with an object for `collection`', 1, function() { var actual = _.groupBy({ 'a': 4.2, 'b': 6.1, 'c': 6.4 }, function(num) { return Math.floor(num); }); deepEqual(actual, { '4': [4.2], '6': [6.1, 6.4] }); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 1, 3], iteratee = function(value) { value.push(value[0]); return value; }, predicate = function(value) { return value[0] > 1; }, actual = _(array).groupBy(_.identity).map(iteratee).filter(predicate).take().value(); deepEqual(actual, [[2, 2]]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.has'); (function() { test('should check for own properties', 2, function() { var object = { 'a': 1 }; strictEqual(_.has(object, 'a'), true); strictEqual(_.has(object, 'b'), false); }); test('should not use the `hasOwnProperty` method of the object', 1, function() { var object = { 'hasOwnProperty': null, 'a': 1 }; strictEqual(_.has(object, 'a'), true); }); test('should not check for inherited properties', 1, function() { function Foo() {} Foo.prototype.a = 1; strictEqual(_.has(new Foo, 'a'), false); }); test('should work with functions', 1, function() { function Foo() {} strictEqual(_.has(Foo, 'prototype'), true); }); test('should return `false` for primitives', 1, function() { var values = falsey.concat(true, 1, 'a'), expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.has(value, 'valueOf'); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.identity'); (function() { test('should return the first argument provided', 1, function() { var object = { 'name': 'fred' }; strictEqual(_.identity(object), object); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.includes'); (function() { _.each({ 'an `arguments` object': arguments, 'an array': [1, 2, 3, 4], 'an object': { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, 'a string': '1234' }, function(collection, key) { var values = _.toArray(collection); test('should work with ' + key + ' and return `true` for matched values', 1, function() { strictEqual(_.includes(collection, 3), true); }); test('should work with ' + key + ' and return `false` for unmatched values', 1, function() { strictEqual(_.includes(collection, 5), false); }); test('should work with ' + key + ' and a positive `fromIndex`', 2, function() { strictEqual(_.includes(collection, values[2], 2), true); strictEqual(_.includes(collection, values[1], 2), false); }); test('should work with ' + key + ' and a `fromIndex` >= `collection.length`', 12, function() { _.each([4, 6, Math.pow(2, 32), Infinity], function(fromIndex) { strictEqual(_.includes(collection, 1, fromIndex), false); strictEqual(_.includes(collection, undefined, fromIndex), false); strictEqual(_.includes(collection, '', fromIndex), false); }); }); test('should work with ' + key + ' and treat falsey `fromIndex` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(true)); var actual = _.map(falsey, function(fromIndex) { return _.includes(collection, values[0], fromIndex); }); deepEqual(actual, expected); }); test('should work with ' + key + ' and treat non-number `fromIndex` values as `0`', 1, function() { strictEqual(_.includes(collection, values[0], '1'), true); }); test('should work with ' + key + ' and a negative `fromIndex`', 2, function() { strictEqual(_.includes(collection, values[2], -2), true); strictEqual(_.includes(collection, values[1], -2), false); }); test('should work with ' + key + ' and a negative `fromIndex` <= negative `collection.length`', 3, function() { _.each([-4, -6, -Infinity], function(fromIndex) { strictEqual(_.includes(collection, values[0], fromIndex), true); }); }); test('should work with ' + key + ' and return an unwrapped value implicitly when chaining', 1, function() { if (!isNpm) { strictEqual(_(collection).includes(3), true); } else { skipTest(); } }); test('should work with ' + key + ' and return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(collection).chain().includes(3) instanceof _); } else { skipTest(); } }); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 2, function() { strictEqual(_.includes(collection, 'bc'), true); strictEqual(_.includes(collection, 'd'), false); }); }); test('should return `false` for empty collections', 1, function() { var expected = _.map(empties, _.constant(false)); var actual = _.map(empties, function(value) { try { return _.includes(value); } catch(e) {} }); deepEqual(actual, expected); }); test('should not be possible to perform a binary search', 1, function() { strictEqual(_.includes([3, 2, 1], 3, true), true); }); test('should match `NaN`', 1, function() { strictEqual(_.includes([1, NaN, 3], NaN), true); }); test('should match `-0` as `0`', 1, function() { strictEqual(_.includes([-0], 0), true); }); test('should be aliased', 2, function() { strictEqual(_.contains, _.includes); strictEqual(_.include, _.includes); }); }(1, 2, 3, 4)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.indexBy'); (function() { test('should use `_.identity` when `iteratee` is nullish', 1, function() { var array = [4, 6, 6], values = [, null, undefined], expected = _.map(values, _.constant({ '4': 4, '6': 6 })); var actual = _.map(values, function(value, index) { return index ? _.indexBy(array, value) : _.indexBy(array); }); deepEqual(actual, expected); }); test('should support the `thisArg` argument', 1, function() { var actual = _.indexBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); deepEqual(actual, { '4': 4.2, '6': 6.4 }); }); test('should only add values to own, not inherited, properties', 2, function() { var actual = _.indexBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); deepEqual(actual.constructor, 4.2); deepEqual(actual.hasOwnProperty, 6.4); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.indexBy(['one', 'two', 'three'], 'length'); deepEqual(actual, { '3': 'two', '5': 'three' }); }); test('should work with a number for `iteratee`', 2, function() { var array = [ [1, 'a'], [2, 'a'], [2, 'b'] ]; deepEqual(_.indexBy(array, 0), { '1': [1, 'a'], '2': [2, 'b'] }); deepEqual(_.indexBy(array, 1), { 'a': [2, 'a'], 'b': [2, 'b'] }); }); test('should work with an object for `collection`', 1, function() { var actual = _.indexBy({ 'a': 4.2, 'b': 6.1, 'c': 6.4 }, function(num) { return Math.floor(num); }); deepEqual(actual, { '4': 4.2, '6': 6.4 }); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 1, 3], predicate = function(value) { return value > 2; }, actual = _(array).indexBy(_.identity).map(square).filter(predicate).take().value(); deepEqual(actual, [4]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.indexOf'); (function() { var array = [1, 2, 3, 1, 2, 3]; test('should return the index of the first matched value', 1, function() { strictEqual(_.indexOf(array, 3), 2); }); test('should work with a positive `fromIndex`', 1, function() { strictEqual(_.indexOf(array, 1, 2), 3); }); test('should work with `fromIndex` >= `array.length`', 1, function() { var values = [6, 8, Math.pow(2, 32), Infinity], expected = _.map(values, _.constant([-1, -1, -1])); var actual = _.map(values, function(fromIndex) { return [ _.indexOf(array, undefined, fromIndex), _.indexOf(array, 1, fromIndex), _.indexOf(array, '', fromIndex) ]; }); deepEqual(actual, expected); }); test('should treat falsey `fromIndex` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(0)); var actual = _.map(falsey, function(fromIndex) { return _.indexOf(array, 1, fromIndex); }); deepEqual(actual, expected); }); test('should perform a binary search when `fromIndex` is a non-number truthy value', 1, function() { var sorted = [4, 4, 5, 5, 6, 6], values = [true, '1', {}], expected = _.map(values, _.constant(2)); var actual = _.map(values, function(value) { return _.indexOf(sorted, 5, value); }); deepEqual(actual, expected); }); test('should work with a negative `fromIndex`', 1, function() { strictEqual(_.indexOf(array, 2, -3), 4); }); test('should work with a negative `fromIndex` <= `-array.length`', 1, function() { var values = [-6, -8, -Infinity], expected = _.map(values, _.constant(0)); var actual = _.map(values, function(fromIndex) { return _.indexOf(array, 1, fromIndex); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('custom `_.indexOf` methods'); (function() { function Foo() {} function custom(array, value, fromIndex) { var index = (fromIndex || 0) - 1, length = array.length; while (++index < length) { var other = array[index]; if (other === value || (value instanceof Foo && other instanceof Foo)) { return index; } } return -1; } var array = [1, new Foo, 3, new Foo], indexOf = _.indexOf; var largeArray = _.times(LARGE_ARRAY_SIZE, function() { return new Foo; }); test('`_.includes` should work with a custom `_.indexOf` method', 2, function() { if (!isModularize) { _.indexOf = custom; ok(_.includes(array, new Foo)); ok(_.includes({ 'a': 1, 'b': new Foo, 'c': 3 }, new Foo)); _.indexOf = indexOf; } else { skipTest(2); } }); test('`_.difference` should work with a custom `_.indexOf` method', 2, function() { if (!isModularize) { _.indexOf = custom; deepEqual(_.difference(array, [new Foo]), [1, 3]); deepEqual(_.difference(array, largeArray), [1, 3]); _.indexOf = indexOf; } else { skipTest(2); } }); test('`_.intersection` should work with a custom `_.indexOf` method', 2, function() { if (!isModularize) { _.indexOf = custom; deepEqual(_.intersection(array, [new Foo]), [array[1]]); deepEqual(_.intersection(largeArray, [new Foo]), [array[1]]); _.indexOf = indexOf; } else { skipTest(2); } }); test('`_.uniq` should work with a custom `_.indexOf` method', 6, function() { _.each([false, true, _.identity], function(param) { if (!isModularize) { _.indexOf = custom; deepEqual(_.uniq(array, param), array.slice(0, 3)); deepEqual(_.uniq(largeArray, param), [largeArray[0]]); _.indexOf = indexOf; } else { skipTest(2); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.initial'); (function() { var array = [1, 2, 3]; test('should accept a falsey `array` argument', 1, function() { var expected = _.map(falsey, _.constant([])); var actual = _.map(falsey, function(value, index) { try { return index ? _.initial(value) : _.initial(); } catch(e) {} }); deepEqual(actual, expected); }); test('should exclude last element', 1, function() { deepEqual(_.initial(array), [1, 2]); }); test('should return an empty when querying empty arrays', 1, function() { deepEqual(_.initial([]), []); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.initial); deepEqual(actual, [[1, 2], [4, 5], [7, 8]]); }); test('should work in a lazy chain sequence', 4, function() { if (!isNpm) { var array = [1, 2, 3], values = []; var actual = _(array).initial().filter(function(value) { values.push(value); return false; }) .value(); deepEqual(actual, []); deepEqual(values, [1, 2]); values = []; actual = _(array).filter(function(value) { values.push(value); return value < 3; }) .initial() .value(); deepEqual(actual, [1]); deepEqual(values, array); } else { skipTest(4); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.inRange'); (function() { test('should work with an `end` argument', 3, function() { strictEqual(_.inRange(3, 5), true); strictEqual(_.inRange(5, 5), false); strictEqual(_.inRange(6, 5), false); }); test('should work with `start` and `end` arguments', 4, function() { strictEqual(_.inRange(1, 1, 5), true); strictEqual(_.inRange(3, 1, 5), true); strictEqual(_.inRange(0, 1, 5), false); strictEqual(_.inRange(5, 1, 5), false); }); test('should treat falsey `start` arguments as `0`', 13, function() { _.each(falsey, function(value, index) { if (index) { strictEqual(_.inRange(0, value), false); strictEqual(_.inRange(0, value, 1), true); } else { strictEqual(_.inRange(0), false); } }); }); test('should work with a floating point `n` value', 4, function() { strictEqual(_.inRange(0.5, 5), true); strictEqual(_.inRange(1.2, 1, 5), true); strictEqual(_.inRange(5.2, 5), false); strictEqual(_.inRange(0.5, 1, 5), false); }); test('should coerce arguments to finite numbers', 1, function() { var actual = [_.inRange(0, '0', 1), _.inRange(0, '1'), _.inRange(0, 0, '1'), _.inRange(0, NaN, 1), _.inRange(-1, -1, NaN)], expected = _.map(actual, _.constant(true)); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.intersection'); (function() { var args = arguments; test('should return the intersection of the given arrays', 1, function() { var actual = _.intersection([1, 3, 2], [5, 2, 1, 4], [2, 1]); deepEqual(actual, [1, 2]); }); test('should return an array of unique values', 2, function() { var array = [1, 1, 3, 2, 2]; deepEqual(_.intersection(array, [5, 2, 2, 1, 4], [2, 1, 1]), [1, 2]); deepEqual(_.intersection(array), [1, 3, 2]); }); test('should match `NaN`', 1, function() { deepEqual(_.intersection([1, NaN, 3], [NaN, 5, NaN]), [NaN]); }); test('should work with large arrays of objects', 1, function() { var object = {}, largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object)); deepEqual(_.intersection([object], largeArray), [object]); }); test('should work with large arrays of objects', 2, function() { var object = {}, largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object)); deepEqual(_.intersection([object], largeArray), [object]); deepEqual(_.intersection(_.range(LARGE_ARRAY_SIZE), null, [1]), [1]); }); test('should work with large arrays of `NaN`', 1, function() { var largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(NaN)); deepEqual(_.intersection([1, NaN, 3], largeArray), [NaN]); }); test('should ignore values that are not arrays or `arguments` objects', 3, function() { var array = [0, 1, null, 3]; deepEqual(_.intersection(array, 3, null, { '0': 1 }), array); deepEqual(_.intersection(null, array, null, [2, 1]), [1]); deepEqual(_.intersection(array, null, args, null), [1, 3]); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var wrapped = _([1, 3, 2]).intersection([5, 2, 1, 4]); ok(wrapped instanceof _); deepEqual(wrapped.value(), [1, 2]); } else { skipTest(2); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.invert'); (function() { test('should invert an object', 2, function() { var object = { 'a': 1, 'b': 2 }, actual = _.invert(object); deepEqual(actual, { '1': 'a', '2': 'b' }); deepEqual(_.invert(actual), { 'a': '1', 'b': '2' }); }); test('should work with an object that has a `length` property', 1, function() { var object = { '0': 'a', '1': 'b', 'length': 2 }; deepEqual(_.invert(object), { 'a': '0', 'b': '1', '2': 'length' }); }); test('should accept a `multiValue` flag', 1, function() { var object = { 'a': 1, 'b': 2, 'c': 1 }; deepEqual(_.invert(object, true), { '1': ['a', 'c'], '2': ['b'] }); }); test('should only add multiple values to own, not inherited, properties', 2, function() { var object = { 'a': 'hasOwnProperty', 'b': 'constructor' }; deepEqual(_.invert(object), { 'hasOwnProperty': 'a', 'constructor': 'b' }); ok(_.isEqual(_.invert(object, true), { 'hasOwnProperty': ['a'], 'constructor': ['b'] })); }); test('should work as an iteratee for `_.map`', 2, function() { var regular = { 'a': 1, 'b': 2, 'c': 1 }, inverted = { '1': 'c', '2': 'b' }; var array = [regular, regular, regular], object = { 'a': regular, 'b': regular, 'c': regular }, expected = _.map(array, _.constant(inverted)); _.each([array, object], function(collection) { var actual = _.map(collection, _.invert); deepEqual(actual, expected); }); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var object = { 'a': 1, 'b': 2 }, wrapped = _(object).invert(); ok(wrapped instanceof _); deepEqual(wrapped.value(), { '1': 'a', '2': 'b' }); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.invoke'); (function() { test('should invoke a methods on each element of a collection', 1, function() { var array = ['a', 'b', 'c']; deepEqual(_.invoke(array, 'toUpperCase'), ['A', 'B', 'C']); }); test('should support invoking with arguments', 1, function() { var array = [function() { return slice.call(arguments); }], actual = _.invoke(array, 'call', null, 'a', 'b', 'c'); deepEqual(actual, [['a', 'b', 'c']]); }); test('should work with a function `methodName` argument', 1, function() { var array = ['a', 'b', 'c']; var actual = _.invoke(array, function(left, right) { return left + this.toUpperCase() + right; }, '(', ')'); deepEqual(actual, ['(A)', '(B)', '(C)']); }); test('should work with an object for `collection`', 1, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }; deepEqual(_.invoke(object, 'toFixed', 1), ['1.0', '2.0', '3.0']); }); test('should treat number values for `collection` as empty', 1, function() { deepEqual(_.invoke(1), []); }); test('should not error on nullish elements', 1, function() { var array = ['a', null, undefined, 'd']; try { var actual = _.invoke(array, 'toUpperCase'); } catch(e) {} deepEqual(_.invoke(array, 'toUpperCase'), ['A', undefined, undefined, 'D']); }); test('should not error on elements with missing properties', 1, function() { var objects = _.map(falsey.concat(_.constant(1)), function(value) { return { 'a': value }; }); var expected = _.times(objects.length - 1, _.constant(undefined)).concat(1); try { var actual = _.invoke(objects, 'a'); } catch(e) {} deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isArguments'); (function() { var args = arguments; test('should return `true` for `arguments` objects', 1, function() { strictEqual(_.isArguments(args), true); }); test('should return `false` for non `arguments` objects', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isArguments(value) : _.isArguments(); }); deepEqual(actual, expected); strictEqual(_.isArguments([1, 2, 3]), false); strictEqual(_.isArguments(true), false); strictEqual(_.isArguments(new Date), false); strictEqual(_.isArguments(new Error), false); strictEqual(_.isArguments(_), false); strictEqual(_.isArguments(slice), false); strictEqual(_.isArguments({ '0': 1, 'callee': _.noop, 'length': 1 }), false); strictEqual(_.isArguments(1), false); strictEqual(_.isArguments(NaN), false); strictEqual(_.isArguments(/x/), false); strictEqual(_.isArguments('a'), false); }); test('should work with an `arguments` object from another realm', 1, function() { if (_._object) { strictEqual(_.isArguments(_._arguments), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isArray'); (function() { var args = arguments; test('should return `true` for arrays', 1, function() { strictEqual(_.isArray([1, 2, 3]), true); }); test('should return `false` for non-arrays', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isArray(value) : _.isArray(); }); deepEqual(actual, expected); strictEqual(_.isArray(args), false); strictEqual(_.isArray(true), false); strictEqual(_.isArray(new Date), false); strictEqual(_.isArray(new Error), false); strictEqual(_.isArray(_), false); strictEqual(_.isArray(slice), false); strictEqual(_.isArray({ '0': 1, 'length': 1 }), false); strictEqual(_.isArray(1), false); strictEqual(_.isArray(NaN), false); strictEqual(_.isArray(/x/), false); strictEqual(_.isArray('a'), false); }); test('should work with an array from another realm', 1, function() { if (_._object) { strictEqual(_.isArray(_._array), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isBoolean'); (function() { var args = arguments; test('should return `true` for booleans', 4, function() { strictEqual(_.isBoolean(true), true); strictEqual(_.isBoolean(false), true); strictEqual(_.isBoolean(Object(true)), true); strictEqual(_.isBoolean(Object(false)), true); }); test('should return `false` for non-booleans', 12, function() { var expected = _.map(falsey, function(value) { return value === false; }); var actual = _.map(falsey, function(value, index) { return index ? _.isBoolean(value) : _.isBoolean(); }); deepEqual(actual, expected); strictEqual(_.isBoolean(args), false); strictEqual(_.isBoolean([1, 2, 3]), false); strictEqual(_.isBoolean(new Date), false); strictEqual(_.isBoolean(new Error), false); strictEqual(_.isBoolean(_), false); strictEqual(_.isBoolean(slice), false); strictEqual(_.isBoolean({ 'a': 1 }), false); strictEqual(_.isBoolean(1), false); strictEqual(_.isBoolean(NaN), false); strictEqual(_.isBoolean(/x/), false); strictEqual(_.isBoolean('a'), false); }); test('should work with a boolean from another realm', 1, function() { if (_._object) { strictEqual(_.isBoolean(_._boolean), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isDate'); (function() { var args = arguments; test('should return `true` for dates', 1, function() { strictEqual(_.isDate(new Date), true); }); test('should return `false` for non-dates', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isDate(value) : _.isDate(); }); deepEqual(actual, expected); strictEqual(_.isDate(args), false); strictEqual(_.isDate([1, 2, 3]), false); strictEqual(_.isDate(true), false); strictEqual(_.isDate(new Error), false); strictEqual(_.isDate(_), false); strictEqual(_.isDate(slice), false); strictEqual(_.isDate({ 'a': 1 }), false); strictEqual(_.isDate(1), false); strictEqual(_.isDate(NaN), false); strictEqual(_.isDate(/x/), false); strictEqual(_.isDate('a'), false); }); test('should work with a date object from another realm', 1, function() { if (_._object) { strictEqual(_.isDate(_._date), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isElement'); (function() { var args = arguments; function Element() { this.nodeType = 1; } test('should use robust check', 7, function() { var element = body || new Element; strictEqual(_.isElement(element), true); strictEqual(_.isElement({ 'nodeType': 1 }), false); strictEqual(_.isElement({ 'nodeType': Object(1) }), false); strictEqual(_.isElement({ 'nodeType': true }), false); strictEqual(_.isElement({ 'nodeType': [1] }), false); strictEqual(_.isElement({ 'nodeType': '1' }), false); strictEqual(_.isElement({ 'nodeType': '001' }), false); }); test('should use a stronger check in browsers', 2, function() { var expected = !_.support.dom; strictEqual(_.isElement(new Element), expected); if (lodashBizarro) { expected = !lodashBizarro.support.dom; strictEqual(lodashBizarro.isElement(new Element), expected); } else { skipTest(); } }); test('should return `false` for non DOM elements', 13, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isElement(value) : _.isElement(); }); deepEqual(actual, expected); strictEqual(_.isElement(args), false); strictEqual(_.isElement([1, 2, 3]), false); strictEqual(_.isElement(true), false); strictEqual(_.isElement(new Date), false); strictEqual(_.isElement(new Error), false); strictEqual(_.isElement(_), false); strictEqual(_.isElement(slice), false); strictEqual(_.isElement({ 'a': 1 }), false); strictEqual(_.isElement(1), false); strictEqual(_.isElement(NaN), false); strictEqual(_.isElement(/x/), false); strictEqual(_.isElement('a'), false); }); test('should work with a DOM element from another realm', 1, function() { if (_._element) { strictEqual(_.isElement(_._element), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isEmpty'); (function() { var args = arguments; test('should return `true` for empty values', 7, function() { var expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { return _.isEmpty(value); }); deepEqual(actual, expected); strictEqual(_.isEmpty(true), true); strictEqual(_.isEmpty(slice), true); strictEqual(_.isEmpty(1), true); strictEqual(_.isEmpty(NaN), true); strictEqual(_.isEmpty(/x/), true); strictEqual(_.isEmpty(), true); }); test('should return `false` for non-empty values', 3, function() { strictEqual(_.isEmpty([0]), false); strictEqual(_.isEmpty({ 'a': 0 }), false); strictEqual(_.isEmpty('a'), false); }); test('should work with an object that has a `length` property', 1, function() { strictEqual(_.isEmpty({ 'length': 0 }), false); }); test('should work with `arguments` objects (test in IE < 9)', 1, function() { strictEqual(_.isEmpty(args), false); }); test('should work with jQuery/MooTools DOM query collections', 1, function() { function Foo(elements) { push.apply(this, elements); } Foo.prototype = { 'length': 0, 'splice': arrayProto.splice }; strictEqual(_.isEmpty(new Foo([])), true); }); test('should not treat objects with negative lengths as array-like', 1, function() { function Foo() {} Foo.prototype.length = -1; strictEqual(_.isEmpty(new Foo), true); }); test('should not treat objects with lengths larger than `MAX_SAFE_INTEGER` as array-like', 1, function() { function Foo() {} Foo.prototype.length = MAX_SAFE_INTEGER + 1; strictEqual(_.isEmpty(new Foo), true); }); test('should not treat objects with non-number lengths as array-like', 1, function() { strictEqual(_.isEmpty({ 'length': '0' }), false); }); test('fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 1, function() { strictEqual(_.isEmpty(shadowObject), false); }); test('skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', 2, function() { function Foo() {} Foo.prototype.a = 1; strictEqual(_.isEmpty(Foo), true); Foo.prototype = { 'a': 1 }; strictEqual(_.isEmpty(Foo), true); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_({}).isEmpty(), true); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_({}).chain().isEmpty() instanceof _); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isEqual'); (function() { test('should perform comparisons between primitive values', 1, function() { var pairs = [ [1, 1, true], [1, Object(1), true], [1, '1', false], [1, 2, false], [-0, -0, true], [0, 0, true], [0, Object(0), true], [Object(0), Object(0), true], [-0, 0, false], [0, '0', false], [0, null, false], [NaN, NaN, true], [NaN, Object(NaN), true], [Object(NaN), Object(NaN), true], [NaN, 'a', false], [NaN, Infinity, false], ['a', 'a', true], ['a', Object('a'), true], [Object('a'), Object('a'), true], ['a', 'b', false], ['a', ['a'], false], [true, true, true], [true, Object(true), true], [Object(true), Object(true), true], [true, 1, false], [true, 'a', false], [false, false, true], [false, Object(false), true], [Object(false), Object(false), true], [false, 0, false], [false, '', false], [null, null, true], [null, undefined, false], [null, {}, false], [null, '', false], [undefined, undefined, true], [undefined, null, false], [undefined, '', false] ]; var expected = _.map(pairs, function(pair) { return pair[2]; }); var actual = _.map(pairs, function(pair) { return _.isEqual(pair[0], pair[1]); }); deepEqual(actual, expected); }); test('should perform comparisons between arrays', 6, function() { var array1 = [true, null, 1, 'a', undefined], array2 = [true, null, 1, 'a', undefined]; strictEqual(_.isEqual(array1, array2), true); array1 = [[1, 2, 3], new Date(2012, 4, 23), /x/, { 'e': 1 }]; array2 = [[1, 2, 3], new Date(2012, 4, 23), /x/, { 'e': 1 }]; strictEqual(_.isEqual(array1, array2), true); array1 = [1]; array1[2] = 3; array2 = [1]; array2[1] = undefined; array2[2] = 3; strictEqual(_.isEqual(array1, array2), true); array1 = [Object(1), false, Object('a'), /x/, new Date(2012, 4, 23), ['a', 'b', [Object('c')]], { 'a': 1 }]; array2 = [1, Object(false), 'a', /x/, new Date(2012, 4, 23), ['a', Object('b'), ['c']], { 'a': 1 }]; strictEqual(_.isEqual(array1, array2), true); array1 = [1, 2, 3]; array2 = [3, 2, 1]; strictEqual(_.isEqual(array1, array2), false); array1 = [1, 2]; array2 = [1, 2, 3]; strictEqual(_.isEqual(array1, array2), false); }); test('should treat arrays with identical values but different non-numeric properties as equal', 3, function() { var array1 = [1, 2, 3], array2 = [1, 2, 3]; array1.every = array1.filter = array1.forEach = array1.indexOf = array1.lastIndexOf = array1.map = array1.some = array1.reduce = array1.reduceRight = null; array2.concat = array2.join = array2.pop = array2.reverse = array2.shift = array2.slice = array2.sort = array2.splice = array2.unshift = null; strictEqual(_.isEqual(array1, array2), true); array1 = [1, 2, 3]; array1.a = 1; array2 = [1, 2, 3]; array2.b = 1; strictEqual(_.isEqual(array1, array2), true); array1 = /x/.exec('vwxyz'); array2 = ['x']; strictEqual(_.isEqual(array1, array2), true); }); test('should work with sparse arrays', 3, function() { var array = Array(1); strictEqual(_.isEqual(array, Array(1)), true); strictEqual(_.isEqual(array, [undefined]), true); strictEqual(_.isEqual(array, Array(2)), false); }); test('should perform comparisons between plain objects', 5, function() { var object1 = { 'a': true, 'b': null, 'c': 1, 'd': 'a', 'e': undefined }, object2 = { 'a': true, 'b': null, 'c': 1, 'd': 'a', 'e': undefined }; strictEqual(_.isEqual(object1, object2), true); object1 = { 'a': [1, 2, 3], 'b': new Date(2012, 4, 23), 'c': /x/, 'd': { 'e': 1 } }; object2 = { 'a': [1, 2, 3], 'b': new Date(2012, 4, 23), 'c': /x/, 'd': { 'e': 1 } }; strictEqual(_.isEqual(object1, object2), true); object1 = { 'a': 1, 'b': 2, 'c': 3 }; object2 = { 'a': 3, 'b': 2, 'c': 1 }; strictEqual(_.isEqual(object1, object2), false); object1 = { 'a': 1, 'b': 2, 'c': 3 }; object2 = { 'd': 1, 'e': 2, 'f': 3 }; strictEqual(_.isEqual(object1, object2), false); object1 = { 'a': 1, 'b': 2 }; object2 = { 'a': 1, 'b': 2, 'c': 3 }; strictEqual(_.isEqual(object1, object2), false); }); test('should perform comparisons of nested objects', 1, function() { var object1 = { 'a': [1, 2, 3], 'b': true, 'c': Object(1), 'd': 'a', 'e': { 'f': ['a', Object('b'), 'c'], 'g': Object(false), 'h': new Date(2012, 4, 23), 'i': _.noop, 'j': 'a' } }; var object2 = { 'a': [1, Object(2), 3], 'b': Object(true), 'c': 1, 'd': Object('a'), 'e': { 'f': ['a', 'b', 'c'], 'g': false, 'h': new Date(2012, 4, 23), 'i': _.noop, 'j': 'a' } }; strictEqual(_.isEqual(object1, object2), true); }); test('should perform comparisons between object instances', 4, function() { function Foo() { this.value = 1; } Foo.prototype.value = 1; function Bar() { this.value = 1; } Bar.prototype.value = 2; strictEqual(_.isEqual(new Foo, new Foo), true); strictEqual(_.isEqual(new Foo, new Bar), false); strictEqual(_.isEqual({ 'value': 1 }, new Foo), false); strictEqual(_.isEqual({ 'value': 2 }, new Bar), false); }); test('should perform comparisons between objects with constructor properties', 5, function() { strictEqual(_.isEqual({ 'constructor': 1 }, { 'constructor': 1 }), true); strictEqual(_.isEqual({ 'constructor': 1 }, { 'constructor': '1' }), false); strictEqual(_.isEqual({ 'constructor': [1] }, { 'constructor': [1] }), true); strictEqual(_.isEqual({ 'constructor': [1] }, { 'constructor': ['1'] }), false); strictEqual(_.isEqual({ 'constructor': Object }, {}), false); }); test('should perform comparisons between arrays with circular references', 4, function() { var array1 = [], array2 = []; array1.push(array1); array2.push(array2); strictEqual(_.isEqual(array1, array2), true); array1.push('b'); array2.push('b'); strictEqual(_.isEqual(array1, array2), true); array1.push('c'); array2.push('d'); strictEqual(_.isEqual(array1, array2), false); array1 = ['a', 'b', 'c']; array1[1] = array1; array2 = ['a', ['a', 'b', 'c'], 'c']; strictEqual(_.isEqual(array1, array2), false); }); test('should perform comparisons between objects with circular references', 4, function() { var object1 = {}, object2 = {}; object1.a = object1; object2.a = object2; strictEqual(_.isEqual(object1, object2), true); object1.b = 0; object2.b = Object(0); strictEqual(_.isEqual(object1, object2), true); object1.c = Object(1); object2.c = Object(2); strictEqual(_.isEqual(object1, object2), false); object1 = { 'a': 1, 'b': 2, 'c': 3 }; object1.b = object1; object2 = { 'a': 1, 'b': { 'a': 1, 'b': 2, 'c': 3 }, 'c': 3 }; strictEqual(_.isEqual(object1, object2), false); }); test('should perform comparisons between objects with multiple circular references', 3, function() { var array1 = [{}], array2 = [{}]; (array1[0].a = array1).push(array1); (array2[0].a = array2).push(array2); strictEqual(_.isEqual(array1, array2), true); array1[0].b = 0; array2[0].b = Object(0); strictEqual(_.isEqual(array1, array2), true); array1[0].c = Object(1); array2[0].c = Object(2); strictEqual(_.isEqual(array1, array2), false); }); test('should perform comparisons between objects with complex circular references', 1, function() { var object1 = { 'foo': { 'b': { 'c': { 'd': {} } } }, 'bar': { 'a': 2 } }; var object2 = { 'foo': { 'b': { 'c': { 'd': {} } } }, 'bar': { 'a': 2 } }; object1.foo.b.c.d = object1; object1.bar.b = object1.foo.b; object2.foo.b.c.d = object2; object2.bar.b = object2.foo.b; strictEqual(_.isEqual(object1, object2), true); }); test('should perform comparisons between objects with shared property values', 1, function() { var object1 = { 'a': [1, 2] }; var object2 = { 'a': [1, 2], 'b': [1, 2] }; object1.b = object1.a; strictEqual(_.isEqual(object1, object2), true); }); test('should work with `arguments` objects (test in IE < 9)', 2, function() { var args1 = (function() { return arguments; }(1, 2, 3)), args2 = (function() { return arguments; }(1, 2, 3)), args3 = (function() { return arguments; }(1, 2)); strictEqual(_.isEqual(args1, args2), true); strictEqual(_.isEqual(args1, args3), false); }); test('should treat `arguments` objects like `Object` objects', 4, function() { var args = (function() { return arguments; }(1, 2, 3)), object = { '0': 1, '1': 2, '2': 3 }; function Foo() {} Foo.prototype = object; strictEqual(_.isEqual(args, object), true); strictEqual(_.isEqual(object, args), true); strictEqual(_.isEqual(args, new Foo), false); strictEqual(_.isEqual(new Foo, args), false); }); test('should perform comparisons between date objects', 4, function() { strictEqual(_.isEqual(new Date(2012, 4, 23), new Date(2012, 4, 23)), true); strictEqual(_.isEqual(new Date(2012, 4, 23), new Date(2013, 3, 25)), false); strictEqual(_.isEqual(new Date(2012, 4, 23), { 'getTime': _.constant(1337756400000) }), false); strictEqual(_.isEqual(new Date('a'), new Date('a')), false); }); test('should perform comparisons between error objects', 1, function() { var pairs = _.map([ 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError' ], function(type, index, errorTypes) { var otherType = errorTypes[++index % errorTypes.length], CtorA = root[type], CtorB = root[otherType]; return [new CtorA('a'), new CtorA('a'), new CtorB('a'), new CtorB('b')]; }); var expected = _.times(pairs.length, _.constant([true, false, false])); var actual = _.map(pairs, function(pair) { return [_.isEqual(pair[0], pair[1]), _.isEqual(pair[0], pair[2]), _.isEqual(pair[2], pair[3])]; }); deepEqual(actual, expected); }); test('should perform comparisons between functions', 2, function() { function a() { return 1 + 2; } function b() { return 1 + 2; } strictEqual(_.isEqual(a, a), true); strictEqual(_.isEqual(a, b), false); }); test('should perform comparisons between regexes', 5, function() { strictEqual(_.isEqual(/x/gim, /x/gim), true); strictEqual(_.isEqual(/x/gim, /x/mgi), true); strictEqual(_.isEqual(/x/gi, /x/g), false); strictEqual(_.isEqual(/x/, /y/), false); strictEqual(_.isEqual(/x/g, { 'global': true, 'ignoreCase': false, 'multiline': false, 'source': 'x' }), false); }); test('should perform comparisons between typed arrays', 1, function() { var pairs = _.map(typedArrays, function(type, index) { var otherType = typedArrays[(index + 1) % typedArrays.length], CtorA = root[type] || function(n) { this.n = n; }, CtorB = root[otherType] || function(n) { this.n = n; }, bufferA = root[type] ? new ArrayBuffer(8) : 8, bufferB = root[otherType] ? new ArrayBuffer(8) : 8, bufferC = root[otherType] ? new ArrayBuffer(16) : 16; return [new CtorA(bufferA), new CtorA(bufferA), new CtorB(bufferB), new CtorB(bufferC)]; }); var expected = _.times(pairs.length, _.constant([true, false, false])); var actual = _.map(pairs, function(pair) { return [_.isEqual(pair[0], pair[1]), _.isEqual(pair[0], pair[2]), _.isEqual(pair[2], pair[3])]; }); deepEqual(actual, expected); }); test('should avoid common type coercions', 9, function() { strictEqual(_.isEqual(true, Object(false)), false); strictEqual(_.isEqual(Object(false), Object(0)), false); strictEqual(_.isEqual(false, Object('')), false); strictEqual(_.isEqual(Object(36), Object('36')), false); strictEqual(_.isEqual(0, ''), false); strictEqual(_.isEqual(1, true), false); strictEqual(_.isEqual(1337756400000, new Date(2012, 4, 23)), false); strictEqual(_.isEqual('36', 36), false); strictEqual(_.isEqual(36, '36'), false); }); test('fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 1, function() { strictEqual(_.isEqual(shadowObject, {}), false); }); test('should return `false` for objects with custom `toString` methods', 1, function() { var primitive, object = { 'toString': function() { return primitive; } }, values = [true, null, 1, 'a', undefined], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { primitive = value; return _.isEqual(object, value); }); deepEqual(actual, expected); }); test('should provide the correct `customizer` arguments', 1, function() { var argsList = [], object1 = { 'a': [1, 2], 'b': null }, object2 = { 'a': [1, 2], 'b': null }; object1.b = object2; object2.b = object1; var expected = [ [object1, object2], [object1.a, object2.a, 'a'], [object1.a[0], object2.a[0], 0], [object1.a[1], object2.a[1], 1], [object1.b, object2.b, 'b'], [object1.b.a, object2.b.a, 'a'], [object1.b.a[0], object2.b.a[0], 0], [object1.b.a[1], object2.b.a[1], 1], [object1.b.b, object2.b.b, 'b'] ]; _.isEqual(object1, object2, function() { argsList.push(slice.call(arguments)); }); deepEqual(argsList, expected); }); test('should correctly set the `this` binding', 1, function() { var actual = _.isEqual('a', 'b', function(a, b) { return this[a] == this[b]; }, { 'a': 1, 'b': 1 }); strictEqual(actual, true); }); test('should handle comparisons if `customizer` returns `undefined`', 1, function() { strictEqual(_.isEqual('a', 'a', _.noop), true); }); test('should return a boolean value even if `customizer` does not', 2, function() { var actual = _.isEqual('a', 'a', _.constant('a')); strictEqual(actual, true); var expected = _.map(falsey, _.constant(false)); actual = []; _.each(falsey, function(value) { actual.push(_.isEqual('a', 'b', _.constant(value))); }); deepEqual(actual, expected); }); test('should ensure `customizer` is a function', 1, function() { var array = [1, 2, 3], eq = _.partial(_.isEqual, array), actual = _.map([array, [1, 0, 3]], eq); deepEqual(actual, [true, false]); }); test('should work as an iteratee for `_.every`', 1, function() { var actual = _.every([1, 1, 1], _.partial(_.isEqual, 1)); ok(actual); }); test('should treat objects created by `Object.create(null)` like any other plain object', 2, function() { function Foo() { this.a = 1; } Foo.prototype.constructor = null; var object2 = { 'a': 1 }; strictEqual(_.isEqual(new Foo, object2), false); if (create) { var object1 = create(null); object1.a = 1; strictEqual(_.isEqual(object1, object2), true); } else { skipTest(); } }); test('should return `true` for like-objects from different documents', 4, function() { // Ensure `_._object` is assigned (unassigned in Opera 10.00). if (_._object) { strictEqual(_.isEqual({ 'a': 1, 'b': 2, 'c': 3 }, _._object), true); strictEqual(_.isEqual({ 'a': 1, 'b': 2, 'c': 2 }, _._object), false); strictEqual(_.isEqual([1, 2, 3], _._array), true); strictEqual(_.isEqual([1, 2, 2], _._array), false); } else { skipTest(4); } }); test('should not error on DOM elements', 1, function() { if (document) { var element1 = document.createElement('div'), element2 = element1.cloneNode(true); try { strictEqual(_.isEqual(element1, element2), false); } catch(e) { ok(false, e.message); } } else { skipTest(); } }); test('should perform comparisons between wrapped values', 32, function() { var stamp = +new Date; var values = [ [[1, 2], [1, 2], [1, 2, 3]], [true, true, false], [new Date(stamp), new Date(stamp), new Date(stamp - 100)], [{ 'a': 1, 'b': 2 }, { 'a': 1, 'b': 2 }, { 'a': 1, 'b': 1 }], [1, 1, 2], [NaN, NaN, Infinity], [/x/, /x/, /x/i], ['a', 'a', 'A'] ]; _.each(values, function(vals) { if (!isNpm) { var wrapped1 = _(vals[0]), wrapped2 = _(vals[1]), actual = wrapped1.isEqual(wrapped2); strictEqual(actual, true); strictEqual(_.isEqual(_(actual), _(true)), true); wrapped1 = _(vals[0]); wrapped2 = _(vals[2]); actual = wrapped1.isEqual(wrapped2); strictEqual(actual, false); strictEqual(_.isEqual(_(actual), _(false)), true); } else { skipTest(4); } }); }); test('should perform comparisons between wrapped and non-wrapped values', 4, function() { if (!isNpm) { var object1 = _({ 'a': 1, 'b': 2 }), object2 = { 'a': 1, 'b': 2 }; strictEqual(object1.isEqual(object2), true); strictEqual(_.isEqual(object1, object2), true); object1 = _({ 'a': 1, 'b': 2 }); object2 = { 'a': 1, 'b': 1 }; strictEqual(object1.isEqual(object2), false); strictEqual(_.isEqual(object1, object2), false); } else { skipTest(4); } }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_('a').isEqual('a'), true); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_('a').chain().isEqual('a') instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isError'); (function() { var args = arguments; test('should return `true` for error objects', 1, function() { var expected = _.map(errors, _.constant(true)); var actual = _.map(errors, function(error) { return _.isError(error) === true; }); deepEqual(actual, expected); }); test('should return `false` for non error objects', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isError(value) : _.isError(); }); deepEqual(actual, expected); strictEqual(_.isError(args), false); strictEqual(_.isError([1, 2, 3]), false); strictEqual(_.isError(true), false); strictEqual(_.isError(new Date), false); strictEqual(_.isError(_), false); strictEqual(_.isError(slice), false); strictEqual(_.isError({ 'a': 1 }), false); strictEqual(_.isError(1), false); strictEqual(_.isError(NaN), false); strictEqual(_.isError(/x/), false); strictEqual(_.isError('a'), false); }); test('should work with an error object from another realm', 1, function() { if (_._object) { var expected = _.map(_._errors, _.constant(true)); var actual = _.map(_._errors, function(error) { return _.isError(error) === true; }); deepEqual(actual, expected); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isFinite'); (function() { var args = arguments; test('should return `true` for finite values', 1, function() { var values = [0, 1, 3.14, -1], expected = _.map(values, _.constant(true)); var actual = _.map(values, function(value) { return _.isFinite(value); }); deepEqual(actual, expected); }); test('should return `false` for non-finite values', 9, function() { var values = [NaN, Infinity, -Infinity, Object(1)], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.isFinite(value); }); deepEqual(actual, expected); strictEqual(_.isFinite(args), false); strictEqual(_.isFinite([1, 2, 3]), false); strictEqual(_.isFinite(true), false); strictEqual(_.isFinite(new Date), false); strictEqual(_.isFinite(new Error), false); strictEqual(_.isFinite({ 'a': 1 }), false); strictEqual(_.isFinite(/x/), false); strictEqual(_.isFinite('a'), false); }); test('should return `false` for non-numeric values', 1, function() { var values = [undefined, [], true, new Date, new Error, '', ' ', '2px'], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.isFinite(value); }); deepEqual(actual, expected); }); test('should return `false` for numeric string values', 1, function() { var values = ['2', '0', '08'], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.isFinite(value); }); deepEqual(actual, expected); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isFunction'); (function() { var args = arguments; test('should return `true` for functions', 2, function() { strictEqual(_.isFunction(_), true); strictEqual(_.isFunction(slice), true); }); test('should return `true` for typed array constructors', 1, function() { var expected = _.map(typedArrays, function(type) { return objToString.call(root[type]) == funcTag; }); var actual = _.map(typedArrays, function(type) { return _.isFunction(root[type]); }); deepEqual(actual, expected); }); test('should return `false` for non-functions', 11, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isFunction(value) : _.isFunction(); }); deepEqual(actual, expected); strictEqual(_.isFunction(args), false); strictEqual(_.isFunction([1, 2, 3]), false); strictEqual(_.isFunction(true), false); strictEqual(_.isFunction(new Date), false); strictEqual(_.isFunction(new Error), false); strictEqual(_.isFunction({ 'a': 1 }), false); strictEqual(_.isFunction(1), false); strictEqual(_.isFunction(NaN), false); strictEqual(_.isFunction(/x/), false); strictEqual(_.isFunction('a'), false); }); test('should work using its fallback', 3, function() { if (!isModularize) { // Simulate native `Uint8Array` constructor with a `toStringTag` of // 'Function' and a `typeof` result of 'object'. var lodash = _.runInContext({ 'Function': { 'prototype': { 'toString': function() { return _.has(this, 'toString') ? this.toString() : fnToString.call(this); } } }, 'Object': _.assign(function(value) { return Object(value); }, { 'prototype': { 'toString': _.assign(function() { return _.has(this, '@@toStringTag') ? this['@@toStringTag'] : objToString.call(this); }, { 'toString': function() { return String(toString); } }) } }), 'Uint8Array': { '@@toStringTag': funcTag, 'toString': function() { return String(Uint8Array || Array); } } }); strictEqual(lodash.isFunction(slice), true); strictEqual(lodash.isFunction(/x/), false); strictEqual(lodash.isFunction(Uint8Array), objToString.call(Uint8Array) == funcTag); } else { skipTest(3); } }); test('should work with host objects in IE 8 document mode (test in IE 11)', 2, function() { // Trigger a Chakra JIT bug. // See https://github.com/jashkenas/underscore/issues/1621. _.each([body, xml], function(object) { if (object) { _.times(100, _.isFunction); strictEqual(_.isFunction(object), false); } else { skipTest(); } }); }); test('should work with a function from another realm', 1, function() { if (_._object) { strictEqual(_.isFunction(_._function), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isMatch'); (function() { test('should perform a deep comparison between `object` and `source`', 5, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }; strictEqual(_.isMatch(object, { 'a': 1 }), true); strictEqual(_.isMatch(object, { 'b': 1 }), false); strictEqual(_.isMatch(object, { 'a': 1, 'c': 3 }), true); strictEqual(_.isMatch(object, { 'c': 3, 'd': 4 }), false); object = { 'a': { 'b': { 'c': 1, 'd': 2 }, 'e': 3 }, 'f': 4 }; strictEqual(_.isMatch(object, { 'a': { 'b': { 'c': 1 } } }), true); }); test('should compare a variety of `source` values', 2, function() { var object1 = { 'a': false, 'b': true, 'c': '3', 'd': 4, 'e': [5], 'f': { 'g': 6 } }, object2 = { 'a': 0, 'b': 1, 'c': 3, 'd': '4', 'e': ['5'], 'f': { 'g': '6' } }; strictEqual(_.isMatch(object1, object1), true); strictEqual(_.isMatch(object1, object2), false); }); test('should return `true` when comparing an empty `source`', 1, function() { var object = { 'a': 1 }, expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { return _.isMatch(object, value); }); deepEqual(actual, expected); }); test('should return `true` when comparing a `source` of empty arrays and objects', 1, function() { var objects = [{ 'a': [1], 'b': { 'c': 1 } }, { 'a': [2, 3], 'b': { 'd': 2 } }], source = { 'a': [], 'b': {} }; var actual = _.filter(objects, function(object) { return _.isMatch(object, source); }); deepEqual(actual, objects); }); test('should not error for falsey `object` values', 1, function() { var values = falsey.slice(1), expected = _.map(values, _.constant(false)), source = { 'a': 1 }; var actual = _.map(values, function(value) { try { return _.isMatch(value, source); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `true` when comparing an empty `source` to a falsey `object`', 1, function() { var values = falsey.slice(1), expected = _.map(values, _.constant(true)), source = {}; var actual = _.map(values, function(value) { try { return _.isMatch(value, source); } catch(e) {} }); deepEqual(actual, expected); }); test('should search arrays of `source` for values', 3, function() { var objects = [{ 'a': ['b'] }, { 'a': ['c', 'd'] }], source = { 'a': ['d'] }, predicate = function(object) { return _.isMatch(object, source); }, actual = _.filter(objects, predicate); deepEqual(actual, [objects[1]]); source = { 'a': ['b', 'd'] }; actual = _.filter(objects, predicate); deepEqual(actual, []); source = { 'a': ['d', 'b'] }; actual = _.filter(objects, predicate); deepEqual(actual, []); }); test('should perform a partial comparison of all objects within arrays of `source`', 1, function() { var source = { 'a': [{ 'b': 1 }, { 'b': 4, 'c': 5 }] }; var objects = [ { 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 5, 'd': 6 }] }, { 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 6, 'd': 7 }] } ]; var actual = _.filter(objects, function(object) { return _.isMatch(object, source); }); deepEqual(actual, [objects[0]]); }); test('should handle a `source` with `undefined` values', 2, function() { var objects = [{ 'a': 1 }, { 'a': 1, 'b': 1 }, { 'a': 1, 'b': undefined }], source = { 'b': undefined }, predicate = function(object) { return _.isMatch(object, source); }, actual = _.map(objects, predicate), expected = [false, false, true]; deepEqual(actual, expected); source = { 'a': { 'c': undefined } }; objects = [{ 'a': { 'b': 1 } }, { 'a':{ 'b':1, 'c': 1 } }, { 'a': { 'b': 1, 'c': undefined } }]; actual = _.map(objects, predicate); deepEqual(actual, expected); }); test('should not match by inherited `source` properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var objects = [{ 'a': 1 }, { 'a': 1, 'b': 2 }], source = new Foo, expected = _.map(objects, _.constant(true)); var actual = _.map(objects, function(object) { return _.isMatch(object, source); }); deepEqual(actual, expected); }); test('should work with a function for `source`', 1, function() { function source() {} source.a = 1; source.b = function() {}; source.c = 3; var objects = [{ 'a': 1 }, { 'a': 1, 'b': source.b, 'c': 3 }]; var actual = _.map(objects, function(object) { return _.isMatch(object, source); }); deepEqual(actual, [false, true]); }); test('should match problem JScript properties (test in IE < 9)', 1, function() { var objects = [{}, shadowObject]; var actual = _.map(objects, function(object) { return _.isMatch(object, shadowObject); }); deepEqual(actual, [false, true]); }); test('should provide the correct `customizer` arguments', 1, function() { var argsList = [], object1 = { 'a': [1, 2], 'b': null }, object2 = { 'a': [1, 2], 'b': null }; object1.b = object2; object2.b = object1; var expected = [ [object1.a, object2.a, 'a'], [object1.a[0], object2.a[0], 0], [object1.a[1], object2.a[1], 1], [object1.b, object2.b, 'b'], [object1.b.a, object2.b.a, 'a'], [object1.b.a[0], object2.b.a[0], 0], [object1.b.a[1], object2.b.a[1], 1], [object1.b.b, object2.b.b, 'b'], [object1.b.b.a, object2.b.b.a, 'a'], [object1.b.b.a[0], object2.b.b.a[0], 0], [object1.b.b.a[1], object2.b.b.a[1], 1], [object1.b.b.b, object2.b.b.b, 'b'] ]; _.isMatch(object1, object2, function() { argsList.push(slice.call(arguments)); }); deepEqual(argsList, expected); }); test('should correctly set the `this` binding', 1, function() { var actual = _.isMatch({ 'a': 1 }, { 'a': 2 }, function(a, b) { return this[a] == this[b]; }, { 'a': 1, 'b': 1 }); strictEqual(actual, true); }); test('should handle comparisons if `customizer` returns `undefined`', 1, function() { strictEqual(_.isMatch({ 'a': 1 }, { 'a': 1 }, _.noop), true); }); test('should return a boolean value even if `customizer` does not', 2, function() { var object = { 'a': 1 }, actual = _.isMatch(object, { 'a': 1 }, _.constant('a')); strictEqual(actual, true); var expected = _.map(falsey, _.constant(false)); actual = []; _.each(falsey, function(value) { actual.push(_.isMatch(object, { 'a': 2 }, _.constant(value))); }); deepEqual(actual, expected); }); test('should ensure `customizer` is a function', 1, function() { var object = { 'a': 1 }, matches = _.partial(_.isMatch, object), actual = _.map([object, { 'a': 2 }], matches); deepEqual(actual, [true, false]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isNaN'); (function() { var args = arguments; test('should return `true` for NaNs', 2, function() { strictEqual(_.isNaN(NaN), true); strictEqual(_.isNaN(Object(NaN)), true); }); test('should return `false` for non-NaNs', 12, function() { var expected = _.map(falsey, function(value) { return value !== value; }); var actual = _.map(falsey, function(value, index) { return index ? _.isNaN(value) : _.isNaN(); }); deepEqual(actual, expected); strictEqual(_.isNaN(args), false); strictEqual(_.isNaN([1, 2, 3]), false); strictEqual(_.isNaN(true), false); strictEqual(_.isNaN(new Date), false); strictEqual(_.isNaN(new Error), false); strictEqual(_.isNaN(_), false); strictEqual(_.isNaN(slice), false); strictEqual(_.isNaN({ 'a': 1 }), false); strictEqual(_.isNaN(1), false); strictEqual(_.isNaN(/x/), false); strictEqual(_.isNaN('a'), false); }); test('should work with `NaN` from another realm', 1, function() { if (_._object) { strictEqual(_.isNaN(_._nan), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isNative'); (function() { var args = arguments; test('should return `true` for native methods', 6, function() { _.each([Array, create, root.encodeURI, slice, Uint8Array], function(func) { if (func) { strictEqual(_.isNative(func), true); } else { skipTest(); } }); if (body) { strictEqual(_.isNative(body.cloneNode), true); } else { skipTest(); } }); test('should return `false` for non-native methods', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isNative(value) : _.isNative(); }); deepEqual(actual, expected); strictEqual(_.isNative(args), false); strictEqual(_.isNative([1, 2, 3]), false); strictEqual(_.isNative(true), false); strictEqual(_.isNative(new Date), false); strictEqual(_.isNative(new Error), false); strictEqual(_.isNative(_), false); strictEqual(_.isNative({ 'a': 1 }), false); strictEqual(_.isNative(1), false); strictEqual(_.isNative(NaN), false); strictEqual(_.isNative(/x/), false); strictEqual(_.isNative('a'), false); }); test('should work with native functions from another realm', 2, function() { if (_._element) { strictEqual(_.isNative(_._element.cloneNode), true); } else { skipTest(); } if (_._object) { strictEqual(_.isNative(_._object.valueOf), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isNull'); (function() { var args = arguments; test('should return `true` for nulls', 1, function() { strictEqual(_.isNull(null), true); }); test('should return `false` for non-nulls', 13, function() { var expected = _.map(falsey, function(value) { return value === null; }); var actual = _.map(falsey, function(value, index) { return index ? _.isNull(value) : _.isNull(); }); deepEqual(actual, expected); strictEqual(_.isNull(args), false); strictEqual(_.isNull([1, 2, 3]), false); strictEqual(_.isNull(true), false); strictEqual(_.isNull(new Date), false); strictEqual(_.isNull(new Error), false); strictEqual(_.isNull(_), false); strictEqual(_.isNull(slice), false); strictEqual(_.isNull({ 'a': 1 }), false); strictEqual(_.isNull(1), false); strictEqual(_.isNull(NaN), false); strictEqual(_.isNull(/x/), false); strictEqual(_.isNull('a'), false); }); test('should work with nulls from another realm', 1, function() { if (_._object) { strictEqual(_.isNull(_._null), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isNumber'); (function() { var args = arguments; test('should return `true` for numbers', 3, function() { strictEqual(_.isNumber(0), true); strictEqual(_.isNumber(Object(0)), true); strictEqual(_.isNumber(NaN), true); }); test('should return `false` for non-numbers', 11, function() { var expected = _.map(falsey, function(value) { return typeof value == 'number'; }); var actual = _.map(falsey, function(value, index) { return index ? _.isNumber(value) : _.isNumber(); }); deepEqual(actual, expected); strictEqual(_.isNumber(args), false); strictEqual(_.isNumber([1, 2, 3]), false); strictEqual(_.isNumber(true), false); strictEqual(_.isNumber(new Date), false); strictEqual(_.isNumber(new Error), false); strictEqual(_.isNumber(_), false); strictEqual(_.isNumber(slice), false); strictEqual(_.isNumber({ 'a': 1 }), false); strictEqual(_.isNumber(/x/), false); strictEqual(_.isNumber('a'), false); }); test('should work with numbers from another realm', 1, function() { if (_._object) { strictEqual(_.isNumber(_._number), true); } else { skipTest(); } }); test('should avoid `[xpconnect wrapped native prototype]` in Firefox', 1, function() { strictEqual(_.isNumber(+"2"), true); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isObject'); (function() { var args = arguments; test('should return `true` for objects', 12, function() { strictEqual(_.isObject(args), true); strictEqual(_.isObject([1, 2, 3]), true); strictEqual(_.isObject(Object(false)), true); strictEqual(_.isObject(new Date), true); strictEqual(_.isObject(new Error), true); strictEqual(_.isObject(_), true); strictEqual(_.isObject(slice), true); strictEqual(_.isObject({ 'a': 1 }), true); strictEqual(_.isObject(Object(0)), true); strictEqual(_.isObject(/x/), true); strictEqual(_.isObject(Object('a')), true); if (document) { strictEqual(_.isObject(body), true); } else { skipTest(); } }); test('should return `false` for non-objects', 1, function() { var symbol = (Symbol || noop)(), values = falsey.concat(true, 1, 'a', symbol), expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value, index) { return index ? _.isObject(value) : _.isObject(); }); deepEqual(actual, expected); }); test('should work with objects from another realm', 8, function() { if (_._element) { strictEqual(_.isObject(_._element), true); } else { skipTest(); } if (_._object) { strictEqual(_.isObject(_._object), true); strictEqual(_.isObject(_._boolean), true); strictEqual(_.isObject(_._date), true); strictEqual(_.isObject(_._function), true); strictEqual(_.isObject(_._number), true); strictEqual(_.isObject(_._regexp), true); strictEqual(_.isObject(_._string), true); } else { skipTest(7); } }); test('should avoid V8 bug #2291 (test in Chrome 19-20)', 1, function() { // Trigger a V8 JIT bug. // See https://code.google.com/p/v8/issues/detail?id=2291. var object = {}; // 1: Useless comparison statement, this is half the trigger. object == object; // 2: Initial check with object, this is the other half of the trigger. _.isObject(object); strictEqual(_.isObject('x'), false); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isPlainObject'); (function() { var element = document && document.createElement('div'); test('should detect plain objects', 5, function() { function Foo(a) { this.a = 1; } strictEqual(_.isPlainObject({}), true); strictEqual(_.isPlainObject({ 'a': 1 }), true); strictEqual(_.isPlainObject({ 'constructor': Foo }), true); strictEqual(_.isPlainObject([1, 2, 3]), false); strictEqual(_.isPlainObject(new Foo(1)), false); }); test('should return `true` for objects with a `[[Prototype]]` of `null`', 1, function() { if (create) { strictEqual(_.isPlainObject(create(null)), true); } else { skipTest(); } }); test('should return `true` for plain objects with a custom `valueOf` property', 2, function() { strictEqual(_.isPlainObject({ 'valueOf': 0 }), true); if (element) { var valueOf = element.valueOf; element.valueOf = 0; strictEqual(_.isPlainObject(element), false); element.valueOf = valueOf; } else { skipTest(); } }); test('should return `false` for DOM elements', 1, function() { if (element) { strictEqual(_.isPlainObject(element), false); } else { skipTest(); } }); test('should return `false` for Object objects without a `toStringTag` of "Object"', 3, function() { strictEqual(_.isPlainObject(arguments), false); strictEqual(_.isPlainObject(Error), false); strictEqual(_.isPlainObject(Math), false); }); test('should return `false` for non-objects', 3, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isPlainObject(value) : _.isPlainObject(); }); deepEqual(actual, expected); strictEqual(_.isPlainObject(true), false); strictEqual(_.isPlainObject('a'), false); }); test('should work with objects from another realm', 1, function() { if (_._object) { strictEqual(_.isPlainObject(_._object), true); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isRegExp'); (function() { var args = arguments; test('should return `true` for regexes', 2, function() { strictEqual(_.isRegExp(/x/), true); strictEqual(_.isRegExp(RegExp('x')), true); }); test('should return `false` for non-regexes', 12, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isRegExp(value) : _.isRegExp(); }); deepEqual(actual, expected); strictEqual(_.isRegExp(args), false); strictEqual(_.isRegExp([1, 2, 3]), false); strictEqual(_.isRegExp(true), false); strictEqual(_.isRegExp(new Date), false); strictEqual(_.isRegExp(new Error), false); strictEqual(_.isRegExp(_), false); strictEqual(_.isRegExp(slice), false); strictEqual(_.isRegExp({ 'a': 1 }), false); strictEqual(_.isRegExp(1), false); strictEqual(_.isRegExp(NaN), false); strictEqual(_.isRegExp('a'), false); }); test('should work with regexes from another realm', 1, function() { if (_._object) { strictEqual(_.isRegExp(_._regexp), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isString'); (function() { var args = arguments; test('should return `true` for strings', 2, function() { strictEqual(_.isString('a'), true); strictEqual(_.isString(Object('a')), true); }); test('should return `false` for non-strings', 12, function() { var expected = _.map(falsey, function(value) { return value === ''; }); var actual = _.map(falsey, function(value, index) { return index ? _.isString(value) : _.isString(); }); deepEqual(actual, expected); strictEqual(_.isString(args), false); strictEqual(_.isString([1, 2, 3]), false); strictEqual(_.isString(true), false); strictEqual(_.isString(new Date), false); strictEqual(_.isString(new Error), false); strictEqual(_.isString(_), false); strictEqual(_.isString(slice), false); strictEqual(_.isString({ '0': 1, 'length': 1 }), false); strictEqual(_.isString(1), false); strictEqual(_.isString(NaN), false); strictEqual(_.isString(/x/), false); }); test('should work with strings from another realm', 1, function() { if (_._object) { strictEqual(_.isString(_._string), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isTypedArray'); (function() { var args = arguments; test('should return `true` for typed arrays', 1, function() { var expected = _.map(typedArrays, function(type) { return type in root; }); var actual = _.map(typedArrays, function(type) { var Ctor = root[type]; return Ctor ? _.isTypedArray(new Ctor(new ArrayBuffer(8))) : false; }); deepEqual(actual, expected); }); test('should return `false` for non typed arrays', 13, function() { var expected = _.map(falsey, _.constant(false)); var actual = _.map(falsey, function(value, index) { return index ? _.isTypedArray(value) : _.isTypedArray(); }); deepEqual(actual, expected); strictEqual(_.isTypedArray(args), false); strictEqual(_.isTypedArray([1, 2, 3]), false); strictEqual(_.isTypedArray(true), false); strictEqual(_.isTypedArray(new Date), false); strictEqual(_.isTypedArray(new Error), false); strictEqual(_.isTypedArray(_), false); strictEqual(_.isTypedArray(slice), false); strictEqual(_.isTypedArray({ 'a': 1 }), false); strictEqual(_.isTypedArray(1), false); strictEqual(_.isTypedArray(NaN), false); strictEqual(_.isTypedArray(/x/), false); strictEqual(_.isTypedArray('a'), false); }); test('should work with typed arrays from another realm', 1, function() { if (_._object) { var props = _.map(typedArrays, function(type) { return '_' + type.toLowerCase(); }); var expected = _.map(props, function(key) { return key in _; }); var actual = _.map(props, function(key) { var value = _[key]; return value ? _.isTypedArray(value) : false; }); deepEqual(actual, expected); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.isUndefined'); (function() { var args = arguments; test('should return `true` for `undefined` values', 2, function() { strictEqual(_.isUndefined(), true); strictEqual(_.isUndefined(undefined), true); }); test('should return `false` for non `undefined` values', 13, function() { var expected = _.map(falsey, function(value) { return value === undefined; }); var actual = _.map(falsey, function(value, index) { return index ? _.isUndefined(value) : _.isUndefined(); }); deepEqual(actual, expected); strictEqual(_.isUndefined(args), false); strictEqual(_.isUndefined([1, 2, 3]), false); strictEqual(_.isUndefined(true), false); strictEqual(_.isUndefined(new Date), false); strictEqual(_.isUndefined(new Error), false); strictEqual(_.isUndefined(_), false); strictEqual(_.isUndefined(slice), false); strictEqual(_.isUndefined({ 'a': 1 }), false); strictEqual(_.isUndefined(1), false); strictEqual(_.isUndefined(NaN), false); strictEqual(_.isUndefined(/x/), false); strictEqual(_.isUndefined('a'), false); }); test('should work with `undefined` from another realm', 1, function() { if (_._object) { strictEqual(_.isUndefined(_._undefined), true); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('isType checks'); (function() { test('should return `false` for subclassed values', 8, function() { var funcs = [ 'isArray', 'isBoolean', 'isDate', 'isError', 'isFunction', 'isNumber', 'isRegExp', 'isString' ]; _.each(funcs, function(methodName) { function Foo() {} Foo.prototype = root[methodName.slice(2)].prototype; var object = new Foo; if (objToString.call(object) == objectTag) { strictEqual(_[methodName](object), false, '`_.' + methodName + '` returns `false`'); } else { skipTest(); } }); }); test('should not error on host objects (test in IE)', 15, function() { var funcs = [ 'isArguments', 'isArray', 'isBoolean', 'isDate', 'isElement', 'isError', 'isFinite', 'isFunction', 'isNaN', 'isNull', 'isNumber', 'isObject', 'isRegExp', 'isString', 'isUndefined' ]; _.each(funcs, function(methodName) { if (xml) { var pass = true; try { _[methodName](xml); } catch(e) { pass = false; } ok(pass, '`_.' + methodName + '` should not error'); } else { skipTest(); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('keys methods'); _.each(['keys', 'keysIn'], function(methodName) { var args = arguments, func = _[methodName], isKeys = methodName == 'keys'; test('`_.' + methodName + '` should return the keys of an object', 1, function() { deepEqual(func({ 'a': 1, 'b': 1 }).sort(), ['a', 'b']); }); test('`_.' + methodName + '` should coerce primitives to objects (test in IE 9)', 2, function() { deepEqual(func('abc').sort(), ['0', '1', '2']); if (!isKeys) { // IE 9 doesn't box numbers in for-in loops. Number.prototype.a = 1; deepEqual(func(0).sort(), ['a']); delete Number.prototype.a; } else { skipTest(); } }); test('`_.' + methodName + '` should treat sparse arrays as dense', 1, function() { var array = [1]; array[2] = 3; deepEqual(func(array).sort(), ['0', '1', '2']); }); test('`_.' + methodName + '` should return an empty array for `null` or `undefined` values', 2, function() { objectProto.a = 1; _.each([null, undefined], function(value) { deepEqual(func(value), []); }); delete objectProto.a; }); test('`_.' + methodName + '` should return keys for custom properties on arrays', 1, function() { var array = [1]; array.a = 1; deepEqual(func(array).sort(), ['0', 'a']); }); test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties of arrays', 1, function() { var expected = isKeys ? ['0'] : ['0', 'a']; arrayProto.a = 1; deepEqual(func([1]).sort(), expected); delete arrayProto.a; }); test('`_.' + methodName + '` should work with `arguments` objects (test in IE < 9)', 1, function() { if (!(isPhantom || isStrict)) { deepEqual(func(args).sort(), ['0', '1', '2']); } else { skipTest(); } }); test('`_.' + methodName + '` should return keys for custom properties on `arguments` objects', 1, function() { if (!(isPhantom || isStrict)) { args.a = 1; deepEqual(func(args).sort(), ['0', '1', '2', 'a']); delete args.a; } else { skipTest(); } }); test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties of `arguments` objects', 1, function() { if (!(isPhantom || isStrict)) { var expected = isKeys ? ['0', '1', '2'] : ['0', '1', '2', 'a']; objectProto.a = 1; deepEqual(func(args).sort(), expected); delete objectProto.a; } else { skipTest(); } }); test('`_.' + methodName + '` should work with string objects (test in IE < 9)', 1, function() { deepEqual(func(Object('abc')).sort(), ['0', '1', '2']); }); test('`_.' + methodName + '` should return keys for custom properties on string objects', 1, function() { var object = Object('a'); object.a = 1; deepEqual(func(object).sort(), ['0', 'a']); }); test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties of string objects', 1, function() { var expected = isKeys ? ['0'] : ['0', 'a']; stringProto.a = 1; deepEqual(func(Object('a')).sort(), expected); delete stringProto.a; }); test('`_.' + methodName + '` fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 3, function() { function Foo() {} Foo.prototype = _.create(shadowObject); deepEqual(func(shadowObject).sort(), shadowProps); var actual = isKeys ? [] : _.without(shadowProps, 'constructor'); deepEqual(func(new Foo).sort(), actual); Foo.prototype.constructor = Foo; deepEqual(func(new Foo).sort(), actual); }); test('`_.' + methodName + '` skips non-enumerable properties (test in IE < 9)', 50, function() { _.forOwn({ 'Array': arrayProto, 'Boolean': Boolean.prototype, 'Date': Date.prototype, 'Error': errorProto, 'Function': funcProto, 'Object': objectProto, 'Number': Number.prototype, 'TypeError': TypeError.prototype, 'RegExp': RegExp.prototype, 'String': stringProto }, function(proto, key) { _.each([proto, _.create(proto)], function(object, index) { var actual = func(proto), isErr = _.endsWith(key, 'Error'), message = 'enumerable properties ' + (index ? 'inherited from' : 'on') + ' `' + key + '.prototype`', props = isErr ? ['constructor', 'toString'] : ['constructor']; actual = isErr ? _.difference(props, actual) : actual; strictEqual(_.isEmpty(actual), !isErr, 'skips non-' + message); proto.a = 1; actual = func(object); delete proto.a; strictEqual(_.includes(actual, 'a'), !(isKeys && index), 'includes ' + message); if (index) { object.constructor = 1; if (isErr) { object.toString = 2; } actual = func(object); ok(_.isEmpty(_.difference(props, actual)), 'includes properties on objects that shadow those on `' + key + '.prototype`'); } }); }); }); test('`_.' + methodName + '` skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', 2, function() { function Foo() {} Foo.a = 1; Foo.prototype.b = 2; var expected = ['a']; deepEqual(func(Foo).sort(), expected); Foo.prototype = { 'b': 2 }; deepEqual(func(Foo).sort(), expected); }); test('`_.' + methodName + '` skips the `constructor` property on prototype objects', 3, function() { function Foo() {} Foo.prototype.a = 1; var expected = ['a']; deepEqual(func(Foo.prototype), expected); Foo.prototype = { 'constructor': Foo, 'a': 1 }; deepEqual(func(Foo.prototype), expected); var Fake = { 'prototype': {} }; Fake.prototype.constructor = Fake; deepEqual(func(Fake.prototype), ['constructor']); }); test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var expected = isKeys ? ['a'] : ['a', 'b']; deepEqual(func(new Foo).sort(), expected); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.last'); (function() { var array = [1, 2, 3]; test('should return the last element', 1, function() { strictEqual(_.last(array), 3); }); test('should return `undefined` when querying empty arrays', 1, function() { var array = []; array['-1'] = 1; strictEqual(_.last([]), undefined); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.last); deepEqual(actual, [3, 6, 9]); }); test('should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { strictEqual(_(array).last(), 3); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain().last() instanceof _); } else { skipTest(); } }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [1, 2, 3, 4]; var wrapped = _(array).filter(function(value) { return value % 2; }); strictEqual(wrapped.last(), 3); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.lastIndexOf'); (function() { var array = [1, 2, 3, 1, 2, 3]; test('should return the index of the last matched value', 1, function() { strictEqual(_.lastIndexOf(array, 3), 5); }); test('should work with a positive `fromIndex`', 1, function() { strictEqual(_.lastIndexOf(array, 1, 2), 0); }); test('should work with `fromIndex` >= `array.length`', 1, function() { var values = [6, 8, Math.pow(2, 32), Infinity], expected = _.map(values, _.constant([-1, 3, -1])); var actual = _.map(values, function(fromIndex) { return [ _.lastIndexOf(array, undefined, fromIndex), _.lastIndexOf(array, 1, fromIndex), _.lastIndexOf(array, '', fromIndex) ]; }); deepEqual(actual, expected); }); test('should treat falsey `fromIndex` values, except `0` and `NaN`, as `array.length`', 1, function() { var expected = _.map(falsey, function(value) { return typeof value == 'number' ? -1 : 5; }); var actual = _.map(falsey, function(fromIndex) { return _.lastIndexOf(array, 3, fromIndex); }); deepEqual(actual, expected); }); test('should perform a binary search when `fromIndex` is a non-number truthy value', 1, function() { var sorted = [4, 4, 5, 5, 6, 6], values = [true, '1', {}], expected = _.map(values, _.constant(3)); var actual = _.map(values, function(value) { return _.lastIndexOf(sorted, 5, value); }); deepEqual(actual, expected); }); test('should work with a negative `fromIndex`', 1, function() { strictEqual(_.lastIndexOf(array, 2, -3), 1); }); test('should work with a negative `fromIndex` <= `-array.length`', 1, function() { var values = [-6, -8, -Infinity], expected = _.map(values, _.constant(0)); var actual = _.map(values, function(fromIndex) { return _.lastIndexOf(array, 1, fromIndex); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('indexOf methods'); _.each(['indexOf', 'lastIndexOf'], function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` should accept a falsey `array` argument', 1, function() { var expected = _.map(falsey, _.constant(-1)); var actual = _.map(falsey, function(value, index) { try { return index ? func(value) : func(); } catch(e) {} }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should return `-1` for an unmatched value', 4, function() { var array = [1, 2, 3], empty = []; strictEqual(func(array, 4), -1); strictEqual(func(array, 4, true), -1); strictEqual(func(empty, undefined), -1); strictEqual(func(empty, undefined, true), -1); }); test('`_.' + methodName + '` should not match values on empty arrays', 2, function() { var array = []; array[-1] = 0; strictEqual(func(array, undefined), -1); strictEqual(func(array, 0, true), -1); }); test('`_.' + methodName + '` should match `NaN`', 2, function() { strictEqual(func([1, NaN, 3], NaN), 1); strictEqual(func([1, 3, NaN], NaN, true), 2); }); test('`_.' + methodName + '` should match `-0` as `0`', 1, function() { strictEqual(func([-0], 0), 0); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.map'); (function() { var array = [1, 2, 3]; test('should map values in `collection` to a new array', 2, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }, expected = ['1', '2', '3']; deepEqual(_.map(array, String), expected); deepEqual(_.map(object, String), expected); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.map(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 2, function() { var callback = function(num, index) { return this[index] + num; }, actual = _.map([1], callback, [2]); deepEqual(actual, [3]); actual = _.map({ 'a': 1 }, callback, { 'a': 2 }); deepEqual(actual, [3]); }); test('should work with a "_.property" style `iteratee`', 1, function() { var objects = [{ 'a': 'x' }, { 'a': 'y' }]; deepEqual(_.map(objects, 'a'), ['x', 'y']); }); test('should iterate over own properties of objects', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var actual = _.map(new Foo, function(value, key) { return key; }); deepEqual(actual, ['a']); }); test('should work on an object with no `iteratee`', 1, function() { var actual = _.map({ 'a': 1, 'b': 2, 'c': 3 }); deepEqual(actual, array); }); test('should handle object arguments with non-numeric length properties', 1, function() { var value = { 'value': 'x' }, object = { 'length': { 'value': 'x' } }; deepEqual(_.map(object, _.identity), [value]); }); test('should treat a nodelist as an array-like object', 1, function() { if (document) { var actual = _.map(document.getElementsByTagName('body'), function(element) { return element.nodeName.toLowerCase(); }); deepEqual(actual, ['body']); } else { skipTest(); } }); test('should accept a falsey `collection` argument', 1, function() { var expected = _.map(falsey, _.constant([])); var actual = _.map(falsey, function(value, index) { try { return index ? _.map(value) : _.map(); } catch(e) {} }); deepEqual(actual, expected); }); test('should treat number values for `collection` as empty', 1, function() { deepEqual(_.map(1), []); }); test('should return a wrapped value when chaining', 1, function() { if (!isNpm) { ok(_(array).map(_.noop) instanceof _); } else { skipTest(); } }); test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [1, 0, [1, 4, 9]]; _(array).map(function(value, index, array) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, [1, 0, array]); args = null; _(array).map(square).map(function(value, index, array) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); args = null; _(array).map(square).map(function(value, index) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); args = null; _(array).map(square).map(function(value) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, [1]); args = null; _(array).map(square).map(function() { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); test('should be aliased', 1, function() { strictEqual(_.collect, _.map); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.mapValues'); (function() { var array = [1, 2], object = { 'a': 1, 'b': 2, 'c': 3 }; test('should map values in `object` to a new object', 1, function() { var actual = _.mapValues(object, String); deepEqual(actual, { 'a': '1', 'b': '2', 'c': '3' }); }); test('should treat arrays like objects', 1, function() { var actual = _.mapValues(array, String); deepEqual(actual, { '0': '1', '1': '2' }); }); test('should provide the correct `iteratee` arguments', 2, function() { _.each([object, array], function(value, index) { var args; _.mapValues(value, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, index ? '0' : 'a', value]); }); }); test('should support the `thisArg` argument', 2, function() { function callback(num, key) { return this[key] + num; } var actual = _.mapValues({ 'a': 1 }, callback, { 'a': 2 }); deepEqual(actual, { 'a': 3 }); actual = _.mapValues([1], callback, [2]); deepEqual(actual, { '0': 3 }); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.mapValues({ 'a': { 'b': 1 } }, 'b'); deepEqual(actual, { 'a': 1 }); }); test('should iterate over own properties of objects', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var actual = _.mapValues(new Foo, function(value, key) { return key; }); deepEqual(actual, { 'a': 'a' }); }); test('should work on an object with no `iteratee`', 2, function() { var actual = _.mapValues({ 'a': 1, 'b': 2, 'c': 3 }); deepEqual(actual, object); notStrictEqual(actual, object); }); test('should accept a falsey `object` argument', 1, function() { var expected = _.map(falsey, _.constant({})); var actual = _.map(falsey, function(value, index) { try { return index ? _.mapValues(value) : _.mapValues(); } catch(e) {} }); deepEqual(actual, expected); }); test('should return a wrapped value when chaining', 1, function() { if (!isNpm) { ok(_(object).mapValues(_.noop) instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.matches'); (function() { test('should create a function that performs a deep comparison between a given object and `source`', 6, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }, matches = _.matches({ 'a': 1 }); strictEqual(matches.length, 1); strictEqual(matches(object), true); matches = _.matches({ 'b': 1 }); strictEqual(matches(object), false); matches = _.matches({ 'a': 1, 'c': 3 }); strictEqual(matches(object), true); matches = _.matches({ 'c': 3, 'd': 4 }); strictEqual(matches(object), false); object = { 'a': { 'b': { 'c': 1, 'd': 2 }, 'e': 3 }, 'f': 4 }; matches = _.matches({ 'a': { 'b': { 'c': 1 } } }); strictEqual(matches(object), true); }); test('should compare a variety of `source` values', 2, function() { var object1 = { 'a': false, 'b': true, 'c': '3', 'd': 4, 'e': [5], 'f': { 'g': 6 } }, object2 = { 'a': 0, 'b': 1, 'c': 3, 'd': '4', 'e': ['5'], 'f': { 'g': '6' } }, matches = _.matches(object1); strictEqual(matches(object1), true); strictEqual(matches(object2), false); }); test('should not change match behavior if `source` is augmented', 9, function() { _.each([{ 'a': { 'b': 2, 'c': 3 } }, { 'a': 1, 'b': 2 }, { 'a': 1 }], function(source, index) { var object = _.cloneDeep(source), matches = _.matches(source); strictEqual(matches(object), true); if (index) { source.a = 2; source.b = 1; source.c = 3; } else { source.a.b = 1; source.a.c = 2; source.a.d = 3; } strictEqual(matches(object), true); strictEqual(matches(source), false); }); }); test('should return `true` when comparing an empty `source`', 1, function() { var object = { 'a': 1 }, expected = _.map(empties, _.constant(true)); var actual = _.map(empties, function(value) { var matches = _.matches(value); return matches(object); }); deepEqual(actual, expected); }); test('should return `true` when comparing a `source` of empty arrays and objects', 1, function() { var objects = [{ 'a': [1], 'b': { 'c': 1 } }, { 'a': [2, 3], 'b': { 'd': 2 } }], matches = _.matches({ 'a': [], 'b': {} }), actual = _.filter(objects, matches); deepEqual(actual, objects); }); test('should not error for falsey `object` values', 1, function() { var expected = _.map(falsey, _.constant(false)), matches = _.matches({ 'a': 1 }); var actual = _.map(falsey, function(value, index) { try { return index ? matches(value) : matches(); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `true` when comparing an empty `source` to a falsey `object`', 1, function() { var expected = _.map(falsey, _.constant(true)), matches = _.matches({}); var actual = _.map(falsey, function(value, index) { try { return index ? matches(value) : matches(); } catch(e) {} }); deepEqual(actual, expected); }); test('should search arrays of `source` for values', 3, function() { var objects = [{ 'a': ['b'] }, { 'a': ['c', 'd'] }], matches = _.matches({ 'a': ['d'] }), actual = _.filter(objects, matches); deepEqual(actual, [objects[1]]); matches = _.matches({ 'a': ['b', 'd'] }); actual = _.filter(objects, matches); deepEqual(actual, []); matches = _.matches({ 'a': ['d', 'b'] }); actual = _.filter(objects, matches); deepEqual(actual, []); }); test('should perform a partial comparison of all objects within arrays of `source`', 1, function() { var objects = [ { 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 5, 'd': 6 }] }, { 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 6, 'd': 7 }] } ]; var matches = _.matches({ 'a': [{ 'b': 1 }, { 'b': 4, 'c': 5 }] }), actual = _.filter(objects, matches); deepEqual(actual, [objects[0]]); }); test('should handle a `source` with `undefined` values', 2, function() { var matches = _.matches({ 'b': undefined }), objects = [{ 'a': 1 }, { 'a': 1, 'b': 1 }, { 'a': 1, 'b': undefined }], actual = _.map(objects, matches), expected = [false, false, true]; deepEqual(actual, expected); matches = _.matches({ 'a': { 'c': undefined } }); objects = [{ 'a': { 'b': 1 } }, { 'a':{ 'b':1, 'c': 1 } }, { 'a': { 'b': 1, 'c': undefined } }]; actual = _.map(objects, matches); deepEqual(actual, expected); }); test('should not match by inherited `source` properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var objects = [{ 'a': 1 }, { 'a': 1, 'b': 2 }], source = new Foo, matches = _.matches(source), actual = _.map(objects, matches), expected = _.map(objects, _.constant(true)); deepEqual(actual, expected); }); test('should work with a function for `source`', 1, function() { function source() {} source.a = 1; source.b = function() {}; source.c = 3; var matches = _.matches(source), objects = [{ 'a': 1 }, { 'a': 1, 'b': source.b, 'c': 3 }], actual = _.map(objects, matches); deepEqual(actual, [false, true]); }); test('should match problem JScript properties (test in IE < 9)', 1, function() { var matches = _.matches(shadowObject), objects = [{}, shadowObject], actual = _.map(objects, matches); deepEqual(actual, [false, true]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.matchesProperty'); (function() { test('should create a function that performs a deep comparison between a property value and `value`', 6, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }, matches = _.matchesProperty('a', 1); strictEqual(matches.length, 1); strictEqual(matches(object), true); matches = _.matchesProperty('b', 3); strictEqual(matches(object), false); matches = _.matchesProperty('a', { 'a': 1, 'c': 3 }); strictEqual(matches({ 'a': object }), true); matches = _.matchesProperty('a', { 'c': 3, 'd': 4 }); strictEqual(matches(object), false); object = { 'a': { 'b': { 'c': 1, 'd': 2 }, 'e': 3 }, 'f': 4 }; matches = _.matchesProperty('a', { 'b': { 'c': 1 } }); strictEqual(matches(object), true); }); test('should compare a variety of values', 2, function() { var object1 = { 'a': false, 'b': true, 'c': '3', 'd': 4, 'e': [5], 'f': { 'g': 6 } }, object2 = { 'a': 0, 'b': 1, 'c': 3, 'd': '4', 'e': ['5'], 'f': { 'g': '6' } }, matches = _.matchesProperty('a', object1); strictEqual(matches({ 'a': object1 }), true); strictEqual(matches({ 'a': object2 }), false); }); test('should not change match behavior if `value` is augmented', 9, function() { _.each([{ 'a': { 'b': 2, 'c': 3 } }, { 'a': 1, 'b': 2 }, { 'a': 1 }], function(source, index) { var object = _.cloneDeep(source), matches = _.matchesProperty('a', source); strictEqual(matches({ 'a': object }), true); if (index) { source.a = 2; source.b = 1; source.c = 3; } else { source.a.b = 1; source.a.c = 2; source.a.d = 3; } strictEqual(matches({ 'a': object }), true); strictEqual(matches({ 'a': source }), false); }); }); test('should return `true` when comparing a `value` of empty arrays and objects', 1, function() { var objects = [{ 'a': [1], 'b': { 'c': 1 } }, { 'a': [2, 3], 'b': { 'd': 2 } }], matches = _.matchesProperty('a', { 'a': [], 'b': {} }); var actual = _.filter(objects, function(object) { return matches({ 'a': object }); }); deepEqual(actual, objects); }); test('should not error for falsey `object` values', 1, function() { var expected = _.map(falsey, _.constant(false)), matches = _.matchesProperty('a', 1); var actual = _.map(falsey, function(value, index) { try { return index ? matches(value) : matches(); } catch(e) {} }); deepEqual(actual, expected); }); test('should search arrays of `value` for values', 3, function() { var objects = [{ 'a': ['b'] }, { 'a': ['c', 'd'] }], matches = _.matchesProperty('a', ['d']), actual = _.filter(objects, matches); deepEqual(actual, [objects[1]]); matches = _.matchesProperty('a', ['b', 'd']); actual = _.filter(objects, matches); deepEqual(actual, []); matches = _.matchesProperty('a', ['d', 'b']); actual = _.filter(objects, matches); deepEqual(actual, []); }); test('should perform a partial comparison of all objects within arrays of `value`', 1, function() { var objects = [ { 'a': [{ 'a': 1, 'b': 2 }, { 'a': 4, 'b': 5, 'c': 6 }] }, { 'a': [{ 'a': 1, 'b': 2 }, { 'a': 4, 'b': 6, 'c': 7 }] } ]; var matches = _.matchesProperty('a', [{ 'a': 1 }, { 'a': 4, 'b': 5 }]), actual = _.filter(objects, matches); deepEqual(actual, [objects[0]]); }); test('should handle a `value` with `undefined` values', 2, function() { var matches = _.matchesProperty('b', undefined), objects = [{ 'a': 1 }, { 'a': 1, 'b': 1 }, { 'a': 1, 'b': undefined }], actual = _.map(objects, matches); deepEqual(actual, [true, false, true]); matches = _.matchesProperty('a', { 'b': undefined }); objects = [{ 'a': { 'a': 1 } }, { 'a': { 'a': 1, 'b': 1 } }, { 'a': { 'a': 1, 'b': undefined } }]; actual = _.map(objects, matches); deepEqual(actual, [false, false, true]); }); test('should not match by inherited `value` properties', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var objects = [{ 'a': { 'a': 1 } }, { 'a': { 'a': 1, 'b': 2 } }], source = new Foo, matches = _.matchesProperty('a', source), actual = _.map(objects, matches), expected = _.map(objects, _.constant(true)); deepEqual(actual, expected); }); test('should work with a function for `value`', 1, function() { function source() {} source.a = 1; source.b = function() {}; source.c = 3; var matches = _.matchesProperty('a', source), objects = [{ 'a': { 'a': 1 } }, { 'a': { 'a': 1, 'b': source.b, 'c': 3 } }], actual = _.map(objects, matches); deepEqual(actual, [false, true]); }); test('should match problem JScript properties (test in IE < 9)', 1, function() { var matches = _.matchesProperty('a', shadowObject), objects = [{ 'a': {} }, { 'a': shadowObject }], actual = _.map(objects, matches); deepEqual(actual, [false, true]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.max'); (function() { test('should return the largest value from a collection', 1, function() { strictEqual(_.max([1, 2, 3]), 3); }); test('should return `-Infinity` for empty collections', 1, function() { var expected = _.map(empties, _.constant(-Infinity)); var actual = _.map(empties, function(value) { try { return _.max(value); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `-Infinity` for non-numeric collection values', 1, function() { var collections = [['a', 'b'], { 'a': 'a', 'b': 'b' }], expected = _.map(collections, _.constant(-Infinity)); var actual = _.map(collections, function(value) { try { return _.max(value); } catch(e) {} }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.memoize'); (function() { test('should memoize results based on the first argument provided', 2, function() { var memoized = _.memoize(function(a, b, c) { return a + b + c; }); strictEqual(memoized(1, 2, 3), 6); strictEqual(memoized(1, 3, 5), 6); }); test('should support a `resolver` argument', 2, function() { var fn = function(a, b, c) { return a + b + c; }, memoized = _.memoize(fn, fn); strictEqual(memoized(1, 2, 3), 6); strictEqual(memoized(1, 3, 5), 9); }); test('should not set a `this` binding', 2, function() { var memoized = _.memoize(function(a, b, c) { return a + this.b + this.c; }); var object = { 'b': 2, 'c': 3, 'memoized': memoized }; strictEqual(object.memoized(1), 6); strictEqual(object.memoized(2), 7); }); test('should throw a TypeError if `resolve` is truthy and not a function', function() { raises(function() { _.memoize(_.noop, {}); }, TypeError); }); test('should not error if `resolve` is falsey', function() { var expected = _.map(falsey, _.constant(true)); var actual = _.map(falsey, function(value, index) { try { return _.isFunction(index ? _.memoize(_.noop, value) : _.memoize(_.noop)); } catch(e) {} }); deepEqual(actual, expected); }); test('should check cache for own properties', 1, function() { var actual = [], memoized = _.memoize(_.identity); _.each(shadowProps, function(value) { actual.push(memoized(value)); }); deepEqual(actual, shadowProps); }); test('should expose a `cache` object on the `memoized` function which implements `Map` interface', 18, function() { _.times(2, function(index) { var resolver = index ? _.identity : null, memoized = _.memoize(function(value) { return 'value:' + value; }, resolver), cache = memoized.cache; memoized('a'); strictEqual(cache.has('a'), true); strictEqual(cache.get('a'), 'value:a'); strictEqual(cache['delete']('a'), true); strictEqual(cache['delete']('b'), false); strictEqual(cache.set('b', 'value:b'), cache); strictEqual(cache.has('b'), true); strictEqual(cache.get('b'), 'value:b'); strictEqual(cache['delete']('b'), true); strictEqual(cache['delete']('a'), false); }); }); test('should skip the `__proto__` key', 8, function() { _.times(2, function(index) { var count = 0, key = '__proto__', resolver = index && _.identity; var memoized = _.memoize(function() { count++; return []; }, resolver); var cache = memoized.cache; memoized(key); memoized(key); strictEqual(count, 2); strictEqual(cache.get(key), undefined); strictEqual(cache['delete'](key), false); ok(!(cache.__data__ instanceof Array)); }); }); test('should allow `_.memoize.Cache` to be customized', 4, function() { var oldCache = _.memoize.Cache function Cache() { this.__data__ = []; } Cache.prototype = { 'delete': function(key) { var data = this.__data__; var index = _.findIndex(data, function(entry) { return key === entry.key; }); if (index < 0) { return false; } data.splice(index, 1); return true; }, 'get': function(key) { return _.find(this.__data__, function(entry) { return key === entry.key; }).value; }, 'has': function(key) { return _.some(this.__data__, function(entry) { return key === entry.key; }); }, 'set': function(key, value) { this.__data__.push({ 'key': key, 'value': value }); } }; _.memoize.Cache = Cache; var memoized = _.memoize(function(object) { return '`id` is "' + object.id + '"'; }); var actual = memoized({ 'id': 'a' }); strictEqual(actual, '`id` is "a"'); var key = { 'id': 'b' }; actual = memoized(key); strictEqual(actual, '`id` is "b"'); var cache = memoized.cache; strictEqual(cache.has(key), true); cache['delete'](key); strictEqual(cache.has(key), false); _.memoize.Cache = oldCache; }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.merge'); (function() { var args = arguments; test('should merge `source` into the destination object', 1, function() { var names = { 'characters': [ { 'name': 'barney' }, { 'name': 'fred' } ] }; var ages = { 'characters': [ { 'age': 36 }, { 'age': 40 } ] }; var heights = { 'characters': [ { 'height': '5\'4"' }, { 'height': '5\'5"' } ] }; var expected = { 'characters': [ { 'name': 'barney', 'age': 36, 'height': '5\'4"' }, { 'name': 'fred', 'age': 40, 'height': '5\'5"' } ] }; deepEqual(_.merge(names, ages, heights), expected); }); test('should merge sources containing circular references', 1, function() { var object = { 'foo': { 'a': 1 }, 'bar': { 'a': 2 } }; var source = { 'foo': { 'b': { 'c': { 'd': {} } } }, 'bar': {} }; source.foo.b.c.d = source; source.bar.b = source.foo.b; var actual = _.merge(object, source); ok(actual.bar.b === actual.foo.b && actual.foo.b.c.d === actual.foo.b.c.d.foo.b.c.d); }); test('should treat sources that are sparse arrays as dense', 2, function() { var array = Array(3); array[0] = 1; array[2] = 3; var actual = _.merge([], array), expected = array.slice(); expected[1] = undefined; ok('1' in actual); deepEqual(actual, expected); }); test('should merge `arguments` objects', 3, function() { var object1 = { 'value': args }, object2 = { 'value': { '3': 4 } }, expected = { '0': 1, '1': 2, '2': 3, '3': 4 }, actual = _.merge(object1, object2); ok(!_.isArguments(actual.value)); deepEqual(actual.value, expected); delete object1.value[3]; actual = _.merge(object2, object1); deepEqual(actual.value, expected); }); test('should merge typed arrays', 4, function() { var array1 = [0], array2 = [0, 0], array3 = [0, 0, 0, 0], array4 = _.range(0, 8, 0); var arrays = [array2, array1, array4, array3, array2, array4, array4, array3, array2], buffer = ArrayBuffer && new ArrayBuffer(8); // juggle for `Float64Array` shim if (root.Float64Array && (new Float64Array(buffer)).length == 8) { arrays[1] = array4; } var expected = _.map(typedArrays, function(type, index) { var array = arrays[index].slice(); array[0] = 1; return root[type] ? { 'value': array } : false; }); var actual = _.map(typedArrays, function(type) { var Ctor = root[type]; return Ctor ? _.merge({ 'value': new Ctor(buffer) }, { 'value': [1] }) : false; }); ok(_.isArray(actual)); deepEqual(actual, expected); expected = _.map(typedArrays, function(type, index) { var array = arrays[index].slice(); array.push(1); return root[type] ? { 'value': array } : false; }); actual = _.map(typedArrays, function(type, index) { var Ctor = root[type], array = _.range(arrays[index].length); array.push(1); return Ctor ? _.merge({ 'value': array }, { 'value': new Ctor(buffer) }) : false; }); ok(_.isArray(actual)); deepEqual(actual, expected); }); test('should work with four arguments', 1, function() { var expected = { 'a': 4 }; deepEqual(_.merge({ 'a': 1 }, { 'a': 2 }, { 'a': 3 }, expected), expected); }); test('should assign `null` values', 1, function() { var actual = _.merge({ 'a': 1 }, { 'a': null }); strictEqual(actual.a, null); }); test('should not assign `undefined` values', 1, function() { var actual = _.merge({ 'a': 1 }, { 'a': undefined, 'b': undefined }); deepEqual(actual, { 'a': 1 }); }); test('should not not error on DOM elements', 1, function() { var object1 = { 'el': document && document.createElement('div') }, object2 = { 'el': document && document.createElement('div') }, pairs = [[{}, object1], [object1, object2]], expected = _.map(pairs, _.constant(true)); var actual = _.map(pairs, function(pair) { try { return _.merge(pair[0], pair[1]).el === pair[1].el; } catch(e) {} }); deepEqual(actual, expected); }); test('should assign non array/plain-object values directly', 1, function() { function Foo() {} var values = [new Foo, new Boolean, new Date, Foo, new Number, new String, new RegExp], expected = _.map(values, _.constant(true)); var actual = _.map(values, function(value) { var object = _.merge({}, { 'a': value }); return object.a === value; }); deepEqual(actual, expected); }); test('should work with a function `object` value', 2, function() { function Foo() {} var source = { 'a': 1 }, actual = _.merge(Foo, source); strictEqual(actual, Foo); strictEqual(Foo.a, 1); }); test('should work with a non-plain `object` value', 2, function() { function Foo() {} var object = new Foo, source = { 'a': 1 }, actual = _.merge(object, source); strictEqual(actual, object); strictEqual(object.a, 1); }); test('should pass thru primitive `object` values', 1, function() { var values = [true, 1, '1']; var actual = _.map(values, function(value) { return _.merge(value, { 'a': 1 }); }); deepEqual(actual, values); }); test('should handle merging if `customizer` returns `undefined`', 2, function() { var actual = _.merge({ 'a': { 'b': [1, 1] } }, { 'a': { 'b': [0] } }, _.noop); deepEqual(actual, { 'a': { 'b': [0, 1] } }); actual = _.merge([], [undefined], _.identity); deepEqual(actual, [undefined]); }); test('should defer to `customizer` when it returns a value other than `undefined`', 1, function() { var actual = _.merge({ 'a': { 'b': [0, 1] } }, { 'a': { 'b': [2] } }, function(a, b) { return _.isArray(a) ? a.concat(b) : undefined; }); deepEqual(actual, { 'a': { 'b': [0, 1, 2] } }); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.min'); (function() { test('should return the smallest value from a collection', 1, function() { strictEqual(_.min([1, 2, 3]), 1); }); test('should return `Infinity` for empty collections', 1, function() { var expected = _.map(empties, _.constant(Infinity)); var actual = _.map(empties, function(value) { try { return _.min(value); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `Infinity` for non-numeric collection values', 1, function() { var collections = [['a', 'b'], { 'a': 'a', 'b': 'b' }], expected = _.map(collections, _.constant(Infinity)); var actual = _.map(collections, function(value) { try { return _.min(value); } catch(e) {} }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('extremum methods'); _.each(['max', 'min'], function(methodName) { var array = [1, 2, 3], func = _[methodName], isMax = methodName == 'max'; test('`_.' + methodName + '` should work with Date objects', 1, function() { var curr = new Date, past = new Date(0); strictEqual(func([curr, past]), isMax ? curr : past); }); test('`_.' + methodName + '` should work with an `iteratee` argument', 1, function() { var actual = func(array, function(num) { return -num; }); strictEqual(actual, isMax ? 1 : 3); }); test('`_.' + methodName + '` should provide the correct `iteratee` arguments when iterating an array', 1, function() { var args; func(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 0, array]); }); test('`_.' + methodName + '` should provide the correct `iteratee` arguments when iterating an object', 1, function() { var args, object = { 'a': 1, 'b': 2 }, firstKey = _.first(_.keys(object)); var expected = firstKey == 'a' ? [1, 'a', object] : [2, 'b', object]; func(object, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, expected); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func(array, function(num, index) { return -this[index]; }, array); strictEqual(actual, isMax ? 1 : 3); }); test('should work with a "_.property" style `iteratee`', 2, function() { var objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }], actual = func(objects, 'a'); deepEqual(actual, objects[isMax ? 1 : 2]); var arrays = [[2], [3], [1]]; actual = func(arrays, 0); deepEqual(actual, arrays[isMax ? 1 : 2]); }); test('`_.' + methodName + '` should work when `iteratee` returns +/-Infinity', 1, function() { var value = isMax ? -Infinity : Infinity, object = { 'a': value }; var actual = func([object, { 'a': value }], function(object) { return object.a; }); strictEqual(actual, object); }); test('`_.' + methodName + '` should iterate an object', 1, function() { var actual = func({ 'a': 1, 'b': 2, 'c': 3 }); strictEqual(actual, isMax ? 3 : 1); }); test('`_.' + methodName + '` should iterate a string', 2, function() { _.each(['abc', Object('abc')], function(value) { var actual = func(value); strictEqual(actual, isMax ? 'c' : 'a'); }); }); test('`_.' + methodName + '` should work with extremely large arrays', 1, function() { var array = _.range(0, 5e5); strictEqual(func(array), isMax ? 499999 : 0); }); test('`_.' + methodName + '` should work as an iteratee for `_.map`', 3, function() { var arrays = [[2, 1], [5, 4], [7, 8]], objects = [{ 'a': 2, 'b': 1 }, { 'a': 5, 'b': 4 }, { 'a': 7, 'b': 8 }], expected = isMax ? [2, 5, 8] : [1, 4, 7]; deepEqual(_.map(arrays, func), expected); deepEqual(_.map(objects, func), expected); deepEqual(_.map('abc', func), ['a', 'b', 'c']); }); test('`_.' + methodName + '` should work when chaining on an array with only one value', 1, function() { if (!isNpm) { var actual = _([40])[methodName](); strictEqual(actual, 40); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.mixin'); (function() { function Wrapper(value) { if (!(this instanceof Wrapper)) { return new Wrapper(value); } if (_.has(value, '__wrapped__')) { var actions = _.slice(value.__actions__), chain = value.__chain__; value = value.__wrapped__; } this.__actions__ = actions || []; this.__chain__ = chain || false; this.__wrapped__ = value; } Wrapper.prototype.value = function() { return getUnwrappedValue(this); }; var array = ['a'], source = { 'a': function(array) { return array[0]; }, 'b': 'B' }; test('should mixin `source` methods into lodash', 4, function() { if (!isNpm) { _.mixin(source); strictEqual(_.a(array), 'a'); strictEqual(_(array).a().value(), 'a'); delete _.a; delete _.prototype.a; ok(!('b' in _)); ok(!('b' in _.prototype)); delete _.b; delete _.prototype.b; } else { skipTest(4); } }); test('should mixin chaining methods by reference', 2, function() { if (!isNpm) { _.mixin(source); _.a = _.constant('b'); strictEqual(_.a(array), 'b'); strictEqual(_(array).a().value(), 'a'); delete _.a; delete _.prototype.a; } else { skipTest(2); } }); test('should use `this` as the default `object` value', 3, function() { var object = _.create(_); object.mixin(source); strictEqual(object.a(array), 'a'); ok(!('a' in _)); ok(!('a' in _.prototype)); delete Wrapper.a; delete Wrapper.prototype.a; delete Wrapper.b; delete Wrapper.prototype.b; }); test('should accept an `object` argument', 1, function() { var object = {}; _.mixin(object, source); strictEqual(object.a(array), 'a'); }); test('should return `object`', 2, function() { var object = {}; strictEqual(_.mixin(object, source), object); strictEqual(_.mixin(), _); }); test('should work with a function for `object`', 2, function() { _.mixin(Wrapper, source); var wrapped = Wrapper(array), actual = wrapped.a(); strictEqual(actual.value(), 'a'); ok(actual instanceof Wrapper); delete Wrapper.a; delete Wrapper.prototype.a; delete Wrapper.b; delete Wrapper.prototype.b; }); test('should not assign inherited `source` properties', 1, function() { function Foo() {} Foo.prototype.a = _.noop; deepEqual(_.mixin({}, new Foo, {}), {}); }); test('should accept an `options` argument', 16, function() { function message(func, chain) { return (func === _ ? 'lodash' : 'provided') + ' function should ' + (chain ? '' : 'not ') + 'chain'; } _.each([_, Wrapper], function(func) { _.each([false, true, { 'chain': false }, { 'chain': true }], function(options) { if (!isNpm) { if (func === _) { _.mixin(source, options); } else { _.mixin(func, source, options); } var wrapped = func(array), actual = wrapped.a(); if (options === true || (options && options.chain)) { strictEqual(actual.value(), 'a', message(func, true)); ok(actual instanceof func, message(func, true)); } else { strictEqual(actual, 'a', message(func, false)); ok(!(actual instanceof func), message(func, false)); } delete func.a; delete func.prototype.a; delete func.b; delete func.prototype.b; } else { skipTest(2); } }); }); }); test('should not extend lodash when an `object` is provided with an empty `options` object', 1, function() { _.mixin({ 'a': _.noop }, {}); ok(!('a' in _)); delete _.a; }); test('should not error for non-object `options` values', 2, function() { var pass = true; try { _.mixin({}, source, 1); } catch(e) { pass = false; } ok(pass); pass = true; try { _.mixin(source, 1); } catch(e) { pass = false; } delete _.a; delete _.prototype.a; delete _.b; delete _.prototype.b; ok(pass); }); test('should not return the existing wrapped value when chaining', 2, function() { _.each([_, Wrapper], function(func) { if (!isNpm) { if (func === _) { var wrapped = _(source), actual = wrapped.mixin(); strictEqual(actual.value(), _); } else { wrapped = _(func); actual = wrapped.mixin(source); notStrictEqual(actual, wrapped); } delete func.a; delete func.prototype.a; delete func.b; delete func.prototype.b; } else { skipTest(); } }); }); test('should produce methods that work in a lazy chain sequence', 1, function() { if (!isNpm) { _.mixin({ 'a': _.countBy, 'b': _.filter }); var predicate = function(value) { return value > 2; }, actual = _([1, 2, 1, 3]).a(_.identity).map(square).b(predicate).take().value(); deepEqual(actual, [4]); delete _.a; delete _.prototype.a; delete _.b; delete _.prototype.b; } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.negate'); (function() { test('should create a function that negates the result of `func`', 2, function() { var negate = _.negate(function(n) { return n % 2 == 0; }); strictEqual(negate(1), true); strictEqual(negate(2), false); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.noop'); (function() { test('should return `undefined`', 1, function() { var values = empties.concat(true, new Date, _, 1, /x/, 'a'), expected = _.map(values, _.constant()); var actual = _.map(values, function(value, index) { return index ? _.noop(value) : _.noop(); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.noConflict'); (function() { test('should return the `lodash` function', 1, function() { if (!isModularize) { var oldDash = root._; strictEqual(_.noConflict(), _); root._ = oldDash; } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.now'); (function() { asyncTest('should return the number of milliseconds that have elapsed since the Unix epoch', 2, function() { var stamp = +new Date, actual = _.now(); ok(actual >= stamp); if (!(isRhino && isModularize)) { setTimeout(function() { ok(_.now() > actual); QUnit.start(); }, 32); } else { skipTest(); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.omit'); (function() { var args = arguments, object = { 'a': 1, 'b': 2, 'c': 3 }, expected = { 'b': 2 }; test('should create an object with omitted properties', 2, function() { deepEqual(_.omit(object, 'a'), { 'b': 2, 'c': 3 }); deepEqual(_.omit(object, 'a', 'c'), expected); }); test('should support picking an array of properties', 1, function() { deepEqual(_.omit(object, ['a', 'c']), expected); }); test('should support picking an array of properties and individual properties', 1, function() { deepEqual(_.omit(object, ['a'], 'c'), expected); }); test('should iterate over inherited properties', 1, function() { function Foo() {} Foo.prototype = object; deepEqual(_.omit(new Foo, 'a', 'c'), expected); }); test('should return an empty object when `object` is `null` or `undefined`', 2, function() { objectProto.a = 1; _.each([null, undefined], function(value) { deepEqual(_.omit(value, 'valueOf'), {}); }); delete objectProto.a; }); test('should work with `arguments` objects as secondary arguments', 1, function() { deepEqual(_.omit(object, args), expected); }); test('should work with an array `object` argument', 1, function() { deepEqual(_.omit([1, 2, 3], '0', '2'), { '1': 2 }); }); test('should work with a primitive `object` argument', 1, function() { stringProto.a = 1; stringProto.b = 2; deepEqual(_.omit('', 'b'), { 'a': 1 }); delete stringProto.a; delete stringProto.b; }); test('should work with a `predicate` argument', 1, function() { var actual = _.omit(object, function(num) { return num != 2; }); deepEqual(actual, expected); }); test('should provide the correct `predicate` arguments', 1, function() { var args, object = { 'a': 1, 'b': 2 }, lastKey = _.keys(object).pop(); var expected = lastKey == 'b' ? [1, 'a', object] : [2, 'b', object]; _.omit(object, function() { args || (args = slice.call(arguments)); }); deepEqual(args, expected); }); test('should correctly set the `this` binding', 1, function() { var actual = _.omit(object, function(num) { return num != this.b; }, { 'b': 2 }); deepEqual(actual, expected); }); test('should coerce property names to strings', 1, function() { deepEqual(_.omit({ '0': 'a' }, 0), {}); }); }('a', 'c')); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.once'); (function() { test('should invoke `func` once', 2, function() { var count = 0, once = _.once(function() { return ++count; }); once(); strictEqual(once(), 1); strictEqual(count, 1); }); test('should not set a `this` binding', 2, function() { var once = _.once(function() { return ++this.count; }), object = { 'count': 0, 'once': once }; object.once(); strictEqual(object.once(), 1); strictEqual(object.count, 1); }); test('should ignore recursive calls', 2, function() { var count = 0; var once = _.once(function() { once(); return ++count; }); strictEqual(once(), 1); strictEqual(count, 1); }); test('should not throw more than once', 2, function() { var pass = true; var once = _.once(function() { throw new Error; }); raises(function() { once(); }, Error); try { once(); } catch(e) { pass = false; } ok(pass); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pad'); (function() { test('should pad a string to a given length', 1, function() { strictEqual(_.pad('abc', 9), ' abc '); }); test('should truncate pad characters to fit the pad length', 2, function() { strictEqual(_.pad('abc', 8), ' abc '); strictEqual(_.pad('abc', 8, '_-'), '_-abc_-_'); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.pad(Object('abc'), 4), 'abc '); strictEqual(_.pad({ 'toString': _.constant('abc') }, 5), ' abc '); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.padLeft'); (function() { test('should pad a string to a given length', 1, function() { strictEqual(_.padLeft('abc', 6), ' abc'); }); test('should truncate pad characters to fit the pad length', 1, function() { strictEqual(_.padLeft('abc', 6, '_-'), '_-_abc'); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.padLeft(Object('abc'), 4), ' abc'); strictEqual(_.padLeft({ 'toString': _.constant('abc') }, 5), ' abc'); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.padRight'); (function() { test('should pad a string to a given length', 1, function() { strictEqual(_.padRight('abc', 6), 'abc '); }); test('should truncate pad characters to fit the pad length', 1, function() { strictEqual(_.padRight('abc', 6, '_-'), 'abc_-_'); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.padRight(Object('abc'), 4), 'abc '); strictEqual(_.padRight({ 'toString': _.constant('abc') }, 5), 'abc '); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('pad methods'); _.each(['pad', 'padLeft', 'padRight'], function(methodName) { var func = _[methodName], isPadLeft = methodName == 'padLeft'; test('`_.' + methodName + '` should not pad is string is >= `length`', 2, function() { strictEqual(func('abc', 2), 'abc'); strictEqual(func('abc', 3), 'abc'); }); test('`_.' + methodName + '` should treat negative `length` as `0`', 2, function() { _.each([0, -2], function(length) { strictEqual(func('abc', length), 'abc'); }); }); test('`_.' + methodName + '` should coerce `length` to a number', 2, function() { _.each(['', '4'], function(length) { var actual = length ? (isPadLeft ? ' abc' : 'abc ') : 'abc'; strictEqual(func('abc', length), actual); }); }); test('`_.' + methodName + '` should return an empty string when provided `null`, `undefined`, or empty string and `chars`', 6, function() { _.each([null, '_-'], function(chars) { strictEqual(func(null, 0, chars), ''); strictEqual(func(undefined, 0, chars), ''); strictEqual(func('', 0, chars), ''); }); }); test('`_.' + methodName + '` should work with `null`, `undefined`, or empty string for `chars`', 3, function() { notStrictEqual(func('abc', 6, null), 'abc'); notStrictEqual(func('abc', 6, undefined), 'abc'); strictEqual(func('abc', 6, ''), 'abc'); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pairs'); (function() { test('should create a two dimensional array of key-value pairs', 1, function() { var object = { 'a': 1, 'b': 2 }; deepEqual(_.pairs(object), [['a', 1], ['b', 2]]); }); test('should work with an object that has a `length` property', 1, function() { var object = { '0': 'a', '1': 'b', 'length': 2 }; deepEqual(_.pairs(object), [['0', 'a'], ['1', 'b'], ['length', 2]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.parseInt'); (function() { test('should accept a `radix` argument', 1, function() { var expected = _.range(2, 37); var actual = _.map(expected, function(radix) { return _.parseInt('10', radix); }); deepEqual(actual, expected); }); test('should use a radix of `10`, for non-hexadecimals, if `radix` is `undefined` or `0`', 4, function() { strictEqual(_.parseInt('10'), 10); strictEqual(_.parseInt('10', 0), 10); strictEqual(_.parseInt('10', 10), 10); strictEqual(_.parseInt('10', undefined), 10); }); test('should use a radix of `16`, for hexadecimals, if `radix` is `undefined` or `0`', 8, function() { _.each(['0x20', '0X20'], function(string) { strictEqual(_.parseInt(string), 32); strictEqual(_.parseInt(string, 0), 32); strictEqual(_.parseInt(string, 16), 32); strictEqual(_.parseInt(string, undefined), 32); }); }); test('should use a radix of `10` for string with leading zeros', 2, function() { strictEqual(_.parseInt('08'), 8); strictEqual(_.parseInt('08', 10), 8); }); test('should parse strings with leading whitespace (test in Chrome, Firefox, and Opera)', 2, function() { var expected = [8, 8, 10, 10, 32, 32, 32, 32]; _.times(2, function(index) { var actual = [], func = (index ? (lodashBizarro || {}) : _).parseInt; if (func) { _.times(2, function(otherIndex) { var string = otherIndex ? '10' : '08'; actual.push( func(whitespace + string, 10), func(whitespace + string) ); }); _.each(['0x20', '0X20'], function(string) { actual.push( func(whitespace + string), func(whitespace + string, 16) ); }); deepEqual(actual, expected); } else { skipTest(); } }); }); test('should coerce `radix` to a number', 2, function() { var object = { 'valueOf': _.constant(0) }; strictEqual(_.parseInt('08', object), 8); strictEqual(_.parseInt('0x20', object), 32); }); test('should work as an iteratee for `_.map`', 2, function() { var strings = _.map(['6', '08', '10'], Object), actual = _.map(strings, _.parseInt); deepEqual(actual, [6, 8, 10]); actual = _.map('123', _.parseInt); deepEqual(actual, [1, 2, 3]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('partial methods'); _.each(['partial', 'partialRight'], function(methodName) { var func = _[methodName], isPartial = methodName == 'partial', ph = func.placeholder; test('`_.' + methodName + '` partially applies arguments', 1, function() { var par = func(_.identity, 'a'); strictEqual(par(), 'a'); }); test('`_.' + methodName + '` creates a function that can be invoked with additional arguments', 1, function() { var fn = function(a, b) { return [a, b]; }, par = func(fn, 'a'), expected = ['a', 'b']; deepEqual(par('b'), isPartial ? expected : expected.reverse()); }); test('`_.' + methodName + '` works when there are no partially applied arguments and the created function is invoked without additional arguments', 1, function() { var fn = function() { return arguments.length; }, par = func(fn); strictEqual(par(), 0); }); test('`_.' + methodName + '` works when there are no partially applied arguments and the created function is invoked with additional arguments', 1, function() { var par = func(_.identity); strictEqual(par('a'), 'a'); }); test('`_.' + methodName + '` should support placeholders', 4, function() { var fn = function() { return slice.call(arguments); }, par = func(fn, ph, 'b', ph); deepEqual(par('a', 'c'), ['a', 'b', 'c']); deepEqual(par('a'), ['a', 'b', undefined]); deepEqual(par(), [undefined, 'b', undefined]); if (isPartial) { deepEqual(par('a', 'c', 'd'), ['a', 'b', 'c', 'd']); } else { par = func(fn, ph, 'c', ph); deepEqual(par('a', 'b', 'd'), ['a', 'b', 'c', 'd']); } }); test('`_.' + methodName + '` should not set a `this` binding', 3, function() { var fn = function() { return this.a; }, object = { 'a': 1 }; var par = func(_.bind(fn, object)); strictEqual(par(), object.a); par = _.bind(func(fn), object); strictEqual(par(), object.a); object.par = func(fn); strictEqual(object.par(), object.a); }); test('`_.' + methodName + '` creates a function with a `length` of `0`', 1, function() { var fn = function(a, b, c) {}, par = func(fn, 'a'); strictEqual(par.length, 0); }); test('`_.' + methodName + '` ensure `new partialed` is an instance of `func`', 2, function() { function Foo(value) { return value && object; } var object = {}, par = func(Foo); ok(new par instanceof Foo); strictEqual(new par(true), object); }); test('`_.' + methodName + '` should clone metadata for created functions', 3, function() { function greet(greeting, name) { return greeting + ' ' + name; } var par1 = func(greet, 'hi'), par2 = func(par1, 'barney'), par3 = func(par1, 'pebbles'); strictEqual(par1('fred'), isPartial ? 'hi fred' : 'fred hi'); strictEqual(par2(), isPartial ? 'hi barney' : 'barney hi'); strictEqual(par3(), isPartial ? 'hi pebbles' : 'pebbles hi'); }); test('`_.' + methodName + '` should work with curried methods', 2, function() { var fn = function(a, b, c) { return a + b + c; }, curried = _.curry(func(fn, 1), 2); strictEqual(curried(2, 3), 6); strictEqual(curried(2)(3), 6); }); test('should work with placeholders and curried methods', 1, function() { var fn = function() { return slice.call(arguments); }, curried = _.curry(fn), par = func(curried, ph, 'b', ph, 'd'); deepEqual(par('a', 'c'), ['a', 'b', 'c', 'd']); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.partialRight'); (function() { test('should work as a deep `_.defaults`', 1, function() { var object = { 'a': { 'b': 1 } }, source = { 'a': { 'b': 2, 'c': 3 } }, expected = { 'a': { 'b': 1, 'c': 3 } }; var defaultsDeep = _.partialRight(_.merge, function deep(value, other) { return _.merge(value, other, deep); }); deepEqual(defaultsDeep(object, source), expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('methods using `createWrapper`'); (function() { var ph1 = _.bind.placeholder, ph2 = _.bindKey.placeholder, ph3 = _.partial.placeholder, ph4 = _.partialRight.placeholder; test('combinations of partial functions should work', 1, function() { function fn() { return slice.call(arguments); } var a = _.partial(fn), b = _.partialRight(a, 3), c = _.partial(b, 1); deepEqual(c(2), [1, 2, 3]); }); test('combinations of bound and partial functions should work', 3, function() { function fn() { var result = [this.a]; push.apply(result, arguments); return result; } var expected = [1, 2, 3, 4], object = { 'a': 1, 'fn': fn }; var a = _.bindKey(object, 'fn'), b = _.partialRight(a, 4), c = _.partial(b, 2); deepEqual(c(3), expected); a = _.bind(fn, object); b = _.partialRight(a, 4); c = _.partial(b, 2); deepEqual(c(3), expected); a = _.partial(fn, 2); b = _.bind(a, object); c = _.partialRight(b, 4); deepEqual(c(3), expected); }); test('combinations of functions with placeholders should work', 3, function() { function fn() { return slice.call(arguments); } var expected = [1, 2, 3, 4, 5, 6], object = { 'fn': fn }; var a = _.bindKey(object, 'fn', ph2, 2), b = _.partialRight(a, ph4, 6), c = _.partial(b, 1, ph3, 4); deepEqual(c(3, 5), expected); a = _.bind(fn, object, ph1, 2); b = _.partialRight(a, ph4, 6); c = _.partial(b, 1, ph3, 4); deepEqual(c(3, 5), expected); a = _.partial(fn, ph3, 2); b = _.bind(a, object, 1, ph1, 4); c = _.partialRight(b, ph4, 6); deepEqual(c(3, 5), expected); }); test('combinations of functions with overlaping placeholders should work', 3, function() { function fn() { return slice.call(arguments); } var expected = [1, 2, 3, 4], object = { 'fn': fn }; var a = _.bindKey(object, 'fn', ph2, 2), b = _.partialRight(a, ph4, 4), c = _.partial(b, ph3, 3); deepEqual(c(1), expected); a = _.bind(fn, object, ph1, 2); b = _.partialRight(a, ph4, 4); c = _.partial(b, ph3, 3); deepEqual(c(1), expected); a = _.partial(fn, ph3, 2); b = _.bind(a, object, ph1, 3); c = _.partialRight(b, ph4, 4); deepEqual(c(1), expected); }); test('recursively bound functions should work', 1, function() { function fn() { return this.a; } var a = _.bind(fn, { 'a': 1 }), b = _.bind(a, { 'a': 2 }), c = _.bind(b, { 'a': 3 }); strictEqual(c(), 1); }); test('should work when hot', 12, function() { _.times(2, function(index) { var fn = function() { var result = [this]; push.apply(result, arguments); return result; }; var object = {}, bound1 = index ? _.bind(fn, object, 1) : _.bind(fn, object), expected = [object, 1, 2, 3]; var actual = _.last(_.times(HOT_COUNT, function() { var bound2 = index ? _.bind(bound1, null, 2) : _.bind(bound1); return index ? bound2(3) : bound2(1, 2, 3); })); deepEqual(actual, expected); actual = _.last(_.times(HOT_COUNT, function() { var bound1 = index ? _.bind(fn, object, 1) : _.bind(fn, object), bound2 = index ? _.bind(bound1, null, 2) : _.bind(bound1); return index ? bound2(3) : bound2(1, 2, 3); })); deepEqual(actual, expected); }); _.each(['curry', 'curryRight'], function(methodName, index) { var fn = function(a, b, c) { return [a, b, c]; }, curried = _[methodName](fn), expected = index ? [3, 2, 1] : [1, 2, 3]; var actual = _.last(_.times(HOT_COUNT, function() { return curried(1)(2)(3); })); deepEqual(actual, expected); actual = _.last(_.times(HOT_COUNT, function() { var curried = _[methodName](fn); return curried(1)(2)(3); })); deepEqual(actual, expected); }); _.each(['partial', 'partialRight'], function(methodName, index) { var func = _[methodName], fn = function() { return slice.call(arguments); }, par1 = func(fn, 1), expected = index ? [3, 2, 1] : [1, 2, 3]; var actual = _.last(_.times(HOT_COUNT, function() { var par2 = func(par1, 2); return par2(3); })); deepEqual(actual, expected); actual = _.last(_.times(HOT_COUNT, function() { var par1 = func(fn, 1), par2 = func(par1, 2); return par2(3); })); deepEqual(actual, expected); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.partition'); (function() { var array = [1, 0, 1]; test('should return two groups of elements', 3, function() { deepEqual(_.partition([], _.identity), [[], []]); deepEqual(_.partition(array, _.constant(true)), [array, []]); deepEqual(_.partition(array, _.constant(false)), [[], array]); }); test('should use `_.identity` when `predicate` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant([[1, 1], [0]])); var actual = _.map(values, function(value, index) { return index ? _.partition(array, value) : _.partition(array); }); deepEqual(actual, expected); }); test('should provide the correct `predicate` arguments', 1, function() { var args; _.partition(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.partition([1.1, 0.2, 1.3], function(num) { return this.floor(num); }, Math); deepEqual(actual, [[1.1, 1.3], [0.2]]); }); test('should work with a "_.property" style `predicate`', 1, function() { var objects = [{ 'a': 1 }, { 'a': 1 }, { 'b': 2 }], actual = _.partition(objects, 'a'); deepEqual(actual, [objects.slice(0, 2), objects.slice(2)]); }); test('should work with a number for `predicate`', 2, function() { var array = [ [1, 0], [0, 1], [1, 0] ]; deepEqual(_.partition(array, 0), [[array[0], array[2]], [array[1]]]); deepEqual(_.partition(array, 1), [[array[1]], [array[0], array[2]]]); }); test('should work with an object for `collection`', 1, function() { var actual = _.partition({ 'a': 1.1, 'b': 0.2, 'c': 1.3 }, function(num) { return Math.floor(num); }); deepEqual(actual, [[1.1, 1.3], [0.2]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pick'); (function() { var args = arguments, object = { 'a': 1, 'b': 2, 'c': 3 }, expected = { 'a': 1, 'c': 3 }; test('should create an object of picked properties', 2, function() { deepEqual(_.pick(object, 'a'), { 'a': 1 }); deepEqual(_.pick(object, 'a', 'c'), expected); }); test('should support picking an array of properties', 1, function() { deepEqual(_.pick(object, ['a', 'c']), expected); }); test('should support picking an array of properties and individual properties', 1, function() { deepEqual(_.pick(object, ['a'], 'c'), expected); }); test('should iterate over inherited properties', 1, function() { function Foo() {} Foo.prototype = object; deepEqual(_.pick(new Foo, 'a', 'c'), expected); }); test('should return an empty object when `object` is `null` or `undefined`', 2, function() { _.each([null, undefined], function(value) { deepEqual(_.pick(value, 'valueOf'), {}); }); }); test('should work with `arguments` objects as secondary arguments', 1, function() { deepEqual(_.pick(object, args), expected); }); test('should work with an array `object` argument', 1, function() { deepEqual(_.pick([1, 2, 3], '1'), { '1': 2 }); }); test('should work with a primitive `object` argument', 1, function() { deepEqual(_.pick('', 'slice'), { 'slice': ''.slice }); }); test('should work with a `predicate` argument', 1, function() { var actual = _.pick(object, function(num) { return num != 2; }); deepEqual(actual, expected); }); test('should provide the correct `predicate` arguments', 1, function() { var args, object = { 'a': 1, 'b': 2 }, lastKey = _.keys(object).pop(); var expected = lastKey == 'b' ? [1, 'a', object] : [2, 'b', object]; _.pick(object, function() { args || (args = slice.call(arguments)); }); deepEqual(args, expected); }); test('should correctly set the `this` binding', 1, function() { var actual = _.pick(object, function(num) { return num != this.b; }, { 'b': 2 }); deepEqual(actual, expected); }); test('should coerce property names to strings', 1, function() { deepEqual(_.pick({ '0': 'a', '1': 'b' }, 0), { '0': 'a' }); }); }('a', 'c')); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pluck'); (function() { test('should return an array of property values from each element of a collection', 1, function() { var objects = [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; deepEqual(_.pluck(objects, 'name'), ['barney', 'fred']); }); test('should pluck inherited property values', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; deepEqual(_.pluck([new Foo], 'b'), [2]); }); test('should work with an object for `collection`', 1, function() { var object = { 'a': [1], 'b': [1, 2], 'c': [1, 2, 3] }; deepEqual(_.pluck(object, 'length'), [1, 2, 3]); }); test('should return `undefined` for undefined properties', 1, function() { var array = [{ 'a': 1 }], actual = [_.pluck(array, 'b'), _.pluck(array, 'c')]; deepEqual(actual, [[undefined], [undefined]]); }); test('should work with nullish elements', 1, function() { var objects = [{ 'a': 1 }, null, undefined, { 'a': 4 }]; deepEqual(_.pluck(objects, 'a'), [1, undefined, undefined, 4]); }); test('should coerce `key` to a string', 1, function() { function fn() {} fn.toString = _.constant('fn'); var objects = [{ 'null': 1 }, { 'undefined': 2 }, { 'fn': 3 }, { '[object Object]': 4 }], values = [null, undefined, fn, {}] var actual = _.map(objects, function(object, index) { return _.pluck([object], values[index]); }); deepEqual(actual, [[1], [2], [3], [4]]); }); test('should work in a lazy chain sequence', 2, function() { if (!isNpm) { var array = [{ 'a': 1 }, null, { 'a': 3 }, { 'a': 4 }], actual = _(array).pluck('a').value(); deepEqual(actual, [1, undefined, 3, 4]); actual = _(array).filter(Boolean).pluck('a').value(); deepEqual(actual, [1, 3, 4]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.property'); (function() { test('should create a function that plucks a property value of a given object', 3, function() { var object = { 'a': 1, 'b': 2 }, prop = _.property('a'); strictEqual(prop.length, 1); strictEqual(prop(object), 1); prop = _.property('b'); strictEqual(prop(object), 2); }); test('should work with non-string `prop` arguments', 1, function() { var prop = _.property(1); strictEqual(prop([1, 2, 3]), 2); }); test('should coerce key to a string', 1, function() { function fn() {} fn.toString = _.constant('fn'); var objects = [{ 'null': 1 }, { 'undefined': 2 }, { 'fn': 3 }, { '[object Object]': 4 }], values = [null, undefined, fn, {}] var actual = _.map(objects, function(object, index) { var prop = _.property(values[index]); return prop(object); }); deepEqual(actual, [1, 2, 3, 4]); }); test('should pluck inherited property values', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var prop = _.property('b'); strictEqual(prop(new Foo), 2); }); test('should work when `object` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant(undefined)); var actual = _.map(values, function(value, index) { var prop = _.property('a'); return index ? prop(value) : prop(); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.propertyOf'); (function() { test('should create a function that plucks a property value of a given key', 3, function() { var object = { 'a': 1, 'b': 2 }, propOf = _.propertyOf(object); strictEqual(propOf.length, 1); strictEqual(propOf('a'), 1); strictEqual(propOf('b'), 2); }); test('should pluck inherited property values', 1, function() { function Foo() { this.a = 1; } Foo.prototype.b = 2; var propOf = _.propertyOf(new Foo); strictEqual(propOf('b'), 2); }); test('should work when `object` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant(undefined)); var actual = _.map(values, function(value, index) { var propOf = index ? _.propertyOf(value) : _.propertyOf(); return propOf('a'); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pull'); (function() { test('should modify and return the array', 2, function() { var array = [1, 2, 3], actual = _.pull(array, 1, 3); deepEqual(array, [2]); ok(actual === array); }); test('should preserve holes in arrays', 2, function() { var array = [1, 2, 3, 4]; delete array[1]; delete array[3]; _.pull(array, 1); ok(!('0' in array)); ok(!('2' in array)); }); test('should treat holes as `undefined`', 1, function() { var array = [1, 2, 3]; delete array[1]; _.pull(array, undefined); deepEqual(array, [1, 3]); }); test('should match `NaN`', 1, function() { var array = [1, NaN, 3, NaN]; _.pull(array, NaN); deepEqual(array, [1, 3]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.pullAt'); (function() { test('should modify the array and return removed elements', 2, function() { var array = [1, 2, 3], actual = _.pullAt(array, [0, 1]); deepEqual(array, [3]); deepEqual(actual, [1, 2]); }); test('should work with unsorted indexes', 2, function() { var array = [1, 2, 3, 4], actual = _.pullAt(array, [1, 3, 0]); deepEqual(array, [3]); deepEqual(actual, [2, 4, 1]); }); test('should work with repeated indexes', 2, function() { var array = [1, 2, 3, 4], actual = _.pullAt(array, [0, 2, 0, 1, 0, 2]); deepEqual(array, [4]); deepEqual(actual, [1, 3, 1, 2, 1, 3]); }); test('should use `undefined` for nonexistent indexes', 2, function() { var array = ['a', 'b', 'c'], actual = _.pullAt(array, [2, 4, 0]); deepEqual(array, ['b']); deepEqual(actual, ['c', undefined, 'a']); }); test('should ignore non-index keys', 2, function() { var array = ['a', 'b', 'c'], clone = array.slice(); array['1.1'] = array['-1'] = 1; var values = _.reject(empties, function(value) { return value === 0 || _.isArray(value); }).concat(-1, 1.1); var expected = _.map(values, _.constant(undefined)), actual = _.pullAt(array, values); deepEqual(actual, expected); deepEqual(array, clone); }); test('should return an empty array when no indexes are provided', 4, function() { var array = ['a', 'b', 'c'], actual = _.pullAt(array); deepEqual(array, ['a', 'b', 'c']); deepEqual(actual, []); actual = _.pullAt(array, [], []); deepEqual(array, ['a', 'b', 'c']); deepEqual(actual, []); }); test('should accept multiple index arguments', 2, function() { var array = ['a', 'b', 'c', 'd'], actual = _.pullAt(array, 3, 0, 2); deepEqual(array, ['b']); deepEqual(actual, ['d', 'a', 'c']); }); test('should accept multiple arrays of indexes', 2, function() { var array = ['a', 'b', 'c', 'd'], actual = _.pullAt(array, [3], [0, 2]); deepEqual(array, ['b']); deepEqual(actual, ['d', 'a', 'c']); }); test('should work with a falsey `array` argument when keys are provided', 1, function() { var expected = _.map(falsey, _.constant([undefined, undefined])); var actual = _.map(falsey, function(value) { try { return _.pullAt(value, 0, 1); } catch(e) {} }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.random'); (function() { var array = Array(1000); test('should return `0` or `1` when arguments are not provided', 1, function() { var actual = _.map(array, function() { return _.random(); }); deepEqual(_.uniq(actual).sort(), [0, 1]); }); test('should support a `min` and `max` argument', 1, function() { var min = 5, max = 10; ok(_.some(array, function() { var result = _.random(min, max); return result >= min && result <= max; })); }); test('should support not providing a `max` argument', 1, function() { var min = 0, max = 5; ok(_.some(array, function() { var result = _.random(max); return result >= min && result <= max; })); }); test('should support large integer values', 2, function() { var min = Math.pow(2, 31), max = Math.pow(2, 62); ok(_.every(array, function() { var result = _.random(min, max); return result >= min && result <= max; })); ok(_.some(array, function() { return _.random(Number.MAX_VALUE) > 0; })); }); test('should coerce arguments to numbers', 1, function() { strictEqual(_.random('1', '1'), 1); }); test('should support floats', 2, function() { var min = 1.5, max = 1.6, actual = _.random(min, max); ok(actual % 1); ok(actual >= min && actual <= max); }); test('should support providing a `floating` argument', 3, function() { var actual = _.random(true); ok(actual % 1 && actual >= 0 && actual <= 1); actual = _.random(2, true); ok(actual % 1 && actual >= 0 && actual <= 2); actual = _.random(2, 4, true); ok(actual % 1 && actual >= 2 && actual <= 4); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [1, 2, 3], expected = _.map(array, _.constant(true)), randoms = _.map(array, _.random); var actual = _.map(randoms, function(result, index) { return result >= 0 && result <= array[index] && (result % 1) == 0; }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.range'); (function() { test('should work with an `end` argument', 1, function() { deepEqual(_.range(4), [0, 1, 2, 3]); }); test('should work with `start` and `end` arguments', 1, function() { deepEqual(_.range(1, 5), [1, 2, 3, 4]); }); test('should work with `start`, `end`, and `step` arguments', 1, function() { deepEqual(_.range(0, 20, 5), [0, 5, 10, 15]); }); test('should support a `step` of `0`', 1, function() { deepEqual(_.range(1, 4, 0), [1, 1, 1]); }); test('should work with a `step` larger than `end`', 1, function() { deepEqual(_.range(1, 5, 20), [1]); }); test('should work with a negative `step` argument', 2, function() { deepEqual(_.range(0, -4, -1), [0, -1, -2, -3]); deepEqual(_.range(21, 10, -3), [21, 18, 15, 12]); }); test('should treat falsey `start` arguments as `0`', 13, function() { _.each(falsey, function(value, index) { if (index) { deepEqual(_.range(value), []); deepEqual(_.range(value, 1), [0]); } else { deepEqual(_.range(), []); } }); }); test('should coerce arguments to finite numbers', 1, function() { var actual = [_.range('0', 1), _.range('1'), _.range(0, 1, '1'), _.range(NaN), _.range(NaN, NaN)]; deepEqual(actual, [[0], [0], [0], [], []]); }); test('should work as an iteratee for `_.map`', 2, function() { var array = [1, 2, 3], object = { 'a': 1, 'b': 2, 'c': 3 }, expected = [[0], [0, 1], [0, 1, 2]]; _.each([array, object], function(collection) { var actual = _.map(collection, _.range); deepEqual(actual, expected); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.rearg'); (function() { function fn() { return slice.call(arguments); } test('should reorder arguments provided to `func`', 1, function() { var rearged = _.rearg(fn, [2, 0, 1]); deepEqual(rearged('b', 'c', 'a'), ['a', 'b', 'c']); }); test('should work with repeated indexes', 1, function() { var rearged = _.rearg(fn, [1, 1, 1]); deepEqual(rearged('c', 'a', 'b'), ['a', 'a', 'a']); }); test('should use `undefined` for nonexistent indexes', 1, function() { var rearged = _.rearg(fn, [1, 4]); deepEqual(rearged('b', 'a', 'c'), ['a', undefined, 'c']); }); test('should use `undefined` for non-index values', 1, function() { var values = _.reject(empties, function(value) { return value === 0 || _.isArray(value); }).concat(-1, 1.1); var expected = _.map(values, _.constant([undefined, 'b', 'c'])); var actual = _.map(values, function(value) { var rearged = _.rearg(fn, [value]); return rearged('a', 'b', 'c'); }); deepEqual(actual, expected); }); test('should not rearrange arguments when no indexes are provided', 2, function() { var rearged = _.rearg(fn); deepEqual(rearged('a', 'b', 'c'), ['a', 'b', 'c']); rearged = _.rearg(fn, [], []); deepEqual(rearged('a', 'b', 'c'), ['a', 'b', 'c']); }); test('should accept multiple index arguments', 1, function() { var rearged = _.rearg(fn, 2, 0, 1); deepEqual(rearged('b', 'c', 'a'), ['a', 'b', 'c']); }); test('should accept multiple arrays of indexes', 1, function() { var rearged = _.rearg(fn, [2], [0, 1]); deepEqual(rearged('b', 'c', 'a'), ['a', 'b', 'c']); }); test('should work with fewer indexes than arguments', 1, function() { var rearged = _.rearg(fn, [1, 0]); deepEqual(rearged('b', 'a', 'c'), ['a', 'b', 'c']); }); test('should work on functions that have been rearged', 1, function() { var rearged1 = _.rearg(fn, 2, 1, 0), rearged2 = _.rearg(rearged1, 1, 0, 2); deepEqual(rearged2('b', 'c', 'a'), ['a', 'b', 'c']); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.reduce'); (function() { var array = [1, 2, 3]; test('should use the first element of a collection as the default `accumulator`', 1, function() { strictEqual(_.reduce(array), 1); }); test('should provide the correct `iteratee` arguments when iterating an array', 2, function() { var args; _.reduce(array, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, [0, 1, 0, array]); args = null; _.reduce(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 2, 1, array]); }); test('should provide the correct `iteratee` arguments when iterating an object', 2, function() { var args, object = { 'a': 1, 'b': 2 }, firstKey = _.first(_.keys(object)); var expected = firstKey == 'a' ? [0, 1, 'a', object] : [0, 2, 'b', object]; _.reduce(object, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, expected); args = null; expected = firstKey == 'a' ? [1, 2, 'b', object] : [2, 1, 'a', object]; _.reduce(object, function() { args || (args = slice.call(arguments)); }); deepEqual(args, expected); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection` (test in IE < 9)', 2, function() { var args; var actual = _.reduce(collection, function(accumulator, value) { args || (args = slice.call(arguments)); return accumulator + value; }); deepEqual(args, ['a', 'b', 1, collection]); strictEqual(actual, 'abc'); }); }); test('should be aliased', 2, function() { strictEqual(_.foldl, _.reduce); strictEqual(_.inject, _.reduce); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.reduceRight'); (function() { var array = [1, 2, 3]; test('should use the last element of a collection as the default `accumulator`', 1, function() { strictEqual(_.reduceRight(array), 3); }); test('should provide the correct `iteratee` arguments when iterating an array', 2, function() { var args; _.reduceRight(array, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, [0, 3, 2, array]); args = null; _.reduceRight(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [3, 2, 1, array]); }); test('should provide the correct `iteratee` arguments when iterating an object', 2, function() { var args, object = { 'a': 1, 'b': 2 }, lastKey = _.last(_.keys(object)); var expected = lastKey == 'b' ? [0, 2, 'b', object] : [0, 1, 'a', object]; _.reduceRight(object, function() { args || (args = slice.call(arguments)); }, 0); deepEqual(args, expected); args = null; expected = lastKey == 'b' ? [2, 1, 'a', object] : [1, 2, 'b', object]; _.reduceRight(object, function() { args || (args = slice.call(arguments)); }); deepEqual(args, expected); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection` (test in IE < 9)', 2, function() { var args; var actual = _.reduceRight(collection, function(accumulator, value) { args || (args = slice.call(arguments)); return accumulator + value; }); deepEqual(args, ['c', 'b', 1, collection]); strictEqual(actual, 'cba'); }); }); test('should be aliased', 1, function() { strictEqual(_.foldr, _.reduceRight); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('reduce methods'); _.each(['reduce', 'reduceRight'], function(methodName) { var func = _[methodName], array = [1, 2, 3], isReduce = methodName == 'reduce'; test('`_.' + methodName + '` should reduce a collection to a single value', 1, function() { var actual = func(['a', 'b', 'c'], function(accumulator, value) { return accumulator + value; }, ''); strictEqual(actual, isReduce ? 'abc' : 'cba'); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func(array, function(sum, num, index) { return sum + this[index]; }, 0, array); deepEqual(actual, 6); }); test('`_.' + methodName + '` should support empty collections without an initial `accumulator` value', 1, function() { var actual = [], expected = _.map(empties, _.constant()); _.each(empties, function(value) { try { actual.push(func(value, _.noop)); } catch(e) {} }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should support empty collections with an initial `accumulator` value', 1, function() { var expected = _.map(empties, _.constant('x')); var actual = _.map(empties, function(value) { try { return func(value, _.noop, 'x'); } catch(e) {} }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should handle an initial `accumulator` value of `undefined`', 1, function() { var actual = func([], _.noop, undefined); strictEqual(actual, undefined); }); test('`_.' + methodName + '` should return `undefined` for empty collections when no `accumulator` is provided (test in IE > 9 and modern browsers)', 2, function() { var array = [], object = { '0': 1, 'length': 0 }; if ('__proto__' in array) { array.__proto__ = object; strictEqual(_.reduce(array, _.noop), undefined); } else { skipTest(); } strictEqual(_.reduce(object, _.noop), undefined); }); test('`_.' + methodName + '` should return an unwrapped value when implicityly chaining', 1, function() { if (!isNpm) { strictEqual(_(array)[methodName](add), 6); } else { skipTest(); } }); test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain()[methodName](add) instanceof _); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.reject'); (function() { var array = [1, 2, 3]; test('should return elements the `predicate` returns falsey for', 1, function() { var actual = _.reject(array, function(num) { return num % 2; }); deepEqual(actual, [2]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('filter methods'); _.each(['filter', 'reject'], function(methodName) { var array = [1, 2, 3, 4], func = _[methodName], isFilter = methodName == 'filter', objects = [{ 'a': 0 }, { 'a': 1 }]; test('`_.' + methodName + '` should not modify the resulting value from within `predicate`', 1, function() { var actual = func([0], function(num, index, array) { array[index] = 1; return isFilter; }); deepEqual(actual, [0]); }); test('`_.' + methodName + '` should work with a "_.property" style `predicate`', 1, function() { deepEqual(func(objects, 'a'), [objects[isFilter ? 1 : 0]]); }); test('`_.' + methodName + '` should work with a "_where" style `predicate`', 1, function() { deepEqual(func(objects, objects[1]), [objects[isFilter ? 1 : 0]]); }); test('`_.' + methodName + '` should not modify wrapped values', 2, function() { if (!isNpm) { var wrapped = _(array); var actual = wrapped[methodName](function(num) { return num < 3; }); deepEqual(actual.value(), isFilter ? [1, 2] : [3, 4]); actual = wrapped[methodName](function(num) { return num > 2; }); deepEqual(actual.value(), isFilter ? [3, 4] : [1, 2]); } else { skipTest(2); } }); test('`_.' + methodName + '` should work in a lazy chain sequence', 2, function() { if (!isNpm) { var object = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, predicate = function(value) { return isFilter ? (value > 6) : (value < 6); }; var expected = [9, 16], actual = _(array).map(square)[methodName](predicate).value(); deepEqual(actual, expected); actual = _(object).mapValues(square)[methodName](predicate).value(); deepEqual(actual, expected); } else { skipTest(2); } }); test('`_.' + methodName + '` should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() { if (!isNpm) { var args, expected = [1, 0, [1, 4, 9, 16]]; _(array)[methodName](function(value, index, array) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, [1, 0, array]); args = null; _(array).map(square)[methodName](function(value, index, array) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); args = null; _(array).map(square)[methodName](function(value, index) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); args = null; _(array).map(square)[methodName](function(value) { args || (args = slice.call(arguments)); }).value(); deepEqual(args, [1]); args = null; _(array).map(square)[methodName](function() { args || (args = slice.call(arguments)); }).value(); deepEqual(args, expected); } else { skipTest(5); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.remove'); (function() { test('should modify the array and return removed elements', 2, function() { var array = [1, 2, 3]; var actual = _.remove(array, function(num) { return num < 3; }); deepEqual(array, [3]); deepEqual(actual, [1, 2]); }); test('should provide the correct `predicate` arguments', 1, function() { var args, array = [1, 2, 3]; _.remove(array, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [1, 0, array]); }); test('should support the `thisArg` argument', 1, function() { var array = [1, 2, 3]; var actual = _.remove(array, function(num, index) { return this[index] < 3; }, array); deepEqual(actual, [1, 2]); }); test('should work with a "_.matches" style `predicate`', 1, function() { var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }]; _.remove(objects, { 'a': 1 }); deepEqual(objects, [{ 'a': 0, 'b': 1 }]); }); test('should work with a "_.matchesProperty" style `predicate`', 1, function() { var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }]; _.remove(objects, 'a', 1); deepEqual(objects, [{ 'a': 0, 'b': 1 }]); }); test('should work with a "_.property" style `predicate`', 1, function() { var objects = [{ 'a': 0 }, { 'a': 1 }]; _.remove(objects, 'a'); deepEqual(objects, [{ 'a': 0 }]); }); test('should preserve holes in arrays', 2, function() { var array = [1, 2, 3, 4]; delete array[1]; delete array[3]; _.remove(array, function(num) { return num === 1; }); ok(!('0' in array)); ok(!('2' in array)); }); test('should treat holes as `undefined`', 1, function() { var array = [1, 2, 3]; delete array[1]; _.remove(array, function(num) { return num == null; }); deepEqual(array, [1, 3]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.repeat'); (function() { test('should repeat a string `n` times', 2, function() { strictEqual(_.repeat('*', 3), '***'); strictEqual(_.repeat('abc', 2), 'abcabc'); }); test('should return an empty string for negative `n` or `n` of `0`', 2, function() { strictEqual(_.repeat('abc', 0), ''); strictEqual(_.repeat('abc', -2), ''); }); test('should coerce `n` to a number', 3, function() { strictEqual(_.repeat('abc'), ''); strictEqual(_.repeat('abc', '2'), 'abcabc'); strictEqual(_.repeat('*', { 'valueOf': _.constant(3) }), '***'); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.repeat(Object('abc'), 2), 'abcabc'); strictEqual(_.repeat({ 'toString': _.constant('*') }, 3), '***'); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.result'); (function() { var object = { 'a': 1, 'b': null, 'c': function() { return this.a; } }; test('should resolve property values', 4, function() { strictEqual(_.result(object, 'a'), 1); strictEqual(_.result(object, 'b'), null); strictEqual(_.result(object, 'c'), 1); strictEqual(_.result(object, 'd'), undefined); }); test('should return `undefined` when `object` is nullish', 2, function() { strictEqual(_.result(null, 'a'), undefined); strictEqual(_.result(undefined, 'a'), undefined); }); test('should return the specified default value for undefined properties', 1, function() { var values = empties.concat(true, new Date, 1, /x/, 'a'); var expected = _.transform(values, function(result, value) { result.push(value, value); }); var actual = _.transform(values, function(result, value) { result.push( _.result(object, 'd', value), _.result(null, 'd', value) ); }); deepEqual(actual, expected); }); test('should execute default function values', 1, function() { var actual = _.result(object, 'd', object.c); strictEqual(actual, 1); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.rest'); (function() { var array = [1, 2, 3]; test('should accept a falsey `array` argument', 1, function() { var expected = _.map(falsey, _.constant([])); var actual = _.map(falsey, function(value, index) { try { return index ? _.rest(value) : _.rest(); } catch(e) {} }); deepEqual(actual, expected); }); test('should exclude the first element', 1, function() { deepEqual(_.rest(array), [2, 3]); }); test('should return an empty when querying empty arrays', 1, function() { deepEqual(_.rest([]), []); }); test('should work as an iteratee for `_.map`', 1, function() { var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], actual = _.map(array, _.rest); deepEqual(actual, [[2, 3], [5, 6], [8, 9]]); }); test('should work in a lazy chain sequence', 4, function() { if (!isNpm) { var array = [1, 2, 3], values = []; var actual = _(array).rest().filter(function(value) { values.push(value); return false; }) .value(); deepEqual(actual, []); deepEqual(values, [2, 3]); values = []; actual = _(array).filter(function(value) { values.push(value); return value > 1; }) .rest() .value(); deepEqual(actual, [3]); deepEqual(values, array); } else { skipTest(4); } }); test('should not execute subsequent iteratees on an empty array in a lazy chain sequence', 4, function() { if (!isNpm) { var array = [1], iteratee = function() { pass = false }, pass = true, actual = _(array).rest().map(iteratee).value(); ok(pass); deepEqual(actual, []); pass = true; actual = _(array).filter(_.identity).rest().map(iteratee).value(); ok(pass); deepEqual(actual, []); } else { skipTest(4); } }); test('should be aliased', 1, function() { strictEqual(_.tail, _.rest); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.runInContext'); (function() { test('should not require a fully populated `context` object', 1, function() { if (!isModularize) { var lodash = _.runInContext({ 'setTimeout': function(callback) { callback(); } }); var pass = false; lodash.delay(function() { pass = true; }, 32); ok(pass); } else { skipTest(); } }); test('should use a zeroed `_.uniqueId` counter', 3, function() { if (!isModularize) { var oldId = (_.uniqueId(), _.uniqueId()), lodash = _.runInContext(); ok(_.uniqueId() > oldId); var id = lodash.uniqueId(); strictEqual(id, '1'); ok(id < oldId); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.sample'); (function() { var array = [1, 2, 3]; test('should return a random element', 1, function() { var actual = _.sample(array); ok(_.includes(array, actual)); }); test('should return two random elements', 1, function() { var actual = _.sample(array, 2); ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(array, actual[0]) && _.includes(array, actual[1])); }); test('should contain elements of the collection', 1, function() { var actual = _.sample(array, array.length); deepEqual(actual.sort(), array); }); test('should treat falsey `n` values, except nullish, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value == null ? 1 : []; }); var actual = _.map(falsey, function(n) { return _.sample([1], n); }); deepEqual(actual, expected); }); test('should return an empty array when `n` < `1` or `NaN`', 3, function() { _.each([0, -1, -Infinity], function(n) { deepEqual(_.sample(array, n), []); }); }); test('should return all elements when `n` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(n) { deepEqual(_.sample(array, n).sort(), array); }); }); test('should return `undefined` when sampling an empty array', 1, function() { strictEqual(_.sample([]), undefined); }); test('should return an empty array for empty collections', 1, function() { var expected = _.transform(empties, function(result) { result.push(undefined, []); }); var actual = []; _.each(empties, function(value) { try { actual.push(_.sample(value), _.sample(value, 1)); } catch(e) {} }); deepEqual(actual, expected); }); test('should sample an object', 2, function() { var object = { 'a': 1, 'b': 2, 'c': 3 }, actual = _.sample(object); ok(_.includes(array, actual)); actual = _.sample(object, 2); ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(array, actual[0]) && _.includes(array, actual[1])); }); test('should work as an iteratee for `_.map`', 2, function() { var array1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array2 = ['abc', 'def', 'ghi']; _.each([array1, array2], function(values) { var a = values[0], b = values[1], c = values[2], actual = _.map(values, _.sample); ok(_.includes(a, actual[0]) && _.includes(b, actual[1]) && _.includes(c, actual[2])); }); }); test('should return a wrapped value when chaining and `n` is provided', 2, function() { if (!isNpm) { var wrapped = _(array).sample(2), actual = wrapped.value(); ok(wrapped instanceof _); ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(array, actual[0]) && _.includes(array, actual[1])); } else { skipTest(2); } }); test('should return an unwrapped value when chaining and `n` is not provided', 1, function() { if (!isNpm) { var actual = _(array).sample(); ok(_.includes(array, actual)); } else { skipTest(); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain().sample() instanceof _); } else { skipTest(); } }); test('should use a stored reference to `_.sample` when chaining', 2, function() { if (!isNpm) { var sample = _.sample; _.sample = _.noop; var wrapped = _(array); notStrictEqual(wrapped.sample(), undefined); notStrictEqual(wrapped.sample(2).value(), undefined); _.sample = sample; } else { skipTest(2); } }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 2, function() { var actual = _.sample(collection); ok(_.includes(collection, actual)); actual = _.sample(collection, 2); ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(collection, actual[0]) && _.includes(collection, actual[1])); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.shuffle'); (function() { var array = [1, 2, 3], object = { 'a': 1, 'b': 2, 'c': 3 }; test('should return a new array', 1, function() { notStrictEqual(_.shuffle(array), array); }); test('should contain the same elements after a collection is shuffled', 2, function() { deepEqual(_.shuffle(array).sort(), array); deepEqual(_.shuffle(object).sort(), array); }); test('should shuffle small collections', 1, function() { var actual = _.times(1000, function() { return _.shuffle([1, 2]); }); deepEqual(_.sortBy(_.uniq(actual, String), '0'), [[1, 2], [2, 1]]); }); test('should treat number values for `collection` as empty', 1, function() { deepEqual(_.shuffle(1), []); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 1, function() { var actual = _.shuffle(collection); deepEqual(actual.sort(), ['a','b', 'c']); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.size'); (function() { var args = arguments, array = [1, 2, 3]; test('should return the number of own enumerable properties of an object', 1, function() { strictEqual(_.size({ 'one': 1, 'two': 2, 'three': 3 }), 3); }); test('should return the length of an array', 1, function() { strictEqual(_.size(array), 3); }); test('should accept a falsey `object` argument', 1, function() { var expected = _.map(falsey, _.constant(0)); var actual = _.map(falsey, function(value, index) { try { return index ? _.size(value) : _.size(); } catch(e) {} }); deepEqual(actual, expected); }); test('should work with `arguments` objects (test in IE < 9)', 1, function() { strictEqual(_.size(args), 3); }); test('should work with jQuery/MooTools DOM query collections', 1, function() { function Foo(elements) { push.apply(this, elements); } Foo.prototype = { 'length': 0, 'splice': arrayProto.splice }; strictEqual(_.size(new Foo(array)), 3); }); test('should not treat objects with negative lengths as array-like', 1, function() { strictEqual(_.size({ 'length': -1 }), 1); }); test('should not treat objects with lengths larger than `MAX_SAFE_INTEGER` as array-like', 1, function() { strictEqual(_.size({ 'length': MAX_SAFE_INTEGER + 1 }), 1); }); test('should not treat objects with non-number lengths as array-like', 1, function() { strictEqual(_.size({ 'length': '0' }), 1); }); test('fixes the JScript `[[DontEnum]]` bug (test in IE < 9)', 1, function() { strictEqual(_.size(shadowObject), 7); }); _.each({ 'literal': 'abc', 'object': Object('abc') }, function(collection, key) { test('should work with a string ' + key + ' for `collection`', 1, function() { deepEqual(_.size(collection), 3); }); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.slice'); (function() { var array = [1, 2, 3]; test('should use a default `start` of `0` and a default `end` of `array.length`', 2, function() { var actual = _.slice(array); deepEqual(actual, array); notStrictEqual(actual, array); }); test('should work with a positive `start`', 2, function() { deepEqual(_.slice(array, 1), [2, 3]); deepEqual(_.slice(array, 1, 3), [2, 3]); }); test('should work with a `start` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(start) { deepEqual(_.slice(array, start), []); }); }); test('should treat falsey `start` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(array)); var actual = _.map(falsey, function(start) { return _.slice(array, start); }); deepEqual(actual, expected); }); test('should work with a negative `start`', 1, function() { deepEqual(_.slice(array, -1), [3]); }); test('should work with a negative `start` <= negative `array.length`', 3, function() { _.each([-3, -4, -Infinity], function(start) { deepEqual(_.slice(array, start), array); }); }); test('should work with `start` >= `end`', 2, function() { _.each([2, 3], function(start) { deepEqual(_.slice(array, start, 2), []); }); }); test('should work with a positive `end`', 1, function() { deepEqual(_.slice(array, 0, 1), [1]); }); test('should work with a `end` >= `array.length`', 4, function() { _.each([3, 4, Math.pow(2, 32), Infinity], function(end) { deepEqual(_.slice(array, 0, end), array); }); }); test('should treat falsey `end` values, except `undefined`, as `0`', 1, function() { var expected = _.map(falsey, function(value) { return value === undefined ? array : []; }); var actual = _.map(falsey, function(end) { return _.slice(array, 0, end); }); deepEqual(actual, expected); }); test('should work with a negative `end`', 1, function() { deepEqual(_.slice(array, 0, -1), [1, 2]); }); test('should work with a negative `end` <= negative `array.length`', 3, function() { _.each([-3, -4, -Infinity], function(end) { deepEqual(_.slice(array, 0, end), []); }); }); test('should coerce `start` and `end` to integers', 1, function() { var positions = [[0.1, 1.1], ['0', 1], [0, '1'], ['1'], [NaN, 1], [1, NaN]]; var actual = _.map(positions, function(pos) { return _.slice.apply(_, [array].concat(pos)); }); deepEqual(actual, [[1], [1], [1], [2, 3], [1], []]); }); test('should work as an iteratee for `_.map`', 2, function() { var array = [[1], [2, 3]], actual = _.map(array, _.slice); deepEqual(actual, array); notStrictEqual(actual, array); }); test('should work in a lazy chain sequence', 38, function() { if (!isNpm) { var wrapped = _(array); _.each(['map', 'filter'], function(methodName) { deepEqual(wrapped[methodName]().slice(0, -1).value(), [1, 2]); deepEqual(wrapped[methodName]().slice(1).value(), [2, 3]); deepEqual(wrapped[methodName]().slice(1, 3).value(), [2, 3]); deepEqual(wrapped[methodName]().slice(-1).value(), [3]); deepEqual(wrapped[methodName]().slice(4).value(), []); deepEqual(wrapped[methodName]().slice(3, 2).value(), []); deepEqual(wrapped[methodName]().slice(0, -4).value(), []); deepEqual(wrapped[methodName]().slice(0, null).value(), []); deepEqual(wrapped[methodName]().slice(0, 4).value(), array); deepEqual(wrapped[methodName]().slice(-4).value(), array); deepEqual(wrapped[methodName]().slice(null).value(), array); deepEqual(wrapped[methodName]().slice(0, 1).value(), [1]); deepEqual(wrapped[methodName]().slice(NaN, '1').value(), [1]); deepEqual(wrapped[methodName]().slice(0.1, 1.1).value(), [1]); deepEqual(wrapped[methodName]().slice('0', 1).value(), [1]); deepEqual(wrapped[methodName]().slice(0, '1').value(), [1]); deepEqual(wrapped[methodName]().slice('1').value(), [2, 3]); deepEqual(wrapped[methodName]().slice(NaN, 1).value(), [1]); deepEqual(wrapped[methodName]().slice(1, NaN).value(), []); }); } else { skipTest(38); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.some'); (function() { test('should return `false` for empty collections', 1, function() { var expected = _.map(empties, _.constant(false)); var actual = _.map(empties, function(value) { try { return _.some(value, _.identity); } catch(e) {} }); deepEqual(actual, expected); }); test('should return `true` if `predicate` returns truthy for any element in the collection', 2, function() { strictEqual(_.some([false, 1, ''], _.identity), true); strictEqual(_.some([null, 'x', 0], _.identity), true); }); test('should return `false` if `predicate` returns falsey for all elements in the collection', 2, function() { strictEqual(_.some([false, false, false], _.identity), false); strictEqual(_.some([null, 0, ''], _.identity), false); }); test('should return `true` as soon as `predicate` returns truthy', 1, function() { strictEqual(_.some([null, true, null], _.identity), true); }); test('should work with a "_.property" style `predicate`', 2, function() { var objects = [{ 'a': 0, 'b': 0 }, { 'a': 0, 'b': 1 }]; strictEqual(_.some(objects, 'a'), false); strictEqual(_.some(objects, 'b'), true); }); test('should work with a "_where" style `predicate`', 2, function() { var objects = [{ 'a': 0, 'b': 0 }, { 'a': 1, 'b': 1}]; strictEqual(_.some(objects, { 'a': 0 }), true); strictEqual(_.some(objects, { 'b': 2 }), false); }); test('should use `_.identity` when `predicate` is nullish', 2, function() { var values = [, null, undefined], expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value, index) { var array = [0, 0]; return index ? _.some(array, value) : _.some(array); }); deepEqual(actual, expected); expected = _.map(values, _.constant(true)); actual = _.map(values, function(value, index) { var array = [0, 1]; return index ? _.some(array, value) : _.some(array); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([[1]], _.some); deepEqual(actual, [true]); }); test('should be aliased', 1, function() { strictEqual(_.any, _.some); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.sortBy'); (function() { function Pair(a, b, c) { this.a = a; this.b = b; this.c = c; } var objects = [ { 'a': 'x', 'b': 3 }, { 'a': 'y', 'b': 4 }, { 'a': 'x', 'b': 1 }, { 'a': 'y', 'b': 2 } ]; var stableOrder = [ new Pair(1, 1, 1), new Pair(1, 2, 1), new Pair(1, 1, 1), new Pair(1, 2, 1), new Pair(1, 3, 1), new Pair(1, 4, 1), new Pair(1, 5, 1), new Pair(1, 6, 1), new Pair(2, 1, 2), new Pair(2, 2, 2), new Pair(2, 3, 2), new Pair(2, 4, 2), new Pair(2, 5, 2), new Pair(2, 6, 2), new Pair(undefined, 1, 1), new Pair(undefined, 2, 1), new Pair(undefined, 3, 1), new Pair(undefined, 4, 1), new Pair(undefined, 5, 1), new Pair(undefined, 6, 1) ]; test('should sort in ascending order', 1, function() { var actual = _.pluck(_.sortBy(objects, function(object) { return object.b; }), 'b'); deepEqual(actual, [1, 2, 3, 4]); }); test('should perform a stable sort (test in V8)', 1, function() { var actual = _.sortBy(stableOrder, function(pair) { return pair.a; }); deepEqual(actual, stableOrder); }); test('should use `_.identity` when `iteratee` is nullish', 1, function() { var array = [3, 2, 1], values = [, null, undefined], expected = _.map(values, _.constant([1, 2, 3])); var actual = _.map(values, function(value, index) { return index ? _.sortBy(array, value) : _.sortBy(array); }); deepEqual(actual, expected); }); test('should move `undefined` and `NaN` values to the end', 1, function() { var array = [NaN, undefined, 4, 1, undefined, 3, NaN, 2]; deepEqual(_.sortBy(array), [1, 2, 3, 4, undefined, undefined, NaN, NaN]); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.sortBy(objects, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [objects[0], 0, objects]); }); test('should support the `thisArg` argument', 1, function() { var actual = _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); deepEqual(actual, [3, 1, 2]); }); test('should work with a "_.property" style `iteratee`', 1, function() { var actual = _.pluck(_.sortBy(objects.concat(undefined), 'b'), 'b'); deepEqual(actual, [1, 2, 3, 4, undefined]); }); test('should work with an object for `collection`', 1, function() { var actual = _.sortBy({ 'a': 1, 'b': 2, 'c': 3 }, function(num) { return Math.sin(num); }); deepEqual(actual, [3, 1, 2]); }); test('should treat number values for `collection` as empty', 1, function() { deepEqual(_.sortBy(1), []); }); test('should coerce arrays returned from `iteratee`', 1, function() { var actual = _.sortBy(objects, function(object) { var result = [object.a, object.b]; result.toString = function() { return String(this[0]); }; return result; }); deepEqual(actual, [objects[0], objects[2], objects[1], objects[3]]); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([[2, 1, 3], [3, 2, 1]], _.sortBy); deepEqual(actual, [[1, 2, 3], [1, 2, 3]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.sortByOrder'); (function() { var objects = [ { 'a': 'x', 'b': 3 }, { 'a': 'y', 'b': 4 }, { 'a': 'x', 'b': 1 }, { 'a': 'y', 'b': 2 } ]; test('should sort multiple properties by specified orders', 1, function() { var actual = _.sortByOrder(objects, ['a', 'b'], [false, true]); deepEqual(actual, [objects[3], objects[1], objects[2], objects[0]]); }); test('should sort a property in ascending order when its order is not specified', 1, function() { var actual = _.sortByOrder(objects, ['a', 'b'], [false]); deepEqual(actual, [objects[3], objects[1], objects[2], objects[0]]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('sortBy methods'); _.each(['sortByAll', 'sortByOrder'], function(methodName) { var func = _[methodName]; function Pair(a, b, c) { this.a = a; this.b = b; this.c = c; } var objects = [ { 'a': 'x', 'b': 3 }, { 'a': 'y', 'b': 4 }, { 'a': 'x', 'b': 1 }, { 'a': 'y', 'b': 2 } ]; var stableOrder = [ new Pair(1, 1, 1), new Pair(1, 2, 1), new Pair(1, 1, 1), new Pair(1, 2, 1), new Pair(1, 3, 1), new Pair(1, 4, 1), new Pair(1, 5, 1), new Pair(1, 6, 1), new Pair(2, 1, 2), new Pair(2, 2, 2), new Pair(2, 3, 2), new Pair(2, 4, 2), new Pair(2, 5, 2), new Pair(2, 6, 2), new Pair(undefined, 1, 1), new Pair(undefined, 2, 1), new Pair(undefined, 3, 1), new Pair(undefined, 4, 1), new Pair(undefined, 5, 1), new Pair(undefined, 6, 1) ]; test('`_.' + methodName + '` should sort mutliple properties in ascending order', 1, function() { var actual = func(objects, ['a', 'b']); deepEqual(actual, [objects[2], objects[0], objects[3], objects[1]]); }); test('`_.' + methodName + '` should perform a stable sort (test in IE > 8, Opera, and V8)', 1, function() { var actual = func(stableOrder, ['a', 'c']); deepEqual(actual, stableOrder); }); test('`_.' + methodName + '` should not error on nullish elements', 1, function() { try { var actual = func(objects.concat(undefined), ['a', 'b']); } catch(e) {} deepEqual(actual, [objects[2], objects[0], objects[3], objects[1], undefined]); }); test('`_.' + methodName + '` should work as an iteratee for `_.reduce`', 1, function() { var objects = [ { 'a': 'x', '0': 3 }, { 'a': 'y', '0': 4 }, { 'a': 'x', '0': 1 }, { 'a': 'y', '0': 2 } ]; var funcs = [func, _.partialRight(func, 'bogus')], expected = _.map(funcs, _.constant([objects[0], objects[2], objects[1], objects[3]])); var actual = _.map(funcs, function(func) { return _.reduce([['a']], func, objects); }); deepEqual(actual, expected); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('sortedIndex methods'); _.each(['sortedIndex', 'sortedLastIndex'], function(methodName) { var array = [30, 50], func = _[methodName], isSortedIndex = methodName == 'sortedIndex', objects = [{ 'x': 30 }, { 'x': 50 }]; test('`_.' + methodName + '` should return the correct insert index', 1, function() { var array = [30, 50], values = [30, 40, 50], expected = isSortedIndex ? [0, 1, 1] : [1, 1, 2]; var actual = _.map(values, function(value) { return func(array, value); }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should work with an array of strings', 1, function() { var array = ['a', 'c'], values = ['a', 'b', 'c'], expected = isSortedIndex ? [0, 1, 1] : [1, 1, 2]; var actual = _.map(values, function(value) { return func(array, value); }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should accept a falsey `array` argument and a `value`', 1, function() { var expected = _.map(falsey, _.constant([0, 0, 0])); var actual = _.map(falsey, function(array) { return [func(array, 1), func(array, undefined), func(array, NaN)]; }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should provide the correct `iteratee` arguments', 1, function() { var args; func(array, 40, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [40]); }); test('`_.' + methodName + '` should support the `thisArg` argument', 1, function() { var actual = func(array, 40, function(num) { return this[num]; }, { '30': 30, '40': 40, '50': 50 }); strictEqual(actual, 1); }); test('`_.' + methodName + '` should work with a "_.property" style `iteratee`', 1, function() { var actual = func(objects, { 'x': 40 }, 'x'); strictEqual(actual, 1); }); test('`_.' + methodName + '` should align with `_.sortBy`', 8, function() { var expected = [1, '2', {}, undefined, NaN, NaN]; _.each([ [NaN, 1, '2', {}, NaN, undefined], ['2', 1, NaN, {}, NaN, undefined] ], function(array) { deepEqual(_.sortBy(array), expected); strictEqual(func(expected, 3), 2); strictEqual(func(expected, undefined), isSortedIndex ? 3 : 4); strictEqual(func(expected, NaN), isSortedIndex ? 4 : 6); }); }); test('`_.' + methodName + '` should support arrays larger than `MAX_ARRAY_LENGTH / 2`', 12, function() { _.each([Math.ceil(MAX_ARRAY_LENGTH / 2), MAX_ARRAY_LENGTH], function(length) { var array = [], values = [MAX_ARRAY_LENGTH, NaN, undefined]; array.length = length; _.each(values, function(value) { var steps = 0, actual = func(array, value, function(value) { steps++; return value; }); var expected = (isSortedIndex ? !_.isNaN(value) : _.isFinite(value)) ? 0 : Math.min(length, MAX_ARRAY_INDEX); // Avoid false fails in older Firefox. if (array.length == length) { ok(steps == 32 || steps == 33); strictEqual(actual, expected); } else { skipTest(2); } }); }); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.spread'); (function() { test('should spread arguments to `func`', 1, function() { var spread = _.spread(add); strictEqual(spread([4, 2]), 6); }); test('should throw a TypeError when receiving a non-array `array` argument', 1, function() { raises(function() { _.spread(4, 2); }, TypeError); }); test('should provide the correct `func` arguments', 1, function() { var args; var spread = _.spread(function() { args = slice.call(arguments); }); spread([4, 2], 'ignored'); deepEqual(args, [4, 2]); }); test('should not set a `this` binding', 1, function() { var spread = _.spread(function(x, y) { return this[x] + this[y]; }); var object = { 'spread': spread, 'x': 4, 'y': 2 }; strictEqual(object.spread(['x', 'y']), 6); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.startsWith'); (function() { var string = 'abc'; test('should return `true` if a string starts with `target`', 1, function() { strictEqual(_.startsWith(string, 'a'), true); }); test('should return `false` if a string does not start with `target`', 1, function() { strictEqual(_.startsWith(string, 'b'), false); }); test('should work with a `position` argument', 1, function() { strictEqual(_.startsWith(string, 'b', 1), true); }); test('should work with `position` >= `string.length`', 4, function() { _.each([3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { strictEqual(_.startsWith(string, 'a', position), false); }); }); test('should treat falsey `position` values as `0`', 1, function() { var expected = _.map(falsey, _.constant(true)); var actual = _.map(falsey, function(position) { return _.startsWith(string, 'a', position); }); deepEqual(actual, expected); }); test('should treat a negative `position` as `0`', 6, function() { _.each([-1, -3, -Infinity], function(position) { strictEqual(_.startsWith(string, 'a', position), true); strictEqual(_.startsWith(string, 'b', position), false); }); }); test('should return `true` when `target` is an empty string regardless of `position`', 1, function() { ok(_.every([-Infinity, NaN, -3, -1, 0, 1, 2, 3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { return _.startsWith(string, '', position, true); })); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.startsWith and lodash.endsWith'); _.each(['startsWith', 'endsWith'], function(methodName) { var func = _[methodName], isStartsWith = methodName == 'startsWith'; var string = 'abc', chr = isStartsWith ? 'a' : 'c'; test('`_.' + methodName + '` should coerce `string` to a string', 2, function() { strictEqual(func(Object(string), chr), true); strictEqual(func({ 'toString': _.constant(string) }, chr), true); }); test('`_.' + methodName + '` should coerce `target` to a string', 2, function() { strictEqual(func(string, Object(chr)), true); strictEqual(func(string, { 'toString': _.constant(chr) }), true); }); test('`_.' + methodName + '` should coerce `position` to a number', 2, function() { var position = isStartsWith ? 1 : 2; strictEqual(func(string, 'b', Object(position)), true); strictEqual(func(string, 'b', { 'toString': _.constant(String(position)) }), true); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.sum'); (function() { test('should return the sum of an array of numbers', 1, function() { strictEqual(_.sum([6, 4, 2]), 12); }); test('should return `0` when passing empty `array` values', 1, function() { var expected = _.map(empties, _.constant(0)); var actual = _.map(empties, function(value) { return _.sum(value); }); deepEqual(actual, expected); }); test('should coerce values to numbers and `NaN` to `0`', 1, function() { strictEqual(_.sum(['1', NaN, '2']), 3); }); test('should iterate an object', 1, function() { strictEqual(_.sum({ 'a': 1, 'b': 2, 'c': 3 }), 6); }); test('should iterate a string', 2, function() { _.each(['123', Object('123')], function(value) { strictEqual(_.sum(value), 6); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.support'); (function() { test('should contain properties with boolean values', 1, function() { ok(_.every(_.values(_.support), function(value) { return value === true || value === false; })); }); test('should not contain minified properties (test production builds)', 1, function() { var props = [ 'argsTag', 'argsObject', 'dom', 'enumErrorProps', 'enumPrototypes', 'fastBind', 'funcDecomp', 'funcNames', 'hostObject', 'nodeTag', 'nonEnumArgs', 'nonEnumShadows', 'nonEnumStrings', 'ownLast', 'spliceObjects', 'unindexedChars' ]; ok(_.isEmpty(_.difference(_.keys(_.support), props))); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.tap'); (function() { test('should intercept and return the given value', 2, function() { if (!isNpm) { var intercepted, array = [1, 2, 3]; var actual = _.tap(array, function(value) { intercepted = value; }); strictEqual(actual, array); strictEqual(intercepted, array); } else { skipTest(2); } }); test('should intercept unwrapped values and return wrapped values when chaining', 2, function() { if (!isNpm) { var intercepted, array = [1, 2, 3]; var wrapped = _(array).tap(function(value) { intercepted = value; value.pop(); }); ok(wrapped instanceof _); wrapped.value(); strictEqual(intercepted, array); } else { skipTest(2); } }); test('should support the `thisArg` argument', 1, function() { if (!isNpm) { var array = [1, 2]; var wrapped = _(array.slice()).tap(function(value) { value.push(this[0]); }, array); deepEqual(wrapped.value(), [1, 2, 1]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.template'); (function() { test('should escape values in "escape" delimiters', 1, function() { var strings = ['<p><%- value %></p>', '<p><%-value%></p>', '<p><%-\nvalue\n%></p>'], expected = _.map(strings, _.constant('<p>&amp;&lt;&gt;&quot;&#39;&#96;\/</p>')), data = { 'value': '&<>"\'`\/' }; var actual = _.map(strings, function(string) { return _.template(string)(data); }); deepEqual(actual, expected); }); test('should evaluate JavaScript in "evaluate" delimiters', 1, function() { var compiled = _.template( '<ul><%\ for (var key in collection) {\ %><li><%= collection[key] %></li><%\ } %></ul>' ); var data = { 'collection': { 'a': 'A', 'b': 'B' } }, actual = compiled(data); strictEqual(actual, '<ul><li>A</li><li>B</li></ul>'); }); test('should interpolate data object properties', 1, function() { var strings = ['<%= a %>BC', '<%=a%>BC', '<%=\na\n%>BC'], expected = _.map(strings, _.constant('ABC')), data = { 'a': 'A' }; var actual = _.map(strings, function(string) { return _.template(string)(data); }); deepEqual(actual, expected); }); test('should support escaped values in "interpolation" delimiters', 1, function() { var compiled = _.template('<%= a ? "a=\\"A\\"" : "" %>'), data = { 'a': true }; strictEqual(compiled(data), 'a="A"'); }); test('should work with "interpolate" delimiters containing ternary operators', 1, function() { var compiled = _.template('<%= value ? value : "b" %>'), data = { 'value': 'a' }; strictEqual(compiled(data), 'a'); }); test('should work with "interpolate" delimiters containing global values', 1, function() { var compiled = _.template('<%= typeof Math.abs %>'); try { var actual = compiled(); } catch(e) {} strictEqual(actual, 'function'); }); test('should work with complex "interpolate" delimiters', 22, function() { _.each({ '<%= a + b %>': '3', '<%= b - a %>': '1', '<%= a = b %>': '2', '<%= !a %>': 'false', '<%= ~a %>': '-2', '<%= a * b %>': '2', '<%= a / b %>': '0.5', '<%= a % b %>': '1', '<%= a >> b %>': '0', '<%= a << b %>': '4', '<%= a & b %>': '0', '<%= a ^ b %>': '3', '<%= a | b %>': '3', '<%= {}.toString.call(0) %>': numberTag, '<%= a.toFixed(2) %>': '1.00', '<%= obj["a"] %>': '1', '<%= delete a %>': 'true', '<%= "a" in obj %>': 'true', '<%= obj instanceof Object %>': 'true', '<%= new Boolean %>': 'false', '<%= typeof a %>': 'number', '<%= void a %>': '' }, function(value, key) { var compiled = _.template(key), data = { 'a': 1, 'b': 2 }; strictEqual(compiled(data), value, key); }); }); test('should parse ES6 template delimiters', 2, function() { var data = { 'value': 2 }; strictEqual(_.template('1${value}3')(data), '123'); strictEqual(_.template('${"{" + value + "\\}"}')(data), '{2}'); }); test('should not reference `_.escape` when "escape" delimiters are not used', 1, function() { var compiled = _.template('<%= typeof __e %>'); strictEqual(compiled({}), 'undefined'); }); test('should allow referencing variables declared in "evaluate" delimiters from other delimiters', 1, function() { var compiled = _.template('<% var b = a; %><%= b.value %>'), data = { 'a': { 'value': 1 } }; strictEqual(compiled(data), '1'); }); test('should support single line comments in "evaluate" delimiters (test production builds)', 1, function() { var compiled = _.template('<% // A code comment. %><% if (value) { %>yap<% } else { %>nope<% } %>'), data = { 'value': true }; strictEqual(compiled(data), 'yap'); }); test('should work with custom delimiters', 2, function() { _.times(2, function(index) { var settingsClone = _.clone(_.templateSettings); var settings = _.assign(index ? _.templateSettings : {}, { 'escape': /\{\{-([\s\S]+?)\}\}/g, 'evaluate': /\{\{([\s\S]+?)\}\}/g, 'interpolate': /\{\{=([\s\S]+?)\}\}/g }); var compiled = _.template('<ul>{{ _.each(collection, function(value, index) {}}<li>{{= index }}: {{- value }}</li>{{}); }}</ul>', index ? null : settings), expected = '<ul><li>0: a &amp; A</li><li>1: b &amp; B</li></ul>', data = { 'collection': ['a & A', 'b & B'] }; strictEqual(compiled(data), expected); _.assign(_.templateSettings, settingsClone); }); }); test('should work with custom delimiters containing special characters', 2, function() { _.times(2, function(index) { var settingsClone = _.clone(_.templateSettings); var settings = _.assign(index ? _.templateSettings : {}, { 'escape': /<\?-([\s\S]+?)\?>/g, 'evaluate': /<\?([\s\S]+?)\?>/g, 'interpolate': /<\?=([\s\S]+?)\?>/g }); var compiled = _.template('<ul><? _.each(collection, function(value, index) { ?><li><?= index ?>: <?- value ?></li><? }); ?></ul>', index ? null : settings), expected = '<ul><li>0: a &amp; A</li><li>1: b &amp; B</li></ul>', data = { 'collection': ['a & A', 'b & B'] }; strictEqual(compiled(data), expected); _.assign(_.templateSettings, settingsClone); }); }); test('should work with strings without delimiters', 1, function() { var expected = 'abc'; strictEqual(_.template(expected)({}), expected); }); test('should support the "imports" option', 1, function() { var compiled = _.template('<%= a %>', { 'imports': { 'a': 1 } }); strictEqual(compiled({}), '1'); }); test('should support the "variable" options', 1, function() { var compiled = _.template( '<% _.each( data.a, function( value ) { %>' + '<%= value.valueOf() %>' + '<% }) %>', { 'variable': 'data' } ); var data = { 'a': [1, 2, 3] }; try { strictEqual(compiled(data), '123'); } catch(e) { ok(false, e.message); } }); test('should support the legacy `options` param signature', 1, function() { var compiled = _.template('<%= data.a %>', null, { 'variable': 'data' }), data = { 'a': 1 }; strictEqual(compiled(data), '1'); }); test('should use a `with` statement by default', 1, function() { var compiled = _.template('<%= index %><%= collection[index] %><% _.each(collection, function(value, index) { %><%= index %><% }); %>'), actual = compiled({ 'index': 1, 'collection': ['a', 'b', 'c'] }); strictEqual(actual, '1b012'); }); test('should work correctly with `this` references', 2, function() { var compiled = _.template('a<%= this.String("b") %>c'); strictEqual(compiled(), 'abc'); var object = { 'b': 'B' }; object.compiled = _.template('A<%= this.b %>C', { 'variable': 'obj' }); strictEqual(object.compiled(), 'ABC'); }); test('should work with backslashes', 1, function() { var compiled = _.template('<%= a %> \\b'), data = { 'a': 'A' }; strictEqual(compiled(data), 'A \\b'); }); test('should work with escaped characters in string literals', 2, function() { var compiled = _.template('<% print("\'\\n\\r\\t\\u2028\\u2029\\\\") %>'); strictEqual(compiled(), "'\n\r\t\u2028\u2029\\"); var data = { 'a': 'A' }; compiled = _.template('\'\n\r\t<%= a %>\u2028\u2029\\"'); strictEqual(compiled(data), '\'\n\r\tA\u2028\u2029\\"'); }); test('should handle \\u2028 & \\u2029 characters', 1, function() { var compiled = _.template('\u2028<%= "\\u2028\\u2029" %>\u2029'); strictEqual(compiled(), '\u2028\u2028\u2029\u2029'); }); test('should work with statements containing quotes', 1, function() { var compiled = _.template("<%\ if (a == 'A' || a == \"a\") {\ %>'a',\"A\"<%\ } %>" ); var data = { 'a': 'A' }; strictEqual(compiled(data), "'a',\"A\""); }); test('should work with templates containing newlines and comments', 1, function() { var compiled = _.template('<%\n\ // A code comment.\n\ if (value) { value += 3; }\n\ %><p><%= value %></p>' ); strictEqual(compiled({ 'value': 3 }), '<p>6</p>'); }); test('should not error with IE conditional comments enabled (test with development build)', 1, function() { var compiled = _.template(''), pass = true; /*@cc_on @*/ try { compiled(); } catch(e) { pass = false; } ok(pass); }); test('should tokenize delimiters', 1, function() { var compiled = _.template('<span class="icon-<%= type %>2"></span>'), data = { 'type': 1 }; strictEqual(compiled(data), '<span class="icon-12"></span>'); }); test('should evaluate delimiters once', 1, function() { var actual = [], compiled = _.template('<%= func("a") %><%- func("b") %><% func("c") %>'), data = { 'func': function(value) { actual.push(value); } }; compiled(data); deepEqual(actual, ['a', 'b', 'c']); }); test('should match delimiters before escaping text', 1, function() { var compiled = _.template('<<\n a \n>>', { 'evaluate': /<<(.*?)>>/g }); strictEqual(compiled(), '<<\n a \n>>'); }); test('should resolve `null` and `undefined` values to an empty string', 3, function() { var compiled = _.template('<%= a %><%- a %>'), data = { 'a': null }; strictEqual(compiled(data), ''); data = { 'a': undefined }; strictEqual(compiled(data), ''); data = { 'a': {} }; compiled = _.template('<%= a.b %><%- a.b %>'); strictEqual(compiled(data), ''); }); test('should parse delimiters without newlines', 1, function() { var expected = '<<\nprint("<p>" + (value ? "yes" : "no") + "</p>")\n>>', compiled = _.template(expected, { 'evaluate': /<<(.+?)>>/g }), data = { 'value': true }; strictEqual(compiled(data), expected); }); test('should support recursive calls', 1, function() { var compiled = _.template('<%= a %><% a = _.template(c)(obj) %><%= a %>'), data = { 'a': 'A', 'b': 'B', 'c': '<%= b %>' }; strictEqual(compiled(data), 'AB'); }); test('should coerce `text` argument to a string', 1, function() { var object = { 'toString': _.constant('<%= a %>') }, data = { 'a': 1 }; strictEqual(_.template(object)(data), '1'); }); test('should not augment the `options` object', 1, function() { var options = {}; _.template('', options); deepEqual(options, {}); }); test('should not modify `_.templateSettings` when `options` are provided', 2, function() { var data = { 'a': 1 }; ok(!('a' in _.templateSettings)); _.template('', {}, data); ok(!('a' in _.templateSettings)); delete _.templateSettings.a; }); test('should not error for non-object `data` and `options` values', 2, function() { var pass = true; try { _.template('')(1); } catch(e) { pass = false; } ok(pass); pass = true; try { _.template('', 1)(1); } catch(e) { pass = false; } ok(pass); }); test('should expose the source for compiled templates', 1, function() { var compiled = _.template('x'), values = [String(compiled), compiled.source], expected = _.map(values, _.constant(true)); var actual = _.map(values, function(value) { return _.includes(value, '__p'); }); deepEqual(actual, expected); }); test('should expose the source when a SyntaxError occurs', 1, function() { try { _.template('<% if x %>'); } catch(e) { var source = e.source; } ok(_.includes(source, '__p')); }); test('should not include sourceURLs in the source', 1, function() { var options = { 'sourceURL': '/a/b/c' }, compiled = _.template('x', options), values = [compiled.source, undefined]; try { _.template('<% if x %>', options); } catch(e) { values[1] = e.source; } var expected = _.map(values, _.constant(false)); var actual = _.map(values, function(value) { return _.includes(value, 'sourceURL'); }); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var array = ['<%= a %>', '<%- b %>', '<% print(c) %>'], compiles = _.map(array, _.template), data = { 'a': 'one', 'b': '`two`', 'c': 'three' }; var actual = _.map(compiles, function(compiled) { return compiled(data); }); deepEqual(actual, ['one', '&#96;two&#96;', 'three']); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.trunc'); (function() { var string = 'hi-diddly-ho there, neighborino'; test('should truncate to a length of `30` by default', 1, function() { strictEqual(_.trunc(string), 'hi-diddly-ho there, neighbo...'); }); test('should not truncate if `string` is <= `length`', 2, function() { strictEqual(_.trunc(string, string.length), string); strictEqual(_.trunc(string, string.length + 2), string); }); test('should truncate string the given length', 1, function() { strictEqual(_.trunc(string, 24), 'hi-diddly-ho there, n...'); }); test('should support a `omission` option', 1, function() { strictEqual(_.trunc(string, { 'omission': ' [...]' }), 'hi-diddly-ho there, neig [...]'); }); test('should support a `length` option', 1, function() { strictEqual(_.trunc(string, { 'length': 4 }), 'h...'); }); test('should support a `separator` option', 2, function() { strictEqual(_.trunc(string, { 'length': 24, 'separator': ' ' }), 'hi-diddly-ho there,...'); strictEqual(_.trunc(string, { 'length': 24, 'separator': /,? +/ }), 'hi-diddly-ho there...'); }); test('should treat negative `length` as `0`', 4, function() { _.each([0, -2], function(length) { strictEqual(_.trunc(string, length), '...'); strictEqual(_.trunc(string, { 'length': length }), '...'); }); }); test('should coerce `length` to an integer', 8, function() { _.each(['', NaN, 4.5, '4'], function(length, index) { var actual = index > 1 ? 'h...' : '...'; strictEqual(_.trunc(string, length), actual); strictEqual(_.trunc(string, { 'length': { 'valueOf': _.constant(length) } }), actual); }); }); test('should coerce `string` to a string', 2, function() { strictEqual(_.trunc(Object(string), 4), 'h...'); strictEqual(_.trunc({ 'toString': _.constant(string) }, 5), 'hi...'); }); test('should work as an iteratee for `_.map`', 1, function() { var actual = _.map([string, string, string], _.trunc), truncated = 'hi-diddly-ho there, neighbo...'; deepEqual(actual, [truncated, truncated, truncated]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.throttle'); (function() { asyncTest('should throttle a function', 2, function() { if (!(isRhino && isModularize)) { var callCount = 0, throttled = _.throttle(function() { callCount++; }, 32); throttled(); throttled(); throttled(); var lastCount = callCount; ok(callCount > 0); setTimeout(function() { ok(callCount > lastCount); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); asyncTest('subsequent calls should return the result of the first call', 5, function() { if (!(isRhino && isModularize)) { var throttled = _.throttle(_.identity, 32), result = [throttled('a'), throttled('b')]; deepEqual(result, ['a', 'a']); setTimeout(function() { var result = [throttled('x'), throttled('y')]; notEqual(result[0], 'a'); notStrictEqual(result[0], undefined); notEqual(result[1], 'y'); notStrictEqual(result[1], undefined); QUnit.start(); }, 64); } else { skipTest(5); QUnit.start(); } }); asyncTest('should clear timeout when `func` is called', 1, function() { if (!isModularize) { var callCount = 0, dateCount = 0; var getTime = function() { return ++dateCount == 5 ? Infinity : +new Date; }; var lodash = _.runInContext(_.assign({}, root, { 'Date': function() { return { 'getTime': getTime }; } })); var throttled = lodash.throttle(function() { callCount++; }, 32); throttled(); throttled(); throttled(); setTimeout(function() { strictEqual(callCount, 2); QUnit.start(); }, 64); } else { skipTest(); QUnit.start(); } }); asyncTest('should not trigger a trailing call when invoked once', 2, function() { if (!(isRhino && isModularize)) { var callCount = 0, throttled = _.throttle(function() { callCount++; }, 32); throttled(); strictEqual(callCount, 1); setTimeout(function() { strictEqual(callCount, 1); QUnit.start(); }, 64); } else { skipTest(2); QUnit.start(); } }); _.times(2, function(index) { asyncTest('should trigger a call when invoked repeatedly' + (index ? ' and `leading` is `false`' : ''), 1, function() { if (!(isRhino && isModularize)) { var callCount = 0, limit = (argv || isPhantom) ? 1000 : 320, options = index ? { 'leading': false } : {}; var throttled = _.throttle(function() { callCount++; }, 32, options); var start = +new Date; while ((new Date - start) < limit) { throttled(); } var actual = callCount > 1; setTimeout(function() { ok(actual); QUnit.start(); }, 1); } else { skipTest(); QUnit.start(); } }); }); asyncTest('should apply default options correctly', 3, function() { if (!(isRhino && isModularize)) { var callCount = 0; var throttled = _.throttle(function(value) { callCount++; return value; }, 32, {}); strictEqual(throttled('a'), 'a'); strictEqual(throttled('b'), 'a'); setTimeout(function() { strictEqual(callCount, 2); QUnit.start(); }, 256); } else { skipTest(3); QUnit.start(); } }); test('should support a `leading` option', 4, function() { _.each([true, { 'leading': true }], function(options) { if (!(isRhino && isModularize)) { var withLeading = _.throttle(_.identity, 32, options); strictEqual(withLeading('a'), 'a'); } else { skipTest(); } }); _.each([false, { 'leading': false }], function(options) { if (!(isRhino && isModularize)) { var withoutLeading = _.throttle(_.identity, 32, options); strictEqual(withoutLeading('a'), undefined); } else { skipTest(); } }); }); asyncTest('should support a `trailing` option', 6, function() { if (!(isRhino && isModularize)) { var withCount = 0, withoutCount = 0; var withTrailing = _.throttle(function(value) { withCount++; return value; }, 64, { 'trailing': true }); var withoutTrailing = _.throttle(function(value) { withoutCount++; return value; }, 64, { 'trailing': false }); strictEqual(withTrailing('a'), 'a'); strictEqual(withTrailing('b'), 'a'); strictEqual(withoutTrailing('a'), 'a'); strictEqual(withoutTrailing('b'), 'a'); setTimeout(function() { strictEqual(withCount, 2); strictEqual(withoutCount, 1); QUnit.start(); }, 256); } else { skipTest(6); QUnit.start(); } }); asyncTest('should not update `lastCalled`, at the end of the timeout, when `trailing` is `false`', 1, function() { if (!(isRhino && isModularize)) { var callCount = 0; var throttled = _.throttle(function() { callCount++; }, 64, { 'trailing': false }); throttled(); throttled(); setTimeout(function() { throttled(); throttled(); }, 96); setTimeout(function() { ok(callCount > 1); QUnit.start(); }, 192); } else { skipTest(); QUnit.start(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.debounce and lodash.throttle'); _.each(['debounce', 'throttle'], function(methodName) { var func = _[methodName], isDebounce = methodName == 'debounce'; test('_.' + methodName + ' should not error for non-object `options` values', 1, function() { var pass = true; try { func(_.noop, 32, 1); } catch(e) { pass = false; } ok(pass); }); asyncTest('_.' + methodName + ' should have a default `wait` of `0`', 1, function() { if (!(isRhino && isModularize)) { var callCount = 0; var funced = func(function() { callCount++; }); funced(); setTimeout(function() { funced(); strictEqual(callCount, isDebounce ? 1 : 2); QUnit.start(); }, 32); } else { skipTest(); QUnit.start(); } }); asyncTest('_.' + methodName + ' should call `func` with the correct `this` binding', 1, function() { if (!(isRhino && isModularize)) { var object = { 'funced': func(function() { actual.push(this); }, 32) }; var actual = [], expected = _.times(isDebounce ? 1 : 2, _.constant(object)); object.funced(); if (!isDebounce) { object.funced(); } setTimeout(function() { deepEqual(actual, expected); QUnit.start(); }, 64); } else { skipTest(); QUnit.start(); } }); asyncTest('_.' + methodName + ' supports recursive calls', 2, function() { if (!(isRhino && isModularize)) { var actual = [], args = _.map(['a', 'b', 'c'], function(chr) { return [{}, chr]; }), length = isDebounce ? 1 : 2, expected = args.slice(0, length), queue = args.slice(); var funced = func(function() { var current = [this]; push.apply(current, arguments); actual.push(current); var next = queue.shift(); if (next) { funced.call(next[0], next[1]); } }, 64); var next = queue.shift(); funced.call(next[0], next[1]); deepEqual(actual, expected.slice(0, length - 1)); setTimeout(function() { deepEqual(actual, expected); QUnit.start(); }, 96); } else { skipTest(2); QUnit.start(); } }); asyncTest('_.' + methodName + ' should work if the system time is set backwards', 1, function() { if (!isModularize) { var callCount = 0, dateCount = 0; var getTime = function() { return ++dateCount === 4 ? +new Date(2012, 3, 23, 23, 27, 18) : +new Date; }; var lodash = _.runInContext(_.assign({}, root, { 'Date': function() { return { 'getTime': getTime, 'valueOf': getTime }; } })); var funced = lodash[methodName](function() { callCount++; }, 32); funced(); setTimeout(function() { funced(); strictEqual(callCount, isDebounce ? 1 : 2); QUnit.start(); }, 64); } else { skipTest(); QUnit.start(); } }); asyncTest('_.' + methodName + ' should support cancelling delayed calls', 1, function() { if (!(isRhino && isModularize)) { var callCount = 0; var funced = func(function() { callCount++; }, 32, { 'leading': false }); funced(); funced.cancel(); setTimeout(function() { strictEqual(callCount, 0); QUnit.start(); }, 64); } else { skipTest(); QUnit.start(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.times'); (function() { test('should coerce non-finite `n` values to `0`', 3, function() { _.each([-Infinity, NaN, Infinity], function(n) { deepEqual(_.times(n), []); }); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.times(1, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [0]); }); test('should support the `thisArg` argument', 1, function() { var expect = [1, 2, 3]; var actual = _.times(3, function(num) { return this[num]; }, expect); deepEqual(actual, expect); }); test('should use `_.identity` when `iteratee` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant([0, 1, 2])); var actual = _.map(values, function(value, index) { return index ? _.times(3, value) : _.times(3); }); deepEqual(actual, expected); }); test('should return an array of the results of each `iteratee` execution', 1, function() { deepEqual(_.times(3, function(n) { return n * 2; }), [0, 2, 4]); }); test('should return an empty array for falsey and negative `n` arguments', 1, function() { var values = falsey.concat(-1, -Infinity), expected = _.map(values, _.constant([])); var actual = _.map(values, function(value, index) { return index ? _.times(value) : _.times(); }); deepEqual(actual, expected); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var wrapped = _(3).times(); ok(wrapped instanceof _); deepEqual(wrapped.value(), [0, 1, 2]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.toArray'); (function() { test('should return the values of objects', 1, function() { var array = [1, 2], object = { 'a': 1, 'b': 2 }; deepEqual(_.toArray(object), array); }); test('should work with a string for `collection` (test in Opera < 10.52)', 2, function() { deepEqual(_.toArray('ab'), ['a', 'b']); deepEqual(_.toArray(Object('ab')), ['a', 'b']); }); test('should work in a lazy chain sequence', 2, function() { if (!isNpm) { var actual = _([1, 2]).map(String).toArray().value(); deepEqual(actual, ['1', '2']); actual = _({ 'a': 1, 'b': 2 }).toArray().map(String).value(); deepEqual(actual, ['1', '2']); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.slice and lodash.toArray'); _.each(['slice', 'toArray'], function(methodName) { var args = (function() { return arguments; }(1, 2, 3)), array = [1, 2, 3], func = _[methodName]; test('should return a dense array', 3, function() { var sparse = Array(3); sparse[1] = 2; var actual = func(sparse); ok('0' in actual); ok('2' in actual); deepEqual(actual, sparse); }); test('should treat array-like objects like arrays', 2, function() { var object = { '0': 'a', '1': 'b', '2': 'c', 'length': 3 }; deepEqual(func(object), ['a', 'b', 'c']); deepEqual(func(args), array); }); test('should return a shallow clone of arrays', 2, function() { var actual = func(array); deepEqual(actual, array); notStrictEqual(actual, array); }); test('should work with a node list for `collection` (test in IE < 9)', 1, function() { if (document) { try { var nodeList = document.getElementsByTagName('body'), actual = func(nodeList); } catch(e) {} deepEqual(actual, [body]); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.toPlainObject'); (function() { var args = arguments; test('should flatten inherited properties', 1, function() { function Foo() { this.b = 2; } Foo.prototype.c = 3; var actual = _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 }); }); test('should convert `arguments` objects to plain objects', 1, function() { var actual = _.toPlainObject(args), expected = { '0': 1, '1': 2, '2': 3 }; deepEqual(actual, expected); }); test('should convert arrays to plain objects', 1, function() { var actual = _.toPlainObject(['a', 'b', 'c']), expected = { '0': 'a', '1': 'b', '2': 'c' }; deepEqual(actual, expected); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.transform'); (function() { function Foo() { this.a = 1; this.b = 2; this.c = 3; } test('should create an object with the same `[[Prototype]]` as `object` when `accumulator` is `null` or `undefined`', 4, function() { var accumulators = [, null, undefined], expected = _.map(accumulators, _.constant(true)), object = new Foo; var iteratee = function(result, value, key) { result[key] = value * value; }; var mapper = function(accumulator, index) { return index ? _.transform(object, iteratee, accumulator) : _.transform(object, iteratee); }; var results = _.map(accumulators, mapper); var actual = _.map(results, function(result) { return result instanceof Foo; }); deepEqual(actual, expected); expected = _.map(accumulators, _.constant({ 'a': 1, 'b': 4, 'c': 9 })); actual = _.map(results, _.clone); deepEqual(actual, expected); object = { 'a': 1, 'b': 2, 'c': 3 }; actual = _.map(accumulators, mapper); deepEqual(actual, expected); object = [1, 2, 3]; expected = _.map(accumulators, _.constant([1, 4, 9])); actual = _.map(accumulators, mapper); deepEqual(actual, expected); }); test('should support an `accumulator` value', 4, function() { var values = [new Foo, [1, 2, 3], { 'a': 1, 'b': 2, 'c': 3 }], expected = _.map(values, _.constant([0, 1, 4, 9])); var actual = _.map(values, function(value) { return _.transform(value, function(result, value) { result.push(value * value); }, [0]); }); deepEqual(actual, expected); var object = { '_': 0, 'a': 1, 'b': 4, 'c': 9 }; expected = [object, { '_': 0, '0': 1, '1': 4, '2': 9 }, object]; actual = _.map(values, function(value) { return _.transform(value, function(result, value, key) { result[key] = value * value; }, { '_': 0 }); }); deepEqual(actual, expected); object = {}; expected = _.map(values, _.constant(object)); actual = _.map(values, function(value) { return _.transform(value, _.noop, object); }); deepEqual(actual, expected); actual = _.map(values, function(value) { return _.transform(null, null, object); }); deepEqual(actual, expected); }); test('should treat sparse arrays as dense', 1, function() { var actual = _.transform(Array(1), function(result, value, index) { result[index] = String(value); }); deepEqual(actual, ['undefined']); }); test('should work without an `iteratee` argument', 1, function() { ok(_.transform(new Foo) instanceof Foo); }); test('should check that `object` is an object before using its `[[Prototype]]`', 2, function() { var Ctors = [Boolean, Boolean, Number, Number, Number, String, String], values = [true, false, 0, 1, NaN, '', 'a'], expected = _.map(values, _.constant({})); var results = _.map(values, function(value) { return _.transform(value); }); deepEqual(results, expected); expected = _.map(values, _.constant(false)); var actual = _.map(results, function(value, index) { return value instanceof Ctors[index]; }); deepEqual(actual, expected); }); test('should create an empty object when provided a falsey `object` argument', 1, function() { var expected = _.map(falsey, _.constant({})); var actual = _.map(falsey, function(value, index) { return index ? _.transform(value) : _.transform(); }); deepEqual(actual, expected); }); _.each({ 'array': [1, 2, 3], 'object': { 'a': 1, 'b': 2, 'c': 3 } }, function(object, key) { test('should provide the correct `iteratee` arguments when transforming an ' + key, 2, function() { var args; _.transform(object, function() { args || (args = slice.call(arguments)); }); var first = args[0]; if (key == 'array') { ok(first !== object && _.isArray(first)); deepEqual(args, [first, 1, 0, object]); } else { ok(first !== object && _.isPlainObject(first)); deepEqual(args, [first, 1, 'a', object]); } }); test('should support the `thisArg` argument when transforming an ' + key, 2, function() { var actual = _.transform(object, function(result, value, key) { result[key] = this[key]; }, null, object); deepEqual(actual, object); notStrictEqual(actual, object); }); }); test('should create an object from the same realm as `object`', 1, function() { var objects = _.transform(_, function(result, value, key) { if (_.startsWith(key, '_') && _.isObject(value) && !_.isElement(value)) { result.push(value); } }, []); var expected = _.times(objects.length, _.constant(true)); var actual = _.map(objects, function(object) { var Ctor = object.constructor, result = _.transform(object); if (result === object) { return false; } if (_.isTypedArray(object)) { return result instanceof Array; } return result instanceof Ctor || !(new Ctor instanceof Ctor); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('trim methods'); _.each(['trim', 'trimLeft', 'trimRight'], function(methodName, index) { var func = _[methodName]; var parts = []; if (index != 2) { parts.push('leading'); } if (index != 1) { parts.push('trailing'); } parts = parts.join(' and '); test('`_.' + methodName + '` should remove ' + parts + ' whitespace', 1, function() { var string = whitespace + 'a b c' + whitespace, expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''); strictEqual(func(string), expected); }); test('`_.' + methodName + '` should not remove non-whitespace characters', 1, function() { // Zero-width space (zws), next line character (nel), and non-character (bom) are not whitespace. var problemChars = '\x85\u200b\ufffe', string = problemChars + 'a b c' + problemChars; strictEqual(func(string), string); }); test('`_.' + methodName + '` should coerce `string` to a string', 1, function() { var object = { 'toString': _.constant(whitespace + 'a b c' + whitespace) }, expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''); strictEqual(func(object), expected); }); test('`_.' + methodName + '` should remove ' + parts + ' `chars`', 1, function() { var string = '-_-a-b-c-_-', expected = (index == 2 ? '-_-' : '') + 'a-b-c' + (index == 1 ? '-_-' : ''); strictEqual(func(string, '_-'), expected); }); test('`_.' + methodName + '` should coerce `chars` to a string', 1, function() { var object = { 'toString': _.constant('_-') }, string = '-_-a-b-c-_-', expected = (index == 2 ? '-_-' : '') + 'a-b-c' + (index == 1 ? '-_-' : ''); strictEqual(func(string, object), expected); }); test('`_.' + methodName + '` should return an empty string when provided `null`, `undefined`, or empty string and `chars`', 6, function() { _.each([null, '_-'], function(chars) { strictEqual(func(null, chars), ''); strictEqual(func(undefined, chars), ''); strictEqual(func('', chars), ''); }); }); test('`_.' + methodName + '` should work with `null`, `undefined`, or empty string for `chars`', 3, function() { var string = whitespace + 'a b c' + whitespace, expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''); strictEqual(func(string, null), expected); strictEqual(func(string, undefined), expected); strictEqual(func(string, ''), string); }); test('`_.' + methodName + '` should work as an iteratee for `_.map`', 1, function() { var string = Object(whitespace + 'a b c' + whitespace), trimmed = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''), actual = _.map([string, string, string], func); deepEqual(actual, [trimmed, trimmed, trimmed]); }); test('`_.' + methodName + '` should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { var string = whitespace + 'a b c' + whitespace, expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''); strictEqual(_(string)[methodName](), expected); } else { skipTest(); } }); test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { var string = whitespace + 'a b c' + whitespace; ok(_(string).chain()[methodName]() instanceof _); } else { skipTest(); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.unescape'); (function() { var escaped = '&amp;&lt;&gt;&quot;&#39;\/', unescaped = '&<>"\'\/'; escaped += escaped; unescaped += unescaped; test('should unescape entities in the correct order', 1, function() { strictEqual(_.unescape('&amp;lt;'), '&lt;'); }); test('should unescape the proper entities', 1, function() { strictEqual(_.unescape(escaped), unescaped); }); test('should not unescape the "&#x2F;" entity', 1, function() { strictEqual(_.unescape('&#x2F;'), '&#x2F;'); }); test('should handle strings with nothing to unescape', 1, function() { strictEqual(_.unescape('abc'), 'abc'); }); test('should unescape the same characters escaped by `_.escape`', 1, function() { strictEqual(_.unescape(_.escape(unescaped)), unescaped); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.union'); (function() { var args = arguments; test('should return the union of the given arrays', 1, function() { var actual = _.union([1, 3, 2], [5, 2, 1, 4], [2, 1]); deepEqual(actual, [1, 3, 2, 5, 4]); }); test('should not flatten nested arrays', 1, function() { var actual = _.union([1, 3, 2], [1, [5]], [2, [4]]); deepEqual(actual, [1, 3, 2, [5], [4]]); }); test('should ignore values that are not arrays or `arguments` objects', 3, function() { var array = [0]; deepEqual(_.union(array, 3, null, { '0': 1 }), array); deepEqual(_.union(null, array, null, [2, 1]), [0, 2, 1]); deepEqual(_.union(array, null, args, null), [0, 1, 2, 3]); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.uniq'); (function() { var objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }, { 'a': 2 }, { 'a': 3 }, { 'a': 1 }]; test('should return unique values of an unsorted array', 1, function() { var array = [2, 3, 1, 2, 3, 1]; deepEqual(_.uniq(array), [2, 3, 1]); }); test('should return unique values of a sorted array', 1, function() { var array = [1, 1, 2, 2, 3]; deepEqual(_.uniq(array), [1, 2, 3]); }); test('should treat object instances as unique', 1, function() { deepEqual(_.uniq(objects), objects); }); test('should not treat `NaN` as unique', 1, function() { deepEqual(_.uniq([1, NaN, 3, NaN]), [1, NaN, 3]); }); test('should work with `isSorted`', 3, function() { var expected = [1, 2, 3]; deepEqual(_.uniq([1, 2, 3], true), expected); deepEqual(_.uniq([1, 1, 2, 2, 3], true), expected); deepEqual(_.uniq([1, 2, 3, 3, 3, 3, 3], true), expected); }); test('should work with an `iteratee` argument', 2, function() { _.each([objects, _.sortBy(objects, 'a')], function(array, index) { var isSorted = !!index, expected = isSorted ? [objects[2], objects[0], objects[1]] : objects.slice(0, 3); var actual = _.uniq(array, isSorted, function(object) { return object.a; }); deepEqual(actual, expected); }); }); test('should provide the correct `iteratee` arguments', 1, function() { var args; _.uniq(objects, function() { args || (args = slice.call(arguments)); }); deepEqual(args, [objects[0], 0, objects]); }); test('should work with `iteratee` without specifying `isSorted`', 1, function() { var actual = _.uniq(objects, function(object) { return object.a; }); deepEqual(actual, objects.slice(0, 3)); }); test('should support the `thisArg` argument', 1, function() { var actual = _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); deepEqual(actual, [1, 2, 3]); }); test('should work with a "_.property" style `iteratee`', 2, function() { var actual = _.uniq(objects, 'a'); deepEqual(actual, objects.slice(0, 3)); var arrays = [[2], [3], [1], [2], [3], [1]]; actual = _.uniq(arrays, 0); deepEqual(actual, arrays.slice(0, 3)); }); test('should perform an unsorted uniq when used as an iteratee for `_.map`', 1, function() { var array = [[2, 1, 2], [1, 2, 1]], actual = _.map(array, _.uniq); deepEqual(actual, [[2, 1], [1, 2]]); }); test('should work with large arrays', 1, function() { var largeArray = [], expected = [0, 'a', {}], count = Math.ceil(LARGE_ARRAY_SIZE / expected.length); _.times(count, function() { push.apply(largeArray, expected); }); deepEqual(_.uniq(largeArray), expected); }); test('should work with large arrays of boolean, `NaN`, `null`, and `undefined` values', 1, function() { var largeArray = [], expected = [true, false, NaN, null, undefined], count = Math.ceil(LARGE_ARRAY_SIZE / expected.length); _.times(count, function() { push.apply(largeArray, expected); }); deepEqual(_.uniq(largeArray), expected); }); test('should work with large arrays of symbols', 1, function() { if (Symbol) { var largeArray = _.times(LARGE_ARRAY_SIZE, function() { return Symbol(); }); deepEqual(_.uniq(largeArray), largeArray); } else { skipTest(); } }); test('should distinguish between numbers and numeric strings', 1, function() { var array = [], expected = ['2', 2, Object('2'), Object(2)], count = Math.ceil(LARGE_ARRAY_SIZE / expected.length); _.times(count, function() { push.apply(array, expected); }); deepEqual(_.uniq(array), expected); }); _.each({ 'an object': ['a'], 'a number': 0, 'a string': '0' }, function(callback, key) { test('should work with ' + key + ' for `iteratee`', 1, function() { var actual = _.uniq([['a'], ['b'], ['a']], callback); deepEqual(actual, [['a'], ['b']]); }); }); test('should be aliased', 1, function() { strictEqual(_.unique, _.uniq); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.uniqueId'); (function() { test('should generate unique ids', 1, function() { var actual = _.times(1000, function() { return _.uniqueId(); }); strictEqual(_.uniq(actual).length, actual.length); }); test('should return a string value when not providing a prefix argument', 1, function() { strictEqual(typeof _.uniqueId(), 'string'); }); test('should coerce the prefix argument to a string', 1, function() { var actual = [_.uniqueId(3), _.uniqueId(2), _.uniqueId(1)]; ok(/3\d+,2\d+,1\d+/.test(actual)); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.values'); (function() { test('should get the values of an object', 1, function() { var object = { 'a': 1, 'b': 2 }; deepEqual(_.values(object), [1, 2]); }); test('should work with an object that has a `length` property', 1, function() { var object = { '0': 'a', '1': 'b', 'length': 2 }; deepEqual(_.values(object), ['a', 'b', 2]); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.where'); (function() { test('should filter by `source` properties', 12, function() { var objects = [ { 'a': 1 }, { 'a': 1 }, { 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }, { 'a': 3 } ]; var pairs = [ [{ 'a': 1 }, [{ 'a': 1 }, { 'a': 1 }, { 'a': 1, 'b': 2 }]], [{ 'a': 2 }, [{ 'a': 2, 'b': 2 }]], [{ 'a': 3 }, [{ 'a': 3 }]], [{ 'b': 1 }, []], [{ 'b': 2 }, [{ 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }]], [{ 'a': 1, 'b': 2 }, [{ 'a': 1, 'b': 2 }]] ]; _.each(pairs, function(pair) { var actual = _.where(objects, pair[0]); deepEqual(actual, pair[1]); ok(_.isEmpty(_.difference(actual, objects))); }); }); test('should work with an object for `collection`', 1, function() { var object = { 'x': { 'a': 1 }, 'y': { 'a': 3 }, 'z': { 'a': 1, 'b': 2 } }; var actual = _.where(object, { 'a': 1 }); deepEqual(actual, [object.x, object.z]); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [ { 'a': 1 }, { 'a': 3 }, { 'a': 1, 'b': 2 } ]; var actual = _(array).where({ 'a': 1 }).value(); deepEqual(actual, [array[0], array[2]]); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.without'); (function() { test('should use strict equality to determine the values to reject', 2, function() { var object1 = { 'a': 1 }, object2 = { 'b': 2 }, array = [object1, object2]; deepEqual(_.without(array, { 'a': 1 }), array); deepEqual(_.without(array, object1), [object2]); }); test('should remove all occurrences of each value from an array', 1, function() { var array = [1, 2, 3, 1, 2, 3]; deepEqual(_.without(array, 1, 2), [3, 3]); }); test('should treat string values for `array` as empty', 1, function() { deepEqual(_.without('abc', 'b'), []); }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.words'); (function() { test('should treat latin-1 supplementary letters as words', 1, function() { var expected = _.map(burredLetters, function(letter) { return [letter]; }); var actual = _.map(burredLetters, function(letter) { return _.words(letter); }); deepEqual(actual, expected); }); test('should not treat mathematical operators as words', 1, function() { var operators = ['\xd7', '\xf7'], expected = _.map(operators, _.constant([])), actual = _.map(operators, _.words); deepEqual(actual, expected); }); test('should work as an iteratee for `_.map`', 1, function() { var strings = _.map(['a', 'b', 'c'], Object), actual = _.map(strings, _.words); deepEqual(actual, [['a'], ['b'], ['c']]); }); test('should work with compound words', 6, function() { deepEqual(_.words('aeiouAreVowels'), ['aeiou', 'Are', 'Vowels']); deepEqual(_.words('enable 24h format'), ['enable', '24', 'h', 'format']); deepEqual(_.words('LETTERSAeiouAreVowels'), ['LETTERS', 'Aeiou', 'Are', 'Vowels']); deepEqual(_.words('tooLegit2Quit'), ['too', 'Legit', '2', 'Quit']); deepEqual(_.words('walk500Miles'), ['walk', '500', 'Miles']); deepEqual(_.words('xhr2Request'), ['xhr', '2', 'Request']); }); test('should work with compound words containing diacritical marks', 3, function() { deepEqual(_.words('LETTERSÆiouAreVowels'), ['LETTERS', 'Æiou', 'Are', 'Vowels']); deepEqual(_.words('æiouAreVowels'), ['æiou', 'Are', 'Vowels']); deepEqual(_.words('æiou2Consonants'), ['æiou', '2', 'Consonants']); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.wrap'); (function() { test('should create a wrapped function', 1, function() { var p = _.wrap(_.escape, function(func, text) { return '<p>' + func(text) + '</p>'; }); strictEqual(p('fred, barney, & pebbles'), '<p>fred, barney, &amp; pebbles</p>'); }); test('should provide the correct `wrapper` arguments', 1, function() { var args; var wrapped = _.wrap(_.noop, function() { args || (args = slice.call(arguments)); }); wrapped(1, 2, 3); deepEqual(args, [_.noop, 1, 2, 3]); }); test('should not set a `this` binding', 1, function() { var p = _.wrap(_.escape, function(func) { return '<p>' + func(this.text) + '</p>'; }); var object = { 'p': p, 'text': 'fred, barney, & pebbles' }; strictEqual(object.p(), '<p>fred, barney, &amp; pebbles</p>'); }); test('should use `_.identity` when `wrapper` is nullish', 1, function() { var values = [, null, undefined], expected = _.map(values, _.constant('a')); var actual = _.map(values, function(value, index) { var wrapped = index ? _.wrap('a', value) : _.wrap('a'); return wrapped('b', 'c'); }); deepEqual(actual, expected); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.xor'); (function() { var args = arguments; test('should return the symmetric difference of the given arrays', 1, function() { var actual = _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); deepEqual(actual, [1, 4, 5]); }); test('should return an array of unique values', 2, function() { var actual = _.xor([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]); deepEqual(actual, [1, 4, 5]); actual = _.xor([1, 1]); deepEqual(actual, [1]); }); test('should return a new array when a single array is provided', 1, function() { var array = [1]; notStrictEqual(_.xor(array), array); }); test('should ignore individual secondary arguments', 1, function() { var array = [0]; deepEqual(_.xor(array, 3, null, { '0': 1 }), array); }); test('should ignore values that are not arrays or `arguments` objects', 3, function() { var array = [1, 2]; deepEqual(_.xor(array, 3, null, { '0': 1 }), array); deepEqual(_.xor(null, array, null, [2, 3]), [1, 3]); deepEqual(_.xor(array, null, args, null), [3]); }); test('should return a wrapped value when chaining', 2, function() { if (!isNpm) { var wrapped = _([1, 2, 3]).xor([5, 2, 1, 4]); ok(wrapped instanceof _); deepEqual(wrapped.value(), [3, 5, 4]); } else { skipTest(2); } }); test('should work when in a lazy chain sequence before `first` or `last`', 1, function() { if (!isNpm) { var wrapped = _([1, 2]).slice().xor([2, 3]); var actual = _.map(['first', 'last'], function(methodName) { return wrapped[methodName](); }); deepEqual(actual, [1, 3]); } else { skipTest(); } }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.unzip and lodash.zip'); _.each(['unzip', 'zip'], function(methodName, index) { var func = _[methodName]; func = _.bind(index ? func.apply : func.call, func, null); var object = { 'an empty array': [ [], [] ], '0-tuples': [ [[], []], [] ], '2-tuples': [ [['barney', 'fred'], [36, 40]], [['barney', 36], ['fred', 40]] ], '3-tuples': [ [['barney', 'fred'], [36, 40], [true, false]], [['barney', 36, true], ['fred', 40, false]] ] }; _.forOwn(object, function(pair, key) { test('`_.' + methodName + '` should work with ' + key, 2, function() { var actual = func(pair[0]); deepEqual(actual, pair[1]); deepEqual(func(actual), actual.length ? pair[0] : []); }); }); test('`_.' + methodName + '` should work with tuples of different lengths', 4, function() { var pair = [ [['barney', 36], ['fred', 40, false]], [['barney', 'fred'], [36, 40], [undefined, false]] ]; var actual = func(pair[0]); ok('0' in actual[2]); deepEqual(actual, pair[1]); actual = func(actual); ok('2' in actual[0]); deepEqual(actual, [['barney', 36, undefined], ['fred', 40, false]]); }); test('`_.' + methodName + '` should treat falsey values as empty arrays', 1, function() { var expected = _.map(falsey, _.constant([])); var actual = _.map(falsey, function(value) { return func([value, value, value]); }); deepEqual(actual, expected); }); test('`_.' + methodName + '` should support consuming its return value', 1, function() { var expected = [['barney', 'fred'], [36, 40]]; deepEqual(func(func(func(func(expected)))), expected); }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash.zipObject'); (function() { var object = { 'barney': 36, 'fred': 40 }, array = [['barney', 36], ['fred', 40]]; test('should skip falsey elements in a given two dimensional array', 1, function() { var actual = _.zipObject(array.concat(falsey)); deepEqual(actual, object); }); test('should zip together key/value arrays into an object', 1, function() { var actual = _.zipObject(['barney', 'fred'], [36, 40]); deepEqual(actual, object); }); test('should ignore extra `values`', 1, function() { deepEqual(_.zipObject(['a'], [1, 2]), { 'a': 1 }); }); test('should accept a two dimensional array', 1, function() { var actual = _.zipObject(array); deepEqual(actual, object); }); test('should not assume `keys` is two dimensional if `values` is not provided', 1, function() { var actual = _.zipObject(['barney', 'fred']); deepEqual(actual, { 'barney': undefined, 'fred': undefined }); }); test('should accept a falsey `array` argument', 1, function() { var expected = _.map(falsey, _.constant({})); var actual = _.map(falsey, function(value, index) { try { return index ? _.zipObject(value) : _.zipObject(); } catch(e) {} }); deepEqual(actual, expected); }); test('should support consuming the return value of `_.pairs`', 1, function() { deepEqual(_.zipObject(_.pairs(object)), object); }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var array = [['a', 1], ['b', 2]], predicate = function(value) { return value > 2; }, actual = _(array).zipObject().map(square).filter(predicate).take().value(); deepEqual(actual, [4]); } else { skipTest(); } }); test('should be aliased', 1, function() { strictEqual(_.object, _.zipObject); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).commit'); (function() { test('should execute the chained sequence and returns the wrapped result', 4, function() { if (!isNpm) { var array = [1], wrapped = _(array).push(2).push(3); deepEqual(array, [1]); var otherWrapper = wrapped.commit(); ok(otherWrapper instanceof _); deepEqual(otherWrapper.value(), [1, 2, 3]); deepEqual(wrapped.value(), [1, 2, 3, 2, 3]); } else { skipTest(4); } }); test('should track the `__chain__` value of a wrapper', 2, function() { if (!isNpm) { var wrapper = _([1]).chain().commit().first(); ok(wrapper instanceof _); strictEqual(wrapper.value(), 1); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).concat'); (function() { test('should return a new wrapped array', 3, function() { if (!isNpm) { var array = [1], wrapped = _(array).concat([2, 3]), actual = wrapped.value(); deepEqual(array, [1]); deepEqual(actual, [1, 2, 3]); notStrictEqual(actual, array); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).join'); (function() { var array = [1, 2, 3]; test('should return join all array elements into a string', 2, function() { if (!isNpm) { var wrapped = _(array); strictEqual(wrapped.join('.'), '1.2.3'); strictEqual(wrapped.value(), array); } else { skipTest(2); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_(array).chain().join('.') instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).plant'); (function() { test('should clone the chained sequence planting `value` as the wrapped value', 2, function() { if (!isNpm) { var array1 = [5, null, 3, null, 1], array2 = [10, null, 8, null, 6], wrapper1 = _(array1).thru(_.compact).map(square).takeRight(2).sort(), wrapper2 = wrapper1.plant(array2); deepEqual(wrapper2.value(), [36, 64]); deepEqual(wrapper1.value(), [1, 9]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).pop'); (function() { test('should remove elements from the end of `array`', 5, function() { if (!isNpm) { var array = [1, 2], wrapped = _(array); strictEqual(wrapped.pop(), 2); deepEqual(wrapped.value(), [1]); strictEqual(wrapped.pop(), 1); var actual = wrapped.value(); deepEqual(actual, []); strictEqual(actual, array); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).push'); (function() { test('should append elements to `array`', 2, function() { if (!isNpm) { var array = [1], wrapped = _(array).push(2, 3), actual = wrapped.value(); strictEqual(actual, array); deepEqual(actual, [1, 2, 3]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).replace'); (function() { test('should replace the matched pattern', 2, function() { if (!isNpm) { var wrapped = _('abcdef'); strictEqual(wrapped.replace('def', '123'), 'abc123'); strictEqual(wrapped.replace(/[bdf]/g, '-'), 'a-c-e-'); } else { skipTest(2); } }); test('should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { ok(_('abc').chain().replace('b', '_') instanceof _); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).reverse'); (function() { test('should return the wrapped reversed `array`', 3, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array).reverse(), actual = wrapped.value(); ok(wrapped instanceof _); strictEqual(actual, array); deepEqual(actual, [3, 2, 1]); } else { skipTest(3); } }); test('should work in a lazy chain sequence', 1, function() { if (!isNpm) { var actual = _([1, 2, 3, null]).map(_.identity).reverse().value(); deepEqual(actual, [null, 3, 2, 1]); } else { skipTest(); } }); test('should be lazy when in a lazy chain sequence', 2, function() { if (!isNpm) { var spy = { 'toString': function() { throw new Error('spy was revealed'); } }; try { var wrapped = _(['a', spy]).map(String).reverse(), actual = wrapped.last(); } catch(e) {} ok(wrapped instanceof _); strictEqual(actual, 'a'); } else { skipTest(2); } }); test('should work in a hybrid chain sequence', 4, function() { if (!isNpm) { var array = [1, 2, 3, null]; _.each(['map', 'filter'], function(methodName) { var actual = _(array)[methodName](_.identity).thru(_.compact).reverse().value(); deepEqual(actual, [3, 2, 1]); actual = _(array).thru(_.compact)[methodName](_.identity).pull(1).push(4).reverse().value(); deepEqual(actual, [4, 3, 2]); }); } else { skipTest(4); } }); test('should track the `__chain__` value of a wrapper', 2, function() { if (!isNpm) { var wrapper = _([1, 2, 3]).chain().reverse().first(); ok(wrapper instanceof _); strictEqual(wrapper.value(), 3); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).shift'); (function() { test('should remove elements from the front of `array`', 5, function() { if (!isNpm) { var array = [1, 2], wrapped = _(array); strictEqual(wrapped.shift(), 1); deepEqual(wrapped.value(), [2]); strictEqual(wrapped.shift(), 2); var actual = wrapped.value(); deepEqual(actual, []); strictEqual(actual, array); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).slice'); (function() { test('should return a slice of `array`', 3, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array).slice(0, 2), actual = wrapped.value(); deepEqual(array, [1, 2, 3]); deepEqual(actual, [1, 2]); notStrictEqual(actual, array); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).sort'); (function() { test('should return the wrapped sorted `array`', 2, function() { if (!isNpm) { var array = [3, 1, 2], wrapped = _(array).sort(), actual = wrapped.value(); strictEqual(actual, array); deepEqual(actual, [1, 2, 3]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).splice'); (function() { test('should support removing and inserting elements', 5, function() { if (!isNpm) { var array = [1, 2], wrapped = _(array); deepEqual(wrapped.splice(1, 1, 3).value(), [2]); deepEqual(wrapped.value(), [1, 3]); deepEqual(wrapped.splice(0, 2).value(), [1, 3]); var actual = wrapped.value(); deepEqual(actual, []); strictEqual(actual, array); } else { skipTest(5); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).split'); (function() { test('should support string split', 2, function() { if (!isNpm) { var wrapped = _('abcde'); deepEqual(wrapped.split('c').value(), ['ab', 'de']); deepEqual(wrapped.split(/[bd]/).value(), ['a', 'c', 'e']); } else { skipTest(2); } }); test('should allow mixed string and array prototype methods', 1, function() { if (!isNpm) { var wrapped = _('abc'); strictEqual(wrapped.split('b').join(','), 'a,c'); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).unshift'); (function() { test('should prepend elements to `array`', 2, function() { if (!isNpm) { var array = [3], wrapped = _(array).unshift(1, 2), actual = wrapped.value(); strictEqual(actual, array); deepEqual(actual, [1, 2, 3]); } else { skipTest(2); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('splice objects'); _.each(['pop', 'shift', 'splice'], function(methodName) { test('`_(...).' + methodName + '` should remove the value at index `0` when length is `0` (test in IE 8 compatibility mode)', 2, function() { if (!isNpm) { var wrapped = _({ '0': 1, 'length': 1 }); if (methodName == 'splice') { wrapped.splice(0, 1).value(); } else { wrapped[methodName](); } deepEqual(wrapped.keys().value(), ['length']); strictEqual(wrapped.first(), undefined); } else { skipTest(2); } }); }); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).toString'); (function() { test('should return the `toString` result of the wrapped value', 1, function() { if (!isNpm) { var wrapped = _([1, 2, 3]); strictEqual(String(wrapped), '1,2,3'); } else { skipTest(); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...).value'); (function() { test('should execute the chained sequence and extract the unwrapped value', 4, function() { if (!isNpm) { var array = [1], wrapped = _(array).push(2).push(3); deepEqual(array, [1]); deepEqual(wrapped.value(), [1, 2, 3]); deepEqual(wrapped.value(), [1, 2, 3, 2, 3]); deepEqual(array, [1, 2, 3, 2, 3]); } else { skipTest(4); } }); test('should return the `valueOf` result of the wrapped value', 1, function() { if (!isNpm) { var wrapped = _(123); strictEqual(Number(wrapped), 123); } else { skipTest(); } }); test('should stringify the wrapped value when used by `JSON.stringify`', 1, function() { if (!isNpm && JSON) { var wrapped = _([1, 2, 3]); strictEqual(JSON.stringify(wrapped), '[1,2,3]'); } else { skipTest(); } }); test('should be aliased', 3, function() { if (!isNpm) { var expected = _.prototype.value; strictEqual(_.prototype.run, expected); strictEqual(_.prototype.toJSON, expected); strictEqual(_.prototype.valueOf, expected); } else { skipTest(3); } }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...) methods that return the wrapped modified array'); (function() { var funcs = [ 'push', 'reverse', 'sort', 'unshift' ]; _.each(funcs, function(methodName) { test('`_(...).' + methodName + '` should return a new wrapper', 2, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array), actual = wrapped[methodName](); ok(actual instanceof _); notStrictEqual(actual, wrapped); } else { skipTest(2); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...) methods that return new wrapped values'); (function() { var funcs = [ 'concat', 'slice', 'splice' ]; _.each(funcs, function(methodName) { test('`_(...).' + methodName + '` should return a new wrapped value', 2, function() { if (!isNpm) { var array = [1, 2, 3], wrapped = _(array), actual = wrapped[methodName](); ok(actual instanceof _); notStrictEqual(actual, wrapped); } else { skipTest(2); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash(...) methods that return unwrapped values'); (function() { var funcs = [ 'clone', 'contains', 'every', 'find', 'first', 'has', 'isArguments', 'isArray', 'isBoolean', 'isDate', 'isElement', 'isEmpty', 'isEqual', 'isError', 'isFinite', 'isFunction', 'isNaN', 'isNull', 'isNumber', 'isObject', 'isPlainObject', 'isRegExp', 'isString', 'isUndefined', 'join', 'last', 'max', 'min', 'parseInt', 'pop', 'shift', 'sum', 'random', 'reduce', 'reduceRight', 'some' ]; _.each(funcs, function(methodName) { test('`_(...).' + methodName + '` should return an unwrapped value when implicitly chaining', 1, function() { if (!isNpm) { var array = [1, 2, 3], actual = _(array)[methodName](); ok(!(actual instanceof _)); } else { skipTest(); } }); test('`_(...).' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() { if (!isNpm) { var array = [1, 2, 3], actual = _(array).chain()[methodName](); ok(actual instanceof _); } else { skipTest(); } }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('"Arrays" category methods'); (function() { var args = arguments, array = [1, 2, 3, 4, 5, 6]; test('should work with `arguments` objects', 29, function() { function message(methodName) { return '`_.' + methodName + '` should work with `arguments` objects'; } deepEqual(_.difference(args, [null]), [1, [3], 5], message('difference')); deepEqual(_.difference(array, args), [2, 3, 4, 6], '_.difference should work with `arguments` objects as secondary arguments'); deepEqual(_.union(args, [null, 6]), [1, null, [3], 5, 6], message('union')); deepEqual(_.union(array, args), array.concat([null, [3]]), '_.union should work with `arguments` objects as secondary arguments'); deepEqual(_.compact(args), [1, [3], 5], message('compact')); deepEqual(_.drop(args, 3), [null, 5], message('drop')); deepEqual(_.dropRight(args, 3), [1, null], message('dropRight')); deepEqual(_.dropRightWhile(args,_.identity), [1, null, [3], null], message('dropRightWhile')); deepEqual(_.dropWhile(args,_.identity), [ null, [3], null, 5], message('dropWhile')); deepEqual(_.findIndex(args, _.identity), 0, message('findIndex')); deepEqual(_.findLastIndex(args, _.identity), 4, message('findLastIndex')); deepEqual(_.first(args), 1, message('first')); deepEqual(_.flatten(args), [1, null, 3, null, 5], message('flatten')); deepEqual(_.indexOf(args, 5), 4, message('indexOf')); deepEqual(_.initial(args), [1, null, [3], null], message('initial')); deepEqual(_.intersection(args, [1]), [1], message('intersection')); deepEqual(_.last(args), 5, message('last')); deepEqual(_.lastIndexOf(args, 1), 0, message('lastIndexOf')); deepEqual(_.rest(args, 4), [null, [3], null, 5], message('rest')); deepEqual(_.sortedIndex(args, 6), 5, message('sortedIndex')); deepEqual(_.take(args, 2), [1, null], message('take')); deepEqual(_.takeRight(args, 1), [5], message('takeRight')); deepEqual(_.takeRightWhile(args, _.identity), [5], message('takeRightWhile')); deepEqual(_.takeWhile(args, _.identity), [1], message('takeWhile')); deepEqual(_.uniq(args), [1, null, [3], 5], message('uniq')); deepEqual(_.without(args, null), [1, [3], 5], message('without')); deepEqual(_.zip(args, args), [[1, 1], [null, null], [[3], [3]], [null, null], [5, 5]], message('zip')); if (_.support.argsTag && _.support.argsObject && !_.support.nonEnumArgs) { _.pull(args, null); deepEqual([args[0], args[1], args[2]], [1, [3], 5], message('pull')); _.remove(args, function(value) { return typeof value == 'number'; }); ok(args.length === 1 && _.isEqual(args[0], [3]), message('remove')); } else { skipTest(2); } }); test('should accept falsey primary arguments', 4, function() { function message(methodName) { return '`_.' + methodName + '` should accept falsey primary arguments'; } deepEqual(_.difference(null, array), [], message('difference')); deepEqual(_.intersection(null, array), array, message('intersection')); deepEqual(_.union(null, array), array, message('union')); deepEqual(_.xor(null, array), array, message('xor')); }); test('should accept falsey secondary arguments', 3, function() { function message(methodName) { return '`_.' + methodName + '` should accept falsey secondary arguments'; } deepEqual(_.difference(array, null), array, message('difference')); deepEqual(_.intersection(array, null), array, message('intersection')); deepEqual(_.union(array, null), array, message('union')); }); }(1, null, [3], null, 5)); /*--------------------------------------------------------------------------*/ QUnit.module('"Strings" category methods'); (function() { var stringMethods = [ 'camelCase', 'capitalize', 'escape', 'escapeRegExp', 'kebabCase', 'pad', 'padLeft', 'padRight', 'repeat', 'snakeCase', 'trim', 'trimLeft', 'trimRight', 'trunc', 'unescape' ]; _.each(stringMethods, function(methodName) { var func = _[methodName]; test('`_.' + methodName + '` should return an empty string when provided `null`, `undefined`, or empty string', 3, function() { strictEqual(func(null), ''); strictEqual(func(undefined), ''); strictEqual(func(''), ''); }); }); }()); /*--------------------------------------------------------------------------*/ QUnit.module('lodash methods'); (function() { var allMethods = _.reject(_.functions(_).sort(), function(methodName) { return _.startsWith(methodName, '_'); }); var checkFuncs = [ 'after', 'ary', 'before', 'bind', 'curry', 'curryRight', 'debounce', 'defer', 'delay', 'memoize', 'negate', 'once', 'partial', 'partialRight', 'rearg', 'spread', 'throttle' ]; var rejectFalsey = [ 'backflow', 'compose', 'flow', 'flowRight', 'tap', 'thru' ].concat(checkFuncs); var returnArrays = [ 'at', 'chunk', 'compact', 'difference', 'drop', 'filter', 'flatten', 'functions', 'initial', 'intersection', 'invoke', 'keys', 'map', 'pairs', 'pluck', 'pull', 'pullAt', 'range', 'reject', 'remove', 'rest', 'sample', 'shuffle', 'sortBy', 'sortByAll', 'sortByOrder', 'take', 'times', 'toArray', 'union', 'uniq', 'values', 'where', 'without', 'xor', 'zip' ]; var acceptFalsey = _.difference(allMethods, rejectFalsey); test('should accept falsey arguments', 213, function() { var emptyArrays = _.map(falsey, _.constant([])), isExposed = '_' in root, oldDash = root._; _.each(acceptFalsey, function(methodName) { var expected = emptyArrays, func = _[methodName], pass = true; var actual = _.map(falsey, function(value, index) { try { return index ? func(value) : func(); } catch(e) { pass = false; } }); if (methodName == 'noConflict') { if (isExposed) { root._ = oldDash; } else { delete root._; } } else if (methodName == 'pull') { expected = falsey; } if (_.includes(returnArrays, methodName) && methodName != 'sample') { deepEqual(actual, expected, '_.' + methodName + ' returns an array'); } ok(pass, '`_.' + methodName + '` accepts falsey arguments'); }); // Skip tests for missing methods of modularized builds. _.each(['chain', 'noConflict', 'runInContext'], function(methodName) { if (!_[methodName]) { skipTest(); } }); }); test('should return an array', 72, function() { var array = [1, 2, 3]; _.each(returnArrays, function(methodName) { var actual, func = _[methodName]; switch (methodName) { case 'invoke': actual = func(array, 'toFixed'); break; case 'sample': actual = func(array, 1); break; default: actual = func(array); } ok(_.isArray(actual), '_.' + methodName + ' returns an array'); var isPull = methodName == 'pull'; strictEqual(actual === array, isPull, '_.' + methodName + ' should ' + (isPull ? '' : 'not ') + 'return the provided array'); }); }); test('should throw an error for falsey arguments', 23, function() { _.each(rejectFalsey, function(methodName) { var expected = _.map(falsey, _.constant(true)), func = _[methodName]; var actual = _.map(falsey, function(value, index) { var pass = !index && /^(?:backflow|compose|flow(Right)?)$/.test(methodName); try { index ? func(value) : func(); } catch(e) { pass = _.includes(checkFuncs, methodName) ? e.message == FUNC_ERROR_TEXT : !pass; } return pass; }); deepEqual(actual, expected, '`_.' + methodName + '` rejects falsey arguments'); }); }); test('should handle `null` `thisArg` arguments', 44, function() { var expected = (function() { return this; }).call(null); var funcs = [ 'assign', 'clone', 'cloneDeep', 'countBy', 'dropWhile', 'dropRightWhile', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'groupBy', 'isEqual', 'map', 'mapValues', 'max', 'merge', 'min', 'omit', 'partition', 'pick', 'reduce', 'reduceRight', 'reject', 'remove', 'some', 'sortBy', 'sortedIndex', 'takeWhile', 'takeRightWhile', 'tap', 'times', 'transform', 'thru', 'uniq' ]; _.each(funcs, function(methodName) { var actual, array = ['a'], callback = function() { actual = this; }, func = _[methodName], message = '`_.' + methodName + '` handles `null` `thisArg` arguments'; if (func) { if (_.startsWith(methodName, 'reduce') || methodName == 'transform') { func(array, callback, 0, null); } else if (_.includes(['assign', 'merge'], methodName)) { func(array, array, callback, null); } else if (_.includes(['isEqual', 'sortedIndex'], methodName)) { func(array, 'a', callback, null); } else if (methodName == 'times') { func(1, callback, null); } else { func(array, callback, null); } strictEqual(actual, expected, message); } else { skipTest(); } }); }); test('should not contain minified method names (test production builds)', 1, function() { ok(_.every(_.functions(_), function(methodName) { return methodName.length > 2 || methodName === 'at'; })); }); }()); /*--------------------------------------------------------------------------*/ QUnit.config.asyncRetries = 10; QUnit.config.hidepassed = true; if (!document) { QUnit.config.noglobals = true; QUnit.load(); } }.call(this));
Add `NaN` tests for `_.indexOf` and `_.lastIndexOf` with a `fromIndex`.
test/test.js
Add `NaN` tests for `_.indexOf` and `_.lastIndexOf` with a `fromIndex`.
<ide><path>est/test.js <ide> QUnit.module('indexOf methods'); <ide> <ide> _.each(['indexOf', 'lastIndexOf'], function(methodName) { <del> var func = _[methodName]; <add> var func = _[methodName], <add> isIndexOf = methodName == 'indexOf'; <ide> <ide> test('`_.' + methodName + '` should accept a falsey `array` argument', 1, function() { <ide> var expected = _.map(falsey, _.constant(-1)); <ide> strictEqual(func(array, 0, true), -1); <ide> }); <ide> <del> test('`_.' + methodName + '` should match `NaN`', 2, function() { <del> strictEqual(func([1, NaN, 3], NaN), 1); <del> strictEqual(func([1, 3, NaN], NaN, true), 2); <add> test('`_.' + methodName + '` should match `NaN`', 4, function() { <add> var array = [1, NaN, 3, NaN, 5, NaN]; <add> strictEqual(func(array, NaN), isIndexOf ? 1 : 5); <add> strictEqual(func(array, NaN, 2), isIndexOf ? 3 : 1); <add> strictEqual(func(array, NaN, -2), isIndexOf ? 5 : 3); <add> strictEqual(func([1, 2, NaN, NaN], NaN, true), isIndexOf ? 2 : 3); <ide> }); <ide> <ide> test('`_.' + methodName + '` should match `-0` as `0`', 1, function() {
Java
apache-2.0
1c6e3ae247c5ea819b5c7b7d6bb78690d24e62f7
0
facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.ViewParent; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import androidx.collection.SparseArrayCompat; import com.facebook.litho.Transition.TransitionUnit; import com.facebook.litho.animation.AnimatedProperties; import com.facebook.litho.animation.AnimatedProperty; import com.facebook.litho.animation.AnimatedPropertyNode; import com.facebook.litho.animation.AnimationBinding; import com.facebook.litho.animation.AnimationBindingListener; import com.facebook.litho.animation.ParallelBinding; import com.facebook.litho.animation.PropertyAnimation; import com.facebook.litho.animation.PropertyHandle; import com.facebook.litho.animation.Resolver; import com.facebook.rendercore.Host; import com.facebook.rendercore.RenderCoreSystrace; import com.facebook.rendercore.RootHost; import com.facebook.rendercore.transitions.TransitionsExtensionInput; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Handles animating transitions defined by ComponentSpec's onCreateTransition code. * * <p>USAGE FROM MOUNTSTATE * * <p>Unique per MountState instance. Called from MountState on mount calls to process the * transition keys and handles which transitions to run and when. * * <p>This class is tightly coupled to MountState. When creating new animations, the expected usage * of this class is: 1. {@link #setupTransitions} is called with the current and next {@link * TransitionsExtensionInput}. 2. {@link #isAnimating} and {@link #isDisappearing} can be called to * determine what is/will be animating 3. MountState updates the mount content for changing content. * 4. {@link #runTransitions} is called to restore initial states for the transition and run the new * animations. * * <p>Additionally, any time the {@link MountState} is re-used for a different component tree (e.g. * because it was recycled in a RecyclerView), {@link #reset} should be called to stop running all * existing animations. * * <p>TECHNICAL DETAILS * * <p>- Transition keys are 1-1 mapped to AnimationState - An {@link AnimationState} has many {@link * PropertyState}s (one for each property) - A {@link PropertyState} can have up to one animation. * * <p>An {@link AnimationState} keeps track of the current mount content object, as well as the * state of all animating properties ({@link PropertyState}s). A {@link PropertyState} keeps track * of a {@link AnimatedPropertyNode}, which has the current value of that property in the animation, * and up to one animation and end value. A reverse mapping from animation to property(s) being * animated is tracked in {@link #mAnimationsToPropertyHandles}. * * <p>Combined, these mean that at any point in time, we're able to tell what animation is animating * what property(s). Knowing this, we can properly resolve conflicting animations (animations on the * same property of the same mount content). * * <p>Another important note: sometimes we need to keep values set on properties before or after * animations. * * <p>Examples include an appearFrom value for an animation that starts later in a sequence of * animations (in that case, the appearFrom value must be immediately applied even if the animation * isn't starting until later), and keeping disappearTo values even after an animation has completed * (e.g., consider animating alpha and X position: if the alpha animation finishes first, we still * need to keep the final value until we can remove the animating content). * * <p>As such, our rule is that we should have a {@link PropertyState} on the corresponding {@link * AnimationState} for any property that has a value no necessarily reflected by the most up to date * {@link LayoutOutput} for that transition key in the most recent {@link * TransitionsExtensionInput}. Put another way, animation doesn't always imply movement, but a * temporary change from a canonical {@link LayoutOutput}. */ public class TransitionManager { /** * Whether a piece of content identified by a transition key is appearing, disappearing, or just * possibly changing some properties. */ @IntDef({ChangeType.APPEARED, ChangeType.CHANGED, ChangeType.DISAPPEARED, ChangeType.UNSET}) @Retention(RetentionPolicy.SOURCE) @interface ChangeType { int UNSET = -1; int APPEARED = 0; int CHANGED = 1; int DISAPPEARED = 2; } /** A listener that will be invoked when a mount content has stopped animating. */ public interface OnAnimationCompleteListener<T> { void onAnimationComplete(TransitionId transitionId); void onAnimationUnitComplete(PropertyHandle propertyHandle, T data); } /** The animation state of a single property (e.g. X, Y, ALPHA) on a piece of mount content. */ private static class PropertyState { /** * The {@link AnimatedPropertyNode} for this property: it contains the current animated value * and a way to set a new value. */ public AnimatedPropertyNode animatedPropertyNode; /** The animation, if any, that is currently running on this property. */ public AnimationBinding animation; /** If there's an {@link #animation}, the target value it's animating to. */ public Float targetValue; /** The last mounted value of this property. */ public Float lastMountedValue; /** How many animations are waiting to finish for this property. */ public int numPendingAnimations; } /** * Animation state of a given mount content. Holds everything we currently know about an animating * transition key, such as whether it's appearing, disappearing, or changing, as well as * information about any animating properties on this mount content. */ private static class AnimationState { /** * The states for all the properties of this mount content that have an animated value (e.g. a * value that isn't necessarily their mounted value). */ public final Map<AnimatedProperty, PropertyState> propertyStates = new HashMap<>(); /** * The current mount content for this animation state, if it's mounted, null otherwise. This * mount content can change over time. */ public @Nullable OutputUnitsAffinityGroup<Object> mountContentGroup; /** * Whether the last {@link TransitionsExtensionInput} diff that had this content in it showed * the content appearing, disappearing or changing. */ public int changeType = ChangeType.UNSET; /** While calculating animations, the current (before) LayoutOutput. */ public @Nullable OutputUnitsAffinityGroup<AnimatableItem> currentLayoutOutputsGroup; /** While calculating animations, the next (after) LayoutOutput. */ public @Nullable OutputUnitsAffinityGroup<AnimatableItem> nextLayoutOutputsGroup; /** * Whether this transition key was seen in the last transition, either in the current or next * {@link TransitionsExtensionInput}. */ public boolean seenInLastTransition = false; /** * If this animation is running but the layout changed and it appeared/diappeared without an * equivalent Transition specified, we need to interrupt this animation. */ public boolean shouldFinishUndeclaredAnimation; public boolean hasDisappearingAnimation; } private final Map<AnimationBinding, List<PropertyHandle>> mAnimationsToPropertyHandles = new HashMap<>(); private final TransitionIdMap<AnimationState> mAnimationStates = new TransitionIdMap<>(); private final SparseArrayCompat<String> mTraceNames = new SparseArrayCompat<>(); private final Map<PropertyHandle, Float> mInitialStatesToRestore = new HashMap<>(); private final ArrayList<AnimationBinding> mRunningRootAnimations = new ArrayList<>(); private final TransitionsAnimationBindingListener mAnimationBindingListener = new TransitionsAnimationBindingListener(); private final RootAnimationListener mRootAnimationListener = new RootAnimationListener(); private final TransitionsResolver mResolver = new TransitionsResolver(); private final OnAnimationCompleteListener mOnAnimationCompleteListener; private AnimationBinding mRootAnimationToRun; private final String mDebugTag; private final Map<Host, Boolean> mOverriddenClipChildrenFlags = new LinkedHashMap<>(); public TransitionManager( OnAnimationCompleteListener onAnimationCompleteListener, @Nullable final String debugTag) { mOnAnimationCompleteListener = onAnimationCompleteListener; mDebugTag = debugTag; } void setupTransitions( TransitionsExtensionInput currentInput, TransitionsExtensionInput nextInput, Transition rootTransition) { final Map<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> nextTransitionIds = nextInput.getTransitionIdMapping(); final Map<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> currentTransitionIds = currentInput == null ? null : currentInput.getTransitionIdMapping(); setupTransitions(currentTransitionIds, nextTransitionIds, rootTransition); } /** * Creates (but doesn't start) the animations for the next transition based on the current and * next layout states. * * <p>After this is called, MountState can use {@link #isAnimating} and {@link #isDisappearing} to * check whether certain mount content will animate, commit the layout changes, and then call * {@link #runTransitions} to restore the initial states and run the animations. */ void setupTransitions( @Nullable Map<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> currentTransitionIds, @Nullable Map<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> nextTransitionIds, Transition rootTransition) { RenderCoreSystrace.beginSection("TransitionManager.setupTransition"); for (AnimationState animationState : mAnimationStates.values()) { animationState.seenInLastTransition = false; } if (currentTransitionIds == null) { for (Map.Entry<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> nextTransitionId : nextTransitionIds.entrySet()) { TransitionId transitionId = nextTransitionId.getKey(); final OutputUnitsAffinityGroup<AnimatableItem> nextLayoutOutputsGroup = nextTransitionId.getValue(); recordLayoutOutputsGroupDiff(transitionId, null, nextLayoutOutputsGroup); } } else { final HashSet<TransitionId> seenInNewLayout = new HashSet<>(); for (TransitionId transitionId : nextTransitionIds.keySet()) { final boolean isAutogenerated = transitionId.mType == TransitionId.Type.AUTOGENERATED; final OutputUnitsAffinityGroup<AnimatableItem> nextLayoutOutputsGroup = nextTransitionIds.get(transitionId); final OutputUnitsAffinityGroup<AnimatableItem> currentLayoutOutputsGroup = currentTransitionIds.get(transitionId); if (nextLayoutOutputsGroup != null) { seenInNewLayout.add(transitionId); } else if (isAutogenerated) { // Only appearing animation would be possible, but there is no way to declare appearing // animation for autogenerated ids continue; } recordLayoutOutputsGroupDiff( transitionId, currentLayoutOutputsGroup, nextLayoutOutputsGroup); } for (TransitionId transitionId : currentTransitionIds.keySet()) { if (seenInNewLayout.contains(transitionId)) { // We either already processed this id or it's autogenerated and is not present in the // new layout, thus only disappearing animation would be possible, but there is no way to // declare disappearing animation for autogenerated ids continue; } recordLayoutOutputsGroupDiff(transitionId, currentTransitionIds.get(transitionId), null); } } createTransitionAnimations(rootTransition); // If we recorded any mount content diffs that didn't result in an animation being created for // that transition id, clean them up now. cleanupNonAnimatingAnimationStates(); RenderCoreSystrace.endSection(); } /** * This method will check for running transitions which do not exist after a layout change. * Therefore, they need to be interrupted and "finished". */ // TODO: This is only catching changes in appeared/disappeared items. We need to investigate items // which change without a change transition declared. Also the flag should probably belong // to the properties and not to the AnimationState. void finishUndeclaredTransitions() { for (AnimationState animationState : new ArrayList<>(mAnimationStates.values())) { if (animationState.shouldFinishUndeclaredAnimation) { animationState.shouldFinishUndeclaredAnimation = false; for (PropertyState propertyState : new ArrayList<>(animationState.propertyStates.values())) { final AnimationBinding animationBinding = propertyState.animation; if (animationBinding != null) { animationBinding.stop(); mAnimationBindingListener.finishAnimation(animationBinding); } } } } } /** * Called after {@link #setupTransitions} has been called and the new layout has been mounted. * This restores the state of the previous layout for content that will animate and then starts * the corresponding animations. */ void runTransitions() { RenderCoreSystrace.beginSection("runTransitions"); restoreInitialStates(); if (mDebugTag != null) { debugLogStartingAnimations(); } if (mRootAnimationToRun != null) { mRootAnimationToRun.addListener(mRootAnimationListener); mRootAnimationToRun.start(mResolver); mRootAnimationToRun = null; } RenderCoreSystrace.endSection(); } void removeMountContent(TransitionId transitionId, @OutputUnitType int type) { final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState == null) { return; } final OutputUnitsAffinityGroup<Object> mountContentGroup = animationState.mountContentGroup; if (mountContentGroup == null || mountContentGroup.get(type) == null) { return; } OutputUnitsAffinityGroup<Object> updatedMountContentGroup; if (mountContentGroup.size() > 1) { updatedMountContentGroup = new OutputUnitsAffinityGroup<>(mountContentGroup); updatedMountContentGroup.replace(type, null); } else { // The group is empty now, so just pass null updatedMountContentGroup = null; } setMountContentInner(transitionId, animationState, updatedMountContentGroup); } /** * Sets the mount content for a given key. This is used to initially set mount content, but also * to set content when content is incrementally mounted during an animation. */ void setMountContent( TransitionId transitionId, @Nullable OutputUnitsAffinityGroup<Object> mountContentGroup) { final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState != null) { setMountContentInner(transitionId, animationState, mountContentGroup); } } /** * After transitions have been setup with {@link #setupTransitions}, returns whether the given key * will be/is animating. */ boolean isAnimating(TransitionId transitionId) { return mAnimationStates.contains(transitionId); } /** * After transitions have been setup with {@link #setupTransitions}, returns whether the given key * is disappearing. */ boolean isDisappearing(TransitionId transitionId) { final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState == null) { return false; } return animationState.changeType == ChangeType.DISAPPEARED && animationState.hasDisappearingAnimation; } /** To be called when a MountState is recycled for a new component tree. Clears all animations. */ void reset() { for (TransitionId transitionId : mAnimationStates.ids()) { final AnimationState animationState = mAnimationStates.get(transitionId); setMountContentInner(transitionId, animationState, null); clearLayoutOutputs(animationState); } mAnimationStates.clear(); mTraceNames.clear(); // Clear these so that stopping animations below doesn't cause us to trigger any useless // cleanup. mAnimationsToPropertyHandles.clear(); // Calling stop will cause the animation to be removed from the set, so iterate in reverse // order. for (int i = mRunningRootAnimations.size() - 1; i >= 0; i--) { mRunningRootAnimations.get(i).stop(); } mRunningRootAnimations.clear(); mRootAnimationToRun = null; mOverriddenClipChildrenFlags.clear(); } /** * Called to record the current/next content for a transition key. * * @param currentLayoutOutputsGroup the current group of LayoutOutputs for this key, or null if * the key is appearing * @param nextLayoutOutputsGroup the new group of LayoutOutput for this key, or null if the key is * disappearing */ private void recordLayoutOutputsGroupDiff( TransitionId transitionId, OutputUnitsAffinityGroup<AnimatableItem> currentLayoutOutputsGroup, OutputUnitsAffinityGroup<AnimatableItem> nextLayoutOutputsGroup) { AnimationState animationState = mAnimationStates.get(transitionId); if (animationState == null) { animationState = new AnimationState(); mAnimationStates.put(transitionId, animationState); } if (currentLayoutOutputsGroup == null && nextLayoutOutputsGroup == null) { throw new RuntimeException("Both current and next LayoutOutput groups were null!"); } if (currentLayoutOutputsGroup == null && nextLayoutOutputsGroup != null) { animationState.changeType = ChangeType.APPEARED; } else if (currentLayoutOutputsGroup != null && nextLayoutOutputsGroup != null) { animationState.changeType = ChangeType.CHANGED; } else { if ((animationState.changeType == ChangeType.APPEARED || animationState.changeType == ChangeType.CHANGED) && !animationState.hasDisappearingAnimation) { animationState.shouldFinishUndeclaredAnimation = true; } animationState.changeType = ChangeType.DISAPPEARED; } animationState.currentLayoutOutputsGroup = currentLayoutOutputsGroup; animationState.nextLayoutOutputsGroup = nextLayoutOutputsGroup; recordLastMountedValues(animationState); animationState.seenInLastTransition = true; if (mDebugTag != null) { Log.d( mDebugTag, "Saw transition id " + transitionId + " which is " + changeTypeToString(animationState.changeType)); } } private void recordLastMountedValues(AnimationState animationState) { final AnimatableItem animatableItem = animationState.nextLayoutOutputsGroup != null ? animationState.nextLayoutOutputsGroup.getMostSignificantUnit() : null; // The values for all members of the group should be the same, thus we'll be collected from the // most significant one for (AnimatedProperty property : animationState.propertyStates.keySet()) { final PropertyState propertyState = animationState.propertyStates.get(property); if (animatableItem == null) { propertyState.lastMountedValue = null; } else { propertyState.lastMountedValue = property.get(animatableItem); } } } @Nullable static Transition getRootTransition(List<Transition> allTransitions) { if (allTransitions.isEmpty()) { return null; } if (allTransitions.size() == 1) { return allTransitions.get(0); } return new ParallelTransitionSet(allTransitions); } private void createTransitionAnimations(Transition rootTransition) { mRootAnimationToRun = createAnimationsForTransition(rootTransition); } private AnimationBinding createAnimationsForTransition(Transition transition) { if (transition instanceof TransitionUnit) { return createAnimationsForTransitionUnit((TransitionUnit) transition); } else if (transition instanceof TransitionSet) { return createAnimationsForTransitionSet((TransitionSet) transition); } else { throw new RuntimeException("Unhandled Transition type: " + transition); } } private @Nullable AnimationBinding createAnimationsForTransitionSet(TransitionSet transitionSet) { final ArrayList<Transition> children = transitionSet.getChildren(); final ArrayList<AnimationBinding> createdAnimations = new ArrayList<>(); for (int i = 0, size = children.size(); i < size; i++) { final AnimationBinding animation = createAnimationsForTransition(children.get(i)); if (animation != null) { createdAnimations.add(animation); } } if (createdAnimations.isEmpty()) { return null; } return transitionSet.createAnimation(createdAnimations); } private @Nullable AnimationBinding createAnimationsForTransitionUnit(TransitionUnit transition) { final Transition.AnimationTarget animationTarget = transition.getAnimationTarget(); final ArrayList<AnimationBinding> createdAnimations = new ArrayList<>(); switch (animationTarget.componentTarget.componentTargetType) { case ALL: case AUTO_LAYOUT: createAnimationsForTransitionUnitAllKeys(transition, createdAnimations); break; case LOCAL_KEY: String key = (String) animationTarget.componentTarget.componentTargetExtraData; TransitionId transitionId = mAnimationStates.getScopedId(transition.getOwnerKey(), key); createAnimationsForTransitionUnit(transition, transitionId, createdAnimations); break; case LOCAL_KEY_SET: String[] keys = (String[]) animationTarget.componentTarget.componentTargetExtraData; final String ownerKey = transition.getOwnerKey(); for (int j = 0; j < keys.length; j++) { transitionId = mAnimationStates.getScopedId(ownerKey, keys[j]); if (transitionId != null) { createAnimationsForTransitionUnit(transition, transitionId, createdAnimations); } } break; case GLOBAL_KEY: key = (String) animationTarget.componentTarget.componentTargetExtraData; transitionId = mAnimationStates.getGlobalId(key); createAnimationsForTransitionUnit(transition, transitionId, createdAnimations); break; case GLOBAL_KEY_SET: keys = (String[]) animationTarget.componentTarget.componentTargetExtraData; for (int j = 0; j < keys.length; j++) { transitionId = mAnimationStates.getGlobalId(keys[j]); if (transitionId != null) { createAnimationsForTransitionUnit(transition, transitionId, createdAnimations); } } break; } if (createdAnimations.isEmpty()) { return null; } if (createdAnimations.size() == 1) { return createdAnimations.get(0); } return new ParallelBinding(0, createdAnimations); } private void createAnimationsForTransitionUnitAllKeys( TransitionUnit transition, ArrayList<AnimationBinding> outList) { for (TransitionId transitionId : mAnimationStates.ids()) { final AnimationState animationState = mAnimationStates.get(transitionId); if (!animationState.seenInLastTransition) { continue; } createAnimationsForTransitionUnit(transition, transitionId, outList); } } private void createAnimationsForTransitionUnit( TransitionUnit transition, TransitionId transitionId, ArrayList<AnimationBinding> outList) { final Transition.AnimationTarget animationTarget = transition.getAnimationTarget(); switch (animationTarget.propertyTarget.propertyTargetType) { case AUTO_LAYOUT: for (int i = 0; i < AnimatedProperties.AUTO_LAYOUT_PROPERTIES.length; i++) { final AnimationBinding createdAnimation = maybeCreateAnimation( transition, transitionId, AnimatedProperties.AUTO_LAYOUT_PROPERTIES[i]); if (createdAnimation != null) { outList.add(createdAnimation); } } break; case SET: final AnimatedProperty[] properties = (AnimatedProperty[]) animationTarget.propertyTarget.propertyTargetExtraData; for (int i = 0; i < properties.length; i++) { final AnimationBinding createdAnimation = maybeCreateAnimation(transition, transitionId, properties[i]); if (createdAnimation != null) { outList.add(createdAnimation); } } break; case SINGLE: final AnimationBinding createdAnimation = maybeCreateAnimation( transition, transitionId, (AnimatedProperty) animationTarget.propertyTarget.propertyTargetExtraData); if (createdAnimation != null) { outList.add(createdAnimation); } break; } } private @Nullable AnimationBinding maybeCreateAnimation( TransitionUnit transition, TransitionId transitionId, AnimatedProperty property) { final AnimationState animationState = mAnimationStates.get(transitionId); if (mDebugTag != null) { Log.d( mDebugTag, "Calculating transitions for " + transitionId + "#" + property.getName() + ":"); } if (animationState == null || (animationState.currentLayoutOutputsGroup == null && animationState.nextLayoutOutputsGroup == null)) { if (mDebugTag != null) { Log.d(mDebugTag, " - this transitionId was not seen in the before/after layout state"); } return null; } animationState.hasDisappearingAnimation = transition.hasDisappearAnimation() || animationState.hasDisappearingAnimation; final int changeType = animationState.changeType; final String changeTypeString = changeTypeToString(animationState.changeType); if ((changeType == ChangeType.APPEARED && !transition.hasAppearAnimation()) || (changeType == ChangeType.DISAPPEARED && !transition.hasDisappearAnimation())) { // Interrupt running transitions after a layout change, without the new changeType defined. animationState.shouldFinishUndeclaredAnimation = true; if (mDebugTag != null) { Log.d(mDebugTag, " - did not find matching transition for change type " + changeTypeString); } return null; } final PropertyState existingState = animationState.propertyStates.get(property); final PropertyHandle propertyHandle = new PropertyHandle(transitionId, property); final float startValue; if (existingState != null) { startValue = existingState.animatedPropertyNode.getValue(); } else { if (animationState.changeType != ChangeType.APPEARED) { startValue = property.get(animationState.currentLayoutOutputsGroup.getMostSignificantUnit()); } else { startValue = transition.getAppearFrom().resolve(mResolver, propertyHandle); } } final float endValue; if (animationState.changeType != ChangeType.DISAPPEARED) { endValue = property.get(animationState.nextLayoutOutputsGroup.getMostSignificantUnit()); } else { endValue = transition.getDisappearTo().resolve(mResolver, propertyHandle); } // Don't replace new animations in two cases: 1) we're already animating that property to // the same end value or 2) the start and end values are already the same if (existingState != null && existingState.targetValue != null) { if (endValue == existingState.targetValue) { if (mDebugTag != null) { Log.d(mDebugTag, " - property is already animating to this end value: " + endValue); } return null; } } else if (startValue == endValue) { if (mDebugTag != null) { Log.d( mDebugTag, " - the start and end values were the same: " + startValue + " = " + endValue); } return null; } if (mDebugTag != null) { Log.d(mDebugTag, " - created animation"); } final AnimationBinding animation = transition.createAnimation(propertyHandle, endValue); animation.addListener(mAnimationBindingListener); // We add this transition handler to the binding animation.setTag(transition.getTransitionEndHandler()); PropertyState propertyState = existingState; if (propertyState == null) { propertyState = new PropertyState(); propertyState.animatedPropertyNode = new AnimatedPropertyNode(animationState.mountContentGroup, property); animationState.propertyStates.put(property, propertyState); } propertyState.animatedPropertyNode.setValue(startValue); propertyState.numPendingAnimations++; // Currently, all supported animations can only animate one property at a time, but we think // this will change in the future so we maintain a set here. final List<PropertyHandle> animatedPropertyHandles = new ArrayList<>(); animatedPropertyHandles.add(propertyHandle); mAnimationsToPropertyHandles.put(animation, animatedPropertyHandles); mInitialStatesToRestore.put(propertyHandle, startValue); if (!TextUtils.isEmpty(transition.getTraceName())) { mTraceNames.put(animation.hashCode(), transition.getTraceName()); } return animation; } private void restoreInitialStates() { for (PropertyHandle propertyHandle : mInitialStatesToRestore.keySet()) { final float value = mInitialStatesToRestore.get(propertyHandle); final TransitionId transitionId = propertyHandle.getTransitionId(); final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState.mountContentGroup != null) { setPropertyValue(propertyHandle.getProperty(), value, animationState.mountContentGroup); } } mInitialStatesToRestore.clear(); } private void setMountContentInner( TransitionId transitionId, AnimationState animationState, @Nullable OutputUnitsAffinityGroup<Object> newMountContentGroup) { // If the mount content changes, this means this transition key will be rendered with a // different mount content (View or Drawable) than it was during the last mount, so we need to // migrate animation state from the old mount content to the new one. final OutputUnitsAffinityGroup<Object> mountContentGroup = animationState.mountContentGroup; if ((mountContentGroup == null && newMountContentGroup == null) || (mountContentGroup != null && mountContentGroup.equals(newMountContentGroup))) { return; } if (mDebugTag != null) { Log.d(mDebugTag, "Setting mount content for " + transitionId + " to " + newMountContentGroup); } final Map<AnimatedProperty, PropertyState> animatingProperties = animationState.propertyStates; if (animationState.mountContentGroup != null) { for (AnimatedProperty animatedProperty : animatingProperties.keySet()) { resetProperty(animatedProperty, animationState.mountContentGroup); } recursivelySetChildClippingForGroup(animationState.mountContentGroup, true); } for (PropertyState propertyState : animatingProperties.values()) { propertyState.animatedPropertyNode.setMountContentGroup(newMountContentGroup); } if (newMountContentGroup != null) { recursivelySetChildClippingForGroup(newMountContentGroup, false); } animationState.mountContentGroup = newMountContentGroup; } private void recursivelySetChildClippingForGroup( OutputUnitsAffinityGroup<Object> mountContentGroup, boolean clipChildren) { // We only need to set clipping to view containers (OutputUnitType.HOST) recursivelySetChildClipping(mountContentGroup.get(OutputUnitType.HOST), clipChildren); } /** * Set the clipChildren properties to all Views in the same tree branch from the given one, up to * the top LithoView. * * <p>TODO(17934271): Handle the case where two+ animations with different lifespans share the * same parent, in which case we shouldn't unset clipping until the last item is done animating. */ private void recursivelySetChildClipping(Object mountContent, boolean clipChildren) { if (!(mountContent instanceof View)) { return; } recursivelySetChildClippingForView((View) mountContent, clipChildren); } private void recursivelySetChildClippingForView(View view, boolean clipChildren) { if (view instanceof Host && !(view instanceof RootHost)) { if (clipChildren) { // When clip children is true we want to restore what the view had before. // It can happen that two different animations run on the same parent, in that case we won't // find the view in the map so it is ignored. if (mOverriddenClipChildrenFlags.containsKey(view)) { ((Host) view).setClipChildren(mOverriddenClipChildrenFlags.remove(view)); } } else { // In this case we save the actual configuration and then we set clip to false. mOverriddenClipChildrenFlags.put((Host) view, ((Host) view).getClipChildren()); ((Host) view).setClipChildren(false); } } final ViewParent parent = view.getParent(); if (parent instanceof Host && !(parent instanceof RootHost)) { recursivelySetChildClippingForView((View) parent, clipChildren); } } /** * Removes any AnimationStates that were created in {@link #recordLayoutOutputsGroupDiff} but * never resulted in an animation being created. */ private void cleanupNonAnimatingAnimationStates() { final Set<TransitionId> toRemove = new HashSet<>(); for (TransitionId transitionId : mAnimationStates.ids()) { final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState.propertyStates.isEmpty()) { setMountContentInner(transitionId, animationState, null); clearLayoutOutputs(animationState); toRemove.add(transitionId); } } for (TransitionId transitionId : toRemove) { mAnimationStates.remove(transitionId); } } private void debugLogStartingAnimations() { if (mDebugTag == null) { throw new RuntimeException("Trying to debug log animations without debug flag set!"); } Log.d(mDebugTag, "Starting animations:"); // TODO(t20726089): Restore introspection of animations } private static String changeTypeToString(int changeType) { switch (changeType) { case ChangeType.APPEARED: return "APPEARED"; case ChangeType.CHANGED: return "CHANGED"; case ChangeType.DISAPPEARED: return "DISAPPEARED"; case ChangeType.UNSET: return "UNSET"; default: throw new RuntimeException("Unknown changeType: " + changeType); } } private static void clearLayoutOutputs(AnimationState animationState) { if (animationState.currentLayoutOutputsGroup != null) { animationState.currentLayoutOutputsGroup = null; } if (animationState.nextLayoutOutputsGroup != null) { animationState.nextLayoutOutputsGroup = null; } } private static float getPropertyValue( AnimatedProperty property, OutputUnitsAffinityGroup<AnimatableItem> mountContentGroup) { return property.get(mountContentGroup.getMostSignificantUnit()); } private static void setPropertyValue( AnimatedProperty property, float value, OutputUnitsAffinityGroup<Object> mountContentGroup) { for (int i = 0, size = mountContentGroup.size(); i < size; i++) { property.set(mountContentGroup.getAt(i), value); } } private static void resetProperty( AnimatedProperty property, OutputUnitsAffinityGroup<Object> mountContentGroup) { for (int i = 0, size = mountContentGroup.size(); i < size; i++) { property.reset(mountContentGroup.getAt(i)); } } private class TransitionsAnimationBindingListener implements AnimationBindingListener { private final ArrayList<PropertyAnimation> mTempPropertyAnimations = new ArrayList<>(); @Override public void onScheduledToStartLater(AnimationBinding binding) { updateAnimationStates(binding); } @Override public void onWillStart(AnimationBinding binding) { updateAnimationStates(binding); final String traceName = mTraceNames.get(binding.hashCode()); RenderCoreSystrace.beginAsyncSection(traceName, binding.hashCode()); } @Override public void onFinish(AnimationBinding binding) { final List<PropertyHandle> keys = mAnimationsToPropertyHandles.get(binding); if (keys != null && mOnAnimationCompleteListener != null) { // We loop through all the properties that were animated by this animation for (PropertyHandle propertyHandle : keys) { mOnAnimationCompleteListener.onAnimationUnitComplete(propertyHandle, binding.getTag()); } } finishAnimation(binding); } @Override public void onCanceledBeforeStart(AnimationBinding binding) { finishAnimation(binding); } @Override public boolean shouldStart(AnimationBinding binding) { binding.collectTransitioningProperties(mTempPropertyAnimations); boolean shouldStart = true; // Make sure that all animating properties will animate to a valid position for (int i = 0, size = mTempPropertyAnimations.size(); i < size; i++) { final PropertyAnimation propertyAnimation = mTempPropertyAnimations.get(i); final TransitionId transitionId = propertyAnimation.getTransitionId(); final @Nullable AnimationState animationState = mAnimationStates.get(transitionId); final @Nullable PropertyState propertyState = (animationState != null) ? animationState.propertyStates.get(propertyAnimation.getProperty()) : null; if (mDebugTag != null) { Log.d( mDebugTag, "Trying to start animation on " + transitionId + "#" + propertyAnimation.getProperty().getName() + " to " + propertyAnimation.getTargetValue() + ":"); } if (propertyState == null) { if (mDebugTag != null) { Log.d( mDebugTag, " - Canceling animation, transitionId not found in the AnimationState." + " It has been probably cancelled already."); } shouldStart = false; } if (shouldStart && propertyState.lastMountedValue != null && propertyState.lastMountedValue != propertyAnimation.getTargetValue()) { if (mDebugTag != null) { Log.d( mDebugTag, " - Canceling animation, last mounted value does not equal animation target: " + propertyState.lastMountedValue + " != " + propertyAnimation.getTargetValue()); } shouldStart = false; } } mTempPropertyAnimations.clear(); return shouldStart; } private void updateAnimationStates(AnimationBinding binding) { binding.collectTransitioningProperties(mTempPropertyAnimations); for (int i = 0, size = mTempPropertyAnimations.size(); i < size; i++) { final PropertyAnimation propertyAnimation = mTempPropertyAnimations.get(i); final TransitionId transitionId = propertyAnimation.getTransitionId(); final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState == null) { // This can happen when unmounting all items on running animations. continue; } final PropertyState propertyState = animationState.propertyStates.get(propertyAnimation.getProperty()); propertyState.targetValue = propertyAnimation.getTargetValue(); propertyState.animation = binding; } mTempPropertyAnimations.clear(); } private void finishAnimation(AnimationBinding binding) { final List<PropertyHandle> keys = mAnimationsToPropertyHandles.remove(binding); if (keys == null) { return; } // When an animation finishes, we want to go through all the mount contents it was animating // and see if it was the last active animation. If it was, we know that item is no longer // animating and we can release the animation state. for (int i = 0, size = keys.size(); i < size; i++) { final PropertyHandle propertyHandle = keys.get(i); final TransitionId transitionId = propertyHandle.getTransitionId(); final AnimationState animationState = mAnimationStates.get(transitionId); final AnimatedProperty property = propertyHandle.getProperty(); final boolean isDisappearAnimation = animationState.changeType == ChangeType.DISAPPEARED; // Disappearing animations are treated differently because we want to keep their animated // value up until the point that all animations have finished and we can remove the // disappearing content (disappearing items disappear to a value that is based on a provided // disappearTo value and not a LayoutOutput, so we can't regenerate it). // // For non-disappearing content, we know the end value is already reflected by the // LayoutOutput we transitioned to, so we don't need to persist an animated value. final boolean didFinish; if (isDisappearAnimation) { final PropertyState propertyState = animationState.propertyStates.get(property); if (propertyState == null) { throw new RuntimeException( "Some animation bookkeeping is wrong: tried to remove an animation from the list " + "of active animations, but it wasn't there."); } propertyState.numPendingAnimations--; didFinish = areAllDisappearingAnimationsFinished(animationState); if (didFinish && animationState.mountContentGroup != null) { for (AnimatedProperty animatedProperty : animationState.propertyStates.keySet()) { resetProperty(animatedProperty, animationState.mountContentGroup); } } } else { final PropertyState propertyState = animationState.propertyStates.get(property); if (propertyState == null) { throw new RuntimeException( "Some animation bookkeeping is wrong: tried to remove an animation from the list " + "of active animations, but it wasn't there."); } propertyState.numPendingAnimations--; if (propertyState.numPendingAnimations > 0) { didFinish = false; } else { animationState.propertyStates.remove(property); didFinish = animationState.propertyStates.isEmpty(); if (animationState.mountContentGroup != null) { final float value = getPropertyValue(property, animationState.nextLayoutOutputsGroup); setPropertyValue(property, value, animationState.mountContentGroup); } } } if (didFinish) { if (mDebugTag != null) { Log.d(mDebugTag, "Finished all animations for transition id " + transitionId); } if (animationState.mountContentGroup != null) { recursivelySetChildClippingForGroup(animationState.mountContentGroup, true); } if (mOnAnimationCompleteListener != null) { mOnAnimationCompleteListener.onAnimationComplete(transitionId); } mAnimationStates.remove(transitionId); clearLayoutOutputs(animationState); } } final String traceName = mTraceNames.get(binding.hashCode()); if (!TextUtils.isEmpty(traceName)) { RenderCoreSystrace.endAsyncSection(traceName, binding.hashCode()); mTraceNames.delete(binding.hashCode()); } } private boolean areAllDisappearingAnimationsFinished(AnimationState animationState) { if (animationState.changeType != ChangeType.DISAPPEARED) { throw new RuntimeException("This should only be checked for disappearing animations"); } for (PropertyState propertyState : animationState.propertyStates.values()) { if (propertyState.numPendingAnimations > 0) { return false; } } return true; } } private class TransitionsResolver implements Resolver { @Override public float getCurrentState(PropertyHandle propertyHandle) { final AnimatedProperty animatedProperty = propertyHandle.getProperty(); final TransitionId transitionId = propertyHandle.getTransitionId(); final AnimationState animationState = mAnimationStates.get(transitionId); final PropertyState propertyState = animationState.propertyStates.get(animatedProperty); // Use the current animating value if it exists... if (propertyState != null) { return propertyState.animatedPropertyNode.getValue(); } // ...otherwise, if it's a property not being animated (e.g., the width when content appears // from a width offset), get the property from the LayoutOutput. final OutputUnitsAffinityGroup<AnimatableItem> layoutOutputGroupToCheck = animationState.changeType == ChangeType.APPEARED ? animationState.nextLayoutOutputsGroup : animationState.currentLayoutOutputsGroup; if (layoutOutputGroupToCheck == null) { throw new RuntimeException("Both LayoutOutputs were null!"); } return animatedProperty.get(layoutOutputGroupToCheck.getMostSignificantUnit()); } @Override public AnimatedPropertyNode getAnimatedPropertyNode(PropertyHandle propertyHandle) { final TransitionId transitionId = propertyHandle.getTransitionId(); final AnimationState state = mAnimationStates.get(transitionId); final PropertyState propertyState = state.propertyStates.get(propertyHandle.getProperty()); return propertyState.animatedPropertyNode; } } private class RootAnimationListener implements AnimationBindingListener { @Override public void onScheduledToStartLater(AnimationBinding binding) {} @Override public void onWillStart(AnimationBinding binding) { mRunningRootAnimations.add(binding); } @Override public void onFinish(AnimationBinding binding) { mRunningRootAnimations.remove(binding); } @Override public void onCanceledBeforeStart(AnimationBinding binding) { mRunningRootAnimations.remove(binding); } @Override public boolean shouldStart(AnimationBinding binding) { return true; } } }
litho-core/src/main/java/com/facebook/litho/TransitionManager.java
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.ViewParent; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import androidx.collection.SparseArrayCompat; import com.facebook.litho.Transition.TransitionUnit; import com.facebook.litho.animation.AnimatedProperties; import com.facebook.litho.animation.AnimatedProperty; import com.facebook.litho.animation.AnimatedPropertyNode; import com.facebook.litho.animation.AnimationBinding; import com.facebook.litho.animation.AnimationBindingListener; import com.facebook.litho.animation.ParallelBinding; import com.facebook.litho.animation.PropertyAnimation; import com.facebook.litho.animation.PropertyHandle; import com.facebook.litho.animation.Resolver; import com.facebook.rendercore.Host; import com.facebook.rendercore.RenderCoreSystrace; import com.facebook.rendercore.RootHost; import com.facebook.rendercore.transitions.TransitionsExtensionInput; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Handles animating transitions defined by ComponentSpec's onCreateTransition code. * * <p>USAGE FROM MOUNTSTATE * * <p>Unique per MountState instance. Called from MountState on mount calls to process the * transition keys and handles which transitions to run and when. * * <p>This class is tightly coupled to MountState. When creating new animations, the expected usage * of this class is: 1. {@link #setupTransitions} is called with the current and next {@link * TransitionsExtensionInput}. 2. {@link #isAnimating} and {@link #isDisappearing} can be called to * determine what is/will be animating 3. MountState updates the mount content for changing content. * 4. {@link #runTransitions} is called to restore initial states for the transition and run the new * animations. * * <p>Additionally, any time the {@link MountState} is re-used for a different component tree (e.g. * because it was recycled in a RecyclerView), {@link #reset} should be called to stop running all * existing animations. * * <p>TECHNICAL DETAILS * * <p>- Transition keys are 1-1 mapped to AnimationState - An {@link AnimationState} has many {@link * PropertyState}s (one for each property) - A {@link PropertyState} can have up to one animation. * * <p>An {@link AnimationState} keeps track of the current mount content object, as well as the * state of all animating properties ({@link PropertyState}s). A {@link PropertyState} keeps track * of a {@link AnimatedPropertyNode}, which has the current value of that property in the animation, * and up to one animation and end value. A reverse mapping from animation to property(s) being * animated is tracked in {@link #mAnimationsToPropertyHandles}. * * <p>Combined, these mean that at any point in time, we're able to tell what animation is animating * what property(s). Knowing this, we can properly resolve conflicting animations (animations on the * same property of the same mount content). * * <p>Another important note: sometimes we need to keep values set on properties before or after * animations. * * <p>Examples include an appearFrom value for an animation that starts later in a sequence of * animations (in that case, the appearFrom value must be immediately applied even if the animation * isn't starting until later), and keeping disappearTo values even after an animation has completed * (e.g., consider animating alpha and X position: if the alpha animation finishes first, we still * need to keep the final value until we can remove the animating content). * * <p>As such, our rule is that we should have a {@link PropertyState} on the corresponding {@link * AnimationState} for any property that has a value no necessarily reflected by the most up to date * {@link LayoutOutput} for that transition key in the most recent {@link * TransitionsExtensionInput}. Put another way, animation doesn't always imply movement, but a * temporary change from a canonical {@link LayoutOutput}. */ public class TransitionManager { /** * Whether a piece of content identified by a transition key is appearing, disappearing, or just * possibly changing some properties. */ @IntDef({ChangeType.APPEARED, ChangeType.CHANGED, ChangeType.DISAPPEARED, ChangeType.UNSET}) @Retention(RetentionPolicy.SOURCE) @interface ChangeType { int UNSET = -1; int APPEARED = 0; int CHANGED = 1; int DISAPPEARED = 2; } /** A listener that will be invoked when a mount content has stopped animating. */ public interface OnAnimationCompleteListener<T> { void onAnimationComplete(TransitionId transitionId); void onAnimationUnitComplete(PropertyHandle propertyHandle, T data); } /** The animation state of a single property (e.g. X, Y, ALPHA) on a piece of mount content. */ private static class PropertyState { /** * The {@link AnimatedPropertyNode} for this property: it contains the current animated value * and a way to set a new value. */ public AnimatedPropertyNode animatedPropertyNode; /** The animation, if any, that is currently running on this property. */ public AnimationBinding animation; /** If there's an {@link #animation}, the target value it's animating to. */ public Float targetValue; /** The last mounted value of this property. */ public Float lastMountedValue; /** How many animations are waiting to finish for this property. */ public int numPendingAnimations; } /** * Animation state of a given mount content. Holds everything we currently know about an animating * transition key, such as whether it's appearing, disappearing, or changing, as well as * information about any animating properties on this mount content. */ private static class AnimationState { /** * The states for all the properties of this mount content that have an animated value (e.g. a * value that isn't necessarily their mounted value). */ public final Map<AnimatedProperty, PropertyState> propertyStates = new HashMap<>(); /** * The current mount content for this animation state, if it's mounted, null otherwise. This * mount content can change over time. */ public @Nullable OutputUnitsAffinityGroup<Object> mountContentGroup; /** * Whether the last {@link TransitionsExtensionInput} diff that had this content in it showed * the content appearing, disappearing or changing. */ public int changeType = ChangeType.UNSET; /** While calculating animations, the current (before) LayoutOutput. */ public @Nullable OutputUnitsAffinityGroup<AnimatableItem> currentLayoutOutputsGroup; /** While calculating animations, the next (after) LayoutOutput. */ public @Nullable OutputUnitsAffinityGroup<AnimatableItem> nextLayoutOutputsGroup; /** * Whether this transition key was seen in the last transition, either in the current or next * {@link TransitionsExtensionInput}. */ public boolean seenInLastTransition = false; /** * If this animation is running but the layout changed and it appeared/diappeared without an * equivalent Transition specified, we need to interrupt this animation. */ public boolean shouldFinishUndeclaredAnimation; public boolean hasDisappearingAnimation; } private final Map<AnimationBinding, List<PropertyHandle>> mAnimationsToPropertyHandles = new HashMap<>(); private final TransitionIdMap<AnimationState> mAnimationStates = new TransitionIdMap<>(); private final SparseArrayCompat<String> mTraceNames = new SparseArrayCompat<>(); private final Map<PropertyHandle, Float> mInitialStatesToRestore = new HashMap<>(); private final ArrayList<AnimationBinding> mRunningRootAnimations = new ArrayList<>(); private final TransitionsAnimationBindingListener mAnimationBindingListener = new TransitionsAnimationBindingListener(); private final RootAnimationListener mRootAnimationListener = new RootAnimationListener(); private final TransitionsResolver mResolver = new TransitionsResolver(); private final OnAnimationCompleteListener mOnAnimationCompleteListener; private AnimationBinding mRootAnimationToRun; private final String mDebugTag; private final Map<Host, Boolean> mOverriddenClipChildrenFlags = new LinkedHashMap<>(); public TransitionManager( OnAnimationCompleteListener onAnimationCompleteListener, @Nullable final String debugTag) { mOnAnimationCompleteListener = onAnimationCompleteListener; mDebugTag = debugTag; } void setupTransitions( TransitionsExtensionInput currentInput, TransitionsExtensionInput nextInput, Transition rootTransition) { final Map<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> nextTransitionIds = nextInput.getTransitionIdMapping(); final Map<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> currentTransitionIds = currentInput == null ? null : currentInput.getTransitionIdMapping(); setupTransitions(currentTransitionIds, nextTransitionIds, rootTransition); } /** * Creates (but doesn't start) the animations for the next transition based on the current and * next layout states. * * <p>After this is called, MountState can use {@link #isAnimating} and {@link #isDisappearing} to * check whether certain mount content will animate, commit the layout changes, and then call * {@link #runTransitions} to restore the initial states and run the animations. */ void setupTransitions( @Nullable Map<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> currentTransitionIds, @Nullable Map<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> nextTransitionIds, Transition rootTransition) { RenderCoreSystrace.beginSection("TransitionManager.setupTransition"); for (AnimationState animationState : mAnimationStates.values()) { animationState.seenInLastTransition = false; } if (currentTransitionIds == null) { for (Map.Entry<TransitionId, OutputUnitsAffinityGroup<AnimatableItem>> nextTransitionId : nextTransitionIds.entrySet()) { TransitionId transitionId = nextTransitionId.getKey(); final OutputUnitsAffinityGroup<AnimatableItem> nextLayoutOutputsGroup = nextTransitionId.getValue(); recordLayoutOutputsGroupDiff(transitionId, null, nextLayoutOutputsGroup); } } else { final HashSet<TransitionId> seenInNewLayout = new HashSet<>(); for (TransitionId transitionId : nextTransitionIds.keySet()) { final boolean isAutogenerated = transitionId.mType == TransitionId.Type.AUTOGENERATED; final OutputUnitsAffinityGroup<AnimatableItem> nextLayoutOutputsGroup = nextTransitionIds.get(transitionId); final OutputUnitsAffinityGroup<AnimatableItem> currentLayoutOutputsGroup = currentTransitionIds.get(transitionId); if (nextLayoutOutputsGroup != null) { seenInNewLayout.add(transitionId); } else if (isAutogenerated) { // Only appearing animation would be possible, but there is no way to declare appearing // animation for autogenerated ids continue; } recordLayoutOutputsGroupDiff( transitionId, currentLayoutOutputsGroup, nextLayoutOutputsGroup); } for (TransitionId transitionId : currentTransitionIds.keySet()) { if (seenInNewLayout.contains(transitionId)) { // We either already processed this id or it's autogenerated and is not present in the // new layout, thus only disappearing animation would be possible, but there is no way to // declare disappearing animation for autogenerated ids continue; } recordLayoutOutputsGroupDiff(transitionId, currentTransitionIds.get(transitionId), null); } } createTransitionAnimations(rootTransition); // If we recorded any mount content diffs that didn't result in an animation being created for // that transition id, clean them up now. cleanupNonAnimatingAnimationStates(); RenderCoreSystrace.endSection(); } /** * This method will check for running transitions which do not exist after a layout change. * Therefore, they need to be interrupted and "finished". */ // TODO: This is only catching changes in appeared/disappeared items. We need to investigate items // which change without a change transition declared. Also the flag should probably belong // to the properties and not to the AnimationState. void finishUndeclaredTransitions() { for (AnimationState animationState : new ArrayList<>(mAnimationStates.values())) { if (animationState.shouldFinishUndeclaredAnimation) { animationState.shouldFinishUndeclaredAnimation = false; for (PropertyState propertyState : new ArrayList<>(animationState.propertyStates.values())) { final AnimationBinding animationBinding = propertyState.animation; if (animationBinding != null) { animationBinding.stop(); mAnimationBindingListener.finishAnimation(animationBinding); } } } } } /** * Called after {@link #setupTransitions} has been called and the new layout has been mounted. * This restores the state of the previous layout for content that will animate and then starts * the corresponding animations. */ void runTransitions() { RenderCoreSystrace.beginSection("runTransitions"); restoreInitialStates(); if (mDebugTag != null) { debugLogStartingAnimations(); } if (mRootAnimationToRun != null) { mRootAnimationToRun.addListener(mRootAnimationListener); mRootAnimationToRun.start(mResolver); mRootAnimationToRun = null; } RenderCoreSystrace.endSection(); } void removeMountContent(TransitionId transitionId, @OutputUnitType int type) { final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState == null) { return; } final OutputUnitsAffinityGroup<Object> mountContentGroup = animationState.mountContentGroup; if (mountContentGroup == null || mountContentGroup.get(type) == null) { return; } OutputUnitsAffinityGroup<Object> updatedMountContentGroup; if (mountContentGroup.size() > 1) { updatedMountContentGroup = new OutputUnitsAffinityGroup<>(mountContentGroup); updatedMountContentGroup.replace(type, null); } else { // The group is empty now, so just pass null updatedMountContentGroup = null; } setMountContentInner(transitionId, animationState, updatedMountContentGroup); } /** * Sets the mount content for a given key. This is used to initially set mount content, but also * to set content when content is incrementally mounted during an animation. */ void setMountContent( TransitionId transitionId, @Nullable OutputUnitsAffinityGroup<Object> mountContentGroup) { final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState != null) { setMountContentInner(transitionId, animationState, mountContentGroup); } } /** * After transitions have been setup with {@link #setupTransitions}, returns whether the given key * will be/is animating. */ boolean isAnimating(TransitionId transitionId) { return mAnimationStates.contains(transitionId); } /** * After transitions have been setup with {@link #setupTransitions}, returns whether the given key * is disappearing. */ boolean isDisappearing(TransitionId transitionId) { final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState == null) { return false; } return animationState.changeType == ChangeType.DISAPPEARED && animationState.hasDisappearingAnimation; } /** To be called when a MountState is recycled for a new component tree. Clears all animations. */ void reset() { for (TransitionId transitionId : mAnimationStates.ids()) { final AnimationState animationState = mAnimationStates.get(transitionId); setMountContentInner(transitionId, animationState, null); clearLayoutOutputs(animationState); } mAnimationStates.clear(); mTraceNames.clear(); // Clear these so that stopping animations below doesn't cause us to trigger any useless // cleanup. mAnimationsToPropertyHandles.clear(); // Calling stop will cause the animation to be removed from the set, so iterate in reverse // order. for (int i = mRunningRootAnimations.size() - 1; i >= 0; i--) { mRunningRootAnimations.get(i).stop(); } mRunningRootAnimations.clear(); mRootAnimationToRun = null; mOverriddenClipChildrenFlags.clear(); } /** * Called to record the current/next content for a transition key. * * @param currentLayoutOutputsGroup the current group of LayoutOutputs for this key, or null if * the key is appearing * @param nextLayoutOutputsGroup the new group of LayoutOutput for this key, or null if the key is * disappearing */ private void recordLayoutOutputsGroupDiff( TransitionId transitionId, OutputUnitsAffinityGroup<AnimatableItem> currentLayoutOutputsGroup, OutputUnitsAffinityGroup<AnimatableItem> nextLayoutOutputsGroup) { AnimationState animationState = mAnimationStates.get(transitionId); if (animationState == null) { animationState = new AnimationState(); mAnimationStates.put(transitionId, animationState); } if (currentLayoutOutputsGroup == null && nextLayoutOutputsGroup == null) { throw new RuntimeException("Both current and next LayoutOutput groups were null!"); } if (currentLayoutOutputsGroup == null && nextLayoutOutputsGroup != null) { animationState.changeType = ChangeType.APPEARED; } else if (currentLayoutOutputsGroup != null && nextLayoutOutputsGroup != null) { animationState.changeType = ChangeType.CHANGED; } else { if ((animationState.changeType == ChangeType.APPEARED || animationState.changeType == ChangeType.CHANGED) && !animationState.hasDisappearingAnimation) { animationState.shouldFinishUndeclaredAnimation = true; } animationState.changeType = ChangeType.DISAPPEARED; } animationState.currentLayoutOutputsGroup = currentLayoutOutputsGroup; animationState.nextLayoutOutputsGroup = nextLayoutOutputsGroup; recordLastMountedValues(animationState); animationState.seenInLastTransition = true; if (mDebugTag != null) { Log.d( mDebugTag, "Saw transition id " + transitionId + " which is " + changeTypeToString(animationState.changeType)); } } private void recordLastMountedValues(AnimationState animationState) { final AnimatableItem animatableItem = animationState.nextLayoutOutputsGroup != null ? animationState.nextLayoutOutputsGroup.getMostSignificantUnit() : null; // The values for all members of the group should be the same, thus we'll be collected from the // most significant one for (AnimatedProperty property : animationState.propertyStates.keySet()) { final PropertyState propertyState = animationState.propertyStates.get(property); if (animatableItem == null) { propertyState.lastMountedValue = null; } else { propertyState.lastMountedValue = property.get(animatableItem); } } } @Nullable static Transition getRootTransition(List<Transition> allTransitions) { if (allTransitions.isEmpty()) { return null; } if (allTransitions.size() == 1) { return allTransitions.get(0); } return new ParallelTransitionSet(allTransitions); } private void createTransitionAnimations(Transition rootTransition) { mRootAnimationToRun = createAnimationsForTransition(rootTransition); } private AnimationBinding createAnimationsForTransition(Transition transition) { if (transition instanceof TransitionUnit) { return createAnimationsForTransitionUnit((TransitionUnit) transition); } else if (transition instanceof TransitionSet) { return createAnimationsForTransitionSet((TransitionSet) transition); } else { throw new RuntimeException("Unhandled Transition type: " + transition); } } private @Nullable AnimationBinding createAnimationsForTransitionSet(TransitionSet transitionSet) { final ArrayList<Transition> children = transitionSet.getChildren(); final ArrayList<AnimationBinding> createdAnimations = new ArrayList<>(); for (int i = 0, size = children.size(); i < size; i++) { final AnimationBinding animation = createAnimationsForTransition(children.get(i)); if (animation != null) { createdAnimations.add(animation); } } if (createdAnimations.isEmpty()) { return null; } return transitionSet.createAnimation(createdAnimations); } private @Nullable AnimationBinding createAnimationsForTransitionUnit(TransitionUnit transition) { final Transition.AnimationTarget animationTarget = transition.getAnimationTarget(); final ArrayList<AnimationBinding> createdAnimations = new ArrayList<>(); switch (animationTarget.componentTarget.componentTargetType) { case ALL: case AUTO_LAYOUT: createAnimationsForTransitionUnitAllKeys(transition, createdAnimations); break; case LOCAL_KEY: String key = (String) animationTarget.componentTarget.componentTargetExtraData; TransitionId transitionId = mAnimationStates.getScopedId(transition.getOwnerKey(), key); createAnimationsForTransitionUnit(transition, transitionId, createdAnimations); break; case LOCAL_KEY_SET: String[] keys = (String[]) animationTarget.componentTarget.componentTargetExtraData; final String ownerKey = transition.getOwnerKey(); for (int j = 0; j < keys.length; j++) { transitionId = mAnimationStates.getScopedId(ownerKey, keys[j]); if (transitionId != null) { createAnimationsForTransitionUnit(transition, transitionId, createdAnimations); } } break; case GLOBAL_KEY: key = (String) animationTarget.componentTarget.componentTargetExtraData; transitionId = mAnimationStates.getGlobalId(key); createAnimationsForTransitionUnit(transition, transitionId, createdAnimations); break; case GLOBAL_KEY_SET: keys = (String[]) animationTarget.componentTarget.componentTargetExtraData; for (int j = 0; j < keys.length; j++) { transitionId = mAnimationStates.getGlobalId(keys[j]); if (transitionId != null) { createAnimationsForTransitionUnit(transition, transitionId, createdAnimations); } } break; } if (createdAnimations.isEmpty()) { return null; } if (createdAnimations.size() == 1) { return createdAnimations.get(0); } return new ParallelBinding(0, createdAnimations); } private void createAnimationsForTransitionUnitAllKeys( TransitionUnit transition, ArrayList<AnimationBinding> outList) { for (TransitionId transitionId : mAnimationStates.ids()) { final AnimationState animationState = mAnimationStates.get(transitionId); if (!animationState.seenInLastTransition) { continue; } createAnimationsForTransitionUnit(transition, transitionId, outList); } } private void createAnimationsForTransitionUnit( TransitionUnit transition, TransitionId transitionId, ArrayList<AnimationBinding> outList) { final Transition.AnimationTarget animationTarget = transition.getAnimationTarget(); switch (animationTarget.propertyTarget.propertyTargetType) { case AUTO_LAYOUT: for (int i = 0; i < AnimatedProperties.AUTO_LAYOUT_PROPERTIES.length; i++) { final AnimationBinding createdAnimation = maybeCreateAnimation( transition, transitionId, AnimatedProperties.AUTO_LAYOUT_PROPERTIES[i]); if (createdAnimation != null) { outList.add(createdAnimation); } } break; case SET: final AnimatedProperty[] properties = (AnimatedProperty[]) animationTarget.propertyTarget.propertyTargetExtraData; for (int i = 0; i < properties.length; i++) { final AnimationBinding createdAnimation = maybeCreateAnimation(transition, transitionId, properties[i]); if (createdAnimation != null) { outList.add(createdAnimation); } } break; case SINGLE: final AnimationBinding createdAnimation = maybeCreateAnimation( transition, transitionId, (AnimatedProperty) animationTarget.propertyTarget.propertyTargetExtraData); if (createdAnimation != null) { outList.add(createdAnimation); } break; } } private @Nullable AnimationBinding maybeCreateAnimation( TransitionUnit transition, TransitionId transitionId, AnimatedProperty property) { final AnimationState animationState = mAnimationStates.get(transitionId); if (mDebugTag != null) { Log.d( mDebugTag, "Calculating transitions for " + transitionId + "#" + property.getName() + ":"); } if (animationState == null || (animationState.currentLayoutOutputsGroup == null && animationState.nextLayoutOutputsGroup == null)) { if (mDebugTag != null) { Log.d(mDebugTag, " - this transitionId was not seen in the before/after layout state"); } return null; } animationState.hasDisappearingAnimation = transition.hasDisappearAnimation() || animationState.hasDisappearingAnimation; final int changeType = animationState.changeType; final String changeTypeString = changeTypeToString(animationState.changeType); if ((changeType == ChangeType.APPEARED && !transition.hasAppearAnimation()) || (changeType == ChangeType.DISAPPEARED && !transition.hasDisappearAnimation())) { // Interrupt running transitions after a layout change, without the new changeType defined. animationState.shouldFinishUndeclaredAnimation = true; if (mDebugTag != null) { Log.d(mDebugTag, " - did not find matching transition for change type " + changeTypeString); } return null; } final PropertyState existingState = animationState.propertyStates.get(property); final PropertyHandle propertyHandle = new PropertyHandle(transitionId, property); final float startValue; if (existingState != null) { startValue = existingState.animatedPropertyNode.getValue(); } else { if (animationState.changeType != ChangeType.APPEARED) { startValue = property.get(animationState.currentLayoutOutputsGroup.getMostSignificantUnit()); } else { startValue = transition.getAppearFrom().resolve(mResolver, propertyHandle); } } final float endValue; if (animationState.changeType != ChangeType.DISAPPEARED) { endValue = property.get(animationState.nextLayoutOutputsGroup.getMostSignificantUnit()); } else { endValue = transition.getDisappearTo().resolve(mResolver, propertyHandle); } // Don't replace new animations in two cases: 1) we're already animating that property to // the same end value or 2) the start and end values are already the same if (existingState != null && existingState.targetValue != null) { if (endValue == existingState.targetValue) { if (mDebugTag != null) { Log.d(mDebugTag, " - property is already animating to this end value: " + endValue); } return null; } } else if (startValue == endValue) { if (mDebugTag != null) { Log.d( mDebugTag, " - the start and end values were the same: " + startValue + " = " + endValue); } return null; } if (mDebugTag != null) { Log.d(mDebugTag, " - created animation"); } final AnimationBinding animation = transition.createAnimation(propertyHandle, endValue); animation.addListener(mAnimationBindingListener); // We add this transition handler to the binding animation.setTag(transition.getTransitionEndHandler()); PropertyState propertyState = existingState; if (propertyState == null) { propertyState = new PropertyState(); propertyState.animatedPropertyNode = new AnimatedPropertyNode(animationState.mountContentGroup, property); animationState.propertyStates.put(property, propertyState); } propertyState.animatedPropertyNode.setValue(startValue); propertyState.numPendingAnimations++; // Currently, all supported animations can only animate one property at a time, but we think // this will change in the future so we maintain a set here. final List<PropertyHandle> animatedPropertyHandles = new ArrayList<>(); animatedPropertyHandles.add(propertyHandle); mAnimationsToPropertyHandles.put(animation, animatedPropertyHandles); mInitialStatesToRestore.put(propertyHandle, startValue); if (!TextUtils.isEmpty(transition.getTraceName())) { mTraceNames.put(animation.hashCode(), transition.getTraceName()); } return animation; } private void restoreInitialStates() { for (PropertyHandle propertyHandle : mInitialStatesToRestore.keySet()) { final float value = mInitialStatesToRestore.get(propertyHandle); final TransitionId transitionId = propertyHandle.getTransitionId(); final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState.mountContentGroup != null) { setPropertyValue(propertyHandle.getProperty(), value, animationState.mountContentGroup); } } mInitialStatesToRestore.clear(); } private void setMountContentInner( TransitionId transitionId, AnimationState animationState, @Nullable OutputUnitsAffinityGroup<Object> newMountContentGroup) { // If the mount content changes, this means this transition key will be rendered with a // different mount content (View or Drawable) than it was during the last mount, so we need to // migrate animation state from the old mount content to the new one. final OutputUnitsAffinityGroup<Object> mountContentGroup = animationState.mountContentGroup; if ((mountContentGroup == null && newMountContentGroup == null) || (mountContentGroup != null && mountContentGroup.equals(newMountContentGroup))) { return; } if (mDebugTag != null) { Log.d(mDebugTag, "Setting mount content for " + transitionId + " to " + newMountContentGroup); } final Map<AnimatedProperty, PropertyState> animatingProperties = animationState.propertyStates; if (animationState.mountContentGroup != null) { for (AnimatedProperty animatedProperty : animatingProperties.keySet()) { resetProperty(animatedProperty, animationState.mountContentGroup); } recursivelySetChildClippingForGroup(animationState.mountContentGroup, true); } for (PropertyState propertyState : animatingProperties.values()) { propertyState.animatedPropertyNode.setMountContentGroup(newMountContentGroup); } if (newMountContentGroup != null) { recursivelySetChildClippingForGroup(newMountContentGroup, false); } animationState.mountContentGroup = newMountContentGroup; } private void recursivelySetChildClippingForGroup( OutputUnitsAffinityGroup<Object> mountContentGroup, boolean clipChildren) { // We only need to set clipping to view containers (OutputUnitType.HOST) recursivelySetChildClipping(mountContentGroup.get(OutputUnitType.HOST), clipChildren); } /** * Set the clipChildren properties to all Views in the same tree branch from the given one, up to * the top LithoView. * * <p>TODO(17934271): Handle the case where two+ animations with different lifespans share the * same parent, in which case we shouldn't unset clipping until the last item is done animating. */ private void recursivelySetChildClipping(Object mountContent, boolean clipChildren) { if (!(mountContent instanceof View)) { return; } recursivelySetChildClippingForView((View) mountContent, clipChildren); } private void recursivelySetChildClippingForView(View view, boolean clipChildren) { if (view instanceof Host && !(view instanceof RootHost)) { if (clipChildren) { // When clip children is true we want to restore what the view had before. // It can happen that two different animations run on the same parent, in that case we won't // find the view in the map so it is ignored. if (mOverriddenClipChildrenFlags.containsKey(view)) { ((Host) view).setClipChildren(mOverriddenClipChildrenFlags.remove(view)); } } else { // In this case we save the actual configuration and then we set clip to false. mOverriddenClipChildrenFlags.put((Host) view, ((Host) view).getClipChildren()); ((Host) view).setClipChildren(false); } } final ViewParent parent = view.getParent(); if (parent instanceof Host && !(parent instanceof RootHost)) { recursivelySetChildClippingForView((View) parent, clipChildren); } } /** * Removes any AnimationStates that were created in {@link #recordLayoutOutputsGroupDiff} but * never resulted in an animation being created. */ private void cleanupNonAnimatingAnimationStates() { final Set<TransitionId> toRemove = new HashSet<>(); for (TransitionId transitionId : mAnimationStates.ids()) { final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState.propertyStates.isEmpty()) { setMountContentInner(transitionId, animationState, null); clearLayoutOutputs(animationState); toRemove.add(transitionId); } } for (TransitionId transitionId : toRemove) { mAnimationStates.remove(transitionId); } } private void debugLogStartingAnimations() { if (mDebugTag == null) { throw new RuntimeException("Trying to debug log animations without debug flag set!"); } Log.d(mDebugTag, "Starting animations:"); // TODO(t20726089): Restore introspection of animations } private static String changeTypeToString(int changeType) { switch (changeType) { case ChangeType.APPEARED: return "APPEARED"; case ChangeType.CHANGED: return "CHANGED"; case ChangeType.DISAPPEARED: return "DISAPPEARED"; case ChangeType.UNSET: return "UNSET"; default: throw new RuntimeException("Unknown changeType: " + changeType); } } private static void clearLayoutOutputs(AnimationState animationState) { if (animationState.currentLayoutOutputsGroup != null) { animationState.currentLayoutOutputsGroup = null; } if (animationState.nextLayoutOutputsGroup != null) { animationState.nextLayoutOutputsGroup = null; } } private static float getPropertyValue( AnimatedProperty property, OutputUnitsAffinityGroup<AnimatableItem> mountContentGroup) { return property.get(mountContentGroup.getMostSignificantUnit()); } private static void setPropertyValue( AnimatedProperty property, float value, OutputUnitsAffinityGroup<Object> mountContentGroup) { for (int i = 0, size = mountContentGroup.size(); i < size; i++) { property.set(mountContentGroup.getAt(i), value); } } private static void resetProperty( AnimatedProperty property, OutputUnitsAffinityGroup<Object> mountContentGroup) { for (int i = 0, size = mountContentGroup.size(); i < size; i++) { property.reset(mountContentGroup.getAt(i)); } } private class TransitionsAnimationBindingListener implements AnimationBindingListener { private final ArrayList<PropertyAnimation> mTempPropertyAnimations = new ArrayList<>(); @Override public void onScheduledToStartLater(AnimationBinding binding) { updateAnimationStates(binding); } @Override public void onWillStart(AnimationBinding binding) { updateAnimationStates(binding); final String traceName = mTraceNames.get(binding.hashCode()); RenderCoreSystrace.beginAsyncSection(traceName, binding.hashCode()); } @Override public void onFinish(AnimationBinding binding) { final List<PropertyHandle> keys = mAnimationsToPropertyHandles.get(binding); if (keys != null && mOnAnimationCompleteListener != null) { // We loop through all the properties that were animated by this animation for (PropertyHandle propertyHandle : keys) { mOnAnimationCompleteListener.onAnimationUnitComplete(propertyHandle, binding.getTag()); } } finishAnimation(binding); } @Override public void onCanceledBeforeStart(AnimationBinding binding) { finishAnimation(binding); } @Override public boolean shouldStart(AnimationBinding binding) { binding.collectTransitioningProperties(mTempPropertyAnimations); boolean shouldStart = true; // Make sure that all animating properties will animate to a valid position for (int i = 0, size = mTempPropertyAnimations.size(); i < size; i++) { final PropertyAnimation propertyAnimation = mTempPropertyAnimations.get(i); final TransitionId transitionId = propertyAnimation.getTransitionId(); final @Nullable AnimationState animationState = mAnimationStates.get(transitionId); final @Nullable PropertyState propertyState = (animationState != null) ? animationState.propertyStates.get(propertyAnimation.getProperty()) : null; if (mDebugTag != null) { Log.d( mDebugTag, "Trying to start animation on " + transitionId + "#" + propertyAnimation.getProperty().getName() + " to " + propertyAnimation.getTargetValue() + ":"); } if (propertyState == null) { if (mDebugTag != null) { Log.d( mDebugTag, " - Canceling animation, transitionId not found in the AnimationState." + " It has been probably cancelled already."); } shouldStart = false; } if (shouldStart && propertyState.lastMountedValue != null && propertyState.lastMountedValue != propertyAnimation.getTargetValue()) { if (mDebugTag != null) { Log.d( mDebugTag, " - Canceling animation, last mounted value does not equal animation target: " + propertyState.lastMountedValue + " != " + propertyAnimation.getTargetValue()); } shouldStart = false; } } mTempPropertyAnimations.clear(); return shouldStart; } private void updateAnimationStates(AnimationBinding binding) { binding.collectTransitioningProperties(mTempPropertyAnimations); for (int i = 0, size = mTempPropertyAnimations.size(); i < size; i++) { final PropertyAnimation propertyAnimation = mTempPropertyAnimations.get(i); final TransitionId transitionId = propertyAnimation.getTransitionId(); final AnimationState animationState = mAnimationStates.get(transitionId); if (animationState == null) { ComponentsReporter.emitMessage( ComponentsReporter.LogLevel.ERROR, "NoAnimationState", "No animation state for transitionId=" + transitionId); continue; } final PropertyState propertyState = animationState.propertyStates.get(propertyAnimation.getProperty()); propertyState.targetValue = propertyAnimation.getTargetValue(); propertyState.animation = binding; } mTempPropertyAnimations.clear(); } private void finishAnimation(AnimationBinding binding) { final List<PropertyHandle> keys = mAnimationsToPropertyHandles.remove(binding); if (keys == null) { return; } // When an animation finishes, we want to go through all the mount contents it was animating // and see if it was the last active animation. If it was, we know that item is no longer // animating and we can release the animation state. for (int i = 0, size = keys.size(); i < size; i++) { final PropertyHandle propertyHandle = keys.get(i); final TransitionId transitionId = propertyHandle.getTransitionId(); final AnimationState animationState = mAnimationStates.get(transitionId); final AnimatedProperty property = propertyHandle.getProperty(); final boolean isDisappearAnimation = animationState.changeType == ChangeType.DISAPPEARED; // Disappearing animations are treated differently because we want to keep their animated // value up until the point that all animations have finished and we can remove the // disappearing content (disappearing items disappear to a value that is based on a provided // disappearTo value and not a LayoutOutput, so we can't regenerate it). // // For non-disappearing content, we know the end value is already reflected by the // LayoutOutput we transitioned to, so we don't need to persist an animated value. final boolean didFinish; if (isDisappearAnimation) { final PropertyState propertyState = animationState.propertyStates.get(property); if (propertyState == null) { throw new RuntimeException( "Some animation bookkeeping is wrong: tried to remove an animation from the list " + "of active animations, but it wasn't there."); } propertyState.numPendingAnimations--; didFinish = areAllDisappearingAnimationsFinished(animationState); if (didFinish && animationState.mountContentGroup != null) { for (AnimatedProperty animatedProperty : animationState.propertyStates.keySet()) { resetProperty(animatedProperty, animationState.mountContentGroup); } } } else { final PropertyState propertyState = animationState.propertyStates.get(property); if (propertyState == null) { throw new RuntimeException( "Some animation bookkeeping is wrong: tried to remove an animation from the list " + "of active animations, but it wasn't there."); } propertyState.numPendingAnimations--; if (propertyState.numPendingAnimations > 0) { didFinish = false; } else { animationState.propertyStates.remove(property); didFinish = animationState.propertyStates.isEmpty(); if (animationState.mountContentGroup != null) { final float value = getPropertyValue(property, animationState.nextLayoutOutputsGroup); setPropertyValue(property, value, animationState.mountContentGroup); } } } if (didFinish) { if (mDebugTag != null) { Log.d(mDebugTag, "Finished all animations for transition id " + transitionId); } if (animationState.mountContentGroup != null) { recursivelySetChildClippingForGroup(animationState.mountContentGroup, true); } if (mOnAnimationCompleteListener != null) { mOnAnimationCompleteListener.onAnimationComplete(transitionId); } mAnimationStates.remove(transitionId); clearLayoutOutputs(animationState); } } final String traceName = mTraceNames.get(binding.hashCode()); if (!TextUtils.isEmpty(traceName)) { RenderCoreSystrace.endAsyncSection(traceName, binding.hashCode()); mTraceNames.delete(binding.hashCode()); } } private boolean areAllDisappearingAnimationsFinished(AnimationState animationState) { if (animationState.changeType != ChangeType.DISAPPEARED) { throw new RuntimeException("This should only be checked for disappearing animations"); } for (PropertyState propertyState : animationState.propertyStates.values()) { if (propertyState.numPendingAnimations > 0) { return false; } } return true; } } private class TransitionsResolver implements Resolver { @Override public float getCurrentState(PropertyHandle propertyHandle) { final AnimatedProperty animatedProperty = propertyHandle.getProperty(); final TransitionId transitionId = propertyHandle.getTransitionId(); final AnimationState animationState = mAnimationStates.get(transitionId); final PropertyState propertyState = animationState.propertyStates.get(animatedProperty); // Use the current animating value if it exists... if (propertyState != null) { return propertyState.animatedPropertyNode.getValue(); } // ...otherwise, if it's a property not being animated (e.g., the width when content appears // from a width offset), get the property from the LayoutOutput. final OutputUnitsAffinityGroup<AnimatableItem> layoutOutputGroupToCheck = animationState.changeType == ChangeType.APPEARED ? animationState.nextLayoutOutputsGroup : animationState.currentLayoutOutputsGroup; if (layoutOutputGroupToCheck == null) { throw new RuntimeException("Both LayoutOutputs were null!"); } return animatedProperty.get(layoutOutputGroupToCheck.getMostSignificantUnit()); } @Override public AnimatedPropertyNode getAnimatedPropertyNode(PropertyHandle propertyHandle) { final TransitionId transitionId = propertyHandle.getTransitionId(); final AnimationState state = mAnimationStates.get(transitionId); final PropertyState propertyState = state.propertyStates.get(propertyHandle.getProperty()); return propertyState.animatedPropertyNode; } } private class RootAnimationListener implements AnimationBindingListener { @Override public void onScheduledToStartLater(AnimationBinding binding) {} @Override public void onWillStart(AnimationBinding binding) { mRunningRootAnimations.add(binding); } @Override public void onFinish(AnimationBinding binding) { mRunningRootAnimations.remove(binding); } @Override public void onCanceledBeforeStart(AnimationBinding binding) { mRunningRootAnimations.remove(binding); } @Override public boolean shouldStart(AnimationBinding binding) { return true; } } }
Remove log transition id not found in AnimationState. Reviewed By: andrewpmsmith Differential Revision: D25185809 fbshipit-source-id: bba52f28bbd1be014719b61bff21539998819818
litho-core/src/main/java/com/facebook/litho/TransitionManager.java
Remove log transition id not found in AnimationState.
<ide><path>itho-core/src/main/java/com/facebook/litho/TransitionManager.java <ide> final TransitionId transitionId = propertyAnimation.getTransitionId(); <ide> final AnimationState animationState = mAnimationStates.get(transitionId); <ide> if (animationState == null) { <del> ComponentsReporter.emitMessage( <del> ComponentsReporter.LogLevel.ERROR, <del> "NoAnimationState", <del> "No animation state for transitionId=" + transitionId); <add> // This can happen when unmounting all items on running animations. <ide> continue; <ide> } <ide> final PropertyState propertyState =
Java
apache-2.0
39e8c16fa81624f36042e30242561efccc66589f
0
HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer; import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; import org.apache.zookeeper.KeeperException; /** * <p>Contains a set of methods for the collaboration between the start/stop scripts and the * servers. It allows to delete immediately the znode when the master or the regions server crashes. * The region server / master writes a specific file when it starts / becomes main master. When they * end properly, they delete the file.</p> * <p>In the script, we check for the existence of these files when the program ends. If they still * exist we conclude that the server crashed, likely without deleting their znode. To have a faster * recovery we delete immediately the znode.</p> * <p>The strategy depends on the server type. For a region server we store the znode path in the * file, and use it to delete it. for a master, as the znode path constant whatever the server, we * check its content to make sure that the backup server is not now in charge.</p> */ public class ZNodeClearer { private static final Log LOG = LogFactory.getLog(ZNodeClearer.class); private ZNodeClearer() {} /** * Logs the errors without failing on exception. */ public static void writeMyEphemeralNodeOnDisk(String fileContent) { String fileName = ZNodeClearer.getMyEphemeralNodeFileName(); if (fileName == null) { LOG.warn("Environment variable HBASE_ZNODE_FILE not set; znodes will not be cleared " + "on crash by start scripts (Longer MTTR!)"); return; } FileWriter fstream; try { fstream = new FileWriter(fileName); } catch (IOException e) { LOG.warn("Can't write znode file "+fileName, e); return; } BufferedWriter out = new BufferedWriter(fstream); try { try { out.write(fileContent + "\n"); } finally { try { out.close(); } finally { fstream.close(); } } } catch (IOException e) { LOG.warn("Can't write znode file "+fileName, e); } } /** * read the content of znode file, expects a single line. */ public static String readMyEphemeralNodeOnDisk() throws IOException { String fileName = getMyEphemeralNodeFileName(); if (fileName == null){ throw new FileNotFoundException("No filename; set environment variable HBASE_ZNODE_FILE"); } FileReader znodeFile = new FileReader(fileName); BufferedReader br = null; try { br = new BufferedReader(znodeFile); String file_content = br.readLine(); return file_content; } finally { if (br != null) br.close(); } } /** * Get the name of the file used to store the znode contents */ public static String getMyEphemeralNodeFileName() { return System.getenv().get("HBASE_ZNODE_FILE"); } /** * delete the znode file */ public static void deleteMyEphemeralNodeOnDisk() { String fileName = getMyEphemeralNodeFileName(); if (fileName != null) { new File(fileName).delete(); } } /** * See HBASE-14861. We are extracting master ServerName from rsZnodePath * example: "/hbase/rs/server.example.com,16020,1448266496481" * @param rsZnodePath from HBASE_ZNODE_FILE * @return String representation of ServerName or null if fails */ public static String parseMasterServerName(String rsZnodePath) { String masterServerName = null; try { String[] rsZnodeParts = rsZnodePath.split("/"); masterServerName = rsZnodeParts[rsZnodeParts.length -1]; } catch (IndexOutOfBoundsException e) { LOG.warn("String " + rsZnodePath + " has wrong format", e); } return masterServerName; } /** * * @return true if cluster is configured with master-rs collocation */ private static boolean tablesOnMaster(Configuration conf) { boolean tablesOnMaster = true; String confValue = conf.get(BaseLoadBalancer.TABLES_ON_MASTER); if (confValue != null && confValue.equalsIgnoreCase("none")) { tablesOnMaster = false; } return tablesOnMaster; } /** * Delete the master znode if its content (ServerName string) is the same * as the one in the znode file. (env: HBASE_ZNODE_FILE). I case of master-rs * colloaction we extract ServerName string from rsZnode path.(HBASE-14861) * @return true on successful deletion, false otherwise. */ public static boolean clear(Configuration conf) { Configuration tempConf = new Configuration(conf); tempConf.setInt("zookeeper.recovery.retry", 0); ZooKeeperWatcher zkw; try { zkw = new ZooKeeperWatcher(tempConf, "clean znode for master", new Abortable() { @Override public void abort(String why, Throwable e) {} @Override public boolean isAborted() { return false; } }); } catch (IOException e) { LOG.warn("Can't connect to zookeeper to read the master znode", e); return false; } String znodeFileContent; try { znodeFileContent = ZNodeClearer.readMyEphemeralNodeOnDisk(); if(ZNodeClearer.tablesOnMaster(conf)) { //In case of master crash also remove rsZnode since master is also regionserver ZKUtil.deleteNodeFailSilent(zkw, ZKUtil.joinZNode(zkw.znodePaths.rsZNode,znodeFileContent)); return MasterAddressTracker.deleteIfEquals(zkw, ZNodeClearer.parseMasterServerName(znodeFileContent)); } else { return MasterAddressTracker.deleteIfEquals(zkw, znodeFileContent); } } catch (FileNotFoundException fnfe) { // If no file, just keep going -- return success. LOG.warn("Can't find the znode file; presume non-fatal", fnfe); return true; } catch (IOException e) { LOG.warn("Can't read the content of the znode file", e); return false; } catch (KeeperException e) { LOG.warn("ZooKeeper exception deleting znode", e); return false; } finally { zkw.close(); } } }
hbase-server/src/main/java/org/apache/hadoop/hbase/ZNodeClearer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer; import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; import org.apache.zookeeper.KeeperException; /** * <p>Contains a set of methods for the collaboration between the start/stop scripts and the * servers. It allows to delete immediately the znode when the master or the regions server crashes. * The region server / master writes a specific file when it starts / becomes main master. When they * end properly, they delete the file.</p> * <p>In the script, we check for the existence of these files when the program ends. If they still * exist we conclude that the server crashed, likely without deleting their znode. To have a faster * recovery we delete immediately the znode.</p> * <p>The strategy depends on the server type. For a region server we store the znode path in the * file, and use it to delete it. for a master, as the znode path constant whatever the server, we * check its content to make sure that the backup server is not now in charge.</p> */ public class ZNodeClearer { private static final Log LOG = LogFactory.getLog(ZNodeClearer.class); private ZNodeClearer() {} /** * Logs the errors without failing on exception. */ public static void writeMyEphemeralNodeOnDisk(String fileContent) { String fileName = ZNodeClearer.getMyEphemeralNodeFileName(); if (fileName == null) { LOG.warn("Environment variable HBASE_ZNODE_FILE not set; znodes will not be cleared " + "on crash by start scripts (Longer MTTR!)"); return; } FileWriter fstream; try { fstream = new FileWriter(fileName); } catch (IOException e) { LOG.warn("Can't write znode file "+fileName, e); return; } BufferedWriter out = new BufferedWriter(fstream); try { try { out.write(fileContent + "\n"); } finally { try { out.close(); } finally { fstream.close(); } } } catch (IOException e) { LOG.warn("Can't write znode file "+fileName, e); } } /** * read the content of znode file, expects a single line. */ public static String readMyEphemeralNodeOnDisk() throws IOException { String fileName = getMyEphemeralNodeFileName(); if (fileName == null){ throw new FileNotFoundException("No filename; set environment variable HBASE_ZNODE_FILE"); } FileReader znodeFile = new FileReader(fileName); BufferedReader br = null; try { br = new BufferedReader(znodeFile); String file_content = br.readLine(); return file_content; } finally { if (br != null) br.close(); } } /** * Get the name of the file used to store the znode contents */ public static String getMyEphemeralNodeFileName() { return System.getenv().get("HBASE_ZNODE_FILE"); } /** * delete the znode file */ public static void deleteMyEphemeralNodeOnDisk() { String fileName = getMyEphemeralNodeFileName(); if (fileName != null) { new File(fileName).delete(); } } /** * See HBASE-14861. We are extracting master ServerName from rsZnodePath * example: "/hbase/rs/server.example.com,16020,1448266496481" * @param rsZnodePath from HBASE_ZNODE_FILE * @return String representation of ServerName or null if fails */ public static String parseMasterServerName(String rsZnodePath) { String masterServerName = null; try { String[] rsZnodeParts = rsZnodePath.split("/"); masterServerName = rsZnodeParts[rsZnodeParts.length -1]; } catch (IndexOutOfBoundsException e) { LOG.warn("String " + rsZnodePath + " has wrong format", e); } return masterServerName; } /** * * @return true if cluster is configured with master-rs collocation */ private static boolean tablesOnMaster(Configuration conf) { boolean tablesOnMaster = true; String confValue = conf.get(BaseLoadBalancer.TABLES_ON_MASTER); if (confValue != null && confValue.equalsIgnoreCase("none")) { tablesOnMaster = false; } return tablesOnMaster; } /** * Delete the master znode if its content (ServerName string) is the same * as the one in the znode file. (env: HBASE_ZNODE_FILE). I case of master-rs * colloaction we extract ServerName string from rsZnode path.(HBASE-14861) * @return true on successful deletion, false otherwise. */ public static boolean clear(Configuration conf) { Configuration tempConf = new Configuration(conf); tempConf.setInt("zookeeper.recovery.retry", 0); ZooKeeperWatcher zkw; try { zkw = new ZooKeeperWatcher(tempConf, "clean znode for master", new Abortable() { @Override public void abort(String why, Throwable e) {} @Override public boolean isAborted() { return false; } }); } catch (IOException e) { LOG.warn("Can't connect to zookeeper to read the master znode", e); return false; } String znodeFileContent; try { znodeFileContent = ZNodeClearer.readMyEphemeralNodeOnDisk(); if(ZNodeClearer.tablesOnMaster(conf)) { //In case of master crash also remove rsZnode since master is also regionserver ZKUtil.deleteNodeFailSilent(zkw, znodeFileContent); return MasterAddressTracker.deleteIfEquals(zkw, ZNodeClearer.parseMasterServerName(znodeFileContent)); } else { return MasterAddressTracker.deleteIfEquals(zkw, znodeFileContent); } } catch (FileNotFoundException fnfe) { // If no file, just keep going -- return success. LOG.warn("Can't find the znode file; presume non-fatal", fnfe); return true; } catch (IOException e) { LOG.warn("Can't read the content of the znode file", e); return false; } catch (KeeperException e) { LOG.warn("ZooKeeper exception deleting znode", e); return false; } finally { zkw.close(); } } }
HBASE-19120 IllegalArgumentException from ZNodeClearer when master shuts down
hbase-server/src/main/java/org/apache/hadoop/hbase/ZNodeClearer.java
HBASE-19120 IllegalArgumentException from ZNodeClearer when master shuts down
<ide><path>base-server/src/main/java/org/apache/hadoop/hbase/ZNodeClearer.java <ide> znodeFileContent = ZNodeClearer.readMyEphemeralNodeOnDisk(); <ide> if(ZNodeClearer.tablesOnMaster(conf)) { <ide> //In case of master crash also remove rsZnode since master is also regionserver <del> ZKUtil.deleteNodeFailSilent(zkw, znodeFileContent); <add> ZKUtil.deleteNodeFailSilent(zkw, ZKUtil.joinZNode(zkw.znodePaths.rsZNode,znodeFileContent)); <ide> return MasterAddressTracker.deleteIfEquals(zkw, <ide> ZNodeClearer.parseMasterServerName(znodeFileContent)); <ide> } else {
JavaScript
agpl-3.0
7db82e74f7af9faac8281bc96d7f9a454c8b00f6
0
inukshuk/arkivo-mailer
'use strict'; // --- Dependencies --- var debug = require('debug')('arkivo:mailer'); var assert = require('assert'); var slice = Array.prototype.slice; var properties = Object.defineProperties; var config = require('arkivo/lib/config'); var common = require('arkivo/lib/common'); var extend = common.extend; var md5 = common.md5; var base64 = common.base64; var B = require('bluebird'); var co = B.coroutine; var nm = require('nodemailer'); var version = require('../package.json').version; /** * Arkivo Mailer. * * @class Mailer * @constructor */ function Mailer(options, sync) { assert(sync); assert(sync.subscription); this.options = extend({}, Mailer.defaults); if (config.has('mailer')) extend(this.options, config.get('mailer')); extend(this.options, options); this.sync = sync; } /** * Mailer default configuration. * * @property defaults * @type Object * @static */ Mailer.defaults = { from: '[email protected]', subject: 'Zotero Update', mimetypes: [ 'application/pdf' ] }; properties(Mailer.prototype, { /** * @property created * @type Array */ created: { get: function get$created() { return this.collect(this.sync.created); } }, /** * @property updated * @type Array */ updated: { get: function get$updated() { return this.collect(this.sync.updated); } }, transport: { get: function () { return nm.createTransport(this.options.transport); } }, name: { get: function () { return 'Arkivo-Mailer ' + version; } } }); /** * Send the given item. * * @method send * @return {Promise} */ Mailer.prototype.send = function (item) { this.debug('sending item %s...', item.key); return new B(function (resolve, reject) { this.transport.sendMail({ xMailer: false, headers: { 'X-Mailer': this.name }, to: this.options.recipient, from: this.options.from, subject: this.options.subject, text: this.options.text, html: this.options.html, attachments: item.attachments }, function (error, info) { if (error) return reject(error); if (info.accepted.indexOf(this.options.recipient) === -1) return reject(info); resolve(info); }); }.bind(this)); }; /** * Downloads the item's attachment. * @method download * @return {Promise} */ Mailer.prototype.download = function (item) { this.debug('downloading attachment %s...', item.key); return this .sync .attachment(item) .then(function (message) { if (!message.data) throw Error('attachment is blank'); if (md5(message.data) !== item.data.md5) throw Error('attachment checksum mismatch'); return message.data; }); }; /** * Collect Zotero items with attachments that can * be sent by mail. * * @method collect * @param {Array} keys The list of Zotero keys to look at. * * @return {Promise<Array>} The collected items. */ Mailer.prototype.collect = co(function* (keys) { var i, ii, item, child, data, collection = []; for (i = 0, ii = keys.length; i < ii; ++i) { try { item = this.expand(keys[i]); if (!item) { this.debug('cannot expand "%s": item missing', keys[i]); continue; } // Duplicate items are possible, because child items are // expanded to their parents; therefore, if a sync session // includes an item and one or more of its children, we // might process the item multiple times! if (collection[item.key]) continue; // Skip items without attachments! if (!item.children) continue; child = this.select(item.children); if (!child) { this.debug('skipping "%s": no suitable attachments found', item.key); continue; } data = yield this.download(child); collection.push(this.convert(item, child, data)); } catch (error) { this.debug('failed to collect item: %s', error.message); debug(error.stack); continue; } } return collection; }); /** * Converts items to syntax used by the mailer. * * @method convert * @return Object The converted item. */ Mailer.prototype.convert = function (item, child, data) { return { attachments: [ { filename: child.data.filename, contentType: child.data.contentType, content: base64(data), encoding: 'base64' } ] }; }; /** * Selects the first suitable attachment item. * * @method select * @param {Array} items * @return {Object} */ Mailer.prototype.select = function (items) { if (!items) return undefined; if (!items.length) return undefined; var i, ii, item, next; for (i = 0, ii = items.length; i < ii; ++i) { next = items[i]; if (next.data.itemType !== 'attachment') continue; if (next.data.linkMode !== 'imported_file') continue; if (this.options.mimetypes.indexOf(next.data.contentType) < 0) continue; if (item) { if (item.dateAdded < next.dateAdded) continue; } item = next; } return item; }; /** * Returns the Zotero item for key; if the item has * a parent, returns parent item instead. * * @method expand * @private */ Mailer.prototype.expand = function (key) { var item = this.sync.items[key]; if (item && item.data.parentItem) return this.expand(item.data.parentItem); return item; }; Mailer.prototype.debug = function (message) { debug.apply(null, [ '[%s] ' + message, this.sync.id ].concat(slice.call(arguments, 1))); return this; }; // --- Exports --- module.exports = Mailer;
lib/mailer.js
'use strict'; // --- Dependencies --- var debug = require('debug')('arkivo:mailer'); var assert = require('assert'); var slice = Array.prototype.slice; var properties = Object.defineProperties; var config = require('arkivo/lib/config'); var common = require('arkivo/lib/common'); var extend = common.extend; var md5 = common.md5; var base64 = common.base64; var B = require('bluebird'); var co = B.coroutine; var nm = require('nodemailer'); var version = require('../package.json').version; /** * Arkivo Mailer. * * @class Mailer * @constructor */ function Mailer(options, sync) { assert(sync); assert(sync.subscription); this.options = extend({}, Mailer.defaults); if (config.has('mailer')) extend(this.options, config.get('mailer')); extend(this.options, options); this.sync = sync; } /** * Mailer default configuration. * * @property defaults * @type Object * @static */ Mailer.defaults = { from: '[email protected]', subject: 'Zotero Update', mimetypes: [ 'application/pdf' ] }; properties(Mailer.prototype, { /** * @property created * @type Array */ created: { get: function get$created() { return this.collect(this.sync.created); } }, /** * @property updated * @type Array */ updated: { get: function get$updated() { return this.collect(this.sync.updated); } }, transport: { get: function () { return nm.createTransport(this.options.transport); } }, name: { get: function () { return 'Arkivo-Mailer ' + version; } } }); /** * Send the given item. * * @method send * @return {Promise} */ Mailer.prototype.send = function (item) { this.debug('sending item %s...', item.key); return new B(function (resolve, reject) { this.transport.sendMail({ xMailer: false, headers: { 'X-Mailer': this.name }, to: this.options.recipient, from: this.options.from, subject: this.options.subject, text: this.options.text, html: this.options.html, attachments: item.attachments }, function (error, info) { if (error) return reject(error); // Todo: check mail was delivered to recipient resolve(info); }); }.bind(this)); }; /** * Downloads the item's attachment. * @method download * @return {Promise} */ Mailer.prototype.download = function (item) { this.debug('downloading attachment %s...', item.key); return this .sync .attachment(item) .then(function (message) { if (!message.data) throw Error('attachment is blank'); if (md5(message.data) !== item.data.md5) throw Error('attachment checksum mismatch'); return message.data; }); }; /** * Collect Zotero items with attachments that can * be sent by mail. * * @method collect * @param {Array} keys The list of Zotero keys to look at. * * @return {Promise<Array>} The collected items. */ Mailer.prototype.collect = co(function* (keys) { var i, ii, item, child, data, collection = []; for (i = 0, ii = keys.length; i < ii; ++i) { try { item = this.expand(keys[i]); if (!item) { this.debug('cannot expand "%s": item missing', keys[i]); continue; } // Duplicate items are possible, because child items are // expanded to their parents; therefore, if a sync session // includes an item and one or more of its children, we // might process the item multiple times! if (collection[item.key]) continue; // Skip items without attachments! if (!item.children) continue; child = this.select(item.children); if (!child) { this.debug('skipping "%s": no suitable attachments found', item.key); continue; } data = yield this.download(child); collection.push(this.convert(item, child, data)); } catch (error) { this.debug('failed to collect item: %s', error.message); debug(error.stack); continue; } } return collection; }); /** * Converts items to syntax used by the mailer. * * @method convert * @return Object The converted item. */ Mailer.prototype.convert = function (item, child, data) { return { attachments: [ { filename: child.data.filename, contentType: child.data.contentType, content: base64(data), encoding: 'base64' } ] }; }; /** * Selects the first suitable attachment item. * * @method select * @param {Array} items * @return {Object} */ Mailer.prototype.select = function (items) { if (!items) return undefined; if (!items.length) return undefined; var i, ii, item, next; for (i = 0, ii = items.length; i < ii; ++i) { next = items[i]; if (next.data.itemType !== 'attachment') continue; if (next.data.linkMode !== 'imported_file') continue; if (this.options.mimetypes.indexOf(next.data.contentType) < 0) continue; if (item) { if (item.dateAdded < next.dateAdded) continue; } item = next; } return item; }; /** * Returns the Zotero item for key; if the item has * a parent, returns parent item instead. * * @method expand * @private */ Mailer.prototype.expand = function (key) { var item = this.sync.items[key]; if (item && item.data.parentItem) return this.expand(item.data.parentItem); return item; }; Mailer.prototype.debug = function (message) { debug.apply(null, [ '[%s] ' + message, this.sync.id ].concat(slice.call(arguments, 1))); return this; }; // --- Exports --- module.exports = Mailer;
check accepted for recipient
lib/mailer.js
check accepted for recipient
<ide><path>ib/mailer.js <ide> attachments: item.attachments <ide> <ide> }, function (error, info) { <del> if (error) return reject(error); <del> <del> // Todo: check mail was delivered to recipient <add> if (error) <add> return reject(error); <add> <add> if (info.accepted.indexOf(this.options.recipient) === -1) <add> return reject(info); <ide> <ide> resolve(info); <ide> });
Java
apache-2.0
2d07cde45b2153566a9e32d4a6f42c31c074c6ef
0
mglukhikh/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,adedayo/intellij-community,fitermay/intellij-community,hurricup/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,hurricup/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,izonder/intellij-community,caot/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,da1z/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,fitermay/intellij-community,petteyg/intellij-community,allotria/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,kdwink/intellij-community,vladmm/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,clumsy/intellij-community,retomerz/intellij-community,diorcety/intellij-community,clumsy/intellij-community,kool79/intellij-community,da1z/intellij-community,jagguli/intellij-community,vladmm/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,kool79/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,samthor/intellij-community,Lekanich/intellij-community,ernestp/consulo,fnouama/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,vladmm/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,amith01994/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,caot/intellij-community,kool79/intellij-community,jagguli/intellij-community,dslomov/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,signed/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,allotria/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,amith01994/intellij-community,vladmm/intellij-community,semonte/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,signed/intellij-community,izonder/intellij-community,hurricup/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,consulo/consulo,lucafavatella/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,blademainer/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,semonte/intellij-community,gnuhub/intellij-community,kool79/intellij-community,adedayo/intellij-community,semonte/intellij-community,fitermay/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,robovm/robovm-studio,supersven/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,allotria/intellij-community,semonte/intellij-community,consulo/consulo,supersven/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,ernestp/consulo,asedunov/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ernestp/consulo,wreckJ/intellij-community,ahb0327/intellij-community,samthor/intellij-community,gnuhub/intellij-community,signed/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,da1z/intellij-community,kool79/intellij-community,adedayo/intellij-community,izonder/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,slisson/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,signed/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,signed/intellij-community,izonder/intellij-community,holmes/intellij-community,allotria/intellij-community,kdwink/intellij-community,caot/intellij-community,tmpgit/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,ernestp/consulo,wreckJ/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,fnouama/intellij-community,izonder/intellij-community,diorcety/intellij-community,asedunov/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,Distrotech/intellij-community,signed/intellij-community,da1z/intellij-community,ibinti/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,FHannes/intellij-community,apixandru/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,fitermay/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,asedunov/intellij-community,slisson/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,da1z/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,da1z/intellij-community,slisson/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,samthor/intellij-community,caot/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,Distrotech/intellij-community,supersven/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,diorcety/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,holmes/intellij-community,apixandru/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,allotria/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,diorcety/intellij-community,holmes/intellij-community,allotria/intellij-community,izonder/intellij-community,supersven/intellij-community,xfournet/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,samthor/intellij-community,fnouama/intellij-community,slisson/intellij-community,fnouama/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,robovm/robovm-studio,izonder/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,apixandru/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,consulo/consulo,kool79/intellij-community,adedayo/intellij-community,jagguli/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,supersven/intellij-community,hurricup/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,apixandru/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,clumsy/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,holmes/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,holmes/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,FHannes/intellij-community,semonte/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,samthor/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,fnouama/intellij-community,ryano144/intellij-community,holmes/intellij-community,amith01994/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,supersven/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,da1z/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,da1z/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,signed/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,retomerz/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,holmes/intellij-community,jagguli/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,samthor/intellij-community,petteyg/intellij-community,supersven/intellij-community,caot/intellij-community,petteyg/intellij-community,ryano144/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,clumsy/intellij-community,slisson/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,clumsy/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,slisson/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,slisson/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,caot/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,asedunov/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,caot/intellij-community,slisson/intellij-community,clumsy/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,vvv1559/intellij-community,consulo/consulo,wreckJ/intellij-community,petteyg/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,semonte/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,kool79/intellij-community,holmes/intellij-community,apixandru/intellij-community,ryano144/intellij-community,ernestp/consulo,caot/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,signed/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,slisson/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,adedayo/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,caot/intellij-community,blademainer/intellij-community,ernestp/consulo,fnouama/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,allotria/intellij-community,da1z/intellij-community,retomerz/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,jagguli/intellij-community,fitermay/intellij-community,kdwink/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,nicolargo/intellij-community,semonte/intellij-community,caot/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.util.newProjectWizard; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CustomShortcutSet; import com.intellij.openapi.ui.popup.ListItemDescriptor; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import com.intellij.platform.ProjectTemplate; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.ui.CollectionListModel; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.SearchTextField; import com.intellij.ui.components.JBList; import com.intellij.ui.popup.list.GroupedItemsListRenderer; import com.intellij.ui.speedSearch.FilteringListModel; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * @author Dmitry Avdeev * Date: 11/21/12 */ public class ProjectTypesList { private final JBList myList; private final SearchTextField mySearchField; private final FilteringListModel<TemplateItem> myFilteringListModel; private MinusculeMatcher myMatcher; private Pair<TemplateItem, Integer> myBestMatch; public ProjectTypesList(JBList list, SearchTextField searchField, MultiMap<TemplatesGroup, ProjectTemplate> map) { myList = list; mySearchField = searchField; CollectionListModel<TemplateItem> model = new CollectionListModel<TemplateItem>(buildItems(map)); myFilteringListModel = new FilteringListModel<TemplateItem>(model); myList.setCellRenderer(new GroupedItemsListRenderer(new ListItemDescriptor() { @Nullable @Override public String getTextFor(Object value) { return ((TemplateItem)value).getName(); } @Nullable @Override public String getTooltipFor(Object value) { return null; } @Nullable @Override public Icon getIconFor(Object value) { return ((TemplateItem)value).getIcon(); } @Override public boolean hasSeparatorAboveOf(Object value) { TemplateItem item = (TemplateItem)value; int index = myFilteringListModel.getElementIndex(item); return index == 0 || !myFilteringListModel.getElementAt(index -1).getGroupName().equals(item.getGroupName()); } @Nullable @Override public String getCaptionAboveOf(Object value) { return ((TemplateItem)value).getGroupName(); } })); myFilteringListModel.setFilter(new Condition<TemplateItem>() { @Override public boolean value(TemplateItem item) { return item.getMatchingDegree() > Integer.MIN_VALUE; } }); myList.setModel(myFilteringListModel); mySearchField.addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { String text = "*" + mySearchField.getText().trim(); myMatcher = NameUtil.buildMatcher(text, NameUtil.MatchingCaseSensitivity.NONE); TemplateItem value = (TemplateItem)myList.getSelectedValue(); int degree = value == null ? Integer.MIN_VALUE : value.getMatchingDegree(); myBestMatch = Pair.create(degree > Integer.MIN_VALUE ? value : null, degree); myFilteringListModel.refilter(); if (myBestMatch.first != null) { myList.setSelectedValue(myBestMatch.first, true); } } }); new AnAction() { @Override public void actionPerformed(AnActionEvent e) { InputEvent event = e.getInputEvent(); if (event instanceof KeyEvent) { int row = myList.getSelectedIndex(); int toSelect; switch (((KeyEvent)event).getKeyCode()) { case KeyEvent.VK_UP: toSelect = row == 0 ? myList.getItemsCount() - 1 : row - 1; myList.setSelectedIndex(toSelect); myList.ensureIndexIsVisible(toSelect); break; case KeyEvent.VK_DOWN: toSelect = row < myList.getItemsCount() - 1 ? row + 1 : 0; myList.setSelectedIndex(toSelect); myList.ensureIndexIsVisible(toSelect); break; } } } }.registerCustomShortcutSet(new CustomShortcutSet(KeyEvent.VK_UP, KeyEvent.VK_DOWN), mySearchField); } void resetSelection() { SelectTemplateSettings settings = SelectTemplateSettings.getInstance(); if (settings.getLastGroup() == null || !setSelectedTemplate(settings.getLastGroup(), settings.getLastTemplate())) { myList.setSelectedIndex(0); } } void saveSelection() { TemplateItem item = (TemplateItem)myList.getSelectedValue(); if (item != null) { SelectTemplateSettings.getInstance().setLastTemplate(item.getGroupName(), item.getName()); } } private List<TemplateItem> buildItems(MultiMap<TemplatesGroup, ProjectTemplate> map) { List<TemplateItem> items = new ArrayList<TemplateItem>(); List<TemplatesGroup> groups = new ArrayList<TemplatesGroup>(map.keySet()); Collections.sort(groups, new Comparator<TemplatesGroup>() { @Override public int compare(TemplatesGroup o1, TemplatesGroup o2) { return o1.getName().compareTo(o2.getName()); } }); for (TemplatesGroup group : groups) { for (ProjectTemplate template : map.get(group)) { TemplateItem templateItem = new TemplateItem(template, group); items.add(templateItem); } } return items; } @Nullable public ProjectTemplate getSelectedTemplate() { Object value = myList.getSelectedValue(); return value instanceof TemplateItem ? ((TemplateItem)value).myTemplate : null; } public boolean setSelectedTemplate(@Nullable String group, @Nullable String name) { for (int i = 0; i < myList.getModel().getSize(); i++) { Object o = myList.getModel().getElementAt(i); if (o instanceof TemplateItem && ((TemplateItem)o).myGroup.getName().equals(group) && ((TemplateItem)o).getName().equals(name)) { myList.setSelectedIndex(i); return true; } } return false; } class TemplateItem { private final ProjectTemplate myTemplate; private final TemplatesGroup myGroup; TemplateItem(ProjectTemplate template, TemplatesGroup group) { myTemplate = template; myGroup = group; } String getName() { return myTemplate.getName(); } public String getGroupName() { return myGroup.getName(); } Icon getIcon() { return myTemplate.createModuleBuilder().getNodeIcon(); } protected int getMatchingDegree() { if (myMatcher == null) return Integer.MAX_VALUE; int i = myMatcher.matchingDegree(getGroupName() + " " + getName()); if (myBestMatch == null || i > myBestMatch.second) { myBestMatch = Pair.create(this, i); } return i; } } }
java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.util.newProjectWizard; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CustomShortcutSet; import com.intellij.openapi.ui.popup.ListItemDescriptor; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import com.intellij.platform.ProjectTemplate; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.ui.CollectionListModel; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.SearchTextField; import com.intellij.ui.components.JBList; import com.intellij.ui.popup.list.GroupedItemsListRenderer; import com.intellij.ui.speedSearch.FilteringListModel; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * @author Dmitry Avdeev * Date: 11/21/12 */ public class ProjectTypesList { private final JBList myList; private final SearchTextField mySearchField; private final FilteringListModel<Item> myFilteringListModel; private MinusculeMatcher myMatcher; private Pair<? extends Item, Integer> myBestMatch; public ProjectTypesList(JBList list, SearchTextField searchField, MultiMap<TemplatesGroup, ProjectTemplate> map) { myList = list; mySearchField = searchField; CollectionListModel<Item> model = new CollectionListModel<Item>(buildItems(map)); myFilteringListModel = new FilteringListModel<Item>(model); myList.setCellRenderer(new GroupedItemsListRenderer(new ListItemDescriptor() { @Nullable @Override public String getTextFor(Object value) { return ((Item)value).getName(); } @Nullable @Override public String getTooltipFor(Object value) { return null; } @Nullable @Override public Icon getIconFor(Object value) { return ((Item)value).getIcon(); } @Override public boolean hasSeparatorAboveOf(Object value) { Item item = (Item)value; int index = myFilteringListModel.getElementIndex(item); return index == 0 || !myFilteringListModel.getElementAt(index -1).getGroupName().equals(item.getGroupName()); } @Nullable @Override public String getCaptionAboveOf(Object value) { return ((Item)value).getGroupName(); } })); myFilteringListModel.setFilter(new Condition<Item>() { @Override public boolean value(Item item) { return item.getMatchingDegree() > Integer.MIN_VALUE; } }); myList.setModel(myFilteringListModel); mySearchField.addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { String text = "*" + mySearchField.getText().trim(); myMatcher = NameUtil.buildMatcher(text, NameUtil.MatchingCaseSensitivity.NONE); Item value = (Item)myList.getSelectedValue(); int degree = value == null ? Integer.MIN_VALUE : value.getMatchingDegree(); myBestMatch = Pair.create(degree > Integer.MIN_VALUE ? value : null, degree); myFilteringListModel.refilter(); if (myBestMatch.first != null) { myList.setSelectedValue(myBestMatch.first, true); } } }); new AnAction() { @Override public void actionPerformed(AnActionEvent e) { InputEvent event = e.getInputEvent(); if (event instanceof KeyEvent) { int row = myList.getSelectedIndex(); int toSelect; switch (((KeyEvent)event).getKeyCode()) { case KeyEvent.VK_UP: toSelect = row == 0 ? myList.getItemsCount() - 1 : row - 1; myList.setSelectedIndex(toSelect); myList.ensureIndexIsVisible(toSelect); break; case KeyEvent.VK_DOWN: toSelect = row < myList.getItemsCount() - 1 ? row + 1 : 0; myList.setSelectedIndex(toSelect); myList.ensureIndexIsVisible(toSelect); break; } } } }.registerCustomShortcutSet(new CustomShortcutSet(KeyEvent.VK_UP, KeyEvent.VK_DOWN), mySearchField); } void resetSelection() { SelectTemplateSettings settings = SelectTemplateSettings.getInstance(); if (settings.getLastGroup() == null || !setSelectedTemplate(settings.getLastGroup(), settings.getLastTemplate())) { myList.setSelectedIndex(0); } } void saveSelection() { Item item = (Item)myList.getSelectedValue(); if (item instanceof TemplateItem) { SelectTemplateSettings.getInstance().setLastTemplate(item.getGroupName(), item.getName()); } } private List<? extends Item> buildItems(MultiMap<TemplatesGroup, ProjectTemplate> map) { List<Item> items = new ArrayList<Item>(); List<TemplatesGroup> groups = new ArrayList<TemplatesGroup>(map.keySet()); Collections.sort(groups, new Comparator<TemplatesGroup>() { @Override public int compare(TemplatesGroup o1, TemplatesGroup o2) { return o1.getName().compareTo(o2.getName()); } }); for (TemplatesGroup group : groups) { for (ProjectTemplate template : map.get(group)) { TemplateItem templateItem = new TemplateItem(template, group); items.add(templateItem); } } return items; } @Nullable public ProjectTemplate getSelectedTemplate() { Object value = myList.getSelectedValue(); return value instanceof TemplateItem ? ((TemplateItem)value).myTemplate : null; } public boolean setSelectedTemplate(@Nullable String group, @Nullable String name) { for (int i = 0; i < myList.getModel().getSize(); i++) { Object o = myList.getModel().getElementAt(i); if (o instanceof TemplateItem && ((TemplateItem)o).myGroup.getName().equals(group) && ((TemplateItem)o).getName().equals(name)) { myList.setSelectedIndex(i); return true; } } return false; } abstract static class Item { abstract String getName(); abstract Icon getIcon(); protected abstract int getMatchingDegree(); public abstract String getGroupName(); } class TemplateItem extends Item { private final ProjectTemplate myTemplate; private final TemplatesGroup myGroup; TemplateItem(ProjectTemplate template, TemplatesGroup group) { myTemplate = template; myGroup = group; } @Override String getName() { return myTemplate.getName(); } public String getGroupName() { return myGroup.getName(); } @Override Icon getIcon() { return myTemplate.createModuleBuilder().getNodeIcon(); } @Override protected int getMatchingDegree() { if (myMatcher == null) return Integer.MAX_VALUE; int i = myMatcher.matchingDegree(getGroupName() + " " + getName()); if (myBestMatch == null || i > myBestMatch.second) { myBestMatch = Pair.create(this, i); } return i; } } }
cleanup (cherry picked from commit 56df94a54445f637263dcf749c0c582b4e8210f3)
java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java
cleanup (cherry picked from commit 56df94a54445f637263dcf749c0c582b4e8210f3)
<ide><path>ava/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java <ide> <ide> private final JBList myList; <ide> private final SearchTextField mySearchField; <del> private final FilteringListModel<Item> myFilteringListModel; <add> private final FilteringListModel<TemplateItem> myFilteringListModel; <ide> private MinusculeMatcher myMatcher; <del> private Pair<? extends Item, Integer> myBestMatch; <add> private Pair<TemplateItem, Integer> myBestMatch; <ide> <ide> public ProjectTypesList(JBList list, SearchTextField searchField, MultiMap<TemplatesGroup, ProjectTemplate> map) { <ide> myList = list; <ide> mySearchField = searchField; <ide> <del> CollectionListModel<Item> model = new CollectionListModel<Item>(buildItems(map)); <del> myFilteringListModel = new FilteringListModel<Item>(model); <add> CollectionListModel<TemplateItem> model = new CollectionListModel<TemplateItem>(buildItems(map)); <add> myFilteringListModel = new FilteringListModel<TemplateItem>(model); <ide> <ide> myList.setCellRenderer(new GroupedItemsListRenderer(new ListItemDescriptor() { <ide> @Nullable <ide> @Override <ide> public String getTextFor(Object value) { <del> return ((Item)value).getName(); <add> return ((TemplateItem)value).getName(); <ide> } <ide> <ide> @Nullable <ide> @Nullable <ide> @Override <ide> public Icon getIconFor(Object value) { <del> return ((Item)value).getIcon(); <add> return ((TemplateItem)value).getIcon(); <ide> } <ide> <ide> @Override <ide> public boolean hasSeparatorAboveOf(Object value) { <del> Item item = (Item)value; <add> TemplateItem item = (TemplateItem)value; <ide> int index = myFilteringListModel.getElementIndex(item); <ide> return index == 0 || !myFilteringListModel.getElementAt(index -1).getGroupName().equals(item.getGroupName()); <ide> } <ide> @Nullable <ide> @Override <ide> public String getCaptionAboveOf(Object value) { <del> return ((Item)value).getGroupName(); <add> return ((TemplateItem)value).getGroupName(); <ide> } <ide> })); <ide> <del> myFilteringListModel.setFilter(new Condition<Item>() { <del> @Override <del> public boolean value(Item item) { <add> myFilteringListModel.setFilter(new Condition<TemplateItem>() { <add> @Override <add> public boolean value(TemplateItem item) { <ide> return item.getMatchingDegree() > Integer.MIN_VALUE; <ide> } <ide> }); <ide> String text = "*" + mySearchField.getText().trim(); <ide> myMatcher = NameUtil.buildMatcher(text, NameUtil.MatchingCaseSensitivity.NONE); <ide> <del> Item value = (Item)myList.getSelectedValue(); <add> TemplateItem value = (TemplateItem)myList.getSelectedValue(); <ide> int degree = value == null ? Integer.MIN_VALUE : value.getMatchingDegree(); <ide> myBestMatch = Pair.create(degree > Integer.MIN_VALUE ? value : null, degree); <ide> <ide> } <ide> <ide> void saveSelection() { <del> Item item = (Item)myList.getSelectedValue(); <del> if (item instanceof TemplateItem) { <add> TemplateItem item = (TemplateItem)myList.getSelectedValue(); <add> if (item != null) { <ide> SelectTemplateSettings.getInstance().setLastTemplate(item.getGroupName(), item.getName()); <ide> } <ide> } <ide> <del> private List<? extends Item> buildItems(MultiMap<TemplatesGroup, ProjectTemplate> map) { <del> List<Item> items = new ArrayList<Item>(); <add> private List<TemplateItem> buildItems(MultiMap<TemplatesGroup, ProjectTemplate> map) { <add> List<TemplateItem> items = new ArrayList<TemplateItem>(); <ide> List<TemplatesGroup> groups = new ArrayList<TemplatesGroup>(map.keySet()); <ide> Collections.sort(groups, new Comparator<TemplatesGroup>() { <ide> @Override <ide> return false; <ide> } <ide> <del> abstract static class Item { <del> <del> abstract String getName(); <del> abstract Icon getIcon(); <del> <del> protected abstract int getMatchingDegree(); <del> <del> public abstract String getGroupName(); <del> } <del> <del> class TemplateItem extends Item { <add> class TemplateItem { <ide> <ide> private final ProjectTemplate myTemplate; <ide> private final TemplatesGroup myGroup; <ide> myGroup = group; <ide> } <ide> <del> @Override <ide> String getName() { <ide> return myTemplate.getName(); <ide> } <ide> return myGroup.getName(); <ide> } <ide> <del> @Override <ide> Icon getIcon() { <ide> return myTemplate.createModuleBuilder().getNodeIcon(); <ide> } <ide> <del> @Override <ide> protected int getMatchingDegree() { <ide> if (myMatcher == null) return Integer.MAX_VALUE; <ide> int i = myMatcher.matchingDegree(getGroupName() + " " + getName());
Java
apache-2.0
51f1d5e606b496aa716449bbcefa763aeb4f1ba5
0
hemikak/andes,pumudu88/andes,wso2/andes,ramith/andes,hastef88/andes,Asitha/andes,prabathariyaratna/andes,sdkottegoda/andes,wso2/andes,ThilankaBowala/andes,pumudu88/andes,Asitha/andes,sdkottegoda/andes,prabathariyaratna/andes,a5anka/andes,ramith/andes,ThilankaBowala/andes,hastef88/andes,hastef88/andes,indikasampath2000/andes,hastef88/andes,prabathariyaratna/andes,indikasampath2000/andes,indikasampath2000/andes,pumudu88/andes,wso2/andes,pumudu88/andes,a5anka/andes,hastef88/andes,pumudu88/andes,hemikak/andes,indikasampath2000/andes,ThilankaBowala/andes,Asitha/andes,wso2/andes,ramith/andes,sdkottegoda/andes,Asitha/andes,sdkottegoda/andes,Asitha/andes,hemikak/andes,a5anka/andes,ThilankaBowala/andes,hemikak/andes,prabathariyaratna/andes,hemikak/andes,ramith/andes,ThilankaBowala/andes,a5anka/andes,prabathariyaratna/andes
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.andes.kernel.slot; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.andes.kernel.AndesException; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; /** * This Runnable will calculate safe zone for the cluster time to time. * In normal cases, this should run as long as the Slot manager node is alive */ public class SlotDeleteSafeZoneCalc implements Runnable { private static Log log = LogFactory.getLog(SlotDeleteSafeZoneCalc.class); private AtomicLong slotDeleteSafeZone; private boolean running; private boolean isLive; private int seekInterval; /** * Define a safe zone calculator. This will run once seekInterval * When created by default it is marked as live * * @param seekInterval interval in milliseconds calculation should run */ public SlotDeleteSafeZoneCalc(int seekInterval) { this.seekInterval = seekInterval; this.running = true; this.isLive = true; this.slotDeleteSafeZone = new AtomicLong(Long.MAX_VALUE); } @Override public void run() { if (log.isDebugEnabled()) { log.debug("Slot deletion safe zone calculation started."); } while (running) { if (isLive) { Set<String> nodesWithPublishedMessages; try { nodesWithPublishedMessages = SlotManagerClusterMode.getInstance().getMessagePublishedNodes(); } catch (AndesException e) { log.error("SlotDeleteSafeZoneCalc stopped due to failing to get message published nodes. " + "Retrying after 15 seconds" ,e); try { Thread.sleep(15 * 1000); } catch (InterruptedException e1) { //ignore } continue; } Map<String, Long> nodeInformedSafeZones = SlotManagerClusterMode.getInstance().getNodeInformedSlotDeletionSafeZones(); /** calculate safe zone (minimum value of messageIDs published so far to the * cluster by each node) */ long globalSafeZoneVal = Long.MAX_VALUE; for (String nodeID : nodesWithPublishedMessages) { long safeZoneValue = Long.MAX_VALUE; //get the maximum message id published by node so far Long safeZoneByPublishedMessages = null; try { safeZoneByPublishedMessages = SlotManagerClusterMode.getInstance() .getLastPublishedIDByNode(nodeID); } catch (AndesException e) { log.error("SlotDeleteSafeZoneCalc stopped due to failing to get last published id for node:" + nodeID + ". Retrying after 15 seconds", e); try { Thread.sleep(15 * 1000); } catch (InterruptedException e1) { //ignore } continue; } if (null != safeZoneByPublishedMessages) { safeZoneValue = safeZoneByPublishedMessages; } //If messages are not published, each node will send a messageID giving // assurance that next message id it would generate will be beyond a certain // number Long nodeInformedSafeZone = nodeInformedSafeZones.get(nodeID); /** * if no new messages are published and no new slot assignment happened * node informed value can be bigger. We need to accept that to keep the * safe zone moving */ if (null != nodeInformedSafeZone) { if (Long.MAX_VALUE != safeZoneValue) { if (safeZoneValue < nodeInformedSafeZone) { safeZoneValue = nodeInformedSafeZone; } } else { safeZoneValue = nodeInformedSafeZone; } } if (globalSafeZoneVal > safeZoneValue) { globalSafeZoneVal = safeZoneValue; } } slotDeleteSafeZone.set(globalSafeZoneVal); if (log.isDebugEnabled()) { log.debug("Safe Zone Calculated : " + slotDeleteSafeZone); } try { Thread.sleep(seekInterval); } catch (InterruptedException e) { //silently ignore } } else { try { Thread.sleep(15 * 1000); } catch (InterruptedException e) { //silently ignore } } } } /** * Get slot deletion safe zone calculated in last iteration * * @return current clot deletion safe zone */ public long getSlotDeleteSafeZone() { return slotDeleteSafeZone.get(); } /** * Specifically set slot deletion safe zone * * @param slotDeleteSafeZone safe zone value to be set */ public void setSlotDeleteSafeZone(long slotDeleteSafeZone) { this.slotDeleteSafeZone.set(slotDeleteSafeZone); } /** * Check if safe zone calculator is running * * @return true if calc is running */ public boolean isRunning() { return running; } /** * Define if the calc thread should run. When staring the thread * this should be set to true. Setting false will destroy the calc * thread. * * @param running if the calc thread should run */ public void setRunning(boolean running) { this.running = running; } /** * Check if calc thread is doing calculations actively. * * @return if calc is doing calculations. */ public boolean isLive() { return isLive; } /** * Define if calc thread should do calculations. Setting to false * will not destroy thread but will stop calculations. * * @param isLive set if calc should do calculations */ public void setLive(boolean isLive) { this.isLive = isLive; } /** * Set the interval calc thread is running * * @return seek interval */ public int getSeekInterval() { return seekInterval; } /** * Set interval calc thread should run. Calculating safe zone will be done * once this interval. Set in milliseconds. * * @param seekInterval interval in milliseconds. */ public void setSeekInterval(int seekInterval) { this.seekInterval = seekInterval; } }
modules/andes-core/broker/src/main/java/org/wso2/andes/kernel/slot/SlotDeleteSafeZoneCalc.java
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.andes.kernel.slot; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.andes.kernel.AndesException; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; /** * This Runnable will calculate safe zone for the cluster time to time. * In normal cases, this should run as long as the Slot manager node is alive */ public class SlotDeleteSafeZoneCalc implements Runnable { private static Log log = LogFactory.getLog(SlotDeleteSafeZoneCalc.class); private AtomicLong slotDeleteSafeZone; private boolean running; private boolean isLive; private int seekInterval; /** * Define a safe zone calculator. This will run once seekInterval * When created by default it is marked as live * * @param seekInterval interval in milliseconds calculation should run */ public SlotDeleteSafeZoneCalc(int seekInterval) { this.seekInterval = seekInterval; this.running = true; this.isLive = true; this.slotDeleteSafeZone = new AtomicLong(Long.MAX_VALUE); } @Override public void run() { if (log.isDebugEnabled()) { log.debug("Slot deletion safe zone calculation started."); } while (running) { if (isLive) { Set<String> nodesWithPublishedMessages; try { nodesWithPublishedMessages = SlotManagerClusterMode.getInstance().getMessagePublishedNodes(); } catch (AndesException e) { log.error("SlotDeleteSafeZoneCalc stopped due to failing to get message published nodes.", e); this.setLive(false); continue; } Map<String, Long> nodeInformedSafeZones = SlotManagerClusterMode.getInstance().getNodeInformedSlotDeletionSafeZones(); /** calculate safe zone (minimum value of messageIDs published so far to the * cluster by each node) */ long globalSafeZoneVal = Long.MAX_VALUE; for (String nodeID : nodesWithPublishedMessages) { long safeZoneValue = Long.MAX_VALUE; //get the maximum message id published by node so far Long safeZoneByPublishedMessages = null; try { safeZoneByPublishedMessages = SlotManagerClusterMode.getInstance() .getLastPublishedIDByNode(nodeID); } catch (AndesException e) { log.error("SlotDeleteSafeZoneCalc stopped due to failing to get last published id for node:" + nodeID, e); this.setLive(false); continue; } if (null != safeZoneByPublishedMessages) { safeZoneValue = safeZoneByPublishedMessages; } //If messages are not published, each node will send a messageID giving // assurance that next message id it would generate will be beyond a certain // number Long nodeInformedSafeZone = nodeInformedSafeZones.get(nodeID); /** * if no new messages are published and no new slot assignment happened * node informed value can be bigger. We need to accept that to keep the * safe zone moving */ if (null != nodeInformedSafeZone) { if (Long.MAX_VALUE != safeZoneValue) { if (safeZoneValue < nodeInformedSafeZone) { safeZoneValue = nodeInformedSafeZone; } } else { safeZoneValue = nodeInformedSafeZone; } } if (globalSafeZoneVal > safeZoneValue) { globalSafeZoneVal = safeZoneValue; } } slotDeleteSafeZone.set(globalSafeZoneVal); if (log.isDebugEnabled()) { log.debug("Safe Zone Calculated : " + slotDeleteSafeZone); } try { Thread.sleep(seekInterval); } catch (InterruptedException e) { //silently ignore } } else { try { Thread.sleep(15 * 1000); } catch (InterruptedException e) { //silently ignore } } } } /** * Get slot deletion safe zone calculated in last iteration * * @return current clot deletion safe zone */ public long getSlotDeleteSafeZone() { return slotDeleteSafeZone.get(); } /** * Specifically set slot deletion safe zone * * @param slotDeleteSafeZone safe zone value to be set */ public void setSlotDeleteSafeZone(long slotDeleteSafeZone) { this.slotDeleteSafeZone.set(slotDeleteSafeZone); } /** * Check if safe zone calculator is running * * @return true if calc is running */ public boolean isRunning() { return running; } /** * Define if the calc thread should run. When staring the thread * this should be set to true. Setting false will destroy the calc * thread. * * @param running if the calc thread should run */ public void setRunning(boolean running) { this.running = running; } /** * Check if calc thread is doing calculations actively. * * @return if calc is doing calculations. */ public boolean isLive() { return isLive; } /** * Define if calc thread should do calculations. Setting to false * will not destroy thread but will stop calculations. * * @param isLive set if calc should do calculations */ public void setLive(boolean isLive) { this.isLive = isLive; } /** * Set the interval calc thread is running * * @return seek interval */ public int getSeekInterval() { return seekInterval; } /** * Set interval calc thread should run. Calculating safe zone will be done * once this interval. Set in milliseconds. * * @param seekInterval interval in milliseconds. */ public void setSeekInterval(int seekInterval) { this.seekInterval = seekInterval; } }
fix safe zone calculation logic. It should never stop.
modules/andes-core/broker/src/main/java/org/wso2/andes/kernel/slot/SlotDeleteSafeZoneCalc.java
fix safe zone calculation logic. It should never stop.
<ide><path>odules/andes-core/broker/src/main/java/org/wso2/andes/kernel/slot/SlotDeleteSafeZoneCalc.java <ide> try { <ide> nodesWithPublishedMessages = SlotManagerClusterMode.getInstance().getMessagePublishedNodes(); <ide> } catch (AndesException e) { <del> log.error("SlotDeleteSafeZoneCalc stopped due to failing to get message published nodes.", e); <del> this.setLive(false); <add> log.error("SlotDeleteSafeZoneCalc stopped due to failing to get message published nodes. " <add> + "Retrying after 15 seconds" ,e); <add> try { <add> Thread.sleep(15 * 1000); <add> } catch (InterruptedException e1) { <add> //ignore <add> } <ide> continue; <ide> } <ide> Map<String, Long> nodeInformedSafeZones = <ide> .getLastPublishedIDByNode(nodeID); <ide> } catch (AndesException e) { <ide> log.error("SlotDeleteSafeZoneCalc stopped due to failing to get last published id for node:" + <del> nodeID, e); <del> this.setLive(false); <add> nodeID + ". Retrying after 15 seconds", e); <add> try { <add> Thread.sleep(15 * 1000); <add> } catch (InterruptedException e1) { <add> //ignore <add> } <ide> continue; <ide> } <ide>
Java
mit
735f9ed2bb0c3798ed20e31ecdbc12bf6b20e06b
0
nErumin/Algomoa
package kr.ac.cau.lumin.algomoa.SQLite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Lumin on 2015-11-23. */ public class AlgomoaSQLHelper extends SQLiteOpenHelper { private static final int DATABASE_VER = 1; private static final String DATABASE_NAME = "ProblemDB"; public AlgomoaSQLHelper(Context applicationContext) { super(applicationContext, DATABASE_NAME, null, DATABASE_VER); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
app/src/main/java/kr/ac/cau/lumin/algomoa/SQLite/AlgomoaSQLHelper.java
package kr.ac.cau.lumin.algomoa.SQLite; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Lumin on 2015-11-23. */ public class AlgomoaSQLHelper extends SQLiteOpenHelper { public AlgomoaSQLHelper() { } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
Basic SQLHelper.
app/src/main/java/kr/ac/cau/lumin/algomoa/SQLite/AlgomoaSQLHelper.java
Basic SQLHelper.
<ide><path>pp/src/main/java/kr/ac/cau/lumin/algomoa/SQLite/AlgomoaSQLHelper.java <ide> package kr.ac.cau.lumin.algomoa.SQLite; <ide> <add>import android.content.Context; <ide> import android.database.sqlite.SQLiteDatabase; <ide> import android.database.sqlite.SQLiteOpenHelper; <ide> <ide> * Created by Lumin on 2015-11-23. <ide> */ <ide> public class AlgomoaSQLHelper extends SQLiteOpenHelper { <add> private static final int DATABASE_VER = 1; <add> private static final String DATABASE_NAME = "ProblemDB"; <ide> <del> public AlgomoaSQLHelper() { <ide> <add> public AlgomoaSQLHelper(Context applicationContext) { <add> super(applicationContext, DATABASE_NAME, null, DATABASE_VER); <ide> } <ide> <ide> @Override
Java
mit
4021ad87a66cdbcff86301c22f0e5bf1214ad0ce
0
Georgiana-Baclava/Hash-Tables
package list; import map.MyKey; public class EntryList extends AbstractList{ protected EntryNode first; protected EntryNode last; public EntryNode node = new EntryNode(); public EntryList() { first = null; last = first; } public int size() { int count = 0; EntryNode current = first; while (current != null) { count++; current = current.getNext(); } return count; } public EntryNode getFirstEqual(Object value) { EntryNode current = first; while (current != null) { if (current.key.equals(value)) return current; current = current.getNext(); } return null; } public EntryNode getSortedPosition(Object value) { EntryNode current = (EntryNode) first; while (current != null) { if (current.key.compareTo((MyKey) value) > 0 || current.key.compareTo((MyKey) value) == 0) return current; current = current.getNext(); } return null; } public void insertBefore(Node node, Object value) { EntryNode newNode = new EntryNode((MyKey) value); newNode.setPrev(((EntryNode) node).getPrev()); newNode.setNext(((EntryNode) node)); if (((EntryNode) node).getPrev() == null) first = newNode; else { EntryNode prev = ((EntryNode) node).getPrev(); prev.setNext(newNode); } ((EntryNode) node).setPrev(newNode); } public void add(Object value) { node = new EntryNode((MyKey)value); if (first == null) { first = node; last = first; } else { last.setNext(node); node.setPrev(last); node.setNext(null); last = node; } } public void remove(Node node) { if(((EntryNode)node).getNext() == null && ((EntryNode)node).getPrev() == null) { first = last = null; return; } if (((EntryNode)node).getNext() == null) { EntryNode prev = ((EntryNode)node).getPrev(); prev.setNext(null); ((EntryNode)node).setPrev(null); last = prev; } else if (((EntryNode)node).getPrev() == null) { EntryNode next = ((EntryNode)node).getNext(); next.setPrev(null); ((EntryNode)node).setNext(null); first = next; } else { EntryNode next = ((EntryNode)node).getNext(); EntryNode prev = ((EntryNode)node).getPrev(); prev.setNext(next); next.setPrev(prev); ((EntryNode)node).setPrev(null); ((EntryNode)node).setNext(null); } } public String toString() { String result = ""; EntryNode current = first; if(current == null) return("null"); while(current != null) { result += "(" + current.key.getKey() + ") "; current = current.getNext(); } return result; } }
list/EntryList.java
package list; import map.MyKey; public class EntryList extends AbstractList{ //public MyKey key;//constr gol protected EntryNode first; protected EntryNode last; public EntryNode node = new EntryNode();//tre constr gol public EntryList() { first = null; last = first; } public int size() { int count = 0; EntryNode current = first; while (current != null) { count++; current = current.getNext(); } return count; } public EntryNode getFirstEqual(Object value) { EntryNode current = first;//ce pun? while (current != null) { if (current.key.equals(value)) return current; current = current.getNext(); } return null; } public EntryNode getSortedPosition(Object value) { //MyValue val = new MyValue(); EntryNode current = (EntryNode) first; while (current != null) { if (current.key.compareTo((MyKey) value) > 0 || current.key.compareTo((MyKey) value) == 0) return current; current = current.getNext(); } return null; } public void insertBefore(Node node, Object value) { EntryNode newNode = new EntryNode((MyKey) value); newNode.setPrev(((EntryNode) node).getPrev()); newNode.setNext(((EntryNode) node)); if (((EntryNode) node).getPrev() == null) first = newNode; else { EntryNode prev = ((EntryNode) node).getPrev(); prev.setNext(newNode); } ((EntryNode) node).setPrev(newNode); } public void add(Object value) { node = new EntryNode((MyKey)value); if (first == null) { first = node; last = first;//System.out.println("irene"); } else { last.setNext(node); node.setPrev(last); node.setNext(null); last = node; } // size++; } public void remove(Node node) { if(((EntryNode)node).getNext() == null && ((EntryNode)node).getPrev() == null) { first = last = null; return; } if (((EntryNode)node).getNext() == null) { EntryNode prev = ((EntryNode)node).getPrev(); prev.setNext(null); ((EntryNode)node).setPrev(null); last = prev; } else if (((EntryNode)node).getPrev() == null) { EntryNode next = ((EntryNode)node).getNext(); next.setPrev(null); ((EntryNode)node).setNext(null); first = next; System.out.println("aici"); } else { EntryNode next = ((EntryNode)node).getNext(); EntryNode prev = ((EntryNode)node).getPrev(); prev.setNext(next); next.setPrev(prev); ((EntryNode)node).setPrev(null); ((EntryNode)node).setNext(null); } // size--; } public String toString() { String result = ""; EntryNode current = first; if(current == null) return("null"); while(current != null) { result += "(" + current.key.getKey() + ") "; current = current.getNext(); } return result; } }
Update EntryList.java
list/EntryList.java
Update EntryList.java
<ide><path>ist/EntryList.java <ide> import map.MyKey; <ide> <ide> public class EntryList extends AbstractList{ <del> //public MyKey key;//constr gol <add> <ide> protected EntryNode first; <ide> protected EntryNode last; <del> public EntryNode node = new EntryNode();//tre constr gol <add> public EntryNode node = new EntryNode(); <ide> <ide> public EntryList() { <ide> first = null; <ide> } <ide> <ide> public EntryNode getFirstEqual(Object value) { <del> EntryNode current = first;//ce pun? <add> EntryNode current = first; <ide> while (current != null) { <ide> if (current.key.equals(value)) <ide> return current; <ide> } <ide> <ide> public EntryNode getSortedPosition(Object value) { <del> //MyValue val = new MyValue(); <add> <ide> EntryNode current = (EntryNode) first; <ide> while (current != null) { <ide> if (current.key.compareTo((MyKey) value) > 0 <ide> node = new EntryNode((MyKey)value); <ide> if (first == null) { <ide> first = node; <del> last = first;//System.out.println("irene"); <add> last = first; <ide> } else { <ide> last.setNext(node); <ide> node.setPrev(last); <ide> node.setNext(null); <ide> last = node; <ide> } <del> // size++; <ide> } <ide> <ide> <ide> next.setPrev(null); <ide> ((EntryNode)node).setNext(null); <ide> first = next; <del> System.out.println("aici"); <ide> } <ide> else { <ide> EntryNode next = ((EntryNode)node).getNext(); <ide> ((EntryNode)node).setPrev(null); <ide> ((EntryNode)node).setNext(null); <ide> } <del> // size--; <ide> } <ide> <ide> public String toString() {
Java
agpl-3.0
17bc27c93f92b87ac472e283fa9cf7f4d01e70f2
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
1bf4c5b2-2e62-11e5-9284-b827eb9e62be
hello.java
1bef6342-2e62-11e5-9284-b827eb9e62be
1bf4c5b2-2e62-11e5-9284-b827eb9e62be
hello.java
1bf4c5b2-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>1bef6342-2e62-11e5-9284-b827eb9e62be <add>1bf4c5b2-2e62-11e5-9284-b827eb9e62be
JavaScript
mit
5e36be57684f37cfbefc016b4e1bab5bd3ec1631
0
CensoredUser/winjs,rigdern/winjs,PaulWells/winjs,PaulWells/winjs,edrohler/winjs,IveWong/winjs,ladyinblack/winjs,jmptrader/winjs,ladyinblack/winjs,kevinwsbr/winjs,grork/winjs,GREYFOXRGR/winjs,nobuoka/winjs,CensoredUser/winjs,Guadzilah/winjs,ladyinblack/winjs,nobuoka/winjs,PaulWells/winjs,edrohler/winjs,KevinTCoughlin/winjs,grork/winjs,GREYFOXRGR/winjs,jmptrader/winjs,edrohler/winjs,Guadzilah/winjs,GREYFOXRGR/winjs,gautamsi/winjs,KevinTCoughlin/winjs,rigdern/winjs,rigdern/winjs,kevinwsbr/winjs,nobuoka/winjs,CensoredUser/winjs,Guadzilah/winjs,gautamsi/winjs,gautamsi/winjs,IveWong/winjs,KevinTCoughlin/winjs,kevinwsbr/winjs,IveWong/winjs,grork/winjs,jmptrader/winjs
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. define([ 'exports', '../Core/_Global', '../Core/_WinRT', '../Core/_Base', '../Core/_BaseUtils', '../Core/_ErrorFromName', '../Core/_Log', '../Core/_Resources', '../Core/_WriteProfilerMark', '../Promise', '../Utilities/_ElementUtilities', './_BindingParser', './_Data', './_DomWeakRefTable' ], function declarativeInit(exports, _Global, _WinRT, _Base, _BaseUtils, _ErrorFromName, _Log, _Resources, _WriteProfilerMark, Promise, _ElementUtilities, _BindingParser, _Data, _DomWeakRefTable) { "use strict"; var uid = (Math.random() * 1000) >> 0; // If we have proper weak references then we can move away from using the element's ID property // var optimizeBindingReferences = _WinRT.msSetWeakWinRTProperty && _WinRT.msGetWeakWinRTProperty; var strings = { get attributeBindingSingleProperty() { return "Attribute binding requires a single destination attribute name, often in the form \"this['aria-label']\" or \"width\"."; }, get cannotBindToThis() { return "Can't bind to 'this'."; }, get creatingNewProperty() { return "Creating new property {0}. Full path:{1}"; }, get duplicateBindingDetected() { return "Binding against element with id {0} failed because a duplicate id was detected."; }, get elementNotFound() { return "Element not found:{0}"; }, get errorInitializingBindings() { return "Error initializing bindings: {0}"; }, get propertyDoesNotExist() { return "{0} doesn't exist. Full path:{1}"; }, get idBindingNotSupported() { return "Declarative binding to ID field is not supported. Initializer: {0}"; }, get nestedDOMElementBindingNotSupported() { return "Binding through a property {0} of type HTMLElement is not supported, Full path:{1}."; } }; var markSupportedForProcessing = _BaseUtils.markSupportedForProcessing; var requireSupportedForProcessing = _BaseUtils.requireSupportedForProcessing; function registerAutoDispose(bindable, callback) { var d = bindable._autoDispose; d && d.push(callback); } function autoDispose(bindable) { bindable._autoDispose = (bindable._autoDispose || []).filter(function (callback) { return callback(); }); } function checkBindingToken(element, bindingId) { if (element) { if (element.winBindingToken === bindingId) { return element; } else { _Log.log && _Log.log(_Resources._formatString(strings.duplicateBindingDetected, element.id), "winjs binding", "error"); } } else { return element; } } function setBindingToken(element) { if (element.winBindingToken) { return element.winBindingToken; } var bindingToken = "_win_bind" + (uid++); Object.defineProperty(element, "winBindingToken", { configurable: false, writable: false, enumerable: false, value: bindingToken }); return bindingToken; } function initializerOneBinding(bind, ref, bindingId, source, e, pend, cacheEntry) { var initializer = bind.initializer; if (initializer) { initializer = initializer.winControl || initializer["data-win-control"] || initializer; } if (initializer instanceof Function) { var result = initializer(source, bind.source, e, bind.destination); if (cacheEntry) { if (result && result.cancel) { cacheEntry.bindings.push(function () { result.cancel(); }); } else { // notify the cache that we encountered an uncancellable thing // cacheEntry.nocache = true; } } return result; } else if (initializer && initializer.render) { pend.count++; // notify the cache that we encountered an uncancellable thing // if (cacheEntry) { cacheEntry.nocache = true; } requireSupportedForProcessing(initializer.render).call(initializer, getValue(source, bind.source), e). then(function () { pend.checkComplete(); }); } } function makeBinding(ref, bindingId, pend, bindable, bind, cacheEntry) { var first = true; var bindResult; var canceled = false; autoDispose(bindable); var resolveWeakRef = function () { if (canceled) { return; } var found = checkBindingToken(_DomWeakRefTable._getWeakRefElement(ref), bindingId); if (!found) { _Log.log && _Log.log(_Resources._formatString(strings.elementNotFound, ref), "winjs binding", "info"); if (bindResult) { bindResult.cancel(); } } return found; }; var bindingAction = function (v) { var found = resolveWeakRef(); if (found) { nestedSet(found, bind.destination, v); } if (first) { pend.checkComplete(); first = false; } }; registerAutoDispose(bindable, resolveWeakRef); bindResult = bindWorker(bindable, bind.source, bindingAction); if (bindResult) { var cancel = bindResult.cancel; bindResult.cancel = function () { canceled = true; return cancel.call(bindResult); }; if (cacheEntry) { cacheEntry.bindings.push(function () { bindResult.cancel(); }); } } return bindResult; } function sourceOneBinding(bind, ref, bindingId, source, e, pend, cacheEntry) { var bindable; if (source !== _Global) { source = _Data.as(source); } if (source._getObservable) { bindable = source._getObservable(); } if (bindable) { pend.count++; // declarative binding must use a weak ref to the target element // return makeBinding(ref, bindingId, pend, bindable, bind, cacheEntry); } else { nestedSet(e, bind.destination, getValue(source, bind.source)); } } function filterIdBinding(declBind, bindingStr) { for (var bindIndex = declBind.length - 1; bindIndex >= 0; bindIndex--) { var bind = declBind[bindIndex]; var dest = bind.destination; if (dest.length === 1 && dest[0] === "id") { if (_BaseUtils.validation) { throw new _ErrorFromName("WinJS.Binding.IdBindingNotSupported", _Resources._formatString(strings.idBindingNotSupported, bindingStr)); } _Log.log && _Log.log(_Resources._formatString(strings.idBindingNotSupported, bindingStr), "winjs binding", "error"); declBind.splice(bindIndex, 1); } } return declBind; } function calcBinding(bindingStr, bindingCache) { if (bindingCache) { var declBindCache = bindingCache.expressions[bindingStr]; var declBind; if (!declBindCache) { declBind = filterIdBinding(_BindingParser._bindingParser(bindingStr, _Global), bindingStr); bindingCache.expressions[bindingStr] = declBind; } if (!declBind) { declBind = declBindCache; } return declBind; } else { return filterIdBinding(_BindingParser._bindingParser(bindingStr, _Global), bindingStr); } } function declarativeBindImpl(rootElement, dataContext, skipRoot, bindingCache, defaultInitializer, c) { _WriteProfilerMark("WinJS.Binding:processAll,StartTM"); var pend = { count: 0, checkComplete: function checkComplete() { this.count--; if (this.count === 0) { _WriteProfilerMark("WinJS.Binding:processAll,StopTM"); c(); } } }; var baseElement = (rootElement || _Global.document.body); var selector = "[data-win-bind],[data-win-control]"; var elements = baseElement.querySelectorAll(selector); var neg; if (!skipRoot && (baseElement.getAttribute("data-win-bind") || baseElement.winControl)) { neg = baseElement; } pend.count++; var source = dataContext || _Global; _DomWeakRefTable._DOMWeakRefTable_fastLoadPath = true; try { var baseElementData = _ElementUtilities.data(baseElement); baseElementData.winBindings = baseElementData.winBindings || []; for (var i = (neg ? -1 : 0), l = elements.length; i < l; i++) { var element = i < 0 ? neg : elements[i]; // If we run into a declarative control container (e.g. Binding.Template) we don't process its // children, but we do give it an opportunity to process them later using this data context. // if (element.winControl && element.winControl.constructor && element.winControl.constructor.isDeclarativeControlContainer) { i += element.querySelectorAll(selector).length; var idcc = element.winControl.constructor.isDeclarativeControlContainer; if (typeof idcc === "function") { idcc = requireSupportedForProcessing(idcc); idcc(element.winControl, function (element) { return declarativeBind(element, dataContext, false, bindingCache, defaultInitializer); }); } } // In order to catch controls above we may have elements which don't have bindings, skip them // if (!element.hasAttribute("data-win-bind")) { continue; } var original = element.getAttribute("data-win-bind"); var declBind = calcBinding(original, bindingCache); if (!declBind.implemented) { for (var bindIndex = 0, bindLen = declBind.length; bindIndex < bindLen; bindIndex++) { var bind = declBind[bindIndex]; bind.initializer = bind.initializer || defaultInitializer; if (bind.initializer) { bind.implementation = initializerOneBinding; } else { bind.implementation = sourceOneBinding; } } declBind.implemented = true; } pend.count++; var bindingId = setBindingToken(element); var ref = optimizeBindingReferences ? bindingId : element.id; if (!ref) { // We use our own counter here, as the IE "uniqueId" is only // global to a document, which means that binding against // unparented DOM elements would get duplicate IDs. // // The elements may not be parented at this point, but they // will be parented by the time the binding action is fired. // element.id = ref = bindingId; } _DomWeakRefTable._createWeakRef(element, ref); var elementData = _ElementUtilities.data(element); elementData.winBindings = null; var cacheEntry; if (bindingCache && bindingCache.elements) { cacheEntry = bindingCache.elements[ref]; if (!cacheEntry) { bindingCache.elements[ref] = cacheEntry = { bindings: [] }; } } for (var bindIndex2 = 0, bindLen2 = declBind.length; bindIndex2 < bindLen2; bindIndex2++) { var bind2 = declBind[bindIndex2]; var cancel2 = bind2.implementation(bind2, ref, bindingId, source, element, pend, cacheEntry); if (cancel2) { elementData.winBindings = elementData.winBindings || []; elementData.winBindings.push(cancel2); baseElementData.winBindings.push(cancel2); } } pend.count--; } } finally { _DomWeakRefTable._DOMWeakRefTable_fastLoadPath = false; } pend.checkComplete(); } function declarativeBind(rootElement, dataContext, skipRoot, bindingCache, defaultInitializer) { /// <signature helpKeyword="WinJS.Binding.declarativeBind"> /// <summary locid="WinJS.Binding.declarativeBind"> /// Binds values from the specified data context to elements that are descendants of the specified root element /// and have declarative binding attributes (data-win-bind). /// </summary> /// <param name="rootElement" type="DOMElement" optional="true" locid="WinJS.Binding.declarativeBind_p:rootElement"> /// The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document /// is searched. /// </param> /// <param name="dataContext" type="Object" optional="true" locid="WinJS.Binding.declarativeBind_p:dataContext"> /// The object to use for default data binding. /// </param> /// <param name="skipRoot" type="Boolean" optional="true" locid="WinJS.Binding.declarativeBind_p:skipRoot"> /// If true, the elements to be bound skip the specified root element and include only the children. /// </param> /// <param name="bindingCache" optional="true" locid="WinJS.Binding.declarativeBind_p:bindingCache"> /// The cached binding data. /// </param> /// <param name="defaultInitializer" optional="true" locid="WinJS.Binding.declarativeBind_p:defaultInitializer"> /// The binding initializer to use in the case that one is not specified in a binding expression. If not /// provided the behavior is the same as WinJS.Binding.defaultBind. /// </param> /// <returns type="WinJS.Promise" locid="WinJS.Binding.declarativeBind_returnValue"> /// A promise that completes when each item that contains binding declarations has /// been processed and the update has started. /// </returns> /// </signature> return new Promise(function (c, e, p) { declarativeBindImpl(rootElement, dataContext, skipRoot, bindingCache, defaultInitializer, c, e, p); }).then(null, function (e) { _Log.log && _Log.log(_Resources._formatString(strings.errorInitializingBindings, e && e.message), "winjs binding", "error"); return Promise.wrapError(e); }); } function converter(convert) { /// <signature helpKeyword="WinJS.Binding.converter"> /// <summary locid="WinJS.Binding.converter"> /// Creates a default binding initializer for binding between a source /// property and a destination property with a provided converter function /// that is executed on the value of the source property. /// </summary> /// <param name="convert" type="Function" locid="WinJS.Binding.converter_p:convert"> /// The conversion that operates over the result of the source property /// to produce a value that is set to the destination property. /// </param> /// <returns type="Function" locid="WinJS.Binding.converter_returnValue"> /// The binding initializer. /// </returns> /// </signature> var userConverter = function (source, sourceProperties, dest, destProperties, initialValue) { var bindingId = setBindingToken(dest); var ref = optimizeBindingReferences ? bindingId : dest.id; if (!ref) { dest.id = ref = bindingId; } _DomWeakRefTable._createWeakRef(dest, ref); var bindable; if (source !== _Global) { source = _Data.as(source); } if (source._getObservable) { bindable = source._getObservable(); } if (bindable) { var counter = 0; var workerResult = bindWorker(_Data.as(source), sourceProperties, function (v) { if (++counter === 1) { if (v === initialValue) { return; } } var found = checkBindingToken(_DomWeakRefTable._getWeakRefElement(ref), bindingId); if (found) { nestedSet(found, destProperties, convert(requireSupportedForProcessing(v))); } else if (workerResult) { _Log.log && _Log.log(_Resources._formatString(strings.elementNotFound, ref), "winjs binding", "info"); workerResult.cancel(); } }); return workerResult; } else { var value = getValue(source, sourceProperties); if (value !== initialValue) { nestedSet(dest, destProperties, convert(value)); } } }; return markSupportedForProcessing(userConverter); } function getValue(obj, path) { if (obj !== _Global) { obj = requireSupportedForProcessing(obj); } if (path) { for (var i = 0, len = path.length; i < len && (obj !== null && obj !== undefined) ; i++) { obj = requireSupportedForProcessing(obj[path[i]]); } } return obj; } function nestedSet(dest, destProperties, v) { requireSupportedForProcessing(v); dest = requireSupportedForProcessing(dest); for (var i = 0, len = (destProperties.length - 1) ; i < len; i++) { dest = requireSupportedForProcessing(dest[destProperties[i]]); if (!dest) { _Log.log && _Log.log(_Resources._formatString(strings.propertyDoesNotExist, destProperties[i], destProperties.join(".")), "winjs binding", "error"); return; } else if (dest instanceof _Global.Node) { _Log.log && _Log.log(_Resources._formatString(strings.nestedDOMElementBindingNotSupported, destProperties[i], destProperties.join(".")), "winjs binding", "error"); return; } } if (destProperties.length === 0) { _Log.log && _Log.log(strings.cannotBindToThis, "winjs binding", "error"); return; } var prop = destProperties[destProperties.length - 1]; if (_Log.log) { if (dest[prop] === undefined) { _Log.log(_Resources._formatString(strings.creatingNewProperty, prop, destProperties.join(".")), "winjs binding", "warn"); } } dest[prop] = v; } function attributeSet(dest, destProperties, v) { dest = requireSupportedForProcessing(dest); if (!destProperties || destProperties.length !== 1 || !destProperties[0]) { _Log.log && _Log.log(strings.attributeBindingSingleProperty, "winjs binding", "error"); return; } dest.setAttribute(destProperties[0], v); } function setAttribute(source, sourceProperties, dest, destProperties, initialValue) { /// <signature helpKeyword="WinJS.Binding.setAttribute"> /// <summary locid="WinJS.Binding.setAttribute"> /// Creates a one-way binding between the source object and /// an attribute on the destination element. /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.setAttribute_p:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.setAttribute_p:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.setAttribute_p:dest"> /// The destination object (must be a DOM element). /// </param> /// <param name="destProperties" type="Array" locid="WinJS.Binding.setAttribute_p:destProperties"> /// The path on the destination object to the destination property, this must be a single name. /// </param> /// <param name="initialValue" optional="true" locid="WinJS.Binding.setAttribute_p:initialValue"> /// The known initial value of the target, if the source value is the same as this initial /// value (using ===) then the target is not set the first time. /// </param> /// <returns type="{ cancel: Function }" locid="WinJS.Binding.setAttribute_returnValue"> /// An object with a cancel method that is used to coalesce bindings. /// </returns> /// </signature> var bindingId = setBindingToken(dest); var ref = optimizeBindingReferences ? bindingId : dest.id; if (!ref) { dest.id = ref = bindingId; } _DomWeakRefTable._createWeakRef(dest, ref); var bindable; if (source !== _Global) { source = _Data.as(source); } if (source._getObservable) { bindable = source._getObservable(); } if (bindable) { var counter = 0; var workerResult = bindWorker(bindable, sourceProperties, function (v) { if (++counter === 1) { if (v === initialValue) { return; } } var found = checkBindingToken(_DomWeakRefTable._getWeakRefElement(ref), bindingId); if (found) { attributeSet(found, destProperties, requireSupportedForProcessing(v)); } else if (workerResult) { _Log.log && _Log.log(_Resources._formatString(strings.elementNotFound, ref), "winjs binding", "info"); workerResult.cancel(); } }); return workerResult; } else { var value = getValue(source, sourceProperties); if (value !== initialValue) { attributeSet(dest, destProperties, value); } } } function setAttributeOneTime(source, sourceProperties, dest, destProperties) { /// <signature helpKeyword="WinJS.Binding.setAttributeOneTime"> /// <summary locid="WinJS.Binding.setAttributeOneTime"> /// Sets an attribute on the destination element to the value of the source property /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.setAttributeOneTime_p:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.setAttributeOneTime_p:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.setAttributeOneTime_p:dest"> /// The destination object (must be a DOM element). /// </param> /// <param name="destProperties" type="Array" locid="WinJS.Binding.setAttributeOneTime_p:destProperties"> /// The path on the destination object to the destination property, this must be a single name. /// </param> /// </signature> return attributeSet(dest, destProperties, getValue(source, sourceProperties)); } function addClassOneTime(source, sourceProperties, dest) { /// <signature helpKeyword="WinJS.Binding.addClassOneTime"> /// <summary locid="WinJS.Binding.addClassOneTime"> /// Adds a class or Array list of classes on the destination element to the value of the source property /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.addClassOneTime:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.addClassOneTime:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.addClassOneTime:dest"> /// The destination object (must be a DOM element). /// </param> /// </signature> dest = requireSupportedForProcessing(dest); var value = getValue(source, sourceProperties); if (Array.isArray(value)) { value.forEach(function (className) { _ElementUtilities.addClass(dest, className); }); } else if (value) { _ElementUtilities.addClass(dest, value); } } var defaultBindImpl = converter(function defaultBind_passthrough(v) { return v; }); function defaultBind(source, sourceProperties, dest, destProperties, initialValue) { /// <signature helpKeyword="WinJS.Binding.defaultBind"> /// <summary locid="WinJS.Binding.defaultBind"> /// Creates a one-way binding between the source object and /// the destination object. /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.defaultBind_p:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.defaultBind_p:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.defaultBind_p:dest"> /// The destination object. /// </param> /// <param name="destProperties" type="Array" locid="WinJS.Binding.defaultBind_p:destProperties"> /// The path on the destination object to the destination property. /// </param> /// <param name="initialValue" optional="true" locid="WinJS.Binding.defaultBind_p:initialValue"> /// The known initial value of the target, if the source value is the same as this initial /// value (using ===) then the target is not set the first time. /// </param> /// <returns type="{ cancel: Function }" locid="WinJS.Binding.defaultBind_returnValue"> /// An object with a cancel method that is used to coalesce bindings. /// </returns> /// </signature> return defaultBindImpl(source, sourceProperties, dest, destProperties, initialValue); } function bindWorker(bindable, sourceProperties, func) { if (sourceProperties.length > 1) { var root = {}; var current = root; for (var i = 0, l = sourceProperties.length - 1; i < l; i++) { current = current[sourceProperties[i]] = {}; } current[sourceProperties[sourceProperties.length - 1]] = func; return _Data.bind(bindable, root, true); } else if (sourceProperties.length === 1) { bindable.bind(sourceProperties[0], func, true); return { cancel: function () { bindable.unbind(sourceProperties[0], func); this.cancel = noop; } }; } else { // can't bind to object, so we just push it through // func(bindable); } } function noop() { } function oneTime(source, sourceProperties, dest, destProperties) { /// <signature helpKeyword="WinJS.Binding.oneTime"> /// <summary locid="WinJS.Binding.oneTime"> /// Sets the destination property to the value of the source property. /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.oneTime_p:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.oneTime_p:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.oneTime_p:dest"> /// The destination object. /// </param> /// <param name="destProperties" type="Array" locid="WinJS.Binding.oneTime_p:destProperties"> /// The path on the destination object to the destination property. /// </param> /// <returns type="{ cancel: Function }" locid="WinJS.Binding.oneTime_returnValue"> /// An object with a cancel method that is used to coalesce bindings. /// </returns> /// </signature> nestedSet(dest, destProperties, getValue(source, sourceProperties)); return { cancel: noop }; } function initializer(customInitializer) { /// <signature helpKeyword="WinJS.Binding.initializer"> /// <summary locid="WinJS.Binding.initializer"> /// Marks a custom initializer function as being compatible with declarative data binding. /// </summary> /// <param name="customInitializer" type="Function" locid="WinJS.Binding.initializer_p:customInitializer"> /// The custom initializer to be marked as compatible with declarative data binding. /// </param> /// <returns type="Function" locid="WinJS.Binding.initializer_returnValue"> /// The input customInitializer. /// </returns> /// </signature> return markSupportedForProcessing(customInitializer); } _Base.Namespace._moduleDefine(exports, "WinJS.Binding", { processAll: declarativeBind, oneTime: initializer(oneTime), defaultBind: initializer(defaultBind), converter: converter, initializer: initializer, getValue: getValue, setAttribute: initializer(setAttribute), setAttributeOneTime: initializer(setAttributeOneTime), addClassOneTime: initializer(addClassOneTime), }); });
src/js/WinJS/Binding/_Declarative.js
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. define([ 'exports', '../Core/_Global', '../Core/_WinRT', '../Core/_Base', '../Core/_BaseUtils', '../Core/_ErrorFromName', '../Core/_Log', '../Core/_Resources', '../Core/_WriteProfilerMark', '../Promise', '../Utilities/_ElementUtilities', './_BindingParser', './_Data', './_DomWeakRefTable' ], function declarativeInit(exports, _Global, _WinRT, _Base, _BaseUtils, _ErrorFromName, _Log, _Resources, _WriteProfilerMark, Promise, _ElementUtilities, _BindingParser, _Data, _DomWeakRefTable) { "use strict"; var uid = (Math.random() * 1000) >> 0; // If we have proper weak references then we can move away from using the element's ID property // var optimizeBindingReferences = _WinRT.msSetWeakWinRTProperty && _WinRT.msGetWeakWinRTProperty; var strings = { get attributeBindingSingleProperty() { return "Attribute binding requires a single destination attribute name, often in the form \"this['aria-label']\" or \"width\"."; }, get cannotBindToThis() { return "Can't bind to 'this'."; }, get creatingNewProperty() { return "Creating new property {0}. Full path:{1}"; }, get duplicateBindingDetected() { return "Binding against element with id {0} failed because a duplicate id was detected."; }, get elementNotFound() { return "Element not found:{0}"; }, get errorInitializingBindings() { return "Error initializing bindings: {0}"; }, get propertyDoesNotExist() { return "{0} doesn't exist. Full path:{1}"; }, get idBindingNotSupported() { return "Declarative binding to ID field is not supported. Initializer: {0}"; }, get nestedDOMElementBindingNotSupported() { return "Binding through a property {0} of type HTMLElement is not supported, Full path:{1}."; } }; var markSupportedForProcessing = _BaseUtils.markSupportedForProcessing; var requireSupportedForProcessing = _BaseUtils.requireSupportedForProcessing; function registerAutoDispose(bindable, callback) { var d = bindable._autoDispose; d && d.push(callback); } function autoDispose(bindable) { bindable._autoDispose = (bindable._autoDispose || []).filter(function (callback) { return callback(); }); } function checkBindingToken(element, bindingId) { if (element) { if (element.winBindingToken === bindingId) { return element; } else { _Log.log && _Log.log(_Resources._formatString(strings.duplicateBindingDetected, element.id), "winjs binding", "error"); } } else { return element; } } function setBindingToken(element) { if (element.winBindingToken) { return element.winBindingToken; } var bindingToken = "_win_bind" + (uid++); Object.defineProperty(element, "winBindingToken", { configurable: false, writable: false, enumerable: false, value: bindingToken }); return bindingToken; } function initializerOneBinding(bind, ref, bindingId, source, e, pend, cacheEntry) { var initializer = bind.initializer; if (initializer) { initializer = initializer.winControl || initializer["data-win-control"] || initializer; } if (initializer instanceof Function) { var result = initializer(source, bind.source, e, bind.destination); if (cacheEntry) { if (result && result.cancel) { cacheEntry.bindings.push(function () { result.cancel(); }); } else { // notify the cache that we encountered an uncancellable thing // cacheEntry.nocache = true; } } return result; } else if (initializer && initializer.render) { pend.count++; // notify the cache that we encountered an uncancellable thing // if (cacheEntry) { cacheEntry.nocache = true; } requireSupportedForProcessing(initializer.render).call(initializer, getValue(source, bind.source), e). then(function () { pend.checkComplete(); }); } } function makeBinding(ref, bindingId, pend, bindable, bind, cacheEntry) { var first = true; var bindResult; var canceled = false; autoDispose(bindable); var resolveWeakRef = function () { if (canceled) { return; } var found = checkBindingToken(_DomWeakRefTable._getWeakRefElement(ref), bindingId); if (!found) { _Log.log && _Log.log(_Resources._formatString(strings.elementNotFound, ref), "winjs binding", "info"); if (bindResult) { bindResult.cancel(); } } return found; }; var bindingAction = function (v) { var found = resolveWeakRef(); if (found) { nestedSet(found, bind.destination, v); } if (first) { pend.checkComplete(); first = false; } }; registerAutoDispose(bindable, resolveWeakRef); bindResult = bindWorker(bindable, bind.source, bindingAction); if (bindResult) { var cancel = bindResult.cancel; bindResult.cancel = function () { canceled = true; return cancel.call(bindResult); }; if (cacheEntry) { cacheEntry.bindings.push(function () { bindResult.cancel(); }); } } return bindResult; } function sourceOneBinding(bind, ref, bindingId, source, e, pend, cacheEntry) { var bindable; if (source !== _Global) { source = _Data.as(source); } if (source._getObservable) { bindable = source._getObservable(); } if (bindable) { pend.count++; // declarative binding must use a weak ref to the target element // return makeBinding(ref, bindingId, pend, bindable, bind, cacheEntry); } else { nestedSet(e, bind.destination, getValue(source, bind.source)); } } function filterIdBinding(declBind, bindingStr) { for (var bindIndex = declBind.length - 1; bindIndex >= 0; bindIndex--) { var bind = declBind[bindIndex]; var dest = bind.destination; if (dest.length === 1 && dest[0] === "id") { if (_BaseUtils.validation) { throw new _ErrorFromName("WinJS.Binding.IdBindingNotSupported", _Resources._formatString(strings.idBindingNotSupported, bindingStr)); } _Log.log && _Log.log(_Resources._formatString(strings.idBindingNotSupported, bindingStr), "winjs binding", "error"); declBind.splice(bindIndex, 1); } } return declBind; } function calcBinding(bindingStr, bindingCache) { if (bindingCache) { var declBindCache = bindingCache.expressions[bindingStr]; var declBind; if (!declBindCache) { declBind = filterIdBinding(_BindingParser._bindingParser(bindingStr, _Global), bindingStr); bindingCache.expressions[bindingStr] = declBind; } if (!declBind) { declBind = declBindCache; } return declBind; } else { return filterIdBinding(_BindingParser._bindingParser(bindingStr, _Global), bindingStr); } } function declarativeBindImpl(rootElement, dataContext, skipRoot, bindingCache, defaultInitializer, c) { _WriteProfilerMark("WinJS.Binding:processAll,StartTM"); var pend = { count: 0, checkComplete: function checkComplete() { this.count--; if (this.count === 0) { _WriteProfilerMark("WinJS.Binding:processAll,StopTM"); c(); } } }; var baseElement = (rootElement || _Global.document.body); var selector = "[data-win-bind],[data-win-control]"; var elements = baseElement.querySelectorAll(selector); var neg; if (!skipRoot && baseElement.getAttribute("data-win-bind")) { neg = baseElement; } pend.count++; var source = dataContext || _Global; _DomWeakRefTable._DOMWeakRefTable_fastLoadPath = true; try { var baseElementData = _ElementUtilities.data(baseElement); baseElementData.winBindings = baseElementData.winBindings || []; for (var i = (neg ? -1 : 0), l = elements.length; i < l; i++) { var element = i < 0 ? neg : elements[i]; // If we run into a declarative control container (e.g. Binding.Template) we don't process its // children, but we do give it an opportunity to process them later using this data context. // if (element.winControl && element.winControl.constructor && element.winControl.constructor.isDeclarativeControlContainer) { i += element.querySelectorAll(selector).length; var idcc = element.winControl.constructor.isDeclarativeControlContainer; if (typeof idcc === "function") { idcc = requireSupportedForProcessing(idcc); idcc(element.winControl, function (element) { return declarativeBind(element, dataContext, false, bindingCache, defaultInitializer); }); } } // In order to catch controls above we may have elements which don't have bindings, skip them // if (!element.hasAttribute("data-win-bind")) { continue; } var original = element.getAttribute("data-win-bind"); var declBind = calcBinding(original, bindingCache); if (!declBind.implemented) { for (var bindIndex = 0, bindLen = declBind.length; bindIndex < bindLen; bindIndex++) { var bind = declBind[bindIndex]; bind.initializer = bind.initializer || defaultInitializer; if (bind.initializer) { bind.implementation = initializerOneBinding; } else { bind.implementation = sourceOneBinding; } } declBind.implemented = true; } pend.count++; var bindingId = setBindingToken(element); var ref = optimizeBindingReferences ? bindingId : element.id; if (!ref) { // We use our own counter here, as the IE "uniqueId" is only // global to a document, which means that binding against // unparented DOM elements would get duplicate IDs. // // The elements may not be parented at this point, but they // will be parented by the time the binding action is fired. // element.id = ref = bindingId; } _DomWeakRefTable._createWeakRef(element, ref); var elementData = _ElementUtilities.data(element); elementData.winBindings = null; var cacheEntry; if (bindingCache && bindingCache.elements) { cacheEntry = bindingCache.elements[ref]; if (!cacheEntry) { bindingCache.elements[ref] = cacheEntry = { bindings: [] }; } } for (var bindIndex2 = 0, bindLen2 = declBind.length; bindIndex2 < bindLen2; bindIndex2++) { var bind2 = declBind[bindIndex2]; var cancel2 = bind2.implementation(bind2, ref, bindingId, source, element, pend, cacheEntry); if (cancel2) { elementData.winBindings = elementData.winBindings || []; elementData.winBindings.push(cancel2); baseElementData.winBindings.push(cancel2); } } pend.count--; } } finally { _DomWeakRefTable._DOMWeakRefTable_fastLoadPath = false; } pend.checkComplete(); } function declarativeBind(rootElement, dataContext, skipRoot, bindingCache, defaultInitializer) { /// <signature helpKeyword="WinJS.Binding.declarativeBind"> /// <summary locid="WinJS.Binding.declarativeBind"> /// Binds values from the specified data context to elements that are descendants of the specified root element /// and have declarative binding attributes (data-win-bind). /// </summary> /// <param name="rootElement" type="DOMElement" optional="true" locid="WinJS.Binding.declarativeBind_p:rootElement"> /// The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document /// is searched. /// </param> /// <param name="dataContext" type="Object" optional="true" locid="WinJS.Binding.declarativeBind_p:dataContext"> /// The object to use for default data binding. /// </param> /// <param name="skipRoot" type="Boolean" optional="true" locid="WinJS.Binding.declarativeBind_p:skipRoot"> /// If true, the elements to be bound skip the specified root element and include only the children. /// </param> /// <param name="bindingCache" optional="true" locid="WinJS.Binding.declarativeBind_p:bindingCache"> /// The cached binding data. /// </param> /// <param name="defaultInitializer" optional="true" locid="WinJS.Binding.declarativeBind_p:defaultInitializer"> /// The binding initializer to use in the case that one is not specified in a binding expression. If not /// provided the behavior is the same as WinJS.Binding.defaultBind. /// </param> /// <returns type="WinJS.Promise" locid="WinJS.Binding.declarativeBind_returnValue"> /// A promise that completes when each item that contains binding declarations has /// been processed and the update has started. /// </returns> /// </signature> return new Promise(function (c, e, p) { declarativeBindImpl(rootElement, dataContext, skipRoot, bindingCache, defaultInitializer, c, e, p); }).then(null, function (e) { _Log.log && _Log.log(_Resources._formatString(strings.errorInitializingBindings, e && e.message), "winjs binding", "error"); return Promise.wrapError(e); }); } function converter(convert) { /// <signature helpKeyword="WinJS.Binding.converter"> /// <summary locid="WinJS.Binding.converter"> /// Creates a default binding initializer for binding between a source /// property and a destination property with a provided converter function /// that is executed on the value of the source property. /// </summary> /// <param name="convert" type="Function" locid="WinJS.Binding.converter_p:convert"> /// The conversion that operates over the result of the source property /// to produce a value that is set to the destination property. /// </param> /// <returns type="Function" locid="WinJS.Binding.converter_returnValue"> /// The binding initializer. /// </returns> /// </signature> var userConverter = function (source, sourceProperties, dest, destProperties, initialValue) { var bindingId = setBindingToken(dest); var ref = optimizeBindingReferences ? bindingId : dest.id; if (!ref) { dest.id = ref = bindingId; } _DomWeakRefTable._createWeakRef(dest, ref); var bindable; if (source !== _Global) { source = _Data.as(source); } if (source._getObservable) { bindable = source._getObservable(); } if (bindable) { var counter = 0; var workerResult = bindWorker(_Data.as(source), sourceProperties, function (v) { if (++counter === 1) { if (v === initialValue) { return; } } var found = checkBindingToken(_DomWeakRefTable._getWeakRefElement(ref), bindingId); if (found) { nestedSet(found, destProperties, convert(requireSupportedForProcessing(v))); } else if (workerResult) { _Log.log && _Log.log(_Resources._formatString(strings.elementNotFound, ref), "winjs binding", "info"); workerResult.cancel(); } }); return workerResult; } else { var value = getValue(source, sourceProperties); if (value !== initialValue) { nestedSet(dest, destProperties, convert(value)); } } }; return markSupportedForProcessing(userConverter); } function getValue(obj, path) { if (obj !== _Global) { obj = requireSupportedForProcessing(obj); } if (path) { for (var i = 0, len = path.length; i < len && (obj !== null && obj !== undefined) ; i++) { obj = requireSupportedForProcessing(obj[path[i]]); } } return obj; } function nestedSet(dest, destProperties, v) { requireSupportedForProcessing(v); dest = requireSupportedForProcessing(dest); for (var i = 0, len = (destProperties.length - 1) ; i < len; i++) { dest = requireSupportedForProcessing(dest[destProperties[i]]); if (!dest) { _Log.log && _Log.log(_Resources._formatString(strings.propertyDoesNotExist, destProperties[i], destProperties.join(".")), "winjs binding", "error"); return; } else if (dest instanceof _Global.Node) { _Log.log && _Log.log(_Resources._formatString(strings.nestedDOMElementBindingNotSupported, destProperties[i], destProperties.join(".")), "winjs binding", "error"); return; } } if (destProperties.length === 0) { _Log.log && _Log.log(strings.cannotBindToThis, "winjs binding", "error"); return; } var prop = destProperties[destProperties.length - 1]; if (_Log.log) { if (dest[prop] === undefined) { _Log.log(_Resources._formatString(strings.creatingNewProperty, prop, destProperties.join(".")), "winjs binding", "warn"); } } dest[prop] = v; } function attributeSet(dest, destProperties, v) { dest = requireSupportedForProcessing(dest); if (!destProperties || destProperties.length !== 1 || !destProperties[0]) { _Log.log && _Log.log(strings.attributeBindingSingleProperty, "winjs binding", "error"); return; } dest.setAttribute(destProperties[0], v); } function setAttribute(source, sourceProperties, dest, destProperties, initialValue) { /// <signature helpKeyword="WinJS.Binding.setAttribute"> /// <summary locid="WinJS.Binding.setAttribute"> /// Creates a one-way binding between the source object and /// an attribute on the destination element. /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.setAttribute_p:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.setAttribute_p:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.setAttribute_p:dest"> /// The destination object (must be a DOM element). /// </param> /// <param name="destProperties" type="Array" locid="WinJS.Binding.setAttribute_p:destProperties"> /// The path on the destination object to the destination property, this must be a single name. /// </param> /// <param name="initialValue" optional="true" locid="WinJS.Binding.setAttribute_p:initialValue"> /// The known initial value of the target, if the source value is the same as this initial /// value (using ===) then the target is not set the first time. /// </param> /// <returns type="{ cancel: Function }" locid="WinJS.Binding.setAttribute_returnValue"> /// An object with a cancel method that is used to coalesce bindings. /// </returns> /// </signature> var bindingId = setBindingToken(dest); var ref = optimizeBindingReferences ? bindingId : dest.id; if (!ref) { dest.id = ref = bindingId; } _DomWeakRefTable._createWeakRef(dest, ref); var bindable; if (source !== _Global) { source = _Data.as(source); } if (source._getObservable) { bindable = source._getObservable(); } if (bindable) { var counter = 0; var workerResult = bindWorker(bindable, sourceProperties, function (v) { if (++counter === 1) { if (v === initialValue) { return; } } var found = checkBindingToken(_DomWeakRefTable._getWeakRefElement(ref), bindingId); if (found) { attributeSet(found, destProperties, requireSupportedForProcessing(v)); } else if (workerResult) { _Log.log && _Log.log(_Resources._formatString(strings.elementNotFound, ref), "winjs binding", "info"); workerResult.cancel(); } }); return workerResult; } else { var value = getValue(source, sourceProperties); if (value !== initialValue) { attributeSet(dest, destProperties, value); } } } function setAttributeOneTime(source, sourceProperties, dest, destProperties) { /// <signature helpKeyword="WinJS.Binding.setAttributeOneTime"> /// <summary locid="WinJS.Binding.setAttributeOneTime"> /// Sets an attribute on the destination element to the value of the source property /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.setAttributeOneTime_p:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.setAttributeOneTime_p:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.setAttributeOneTime_p:dest"> /// The destination object (must be a DOM element). /// </param> /// <param name="destProperties" type="Array" locid="WinJS.Binding.setAttributeOneTime_p:destProperties"> /// The path on the destination object to the destination property, this must be a single name. /// </param> /// </signature> return attributeSet(dest, destProperties, getValue(source, sourceProperties)); } function addClassOneTime(source, sourceProperties, dest) { /// <signature helpKeyword="WinJS.Binding.addClassOneTime"> /// <summary locid="WinJS.Binding.addClassOneTime"> /// Adds a class or Array list of classes on the destination element to the value of the source property /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.addClassOneTime:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.addClassOneTime:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.addClassOneTime:dest"> /// The destination object (must be a DOM element). /// </param> /// </signature> dest = requireSupportedForProcessing(dest); var value = getValue(source, sourceProperties); if (Array.isArray(value)) { value.forEach(function (className) { _ElementUtilities.addClass(dest, className); }); } else if (value) { _ElementUtilities.addClass(dest, value); } } var defaultBindImpl = converter(function defaultBind_passthrough(v) { return v; }); function defaultBind(source, sourceProperties, dest, destProperties, initialValue) { /// <signature helpKeyword="WinJS.Binding.defaultBind"> /// <summary locid="WinJS.Binding.defaultBind"> /// Creates a one-way binding between the source object and /// the destination object. /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.defaultBind_p:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.defaultBind_p:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.defaultBind_p:dest"> /// The destination object. /// </param> /// <param name="destProperties" type="Array" locid="WinJS.Binding.defaultBind_p:destProperties"> /// The path on the destination object to the destination property. /// </param> /// <param name="initialValue" optional="true" locid="WinJS.Binding.defaultBind_p:initialValue"> /// The known initial value of the target, if the source value is the same as this initial /// value (using ===) then the target is not set the first time. /// </param> /// <returns type="{ cancel: Function }" locid="WinJS.Binding.defaultBind_returnValue"> /// An object with a cancel method that is used to coalesce bindings. /// </returns> /// </signature> return defaultBindImpl(source, sourceProperties, dest, destProperties, initialValue); } function bindWorker(bindable, sourceProperties, func) { if (sourceProperties.length > 1) { var root = {}; var current = root; for (var i = 0, l = sourceProperties.length - 1; i < l; i++) { current = current[sourceProperties[i]] = {}; } current[sourceProperties[sourceProperties.length - 1]] = func; return _Data.bind(bindable, root, true); } else if (sourceProperties.length === 1) { bindable.bind(sourceProperties[0], func, true); return { cancel: function () { bindable.unbind(sourceProperties[0], func); this.cancel = noop; } }; } else { // can't bind to object, so we just push it through // func(bindable); } } function noop() { } function oneTime(source, sourceProperties, dest, destProperties) { /// <signature helpKeyword="WinJS.Binding.oneTime"> /// <summary locid="WinJS.Binding.oneTime"> /// Sets the destination property to the value of the source property. /// </summary> /// <param name="source" type="Object" locid="WinJS.Binding.oneTime_p:source"> /// The source object. /// </param> /// <param name="sourceProperties" type="Array" locid="WinJS.Binding.oneTime_p:sourceProperties"> /// The path on the source object to the source property. /// </param> /// <param name="dest" type="Object" locid="WinJS.Binding.oneTime_p:dest"> /// The destination object. /// </param> /// <param name="destProperties" type="Array" locid="WinJS.Binding.oneTime_p:destProperties"> /// The path on the destination object to the destination property. /// </param> /// <returns type="{ cancel: Function }" locid="WinJS.Binding.oneTime_returnValue"> /// An object with a cancel method that is used to coalesce bindings. /// </returns> /// </signature> nestedSet(dest, destProperties, getValue(source, sourceProperties)); return { cancel: noop }; } function initializer(customInitializer) { /// <signature helpKeyword="WinJS.Binding.initializer"> /// <summary locid="WinJS.Binding.initializer"> /// Marks a custom initializer function as being compatible with declarative data binding. /// </summary> /// <param name="customInitializer" type="Function" locid="WinJS.Binding.initializer_p:customInitializer"> /// The custom initializer to be marked as compatible with declarative data binding. /// </param> /// <returns type="Function" locid="WinJS.Binding.initializer_returnValue"> /// The input customInitializer. /// </returns> /// </signature> return markSupportedForProcessing(customInitializer); } _Base.Namespace._moduleDefine(exports, "WinJS.Binding", { processAll: declarativeBind, oneTime: initializer(oneTime), defaultBind: initializer(defaultBind), converter: converter, initializer: initializer, getValue: getValue, setAttribute: initializer(setAttribute), setAttributeOneTime: initializer(setAttributeOneTime), addClassOneTime: initializer(addClassOneTime), }); });
Binding declarative processing is not correctly respecting isDeclarativeControlContainer when on the root node passed to the processor (and skipRoot is false).
src/js/WinJS/Binding/_Declarative.js
Binding declarative processing is not correctly respecting isDeclarativeControlContainer when on the root node passed to the processor (and skipRoot is false).
<ide><path>rc/js/WinJS/Binding/_Declarative.js <ide> var selector = "[data-win-bind],[data-win-control]"; <ide> var elements = baseElement.querySelectorAll(selector); <ide> var neg; <del> if (!skipRoot && baseElement.getAttribute("data-win-bind")) { <add> if (!skipRoot && (baseElement.getAttribute("data-win-bind") || baseElement.winControl)) { <ide> neg = baseElement; <ide> } <ide>
Java
apache-2.0
d69b4b305c0c1c4c71c64631475221ccc6cb2690
0
shibing624/similarity
package org.xm.similarity.sentence.morphology; import org.xm.similarity.sentence.ISentenceSimilarity; import org.xm.similarity.word.IWordSimilarity; import org.xm.similarity.word.hownet.concept.ConceptSimilarity; import org.xm.tokenizer.Tokenizer; import org.xm.tokenizer.Word; import java.util.ArrayList; import java.util.List; /** * 基于词形和词序的句子相似度计算算法 * 在考虑语义时,无法直接获取OnceWS(A, B), * 为此,通过记录两个句子的词语匹配对中相似度 * 大于某一阈值的词语对为相同词语,计算次序相似度。 * * @author xuming */ public class SemanticSimilarity implements ISentenceSimilarity { /** * 词形相似度占总相似度的比重 */ private final double LAMBDA1 = 0.8; /** * 词序相似度占总相似度的比重 */ private final double LAMBDA2 = 0.2; /** * 如果两个词语的相似度大于了该阈值, 则作为相同词语,计算词序相似度 */ private final double GAMMA = 0.6; /** * 词语相似度的计算 */ private IWordSimilarity wordSimilarity = null; private static String FILTER_CHARS = "  ,。;?《》()|!,.;?<>|_^…!"; private static SemanticSimilarity instance = null; public static SemanticSimilarity getInstance() { if (instance == null) { instance = new SemanticSimilarity(); } return instance; } private SemanticSimilarity() { this.wordSimilarity = ConceptSimilarity.getInstance(); } /** * 滤掉词串中的空格、标点符号 * * @param words * @return */ private String[] filter(String[] words) { List<String> results = new ArrayList<String>(); for (String w : words) { if (!FILTER_CHARS.contains(w)) { results.add(w.toLowerCase()); } } return results.toArray(new String[results.size()]); } /** * 计算两个句子的相似度 */ @Override public double getSimilarity(String sentence1, String sentence2) { String[] list1 = filter(segment(sentence1)); String[] list2 = filter(segment(sentence2)); return calculate(list1, list2); } /** * 获取两个集合的词形相似度, 同时获取相对于第一个句子中的词语顺序,第二个句子词语的顺序变化次数 * * @param list1 * @param list2 * @return */ public double calculate(String[] list1, String[] list2) { if (list1.length == 0 || list2.length == 0) { return 0; } //首先计算出所有可能的组合 double[][] scores = new double[list1.length][list2.length]; //代表第1个句子对应位置是否已经被使用, 默认为未使用,即false boolean[] firstFlags = new boolean[list1.length]; //代表第2个句子对应位置是否已经被使用, 默认为未使用,即false boolean[] secondFlags = new boolean[list2.length]; //PSecond的定义参见书中5.4.3节, 为避免无必要的初始化数组, //数组中0值表示在第一个句子中没有对应的相似词语,大于0的值 //则表示在第一个句子中的位置(从1开始编号了) int[] PSecond = new int[list2.length]; for (int i = 0; i < list1.length; i++) { //firstFlags[i] = false; for (int j = 0; j < list2.length; j++) { scores[i][j] = wordSimilarity.getSimilarity(list1[i], list2[j]); } } double total_score = 0; //从scores[][]中挑选出最大的一个相似度,然后减去该元素(通过Flags数组表示),进一步求剩余元素中的最大相似度 while (true) { double max_score = 0; int max_row = -1; int max_col = -1; //先挑出相似度最大的一对:<row, column, max_score> for (int i = 0; i < list1.length; i++) { if (firstFlags[i]) continue; for (int j = 0; j < list2.length; j++) { if (secondFlags[j]) continue; if (max_score < scores[i][j]) { max_row = i; max_col = j; max_score = scores[i][j]; } } } if (max_row >= 0) { total_score += max_score; firstFlags[max_row] = true; secondFlags[max_col] = true; if (max_score >= GAMMA) { PSecond[max_col] = max_row + 1; } } else { break; } } double wordSim = (2 * total_score) / (list1.length + list2.length); int previous = 0; int revOrdCount = 0; int onceWSSize = 0; for (int i = 0; i < PSecond.length; i++) { if (PSecond[i] > 0) { onceWSSize++; if (previous > 0 && (previous > PSecond[i])) { revOrdCount++; } previous = PSecond[i]; } } double ordSim = 0; if (onceWSSize == 1) { ordSim = 1; } else if (onceWSSize == 0) { ordSim = 0; } else { ordSim = 1.0 - revOrdCount * 1.0 / (onceWSSize - 1); } System.out.println("wordSim ==> " + wordSim + ", ordSim ==> " + ordSim); return LAMBDA1 * wordSim + LAMBDA2 * ordSim; } public String[] segment(String sentence) { List<Word> list = Tokenizer.segment(sentence); String[] results = new String[list.size()]; for (int i = 0; i < list.size(); i++) { results[i] = list.get(i).getName(); } return results; } }
src/main/java/org/xm/similarity/sentence/morphology/SemanticSimilarity.java
package org.xm.similarity.sentence.morphology; import org.xm.similarity.sentence.ISentenceSimilarity; import org.xm.similarity.word.IWordSimilarity; import org.xm.similarity.word.hownet.concept.ConceptSimilarity; import org.xm.tokenizer.Tokenizer; import org.xm.tokenizer.Word; import java.util.ArrayList; import java.util.List; /** * 基于词形和词序的句子相似度计算算法 * 在考虑语义时,无法直接获取OnceWS(A, B), * 为此,通过记录两个句子的词语匹配对中相似度 * 大于某一阈值的词语对为相同词语,计算次序相似度。 * * @author xuming */ public class SemanticSimilarity implements ISentenceSimilarity { /** * 词形相似度占总相似度的比重 */ private final double LAMBDA1 = 0.8; /** * 词序相似度占总相似度的比重 */ private final double LAMBDA2 = 0.2; /** * 如果两个词语的相似度大于了该阈值, 则作为相同词语,计算词序相似度 */ private final double GAMMA = 0.6; /** * 词语相似度的计算 */ private IWordSimilarity wordSimilarity = null; private static String FILTER_CHARS = "  ,。;?《》()|!,.;?<>|_^…!"; private static SemanticSimilarity instance = null; public static SemanticSimilarity getInstance() { if (instance == null) { instance = new SemanticSimilarity(); } return instance; } private SemanticSimilarity() { this.wordSimilarity = ConceptSimilarity.getInstance(); } /** * 滤掉词串中的空格、标点符号 * * @param words * @return */ private String[] filter(String[] words) { List<String> results = new ArrayList<String>(); for (String w : words) { if (!FILTER_CHARS.contains(w)) { results.add(w.toLowerCase()); } } return results.toArray(new String[results.size()]); } /** * 计算两个句子的相似度 */ @Override public double getSimilarity(String sentence1, String sentence2) { String[] list1 = filter(segment(sentence1)); String[] list2 = filter(segment(sentence2)); return calculate(list1, list2); } /** * 获取两个集合的词形相似度, 同时获取相对于第一个句子中的词语顺序,第二个句子词语的顺序变化次数 * * @param list1 * @param list2 * @return */ public double calculate(String[] list1, String[] list2) { if (list1.length == 0 || list2.length == 0) { return 0; } //首先计算出所有可能的组合 double[][] scores = new double[list1.length][list2.length]; //代表第1个句子对应位置是否已经被使用, 默认为未使用,即false boolean[] firstFlags = new boolean[list1.length]; //代表第2个句子对应位置是否已经被使用, 默认为未使用,即false boolean[] secondFlags = new boolean[list2.length]; //PSecond的定义参见书中5.4.3节, 为避免无必要的初始化数组, //数组中0值表示在第一个句子中没有对应的相似词语,大于0的值 //则表示在第一个句子中的位置(从1开始编号了) int[] PSecond = new int[list2.length]; for (int i = 0; i < list1.length; i++) { //firstFlags[i] = false; for (int j = 0; j < list2.length; j++) { scores[i][j] = wordSimilarity.getSimilarity(list1[i], list2[j]); } } double total_score = 0; //从scores[][]中挑选出最大的一个相似度,然后减去该元素(通过Flags数组表示),进一步求剩余元素中的最大相似度 while (true) { double max_score = 0; int max_row = -1; int max_col = -1; //先挑出相似度最大的一对:<row, column, max_score> for (int i = 0; i < scores.length; i++) { if (firstFlags[i]) continue; for (int j = 0; j < scores.length; j++) { if (secondFlags[j]) continue; if (max_score < scores[i][j]) { max_row = i; max_col = j; max_score = scores[i][j]; } } } if (max_row >= 0) { total_score += max_score; firstFlags[max_row] = true; secondFlags[max_col] = true; if (max_score >= GAMMA) { PSecond[max_col] = max_row + 1; } } else { break; } } double wordSim = (2 * total_score) / (list1.length + list2.length); int previous = 0; int revOrdCount = 0; int onceWSSize = 0; for (int i = 0; i < PSecond.length; i++) { if (PSecond[i] > 0) { onceWSSize++; if (previous > 0 && (previous > PSecond[i])) { revOrdCount++; } previous = PSecond[i]; } } double ordSim = 0; if (onceWSSize == 1) { ordSim = 1; } else if (onceWSSize == 0) { ordSim = 0; } else { ordSim = 1.0 - revOrdCount * 1.0 / (onceWSSize - 1); } System.out.println("wordSim ==> " + wordSim + ", ordSim ==> " + ordSim); return LAMBDA1 * wordSim + LAMBDA2 * ordSim; } public String[] segment(String sentence) { List<Word> list = Tokenizer.segment(sentence); String[] results = new String[list.size()]; for (int i = 0; i < list.size(); i++) { results[i] = list.get(i).getName(); } return results; } }
Fix bug in SemanticSimilarity
src/main/java/org/xm/similarity/sentence/morphology/SemanticSimilarity.java
Fix bug in SemanticSimilarity
<ide><path>rc/main/java/org/xm/similarity/sentence/morphology/SemanticSimilarity.java <ide> int max_col = -1; <ide> <ide> //先挑出相似度最大的一对:<row, column, max_score> <del> for (int i = 0; i < scores.length; i++) { <add> for (int i = 0; i < list1.length; i++) { <ide> if (firstFlags[i]) <ide> continue; <del> for (int j = 0; j < scores.length; j++) { <add> for (int j = 0; j < list2.length; j++) { <ide> if (secondFlags[j]) <ide> continue; <ide>
Java
apache-2.0
53c95f55602879e9dfcb40117a9a1e92b0ba104d
0
nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights
/* * Copyright 2011 Jonathan Anderson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.footlights.boot; import java.net.MalformedURLException; import java.net.URL; import java.security.AllPermission; import java.security.Permissions; import java.util.Map; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; /** Loads "core" code (footlights.core.*, footlights.ui.*) from a known source */ class FootlightsClassLoader extends ClassLoader { /** Constructor */ public FootlightsClassLoader(Iterable<URL> classpaths) throws MalformedURLException { this.classpaths = Iterables.unmodifiableIterable(classpaths); this.knownPackages = Maps.newLinkedHashMap(); corePermissions = new Permissions(); corePermissions.add(new AllPermission()); corePermissions.setReadOnly(); } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> c = findClass(name); if (resolve) resolveClass(c); return c; } /** Find a core Footlights class */ @Override protected synchronized Class<?> findClass(String name) throws ClassNotFoundException { // If the "class name" is very specially encoded, we actually want to load a plugin. if (name.contains("!/")) { String[] tokens = name.split("!/"); if (tokens.length != 2) throw new ClassNotFoundException("Invalid class name: '" + name + "'"); URL classpath; try { classpath = new URL(tokens[0] + "!/"); } catch (MalformedURLException e) { throw new ClassNotFoundException("Invalid classpath: " + tokens[0], e); } String className = tokens[1]; String packageName = className.substring(0, className.lastIndexOf(".")); return ClasspathLoader.create(this, classpath, packageName).loadClass(className); } // We must be loading a core Footlights class or a Java library class. if (!name.startsWith("me.footlights")) return getParent().loadClass(name); // Do we already know what classpath to find the class in? String packageName = name.substring(0, name.lastIndexOf('.')); ClassLoader packageLoader = knownPackages.get(packageName); if (packageLoader != null) return packageLoader.loadClass(name); // Search known package sources. for (String prefix : knownPackages.keySet()) if (packageName.startsWith(prefix)) return knownPackages.get(prefix).loadClass(name); // Fall back to exhaustive search of core classpaths. for (URL url : classpaths) { try { ClasspathLoader loader = ClasspathLoader.create(this, url, packageName); Class<?> c = loader.loadClass(name); knownPackages.put(packageName, loader); return c; } catch (Exception e) {} } throw new ClassNotFoundException("No " + name + " in " + classpaths); } /** Cached permissions given to core classes. */ private final Permissions corePermissions; /** Where we can find core classes. */ private final Iterable<URL> classpaths; /** Mapping of packages to classpaths. */ private final Map<String, ClassLoader> knownPackages; }
Client/Bootstrap/src/main/java/me/footlights/boot/FootlightsClassLoader.java
/* * Copyright 2011 Jonathan Anderson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.footlights.boot; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.security.AllPermission; import java.security.Permissions; import java.util.Map; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; /** Loads "core" code (footlights.core.*, footlights.ui.*) from a known source */ class FootlightsClassLoader extends ClassLoader { /** Constructor */ public FootlightsClassLoader(Iterable<URL> classpaths) throws MalformedURLException { this.classpaths = Iterables.unmodifiableIterable(classpaths); this.knownPackages = Maps.newLinkedHashMap(); corePermissions = new Permissions(); corePermissions.add(new AllPermission()); corePermissions.setReadOnly(); } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> c = findClass(name); if (resolve) resolveClass(c); return c; } /** Find a core Footlights class */ @Override protected synchronized Class<?> findClass(String name) throws ClassNotFoundException { // If the "class name" is very specially encoded, we actually want to load a plugin. if (name.contains("!/")) { String[] tokens = name.split("!/"); if (tokens.length != 2) throw new ClassNotFoundException("Invalid class name: '" + name + "'"); URL classpath; try { classpath = new URL(tokens[0] + "!/"); } catch (MalformedURLException e) { throw new ClassNotFoundException("Invalid classpath: " + tokens[0], e); } String className = tokens[1]; String packageName = className.substring(0, className.lastIndexOf(".")); return ClasspathLoader.create(this, classpath, packageName).loadClass(className); } // We must be loading a core Footlights class or a Java library class. if (!name.startsWith("me.footlights")) return getParent().loadClass(name); // Do we already know what classpath to find the class in? String packageName = name.substring(0, name.lastIndexOf('.')); ClassLoader packageLoader = knownPackages.get(packageName); if (packageLoader != null) return packageLoader.loadClass(name); // Search known package sources. for (String prefix : knownPackages.keySet()) if (packageName.startsWith(prefix)) return knownPackages.get(prefix).loadClass(name); // Fall back to exhaustive search of core classpaths. for (URL url : classpaths) { try { ClasspathLoader loader = ClasspathLoader.create(this, url, packageName); Class<?> c = loader.loadClass(name); knownPackages.put(packageName, loader); return c; } catch (Exception e) {} } throw new ClassNotFoundException("No " + name + " in " + classpaths); } @Override public synchronized URL findResource(String name) { for (URL url : classpaths) { try { URL bigURL = new URL(url.toString() + "/" + name); if (new File(bigURL.getFile()).exists()) return bigURL; } catch(MalformedURLException e) { throw new Error(e); } } return super.findResource(name); } /** Cached permissions given to core classes. */ private final Permissions corePermissions; /** Where we can find core classes. */ private final Iterable<URL> classpaths; /** Mapping of packages to classpaths. */ private final Map<String, ClassLoader> knownPackages; }
No need for FootlightsClassLoader.findResource(). Since FootlightsClassLoader never loads code directly, it never needs to be able to load resources on behalf of code.
Client/Bootstrap/src/main/java/me/footlights/boot/FootlightsClassLoader.java
No need for FootlightsClassLoader.findResource().
<ide><path>lient/Bootstrap/src/main/java/me/footlights/boot/FootlightsClassLoader.java <ide> */ <ide> package me.footlights.boot; <ide> <del>import java.io.File; <ide> import java.net.MalformedURLException; <ide> import java.net.URL; <ide> import java.security.AllPermission; <ide> } <ide> <ide> <del> @Override public synchronized URL findResource(String name) <del> { <del> for (URL url : classpaths) <del> { <del> try <del> { <del> URL bigURL = new URL(url.toString() + "/" + name); <del> if (new File(bigURL.getFile()).exists()) return bigURL; <del> } <del> catch(MalformedURLException e) { throw new Error(e); } <del> } <del> return super.findResource(name); <del> } <del> <del> <ide> /** Cached permissions given to core classes. */ <ide> private final Permissions corePermissions; <ide>
Java
bsd-3-clause
63147c1202c470bb4669f09b31174ca366818da4
0
Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo
package org.caleydo.datadomain.genetic; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.caleydo.core.data.collection.table.DataTable; import org.caleydo.core.data.datadomain.ATableBasedDataDomain; import org.caleydo.core.data.datadomain.DataDomainConfiguration; import org.caleydo.core.data.datadomain.DataDomainManager; import org.caleydo.core.data.datadomain.EDataFilterLevel; import org.caleydo.core.data.id.IDCategory; import org.caleydo.core.data.mapping.IDMappingManager; import org.caleydo.core.data.perspective.PerspectiveInitializationData; import org.caleydo.core.data.selection.SelectionCommand; import org.caleydo.core.data.selection.delta.SelectionDelta; import org.caleydo.core.data.selection.delta.SelectionDeltaItem; import org.caleydo.core.data.virtualarray.events.ReplaceRecordPerspectiveEvent; import org.caleydo.core.data.virtualarray.events.ReplaceRecordPerspectiveListener; import org.caleydo.core.event.view.SelectionCommandEvent; import org.caleydo.core.event.view.tablebased.SelectionUpdateEvent; import org.caleydo.core.view.opengl.canvas.listener.ForeignSelectionCommandListener; import org.caleydo.core.view.opengl.canvas.listener.ForeignSelectionUpdateListener; import org.caleydo.core.view.opengl.util.texture.EIconTextures; /** * Use case specialized to genetic data. * * @author Marc Streit * @author Alexander Lex */ @XmlType @XmlRootElement public class GeneticDataDomain extends ATableBasedDataDomain { public final static String DATA_DOMAIN_TYPE = "org.caleydo.datadomain.genetic"; private static final String CLINICAL_DATADOMAIN_TYPE = "org.caleydo.datadomain.clinical"; /** * Counter used for determining the extension that together with the type * builds the data domain ID. */ private static int extensionID = 0; /** * <code>TRUE</code>if only pathways can be displayed (no gene-expression * data), <code>FALSE</code> otherwise */ private boolean pathwayViewerMode; private ReplaceRecordPerspectiveListener clinicalReplaceContentVirtualArrayListener; private ForeignSelectionUpdateListener clinicalSelectionUpdateListener; private ForeignSelectionCommandListener clinicalSelectionCommandListener; /** * Constructor. Do not create a {@link GeneticDataDomain} yourself, use * {@link DataDomainManager#createDataDomain(String)} instead. */ public GeneticDataDomain() { super(DATA_DOMAIN_TYPE, DATA_DOMAIN_TYPE + DataDomainManager.DATA_DOMAIN_INSTANCE_DELIMITER + extensionID++); icon = EIconTextures.DATA_DOMAIN_GENETIC; } public void createDefaultConfiguration() { configuration = new DataDomainConfiguration(); configuration.setMappingFile("data/bootstrap/bootstrap.xml"); configuration.setColumnDimension(true); configuration.setRecordIDCategory("GENE"); configuration.setDimensionIDCategory("SAMPLE"); configuration.setPrimaryRecordMappingType("DAVID"); configuration.setPrimaryDimensionMappingType("SAMPLE"); configuration.setHumanReadableRecordIDType("GENE_SYMBOL"); configuration.setHumanReadableDimensionIDType("SAMPLE"); configuration.setRecordDenominationPlural("genes"); configuration.setRecordDenominationSingular("gene"); configuration.setDimensionDenominationPlural("samples"); configuration.setDimensionDenominationSingular("sample"); // if (isColumnDimension) { // recordIDCategory = IDCategory.getIDCategory("GENE"); // dimensionIDCategory = IDCategory.getIDCategory("EXPERIMENT"); // // primaryRecordMappingType = IDType.getIDType("DAVID"); // humanReadableRecordIDType = IDType.getIDType("GENE_SYMBOL"); // // primaryDimensionMappingType = IDType.getIDType("DIMENSION"); // humanReadableDimensionIDType = IDType.getIDType("DIMENSION"); // // recordDenominationSingular = "gene"; // recordDenominationPlural = "genes"; // // dimensionDenominationSingular = "sample"; // dimensionDenominationPlural = "samples"; // } else { // recordIDCategory = IDCategory.getIDCategory("EXPERIMENT"); // dimensionIDCategory = IDCategory.getIDCategory("GENE"); // primaryRecordMappingType = IDType.getIDType("DIMENSION"); // humanReadableRecordIDType = IDType.getIDType("DIMENSION"); // // primaryDimensionMappingType = IDType.getIDType("DAVID"); // humanReadableDimensionIDType = IDType.getIDType("GENE_SYMBOL"); // // recordDenominationSingular = "sample"; // recordDenominationPlural = "samples"; // // dimensionDenominationSingular = "gene"; // dimensionDenominationPlural = "genes"; // } pathwayViewerMode = false; } public static DataDomainConfiguration getConfigurationWithSamplesAsRows() { DataDomainConfiguration configuration = new DataDomainConfiguration(); configuration.setMappingFile("data/bootstrap/bootstrap.xml"); configuration.setColumnDimension(false); configuration.setRecordIDCategory("SAMPLE"); configuration.setDimensionIDCategory("GENE"); configuration.setPrimaryRecordMappingType("SAMPLE"); configuration.setPrimaryDimensionMappingType("DAVID"); configuration.setHumanReadableRecordIDType("SAMPLE"); configuration.setHumanReadableDimensionIDType("GENE_SYMBOL"); configuration.setRecordDenominationPlural("samples"); configuration.setRecordDenominationSingular("sample"); configuration.setDimensionDenominationPlural("genes"); configuration.setDimensionDenominationSingular("gene"); return configuration; } @Override public void setTable(DataTable set) { super.setTable(set); } /** * Initializes a virtual array with all elements, according to the data * filters, as defined in {@link EDataFilterLevel}. */ // TODO: Re-write this as a filter // protected void initFullVA() { // // String sLevel = GeneralManager.get().getPreferenceStore() // .getString(PreferenceConstants.DATA_FILTER_LEVEL); // if (sLevel.equals("complete")) { // dataFilterLevel = EDataFilterLevel.COMPLETE; // } else if (sLevel.equals("only_mapping")) { // dataFilterLevel = EDataFilterLevel.ONLY_MAPPING; // } else if (sLevel.equals("only_context")) { // // Only apply only_context when pathways are loaded // // TODO we need to wait for the pathways to be loaded here! // if (PathwayManager.get().size() > 100) { // dataFilterLevel = EDataFilterLevel.ONLY_CONTEXT; // } else { // dataFilterLevel = EDataFilterLevel.ONLY_MAPPING; // } // } else // dataFilterLevel = EDataFilterLevel.COMPLETE; // // // initialize virtual array that contains all (filtered) information // ArrayList<Integer> alTempList = new // ArrayList<Integer>(table.getMetaData() // .depth()); // // for (int iCount = 0; iCount < table.getMetaData().depth(); iCount++) { // if (dataFilterLevel != EDataFilterLevel.COMPLETE) { // // Integer iDavidID = null; // // Here we get mapping data for all values // // FIXME: Due to new mapping system, a mapping involving // // expression index can return a Set of // // values, depending on the IDType that has been specified when // // loading expression data. // // Possibly a different handling of the Set is required. // java.util.Set<Integer> setDavidIDs = GeneralManager.get() // .getIDMappingManager() // .getIDAsSet(recordIDType, primaryRecordMappingType, iCount); // // if ((setDavidIDs != null && !setDavidIDs.isEmpty())) { // iDavidID = (Integer) setDavidIDs.toArray()[0]; // } // // GeneticIDMappingHelper.get().getDavidIDFromDimensionIndex(iCount); // // if (iDavidID == null) { // // generalManager.getLogger().log(new Status(Status.WARNING, // // GeneralManager.PLUGIN_ID, // // "Cannot resolve gene to DAVID ID!")); // continue; // } // // if (dataFilterLevel == EDataFilterLevel.ONLY_CONTEXT) { // // Here all values are contained within pathways as well // PathwayVertexGraphItem tmpPathwayVertexGraphItem = PathwayItemManager // .get().getPathwayVertexGraphItemByDavidId(iDavidID); // // if (tmpPathwayVertexGraphItem == null) { // continue; // } // } // } // // alTempList.add(iCount); // } // RecordVirtualArray recordVA = new RecordVirtualArray(DataTable.RECORD, // alTempList); // // removeDuplicates(recordVA); // // FIXME make this a filter? // table.setRecordVA(DataTable.RECORD, recordVA); // } public boolean isPathwayViewerMode() { return pathwayViewerMode; } public void setPathwayViewerMode(boolean pathwayViewerMode) { this.pathwayViewerMode = pathwayViewerMode; } @Override public void registerEventListeners() { super.registerEventListeners(); if (DataDomainManager.get().getDataDomainByType(CLINICAL_DATADOMAIN_TYPE) == null) return; String clinicalDataDomainID = DataDomainManager.get() .getDataDomainByType(CLINICAL_DATADOMAIN_TYPE).getDataDomainID(); clinicalReplaceContentVirtualArrayListener = new ReplaceRecordPerspectiveListener(); clinicalReplaceContentVirtualArrayListener.setHandler(this); clinicalReplaceContentVirtualArrayListener .setExclusiveDataDomainID(clinicalDataDomainID); eventPublisher.addListener(ReplaceRecordPerspectiveEvent.class, clinicalReplaceContentVirtualArrayListener); clinicalSelectionUpdateListener = new ForeignSelectionUpdateListener(); clinicalSelectionUpdateListener.setHandler(this); clinicalSelectionUpdateListener.setExclusiveDataDomainID(clinicalDataDomainID); eventPublisher.addListener(SelectionUpdateEvent.class, clinicalSelectionUpdateListener); clinicalSelectionCommandListener = new ForeignSelectionCommandListener(); clinicalSelectionCommandListener.setHandler(this); clinicalSelectionCommandListener.setDataDomainID(clinicalDataDomainID); eventPublisher.addListener(SelectionCommandEvent.class, clinicalSelectionCommandListener); } @Override public void unregisterEventListeners() { super.unregisterEventListeners(); if (clinicalReplaceContentVirtualArrayListener != null) { eventPublisher.removeListener(clinicalReplaceContentVirtualArrayListener); clinicalReplaceContentVirtualArrayListener = null; } if (clinicalSelectionUpdateListener != null) { eventPublisher.removeListener(clinicalSelectionUpdateListener); clinicalSelectionUpdateListener = null; } if (clinicalSelectionCommandListener != null) { eventPublisher.removeListener(clinicalSelectionCommandListener); clinicalSelectionCommandListener = null; } } @Override public void handleForeignSelectionUpdate(String dataDomainType, SelectionDelta delta, boolean scrollToSelection, String info) { // if (dataDomainType == CLINICAL_DATADOMAIN_TYPE) // System.out // .println("TODO Convert and re-send selection from clinical to genetic"); if (delta.getIDType() == dimensionIDType) { // for(ISeldelta) SelectionUpdateEvent resendEvent = new SelectionUpdateEvent(); resendEvent.setDataDomainID(this.dataDomainID); SelectionDelta convertedDelta = new SelectionDelta(delta.getIDType()); for (SelectionDeltaItem item : delta) { SelectionDeltaItem convertedItem = new SelectionDeltaItem(); convertedItem.setSelectionType(item.getSelectionType()); Integer converteID = convertClinicalExperimentToGeneticExperiment(item .getID()); if (converteID == null) continue; convertedItem.setID(converteID); convertedItem.setConnectionIDs(item.getConnectionIDs()); convertedItem.setRemove(item.isRemove()); convertedDelta.add(convertedItem); } resendEvent.setSelectionDelta((SelectionDelta) convertedDelta); eventPublisher.triggerEvent(resendEvent); } else return; } @Override public void handleForeignRecordVAUpdate(String dataDomainType, String vaType, PerspectiveInitializationData data) { // FIXME its not clear which dimension va should be updated here // if (dataDomainType.equals(CLINICAL_DATADOMAIN_TYPE)) { // DimensionVirtualArray newDimensionVirtualArray = new // DimensionVirtualArray(); // // for (Integer clinicalContentIndex : virtualArray) { // Integer converteID = // convertClinicalExperimentToGeneticExperiment(clinicalContentIndex); // if (converteID != null) // newDimensionVirtualArray.append(converteID); // // } // replaceDimensionVA(tableID, dataDomainType, DataTable.DIMENSION, // newDimensionVirtualArray); // } } // FIXME its not clear which dimension va should be updated here private Integer convertClinicalExperimentToGeneticExperiment( Integer clinicalContentIndex) { return null; } // // // FIXME - this is a hack for one special dataset (asslaber) // DataTable clinicalSet = ((ATableBasedDataDomain) DataDomainManager.get() // .getDataDomainByType(CLINICAL_DATADOMAIN_TYPE)).getTable(); // int dimensionID = clinicalSet.getDimensionData(DataTable.DIMENSION) // .getDimensionVA().get(1); // // NominalDimension clinicalDimension = (NominalDimension<String>) // clinicalSet // .get(dimensionID); // DimensionVirtualArray origianlGeneticDimensionVA = // table.getDimensionData( // DataTable.DIMENSION).getDimensionVA(); // // String label = (String) clinicalDimension.getRaw(clinicalContentIndex); // // label = label.replace("\"", ""); // // System.out.println(label); // // for (Integer dimensionIndex : origianlGeneticDimensionVA) { // if (label.equals(table.get(dimensionIndex).getLabel())) // return dimensionIndex; // } // // return null; // } @Override public void handleForeignSelectionCommand(String dataDomainType, IDCategory idCategory, SelectionCommand selectionCommand) { if (dataDomainType == CLINICAL_DATADOMAIN_TYPE && idCategory == dimensionIDCategory) { SelectionCommandEvent newCommandEvent = new SelectionCommandEvent(); newCommandEvent.setSelectionCommand(selectionCommand); newCommandEvent.tableIDCategory(idCategory); newCommandEvent.setDataDomainID(dataDomainType); eventPublisher.triggerEvent(newCommandEvent); } } // @Override // public String getRecordLabel(IDType idType, Object id) { // return super.getRecordLabel(idType, id); // // String geneSymbol = null; // // // // Set<String> setGeneSymbols = // // getGeneIDMappingManager().getIDAsSet(idType, // // humanReadableRecordIDType, id); // // // // if ((setGeneSymbols != null && !setGeneSymbols.isEmpty())) { // // geneSymbol = (String) setGeneSymbols.toArray()[0]; // // } // // // // if (geneSymbol != null) // // return geneSymbol;// + " | " + refSeq; // // // else if (refSeq != null) // // // return refSeq; // // else // // return "No mapping"; // // } public IDMappingManager getGeneIDMappingManager() { if (isColumnDimension) return recordIDMappingManager; else return dimensionIDMappingManager; } public IDMappingManager getSampleIDMappingManager() { if (isColumnDimension) return dimensionIDMappingManager; else return recordIDMappingManager; } // FIXME CONTEXT MENU // @Override // public AItemContainer getRecordItemContainer(IDType idType, int id) { // // GeneContextMenuItemContainer geneContainer = new // GeneContextMenuItemContainer(); // geneContainer.setDataDomain(this); // geneContainer.tableID(idType, id); // return geneContainer; // } // FIXME CONTEXT MENU // @Override // public AItemContainer getRecordGroupItemContainer(IDType idType, // ArrayList<Integer> ids) { // GeneRecordGroupMenuItemContainer geneContentGroupContainer = new // GeneRecordGroupMenuItemContainer(); // geneContentGroupContainer.setDataDomain(this); // geneContentGroupContainer.setGeneIDs(recordIDType, ids); // return geneContentGroupContainer; // } }
org.caleydo.datadomain.genetic/src/org/caleydo/datadomain/genetic/GeneticDataDomain.java
package org.caleydo.datadomain.genetic; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.caleydo.core.data.collection.table.DataTable; import org.caleydo.core.data.datadomain.ATableBasedDataDomain; import org.caleydo.core.data.datadomain.DataDomainConfiguration; import org.caleydo.core.data.datadomain.DataDomainManager; import org.caleydo.core.data.datadomain.EDataFilterLevel; import org.caleydo.core.data.id.IDCategory; import org.caleydo.core.data.mapping.IDMappingManager; import org.caleydo.core.data.perspective.PerspectiveInitializationData; import org.caleydo.core.data.selection.SelectionCommand; import org.caleydo.core.data.selection.delta.SelectionDelta; import org.caleydo.core.data.selection.delta.SelectionDeltaItem; import org.caleydo.core.data.virtualarray.events.ReplaceRecordPerspectiveEvent; import org.caleydo.core.data.virtualarray.events.ReplaceRecordPerspectiveListener; import org.caleydo.core.event.view.SelectionCommandEvent; import org.caleydo.core.event.view.tablebased.SelectionUpdateEvent; import org.caleydo.core.view.opengl.canvas.listener.ForeignSelectionCommandListener; import org.caleydo.core.view.opengl.canvas.listener.ForeignSelectionUpdateListener; import org.caleydo.core.view.opengl.util.texture.EIconTextures; /** * Use case specialized to genetic data. * * @author Marc Streit * @author Alexander Lex */ @XmlType @XmlRootElement public class GeneticDataDomain extends ATableBasedDataDomain { public final static String DATA_DOMAIN_TYPE = "org.caleydo.datadomain.genetic"; private static final String CLINICAL_DATADOMAIN_TYPE = "org.caleydo.datadomain.clinical"; /** * Counter used for determining the extension that together with the type * builds the data domain ID. */ private static int extensionID = 0; /** * <code>TRUE</code>if only pathways can be displayed (no gene-expression * data), <code>FALSE</code> otherwise */ private boolean pathwayViewerMode; private ReplaceRecordPerspectiveListener clinicalReplaceContentVirtualArrayListener; private ForeignSelectionUpdateListener clinicalSelectionUpdateListener; private ForeignSelectionCommandListener clinicalSelectionCommandListener; /** * Constructor. Do not create a {@link GeneticDataDomain} yourself, use * {@link DataDomainManager#createDataDomain(String)} instead. */ public GeneticDataDomain() { super(DATA_DOMAIN_TYPE, DATA_DOMAIN_TYPE + DataDomainManager.DATA_DOMAIN_INSTANCE_DELIMITER + extensionID++); icon = EIconTextures.DATA_DOMAIN_GENETIC; } public void createDefaultConfiguration() { configuration = new DataDomainConfiguration(); configuration.setMappingFile("data/bootstrap/bootstrap.xml"); configuration.setColumnDimension(true); configuration.setRecordIDCategory("GENE"); configuration.setDimensionIDCategory("EXPERIMENT"); configuration.setPrimaryRecordMappingType("DAVID"); configuration.setPrimaryDimensionMappingType("DIMENSION"); configuration.setHumanReadableRecordIDType("GENE_SYMBOL"); configuration.setHumanReadableDimensionIDType("DIMENSION"); configuration.setRecordDenominationPlural("genes"); configuration.setRecordDenominationSingular("gene"); configuration.setDimensionDenominationPlural("samples"); configuration.setDimensionDenominationSingular("sample"); // if (isColumnDimension) { // recordIDCategory = IDCategory.getIDCategory("GENE"); // dimensionIDCategory = IDCategory.getIDCategory("EXPERIMENT"); // // primaryRecordMappingType = IDType.getIDType("DAVID"); // humanReadableRecordIDType = IDType.getIDType("GENE_SYMBOL"); // // primaryDimensionMappingType = IDType.getIDType("DIMENSION"); // humanReadableDimensionIDType = IDType.getIDType("DIMENSION"); // // recordDenominationSingular = "gene"; // recordDenominationPlural = "genes"; // // dimensionDenominationSingular = "sample"; // dimensionDenominationPlural = "samples"; // } else { // recordIDCategory = IDCategory.getIDCategory("EXPERIMENT"); // dimensionIDCategory = IDCategory.getIDCategory("GENE"); // primaryRecordMappingType = IDType.getIDType("DIMENSION"); // humanReadableRecordIDType = IDType.getIDType("DIMENSION"); // // primaryDimensionMappingType = IDType.getIDType("DAVID"); // humanReadableDimensionIDType = IDType.getIDType("GENE_SYMBOL"); // // recordDenominationSingular = "sample"; // recordDenominationPlural = "samples"; // // dimensionDenominationSingular = "gene"; // dimensionDenominationPlural = "genes"; // } pathwayViewerMode = false; } public static DataDomainConfiguration getConfigurationWithSamplesAsRows() { DataDomainConfiguration configuration = new DataDomainConfiguration(); configuration.setMappingFile("data/bootstrap/bootstrap.xml"); configuration.setColumnDimension(false); configuration.setRecordIDCategory("SAMPLE"); configuration.setDimensionIDCategory("GENE"); configuration.setPrimaryRecordMappingType("SAMPLE"); configuration.setPrimaryDimensionMappingType("DAVID"); configuration.setHumanReadableRecordIDType("SAMPLE"); configuration.setHumanReadableDimensionIDType("GENE_SYMBOL"); configuration.setRecordDenominationPlural("samples"); configuration.setRecordDenominationSingular("sample"); configuration.setDimensionDenominationPlural("genes"); configuration.setDimensionDenominationSingular("gene"); return configuration; } @Override public void setTable(DataTable set) { super.setTable(set); } /** * Initializes a virtual array with all elements, according to the data * filters, as defined in {@link EDataFilterLevel}. */ // TODO: Re-write this as a filter // protected void initFullVA() { // // String sLevel = GeneralManager.get().getPreferenceStore() // .getString(PreferenceConstants.DATA_FILTER_LEVEL); // if (sLevel.equals("complete")) { // dataFilterLevel = EDataFilterLevel.COMPLETE; // } else if (sLevel.equals("only_mapping")) { // dataFilterLevel = EDataFilterLevel.ONLY_MAPPING; // } else if (sLevel.equals("only_context")) { // // Only apply only_context when pathways are loaded // // TODO we need to wait for the pathways to be loaded here! // if (PathwayManager.get().size() > 100) { // dataFilterLevel = EDataFilterLevel.ONLY_CONTEXT; // } else { // dataFilterLevel = EDataFilterLevel.ONLY_MAPPING; // } // } else // dataFilterLevel = EDataFilterLevel.COMPLETE; // // // initialize virtual array that contains all (filtered) information // ArrayList<Integer> alTempList = new // ArrayList<Integer>(table.getMetaData() // .depth()); // // for (int iCount = 0; iCount < table.getMetaData().depth(); iCount++) { // if (dataFilterLevel != EDataFilterLevel.COMPLETE) { // // Integer iDavidID = null; // // Here we get mapping data for all values // // FIXME: Due to new mapping system, a mapping involving // // expression index can return a Set of // // values, depending on the IDType that has been specified when // // loading expression data. // // Possibly a different handling of the Set is required. // java.util.Set<Integer> setDavidIDs = GeneralManager.get() // .getIDMappingManager() // .getIDAsSet(recordIDType, primaryRecordMappingType, iCount); // // if ((setDavidIDs != null && !setDavidIDs.isEmpty())) { // iDavidID = (Integer) setDavidIDs.toArray()[0]; // } // // GeneticIDMappingHelper.get().getDavidIDFromDimensionIndex(iCount); // // if (iDavidID == null) { // // generalManager.getLogger().log(new Status(Status.WARNING, // // GeneralManager.PLUGIN_ID, // // "Cannot resolve gene to DAVID ID!")); // continue; // } // // if (dataFilterLevel == EDataFilterLevel.ONLY_CONTEXT) { // // Here all values are contained within pathways as well // PathwayVertexGraphItem tmpPathwayVertexGraphItem = PathwayItemManager // .get().getPathwayVertexGraphItemByDavidId(iDavidID); // // if (tmpPathwayVertexGraphItem == null) { // continue; // } // } // } // // alTempList.add(iCount); // } // RecordVirtualArray recordVA = new RecordVirtualArray(DataTable.RECORD, // alTempList); // // removeDuplicates(recordVA); // // FIXME make this a filter? // table.setRecordVA(DataTable.RECORD, recordVA); // } public boolean isPathwayViewerMode() { return pathwayViewerMode; } public void setPathwayViewerMode(boolean pathwayViewerMode) { this.pathwayViewerMode = pathwayViewerMode; } @Override public void registerEventListeners() { super.registerEventListeners(); if (DataDomainManager.get().getDataDomainByType(CLINICAL_DATADOMAIN_TYPE) == null) return; String clinicalDataDomainID = DataDomainManager.get() .getDataDomainByType(CLINICAL_DATADOMAIN_TYPE).getDataDomainID(); clinicalReplaceContentVirtualArrayListener = new ReplaceRecordPerspectiveListener(); clinicalReplaceContentVirtualArrayListener.setHandler(this); clinicalReplaceContentVirtualArrayListener .setExclusiveDataDomainID(clinicalDataDomainID); eventPublisher.addListener(ReplaceRecordPerspectiveEvent.class, clinicalReplaceContentVirtualArrayListener); clinicalSelectionUpdateListener = new ForeignSelectionUpdateListener(); clinicalSelectionUpdateListener.setHandler(this); clinicalSelectionUpdateListener.setExclusiveDataDomainID(clinicalDataDomainID); eventPublisher.addListener(SelectionUpdateEvent.class, clinicalSelectionUpdateListener); clinicalSelectionCommandListener = new ForeignSelectionCommandListener(); clinicalSelectionCommandListener.setHandler(this); clinicalSelectionCommandListener.setDataDomainID(clinicalDataDomainID); eventPublisher.addListener(SelectionCommandEvent.class, clinicalSelectionCommandListener); } @Override public void unregisterEventListeners() { super.unregisterEventListeners(); if (clinicalReplaceContentVirtualArrayListener != null) { eventPublisher.removeListener(clinicalReplaceContentVirtualArrayListener); clinicalReplaceContentVirtualArrayListener = null; } if (clinicalSelectionUpdateListener != null) { eventPublisher.removeListener(clinicalSelectionUpdateListener); clinicalSelectionUpdateListener = null; } if (clinicalSelectionCommandListener != null) { eventPublisher.removeListener(clinicalSelectionCommandListener); clinicalSelectionCommandListener = null; } } @Override public void handleForeignSelectionUpdate(String dataDomainType, SelectionDelta delta, boolean scrollToSelection, String info) { // if (dataDomainType == CLINICAL_DATADOMAIN_TYPE) // System.out // .println("TODO Convert and re-send selection from clinical to genetic"); if (delta.getIDType() == dimensionIDType) { // for(ISeldelta) SelectionUpdateEvent resendEvent = new SelectionUpdateEvent(); resendEvent.setDataDomainID(this.dataDomainID); SelectionDelta convertedDelta = new SelectionDelta(delta.getIDType()); for (SelectionDeltaItem item : delta) { SelectionDeltaItem convertedItem = new SelectionDeltaItem(); convertedItem.setSelectionType(item.getSelectionType()); Integer converteID = convertClinicalExperimentToGeneticExperiment(item .getID()); if (converteID == null) continue; convertedItem.setID(converteID); convertedItem.setConnectionIDs(item.getConnectionIDs()); convertedItem.setRemove(item.isRemove()); convertedDelta.add(convertedItem); } resendEvent.setSelectionDelta((SelectionDelta) convertedDelta); eventPublisher.triggerEvent(resendEvent); } else return; } @Override public void handleForeignRecordVAUpdate(String dataDomainType, String vaType, PerspectiveInitializationData data) { // FIXME its not clear which dimension va should be updated here // if (dataDomainType.equals(CLINICAL_DATADOMAIN_TYPE)) { // DimensionVirtualArray newDimensionVirtualArray = new // DimensionVirtualArray(); // // for (Integer clinicalContentIndex : virtualArray) { // Integer converteID = // convertClinicalExperimentToGeneticExperiment(clinicalContentIndex); // if (converteID != null) // newDimensionVirtualArray.append(converteID); // // } // replaceDimensionVA(tableID, dataDomainType, DataTable.DIMENSION, // newDimensionVirtualArray); // } } // FIXME its not clear which dimension va should be updated here private Integer convertClinicalExperimentToGeneticExperiment( Integer clinicalContentIndex) { return null; } // // // FIXME - this is a hack for one special dataset (asslaber) // DataTable clinicalSet = ((ATableBasedDataDomain) DataDomainManager.get() // .getDataDomainByType(CLINICAL_DATADOMAIN_TYPE)).getTable(); // int dimensionID = clinicalSet.getDimensionData(DataTable.DIMENSION) // .getDimensionVA().get(1); // // NominalDimension clinicalDimension = (NominalDimension<String>) // clinicalSet // .get(dimensionID); // DimensionVirtualArray origianlGeneticDimensionVA = // table.getDimensionData( // DataTable.DIMENSION).getDimensionVA(); // // String label = (String) clinicalDimension.getRaw(clinicalContentIndex); // // label = label.replace("\"", ""); // // System.out.println(label); // // for (Integer dimensionIndex : origianlGeneticDimensionVA) { // if (label.equals(table.get(dimensionIndex).getLabel())) // return dimensionIndex; // } // // return null; // } @Override public void handleForeignSelectionCommand(String dataDomainType, IDCategory idCategory, SelectionCommand selectionCommand) { if (dataDomainType == CLINICAL_DATADOMAIN_TYPE && idCategory == dimensionIDCategory) { SelectionCommandEvent newCommandEvent = new SelectionCommandEvent(); newCommandEvent.setSelectionCommand(selectionCommand); newCommandEvent.tableIDCategory(idCategory); newCommandEvent.setDataDomainID(dataDomainType); eventPublisher.triggerEvent(newCommandEvent); } } // @Override // public String getRecordLabel(IDType idType, Object id) { // return super.getRecordLabel(idType, id); // // String geneSymbol = null; // // // // Set<String> setGeneSymbols = // // getGeneIDMappingManager().getIDAsSet(idType, // // humanReadableRecordIDType, id); // // // // if ((setGeneSymbols != null && !setGeneSymbols.isEmpty())) { // // geneSymbol = (String) setGeneSymbols.toArray()[0]; // // } // // // // if (geneSymbol != null) // // return geneSymbol;// + " | " + refSeq; // // // else if (refSeq != null) // // // return refSeq; // // else // // return "No mapping"; // // } public IDMappingManager getGeneIDMappingManager() { if (isColumnDimension) return recordIDMappingManager; else return dimensionIDMappingManager; } public IDMappingManager getSampleIDMappingManager() { if (isColumnDimension) return dimensionIDMappingManager; else return recordIDMappingManager; } // FIXME CONTEXT MENU // @Override // public AItemContainer getRecordItemContainer(IDType idType, int id) { // // GeneContextMenuItemContainer geneContainer = new // GeneContextMenuItemContainer(); // geneContainer.setDataDomain(this); // geneContainer.tableID(idType, id); // return geneContainer; // } // FIXME CONTEXT MENU // @Override // public AItemContainer getRecordGroupItemContainer(IDType idType, // ArrayList<Integer> ids) { // GeneRecordGroupMenuItemContainer geneContentGroupContainer = new // GeneRecordGroupMenuItemContainer(); // geneContentGroupContainer.setDataDomain(this); // geneContentGroupContainer.setGeneIDs(recordIDType, ids); // return geneContentGroupContainer; // } }
Fixed inconsistencies between xml and default genetic configurations git-svn-id: 149221363d454b9399d51e0b24a857a738336ca8@4346 1f7349ae-fd9f-0d40-aeb8-9798e6c0fce3
org.caleydo.datadomain.genetic/src/org/caleydo/datadomain/genetic/GeneticDataDomain.java
Fixed inconsistencies between xml and default genetic configurations
<ide><path>rg.caleydo.datadomain.genetic/src/org/caleydo/datadomain/genetic/GeneticDataDomain.java <ide> configuration.setColumnDimension(true); <ide> <ide> configuration.setRecordIDCategory("GENE"); <del> configuration.setDimensionIDCategory("EXPERIMENT"); <add> configuration.setDimensionIDCategory("SAMPLE"); <ide> <ide> configuration.setPrimaryRecordMappingType("DAVID"); <del> configuration.setPrimaryDimensionMappingType("DIMENSION"); <add> configuration.setPrimaryDimensionMappingType("SAMPLE"); <ide> <ide> configuration.setHumanReadableRecordIDType("GENE_SYMBOL"); <del> configuration.setHumanReadableDimensionIDType("DIMENSION"); <add> configuration.setHumanReadableDimensionIDType("SAMPLE"); <ide> <ide> configuration.setRecordDenominationPlural("genes"); <ide> configuration.setRecordDenominationSingular("gene");
JavaScript
apache-2.0
e251a9451973370953cb557bd52116ab0887e2c1
0
christabor/etude,christabor/etude,christabor/etude
var ca_presets = { // a much more obvious and intuitive (and simple) // way to map rulesets -- data as code! container: $('#canvii'), players: [], rulesets:[ { '000': [1, 1, 1], '001': [1, 0, 0], '010': [1, 0, 0], '011': [0, 1, 0], '111': [0, 1, 0], '100': [0, 0, 1], '110': [1, 0, 0], '101': [1, 1, 1] }, { '000': [0, 0, 1], '001': [1, 0, 0], '010': [1, 1, 1], '011': [0, 0, 0], '111': [0, 1, 1], '100': [0, 1, 1], '110': [1, 1, 0], '101': [1, 0, 1] }, { '000': [1, 0, 1], '001': [1, 0, 1], '010': [0, 1, 1], '011': [1, 1, 0], '111': [0, 1, 0], '100': [0, 1, 0], '110': [1, 0, 0], '101': [1, 1, 1] }, { '000': [0, 1, 0], '001': [1, 0, 0], '010': [1, 0, 1], '011': [0, 1, 0], '111': [1, 0, 0], '100': [1, 0, 1], '110': [0, 0, 1], '101': [1, 1, 0] }, { '000': [1, 1, 0], '001': [1, 1, 0], '010': [1, 0, 1], '011': [0, 0, 1], '111': [1, 1, 0], '100': [1, 1, 1], '110': [0, 1, 1], '101': [1, 1, 1] }, { '000': [0, 1, 1], '001': [0, 1, 0], '010': [1, 0, 1], '011': [0, 1, 1], '111': [1, 0, 0], '100': [0, 0, 1], '110': [1, 1, 0], '101': [0, 1, 0] }, { '000': [1, 1, 1], '001': [1, 0, 0], '010': [1, 0, 0], '011': [0, 0, 1], '111': [1, 1, 1], '100': [0, 1, 0], '110': [1, 0, 0], '101': [1, 1, 0] }, { '000': [0, 1, 0], '001': [0, 1, 1], '010': [1, 0, 0], '011': [0, 0, 1], '111': [1, 0, 1], '100': [0, 0, 1], '110': [1, 1, 0], '101': [1, 1, 0] } ] }; var CanvasAutomota = function() { var self = this; this.speed = 100; this.states = []; this.size = 4; this.width = 250; this.height = 250; this.generation = 0; this.container = $('<div></div>'); this.gen = $('<p></p>'); this.stop_btn = $('<button class="btn stop-btn">Stop</button>'); this.start_btn = $('<button class="btn start-btn">Start</button>'); this.container.attr({ 'class': 'canvas', 'id': uuid() }); this.updateBox = function(x, y, state) { var states_map = { 0: '#fff', 1: '#000' }; self.ctx.fillStyle = states_map[state]; self.ctx.fillRect(x, y, self.size, self.size); self.ctx.fill(); } this.seedAll = function() { for(var y = 0, i = 0; y <= self.height; y += self.size, i += 1) { for(var x = 0; x <= self.width; x += self.size) { var state = rando(10) === rando(10) ? 1 : 0; self.states.push([x, y, state]); self.updateBox(x, y, state); } } } this.updateState = function(i, x, y, state) { self.states[i] = [x, y, state]; } this.addAll = function() { for(var y = 0, i = 0; y <= self.height; y += self.size, i += 1) { for(var x = 0; x <= self.width; x += self.size) { try { var pattern = [self.states[i - 1][2], self.states[i][2], self.states[i + 1][2]].join(''); var rule = self.ruleset[pattern]; var x1 = x - self.size; var y1 = y - self.size; var x2 = x + self.size; var y2 = x + self.size; self.updateBox(x1, y1, rule[0]); self.updateBox(x, y, rule[1]); self.updateBox(x2, y2, rule[2]); self.updateState(i - 1, x1, y1, rule[0]); self.updateState(i, x, y, rule[1]); self.updateState(i + 1, x2, y2, rule[2]); self.updateState(i + 1, x2, y2, rule[2]); } catch(e) {} } } } this.step = function() { // adds all states, // then draws, before next step self.addAll(); self.generation += 1; self.gen.text('Generation: ' + self.generation); } this.startPlaying = function() { self.interval = setInterval(self.step, self.speed); } this.stopPlaying = function() { clearInterval(self.interval); } this.clearCanvas = function(){ self.ctx.fillStyle = 'white'; self.ctx.fillRect(0, 0, self.size, self.size); self.ctx.fill(); } this.registerToGlobal = function() { ca_presets.players.push(self); } this.restart = function() { self.stopPlaying(); self.clearCanvas(); self.states = []; self.generation = 0; self.gen.text('Generation: ' + self.generation); self.seedAll(); self.startPlaying(); } this.init = function(canvas, ruleset) { ca_presets.container.append(self.container); self.canvas_elem = canvas[0]; self.ruleset = ruleset; self.canvas_elem.width = self.width; self.canvas_elem.height = self.height; self.ctx = self.canvas_elem.getContext('2d'); self.container.wrapInner(self.canvas_elem); self.seedAll(); self.container.prepend(self.gen); self.container.prepend(self.stop_btn); self.container.prepend(self.start_btn); self.start_btn.on('click', self.startPlaying); self.stop_btn.on('click', self.stopPlaying); self.gen.text('Generation: ' + self.generation); self.startPlaying(); self.registerToGlobal(); } }; var elem_ca = (function(){ function initAll() { var restart = $('#restart-all'); restart.on('click', function(){ $(ca_presets.players).each(function(k, player){ player.restart(); }); }); $('canvas').each(function(k, canvas){ var ca = new CanvasAutomota(); ca.init($(canvas), ca_presets.rulesets[k]); }); } // might as well privatize it return { 'init': initAll }; })(); $(document).ready(elem_ca.init);
02-16-2014/box.js
var ca_presets = { // a much more obvious and intuitive (and simple) // way to map rulesets -- data as code! container: $('#canvii'), players: [], rulesets:[ { '000': [1, 1, 1], '001': [1, 0, 0], '010': [1, 0, 0], '011': [0, 1, 0], '111': [0, 1, 0], '100': [0, 0, 1], '110': [1, 0, 0], '101': [1, 1, 1] }, { '000': [0, 0, 1], '001': [1, 0, 0], '010': [1, 1, 1], '011': [0, 0, 0], '111': [0, 1, 1], '100': [0, 1, 1], '110': [1, 1, 0], '101': [1, 0, 1] }, { '000': [1, 0, 1], '001': [1, 0, 1], '010': [0, 1, 1], '011': [1, 1, 0], '111': [0, 1, 0], '100': [0, 1, 0], '110': [1, 0, 0], '101': [1, 1, 1] }, { '000': [0, 1, 0], '001': [1, 0, 0], '010': [1, 0, 1], '011': [0, 1, 0], '111': [1, 0, 0], '100': [1, 0, 1], '110': [0, 0, 1], '101': [1, 1, 0] }, { '000': [1, 1, 0], '001': [1, 1, 0], '010': [1, 0, 1], '011': [0, 0, 1], '111': [1, 1, 0], '100': [1, 1, 1], '110': [0, 1, 1], '101': [1, 1, 1] }, { '000': [0, 1, 1], '001': [0, 1, 0], '010': [1, 0, 1], '011': [0, 1, 1], '111': [1, 0, 0], '100': [0, 0, 1], '110': [1, 1, 0], '101': [0, 1, 0] }, { '000': [1, 1, 1], '001': [1, 0, 0], '010': [1, 0, 0], '011': [0, 0, 1], '111': [1, 1, 1], '100': [0, 1, 0], '110': [1, 0, 0], '101': [1, 1, 0] }, { '000': [0, 1, 0], '001': [0, 1, 1], '010': [1, 0, 0], '011': [0, 0, 1], '111': [1, 0, 1], '100': [0, 0, 1], '110': [1, 1, 0], '101': [1, 1, 0] } ] }; var CanvasAutomota = function() { var self = this; this.speed = 100; this.states = []; this.size = 4; this.width = 250; this.height = 250; this.generation = 0; this.container = $('<div></div>'); this.gen = $('<p></p>'); this.stop_btn = $('<button class="btn stop-btn">Stop</button>'); this.start_btn = $('<button class="btn start-btn">Start</button>'); this.container.attr({ 'class': 'canvas', 'id': uuid() }); this.updateBox = function(x, y, state) { var states_map = { 0: '#fff', 1: '#000' }; self.ctx.fillStyle = states_map[state]; self.ctx.fillRect(x, y, self.size, self.size); self.ctx.fill(); } this.seedAll = function() { for(var y = 0, i = 0; y <= self.height; y += self.size, i += 1) { for(var x = 0; x <= self.width; x += self.size) { var state = rando(10) === rando(10) ? 1 : 0; self.states.push([x, y, state]); self.updateBox(x, y, state); } } } this.updateState = function(i, x, y, state) { self.states[i] = [x, y, state]; } this.addAll = function() { for(var y = 0, i = 0; y <= self.height; y += self.size, i += 1) { for(var x = 0; x <= self.width; x += self.size) { try { var pattern = [self.states[i - 1][2], self.states[i][2], self.states[i + 1][2]].join(''); var rule = self.ruleset[pattern]; var x1 = x - self.size; var y1 = y - self.size; var x2 = x + self.size; var y2 = x + self.size; self.updateBox(x1, y1, rule[0]); self.updateBox(x, y, rule[1]); self.updateBox(x2, y2, rule[2]); self.updateState(i - 1, x1, y1, rule[0]); self.updateState(i, x, y, rule[1]); self.updateState(i + 1, x2, y2, rule[2]); self.updateState(i + 1, x2, y2, rule[2]); } catch(e) {} } } } this.step = function() { // adds all states, // then draws, before next step self.addAll(); self.generation += 1; self.gen.text('Generation: ' + self.generation); } this.startPlaying = function() { self.interval = setInterval(self.step, self.speed); } this.stopPlaying = function() { clearInterval(self.interval); } this.clearCanvas = function(){ self.ctx.fillStyle = 'white'; self.ctx.fillRect(0, 0, self.size, self.size); self.ctx.fill(); } this.registerToGlobal = function() { ca_presets.players.push(self); } this.restart = function() { self.stopPlaying(); self.clearCanvas(); self.states = []; self.seedAll(); self.startPlaying(); } this.init = function(canvas, ruleset) { ca_presets.container.append(self.container); self.canvas_elem = canvas[0]; self.ruleset = ruleset; self.canvas_elem.width = self.width; self.canvas_elem.height = self.height; self.ctx = self.canvas_elem.getContext('2d'); self.container.wrapInner(self.canvas_elem); self.seedAll(); self.container.prepend(self.gen); self.container.prepend(self.stop_btn); self.container.prepend(self.start_btn); self.start_btn.on('click', self.startPlaying); self.stop_btn.on('click', self.stopPlaying); self.gen.text('Generation: ' + self.generation); self.startPlaying(); self.registerToGlobal(); } }; var elem_ca = (function(){ function initAll() { var restart = $('#restart-all'); restart.on('click', function(){ $(ca_presets.players).each(function(k, player){ player.restart(); }); }); $('canvas').each(function(k, canvas){ var ca = new CanvasAutomota(); ca.init($(canvas), ca_presets.rulesets[k]); }); } // might as well privatize it return { 'init': initAll }; })(); $(document).ready(elem_ca.init);
Reset text as well
02-16-2014/box.js
Reset text as well
<ide><path>2-16-2014/box.js <ide> self.stopPlaying(); <ide> self.clearCanvas(); <ide> self.states = []; <add> self.generation = 0; <add> self.gen.text('Generation: ' + self.generation); <ide> self.seedAll(); <ide> self.startPlaying(); <ide> }
Java
apache-2.0
9fbf8988cf275fb1f58b2ba1ede1b5f7528b1533
0
tamalsen/vibur-dbcp,vibur/vibur-dbcp
/** * Copyright 2013 Simeon Malchev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vibur.dbcp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vibur.dbcp.listener.DestroyListener; import org.vibur.objectpool.PoolObjectFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.TimeUnit; /** * @author Simeon Malchev */ public class ConnectionObjectFactory implements PoolObjectFactory<ConnState> { private static final Logger logger = LoggerFactory.getLogger(ConnectionObjectFactory.class); /** Database driver class name */ private final String driverClassName; /** Database JDBC Connection string. */ private final String jdbcUrl; /** User name to use. */ private final String username; /** Password to use. */ private final String password; /** If the connection has stayed in the pool for at least {@code validateIfIdleForSeconds}, * it will be validated before being given to the application using the {@code testConnectionQuery}. * If set to zero, will validate the connection always when it is taken from the pool. * If set to a negative number, will never validate the taken from the pool connection. */ private final int validateIfIdleForSeconds; /** Used to test the validity of the JDBC Connection. Set to {@code null} to disable. */ private final String testConnectionQuery; /** After attempting to acquire a JDBC Connection and failing with an {@code SQLException}, * wait for this value before attempting to acquire a new JDBC Connection again. */ private final long acquireRetryDelayInMs; /** After attempting to acquire a JDBC Connection and failing with an {@code SQLException}, * try to connect these many times before giving up. */ private final int acquireRetryAttempts; /** The default auto-commit state of created connections. */ private final Boolean defaultAutoCommit; /** The default read-only state of created connections. */ private final Boolean defaultReadOnly; /** The default transaction isolation state of created connections. */ private final Integer defaultTransactionIsolation; /** The default catalog state of created connections. */ private final String defaultCatalog; private final DestroyListener destroyListener; public ConnectionObjectFactory(String driverClassName, String jdbcUrl, String username, String password, int validateIfIdleForSeconds, String testConnectionQuery, long acquireRetryDelayInMs, int acquireRetryAttempts, Boolean defaultAutoCommit, Boolean defaultReadOnly, Integer defaultTransactionIsolation, String defaultCatalog, DestroyListener destroyListener) { this.driverClassName = driverClassName; this.jdbcUrl = jdbcUrl; this.username = username; this.password = password; this.validateIfIdleForSeconds = validateIfIdleForSeconds; this.testConnectionQuery = testConnectionQuery; this.acquireRetryDelayInMs = acquireRetryDelayInMs; this.acquireRetryAttempts = acquireRetryAttempts; this.defaultAutoCommit = defaultAutoCommit; this.defaultReadOnly = defaultReadOnly; this.defaultTransactionIsolation = defaultTransactionIsolation; this.defaultCatalog = defaultCatalog; this.destroyListener = destroyListener; try { Class.forName(this.driverClassName); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * {@inheritDoc} * * @throws ViburDBCPException if cannot create the underlying JDBC Connection. * */ public ConnState create() throws ViburDBCPException { int attempt = 0; Connection connection = null; while (connection == null) { try { if (username == null && password == null) connection = DriverManager.getConnection(jdbcUrl); else connection = DriverManager.getConnection(jdbcUrl, username, password); } catch (SQLException e) { logger.debug("Couldn't create a java.sql.Connection, attempt " + attempt, e); if (attempt++ >= acquireRetryAttempts) throw new ViburDBCPException(e); try { TimeUnit.MILLISECONDS.sleep(acquireRetryDelayInMs); } catch (InterruptedException ignore) { } } } logger.trace("Created " + connection); return new ConnState(connection, System.currentTimeMillis()); } private void setDefaultValues(Connection connection) throws ViburDBCPException { try { if (defaultAutoCommit != null) connection.setAutoCommit(defaultAutoCommit); if (defaultReadOnly != null) connection.setReadOnly(defaultReadOnly); if (defaultTransactionIsolation != null) connection.setTransactionIsolation(defaultTransactionIsolation); if (defaultCatalog != null) connection.setCatalog(defaultCatalog); } catch (SQLException e) { throw new ViburDBCPException(e); } } /** {@inheritDoc} */ public boolean readyToTake(ConnState connState) throws ViburDBCPException { if (validateIfIdleForSeconds >= 0) { int idle = (int) (connState.getLastTimeUsedInMillis() - System.currentTimeMillis()) / 1000; if (idle >= validateIfIdleForSeconds) if (!executeTestStatement(connState.connection())) return false; } setDefaultValues(connState.connection()); return true; } /** * {@inheritDoc} * * @throws ViburDBCPException if cannot restore the default values for the underlying JDBC Connection. * */ public boolean readyToRestore(ConnState connState) { connState.setLastTimeUsedInMillis(System.currentTimeMillis()); return true; } private boolean executeTestStatement(Connection connection) { Statement statement = null; try { statement = connection.createStatement(); statement.execute(testConnectionQuery); statement.close(); return true; } catch (SQLException e) { logger.debug("Couldn't validate " + connection, e); try { if (statement != null) statement.close(); } catch (SQLException ignore) { } return false; } } /** {@inheritDoc} */ public void destroy(ConnState connState) { Connection connection = connState.connection(); try { logger.trace("Destroying " + connection); destroyListener.onDestroy(connection); connection.close(); } catch (SQLException e) { logger.debug("Couldn't close " + connection, e); } } }
src/main/java/org/vibur/dbcp/ConnectionObjectFactory.java
/** * Copyright 2013 Simeon Malchev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vibur.dbcp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vibur.dbcp.listener.DestroyListener; import org.vibur.objectpool.PoolObjectFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.TimeUnit; /** * @author Simeon Malchev */ public class ConnectionObjectFactory implements PoolObjectFactory<ConnState> { private static final Logger logger = LoggerFactory.getLogger(ConnectionObjectFactory.class); /** Database driver class name */ private final String driverClassName; /** Database JDBC Connection string. */ private final String jdbcUrl; /** User name to use. */ private final String username; /** Password to use. */ private final String password; /** If the connection has stayed in the pool for at least {@code validateIfIdleForSeconds}, * it will be validated before being given to the application using the {@code testConnectionQuery}. * If set to zero, will validate the connection always when it is taken from the pool. * If set to a negative number, will never validate the taken from the pool connection. */ private final int validateIfIdleForSeconds; /** Used to test the validity of the JDBC Connection. Set to {@code null} to disable. */ private final String testConnectionQuery; /** After attempting to acquire a JDBC Connection and failing with an {@code SQLException}, * wait for this value before attempting to acquire a new JDBC Connection again. */ private final long acquireRetryDelayInMs; /** After attempting to acquire a JDBC Connection and failing with an {@code SQLException}, * try to connect these many times before giving up. */ private final int acquireRetryAttempts; /** The default auto-commit state of created connections. */ private final Boolean defaultAutoCommit; /** The default read-only state of created connections. */ private final Boolean defaultReadOnly; /** The default transaction isolation state of created connections. */ private final Integer defaultTransactionIsolation; /** The default catalog state of created connections. */ private final String defaultCatalog; private final DestroyListener destroyListener; public ConnectionObjectFactory(String driverClassName, String jdbcUrl, String username, String password, int validateIfIdleForSeconds, String testConnectionQuery, long acquireRetryDelayInMs, int acquireRetryAttempts, Boolean defaultAutoCommit, Boolean defaultReadOnly, Integer defaultTransactionIsolation, String defaultCatalog, DestroyListener destroyListener) { this.driverClassName = driverClassName; this.jdbcUrl = jdbcUrl; this.username = username; this.password = password; this.validateIfIdleForSeconds = validateIfIdleForSeconds; this.testConnectionQuery = testConnectionQuery; this.acquireRetryDelayInMs = acquireRetryDelayInMs; this.acquireRetryAttempts = acquireRetryAttempts; this.defaultAutoCommit = defaultAutoCommit; this.defaultReadOnly = defaultReadOnly; this.defaultTransactionIsolation = defaultTransactionIsolation; this.defaultCatalog = defaultCatalog; this.destroyListener = destroyListener; try { Class.forName(this.driverClassName); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * {@inheritDoc} * * @throws ViburDBCPException if cannot create the underlying JDBC Connection. * */ public ConnState create() throws ViburDBCPException { int attempt = 0; Connection connection = null; while (connection == null) { try { if (username == null && password == null) connection = DriverManager.getConnection(jdbcUrl); else connection = DriverManager.getConnection(jdbcUrl, username, password); } catch (SQLException e) { logger.debug("Couldn't create a java.sql.Connection, attempt " + attempt, e); if (attempt++ >= acquireRetryAttempts) throw new ViburDBCPException(e); try { TimeUnit.MILLISECONDS.sleep(acquireRetryDelayInMs); } catch (InterruptedException ignore) { } } } logger.trace("Created " + connection); return new ConnState(connection, System.currentTimeMillis()); } private void setDefaultValues(Connection connection) throws ViburDBCPException { try { if (defaultAutoCommit != null) connection.setAutoCommit(defaultAutoCommit); if (defaultReadOnly != null) connection.setReadOnly(defaultReadOnly); if (defaultTransactionIsolation != null) connection.setTransactionIsolation(defaultTransactionIsolation); if (defaultCatalog != null) connection.setCatalog(defaultCatalog); } catch (SQLException e) { throw new ViburDBCPException(e); } } /** {@inheritDoc} */ public boolean readyToTake(ConnState connState) throws ViburDBCPException { if (validateIfIdleForSeconds >= 0) { int idle = (int) (connState.getLastTimeUsedInMillis() - System.currentTimeMillis()) / 1000; if (idle >= validateIfIdleForSeconds) if (!executeTestStatement(connState.connection())) return false; } setDefaultValues(connState.connection()); return true; } /** * {@inheritDoc} * * @throws ViburDBCPException if cannot restore the default values for the underlying JDBC Connection. * */ public boolean readyToRestore(ConnState connState) { connState.setLastTimeUsedInMillis(System.currentTimeMillis()); return true; } private boolean executeTestStatement(Connection connection) { Statement statement = null; try { statement = connection.createStatement(); statement.execute(testConnectionQuery); statement.close(); return true; } catch (SQLException e) { logger.debug("Couldn't validate " + connection, e); try { if (statement != null) statement.close(); } catch (SQLException ignore) { } return false; } } /** {@inheritDoc} */ public void destroy(ConnState connState) { Connection connection = connState.connection(); try { logger.trace("Destroying " + connection); destroyListener.onDestroy(connection); connection.close(); } catch (SQLException e) { logger.debug("Couldn't close " + connection, e); } } }
minor git-svn-id: 2329b449e16586dcaa28eddb0911986394fb69f2@58 27e81457-bc9d-6bdf-c01a-22e69fa685e4
src/main/java/org/vibur/dbcp/ConnectionObjectFactory.java
minor
<ide><path>rc/main/java/org/vibur/dbcp/ConnectionObjectFactory.java <ide> if (!executeTestStatement(connState.connection())) <ide> return false; <ide> } <add> <ide> setDefaultValues(connState.connection()); <ide> return true; <ide> }
JavaScript
apache-2.0
46441b02847a671dc9510a0cf21f33e8cea026f3
0
anuruddhal/stratos,gayangunarathne/stratos,dinithis/stratos,lasinducharith/stratos,asankasanjaya/stratos,pkdevbox/stratos,apache/stratos,ravihansa3000/stratos,Thanu/stratos,Thanu/stratos,apache/stratos,ravihansa3000/stratos,hsbhathiya/stratos,hsbhathiya/stratos,pubudu538/stratos,gayangunarathne/stratos,gayangunarathne/stratos,hsbhathiya/stratos,pkdevbox/stratos,dinithis/stratos,lasinducharith/stratos,apache/stratos,dinithis/stratos,apache/stratos,asankasanjaya/stratos,asankasanjaya/stratos,pubudu538/stratos,Thanu/stratos,anuruddhal/stratos,lasinducharith/stratos,apache/stratos,anuruddhal/stratos,anuruddhal/stratos,apache/stratos,ravihansa3000/stratos,pkdevbox/stratos,pubudu538/stratos,asankasanjaya/stratos,dinithis/stratos,anuruddhal/stratos,lasinducharith/stratos,hsbhathiya/stratos,pkdevbox/stratos,Thanu/stratos,ravihansa3000/stratos,lasinducharith/stratos,dinithis/stratos,pkdevbox/stratos,gayangunarathne/stratos,pubudu538/stratos,gayangunarathne/stratos,ravihansa3000/stratos,pubudu538/stratos,anuruddhal/stratos,hsbhathiya/stratos,apache/stratos,hsbhathiya/stratos,gayangunarathne/stratos,hsbhathiya/stratos,pubudu538/stratos,pkdevbox/stratos,dinithis/stratos,asankasanjaya/stratos,pubudu538/stratos,ravihansa3000/stratos,anuruddhal/stratos,lasinducharith/stratos,Thanu/stratos,dinithis/stratos,gayangunarathne/stratos,Thanu/stratos,asankasanjaya/stratos,lasinducharith/stratos,asankasanjaya/stratos,Thanu/stratos,ravihansa3000/stratos,pkdevbox/stratos
// repaint function Repaint(){ $("#whiteboard").resize(function(){ jsPlumb.repaintEverything(); }); } // drag function DragEl(el){ jsPlumb.draggable($(el) ,{ containment:"#whiteboard" }); } // JsPlumb Config var color = "gray", exampleColor = "#00f", arrowCommon = { foldback:0.7, fillStyle:color, width:14 }; jsPlumb.importDefaults({ Connector : [ "Bezier", { curviness:63 } ], /*Overlays: [ [ "Arrow", { location:0.7 }, arrowCommon ], ]*/ }); var nodeDropOptions = { activeClass:"dragActive" }; var bottomConnectorOptions = { endpoint:"Rectangle", paintStyle:{ width:25, height:21, fillStyle:'#666' }, isSource:true, connectorStyle : { strokeStyle:"#666" }, isTarget:false, maxConnections:20 }; var endpointOptions = { isTarget:true, endpoint:"Dot", paintStyle:{ fillStyle:"gray" }, dropOptions: nodeDropOptions, maxConnections:1 }; var groupOptions = { isTarget:true, endpoint:"Dot", paintStyle:{ fillStyle:"gray" }, dropOptions: nodeDropOptions, maxConnections:1 }; var generatedCartridgeEndpointOptions = { isTarget:false, endpoint:"Dot", paintStyle:{ fillStyle:"gray" }, dropOptions: '', maxConnections:1 }; var generatedGroupOptions = { isTarget:false, endpoint:"Dot", paintStyle:{ fillStyle:"gray" }, dropOptions: nodeDropOptions, maxConnections:1 }; jsPlumb.ready(function() { //create application level block jsPlumb.addEndpoint('applicationId', { anchor:"BottomCenter" }, bottomConnectorOptions); }); var cartridgeCounter=0; //add cartridge to editor function addJsplumbCartridge(idname, cartridgeCounter) { var Div = $('<div>').attr({'id':cartridgeCounter+'-'+idname, 'data-type':'cartridge', 'data-ctype':idname } ) .addClass('input-false') .attr('data-toggle', 'tooltip') .attr('title',idname) .appendTo('#whiteboard'); $(Div).append('<span>'+idname+'</span>'); $(Div).addClass('stepnode'); jsPlumb.addEndpoint($(Div), { anchor: "TopCenter" }, endpointOptions); // jsPlumb.addEndpoint($(Div), sourceEndpoint); $(Div).append('<div class="notification"><i class="fa fa-exclamation-circle fa-2x"></i></div>'); DragEl($(Div)); Repaint(); } //add group to editor function addJsplumbGroup(groupJSON, cartridgeCounter){ var divRoot = $('<div>').attr({'id':cartridgeCounter+'-'+groupJSON.name,'data-type':'group','data-ctype':groupJSON.name}) .addClass('input-false') .attr('data-toggle', 'tooltip') .attr('title',groupJSON.name) .addClass('stepnode') .appendTo('#whiteboard'); $(divRoot).append('<span>'+groupJSON.name+'</span>'); $(divRoot).append('<div class="notification"><i class="fa fa-exclamation-circle fa-2x"></i></div>'); jsPlumb.addEndpoint($(divRoot), { anchor:"BottomCenter" }, bottomConnectorOptions); jsPlumb.addEndpoint($(divRoot), { anchor: "TopCenter" }, groupOptions); DragEl($(divRoot)); for (var prop in groupJSON) { if(prop == 'cartridges'){ genJsplumbCartridge(groupJSON[prop], divRoot, groupJSON.name) } if(prop == 'groups'){ genJsplumbGroups(groupJSON[prop], divRoot, groupJSON.name) } } function genJsplumbCartridge(item, currentParent, parentName){ for (var i = 0; i < item.length; i++) { var id = item[i]; var divCartridge = $('<div>').attr({'id':cartridgeCounter+'-'+parentName+'-'+item[i],'data-type':'cartridge','data-ctype':item[i]} ) .addClass('input-false') .attr('data-toggle', 'tooltip') .attr('title',item[i]) .addClass('stepnode') .appendTo('#whiteboard'); $(divCartridge).append('<span>'+item[i]+'</span>'); $(divCartridge).append('<div class="notification"><i class="fa fa-exclamation-circle fa-2x"></i></div>'); jsPlumb.addEndpoint($(divCartridge), { anchor: "TopCenter" }, generatedCartridgeEndpointOptions); //add connection options jsPlumb.connect({ source:$(currentParent), target:$(divCartridge), paintStyle:{strokeStyle:"blue", lineWidth:1 }, Connector : [ "Bezier", { curviness:63 } ], anchors:["BottomCenter", "TopCenter"], endpoint:"Dot" }); DragEl($(divCartridge)); } } function genJsplumbGroups(item, currentParent, parentName) { for (var prop in item) { var divGroup = $('<div>').attr({'id':cartridgeCounter+'-'+parentName+'-'+item[prop]['name'],'data-type':'group','data-ctype':item[prop]['name'] }) .addClass('stepnode') .attr('data-toggle', 'tooltip') .attr('title',item[prop]['name']) .addClass('input-false') .appendTo('#whiteboard'); $(divGroup).append('<span>'+item[prop]['name']+'</span>'); $(divGroup).append('<div class="notification"><i class="fa fa-exclamation-circle fa-2x"></i></div>'); jsPlumb.addEndpoint($(divGroup), { anchor:"BottomCenter" }, bottomConnectorOptions); jsPlumb.addEndpoint($(divGroup), { anchor: "TopCenter" }, generatedGroupOptions); //add connection options jsPlumb.connect({ source:$(currentParent), target:$(divGroup), paintStyle:{strokeStyle:"blue", lineWidth:1 }, Connector : [ "Bezier", { curviness:63 } ], anchors:["BottomCenter", "TopCenter"], endpoint:"Dot" }); DragEl($(divGroup)); if(item[prop].hasOwnProperty('cartridges')) { genJsplumbCartridge(item[prop].cartridges, divGroup, parentName+'-'+item[prop]['name'] ); } if(item[prop].hasOwnProperty('groups')) { genJsplumbGroups(item[prop].groups, divGroup, parentName+'-'+item[prop]['name']) } } } } //use to activate tab function activateTab(tab){ $('.nav-tabs a[href="#' + tab + '"]').tab('show'); }; //generate treefor Groups function generateGroupTree(groupJSON){ var rawout = []; //create initial node for tree var rootnode ={}; rootnode.name = groupJSON.name; rootnode.parent = null; rootnode.type = 'groups'; rawout.push(rootnode); for (var prop in groupJSON) { if(prop == 'cartridges'){ getCartridges(groupJSON[prop],rawout, rootnode.name) } if(prop == 'groups'){ getGroups(groupJSON[prop], rawout, rootnode.name) } } function getCartridges(item, collector, parent){ for (var i = 0; i < item.length; i++) { var type = 'cartridges'; var cur_name = item[i]; collector.push({"name": cur_name, "parent": parent, "type": type}); } } function getGroups(item, collector, parent){ for (var prop in item) { var cur_name = item[prop]['name']; var type = 'groups'; collector.push({"name": cur_name, "parent": parent, "type": type}); if(item[prop].hasOwnProperty('cartridges')) { getCartridges(item[prop].cartridges, collector, cur_name); } if(item[prop].hasOwnProperty('groups')) { getGroups(item[prop].groups, collector, cur_name) } } } return rawout; } // ************** Generate the tree diagram ***************** function generateGroupPreview(data) { //clean current graph and text $(".description-section").html(''); //mapping data var dataMap = data.reduce(function(map, node) { map[node.name] = node; return map; }, {}); var treeData = []; data.forEach(function(node) { // add to parent var parent = dataMap[node.parent]; if (parent) { // create child array if it doesn't exist (parent.children || (parent.children = [])) // add node to child array .push(node); } else { // parent is null or missing treeData.push(node); } }); var source = treeData[0]; //generate position for tree view var margin = {top: 25, right: 5, bottom: 5, left: 5}, width = 320 - margin.right - margin.left, height = 500 - margin.top - margin.bottom; var i = 0; var tree = d3.layout.tree() .size([height, width]); var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.x, d.y]; }); function redraw() { svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"); } var svg = d3.select(".description-section").append("svg") .attr("width", width) .attr("height", height) .call(d3.behavior.zoom().on("zoom", redraw)) .append("g") .attr("transform", "translate(" + -90+ "," + margin.top + ")"); // Compute the new tree layout. var nodes = tree.nodes(source).reverse(), links = tree.links(nodes); // Normalize for fixed-depth. nodes.forEach(function(d) { d.y = d.depth * 60; }); // Declare the nodes… var node = svg.selectAll("g.node") .data(nodes, function(d) { return d.id || (d.id = ++i); }); // Enter the nodes. var nodeEnter = node.enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); nodeEnter.append("rect") .attr("x", -10) .attr("y", -10) .attr("rx",2) .attr("ry",2) .attr("width", 20) .attr("height", 20) .attr("stroke-width", 1) .attr("stroke", "silver") .style("fill", "#fff"); nodeEnter.append("text") .attr("y", function(d) { return d.children || d._children ? -20 : 20; }) .attr("dy", ".35em") .attr("text-anchor", "middle") .text(function(d) { return d.name; }) .style("fill-opacity", 1); // Declare the links var link = svg.selectAll("path.link") .data(links, function(d) { return d.target.id; }); // Enter the links. link.enter().insert("path", "g") .attr("class", "link") .attr("d", diagonal); } var applicationJson = {}; //Definition JSON builder function generateJsplumbTree(collector, connections, appeditor){ collector = appeditor.getValue(); collector['components']={}; collector['components']['groups']=[]; collector['components']['cartridges']=[]; collector['components']['dependencies']= collector['dependencies']; delete collector['dependencies']; //generate raw data tree from connections var rawtree = []; $.each(jsPlumb.getConnections(), function (idx, connection) { var dataType = $('#'+connection.targetId).attr('data-type'); var jsonContent = JSON.parse(decodeURIComponent($('#'+connection.targetId).attr('data-generated'))); rawtree.push({ parent: connection.sourceId, content: jsonContent, dtype:dataType, id: connection.targetId }); }); //generate heirache by adding json and extra info var nodes = []; var toplevelNodes = []; var lookupList = {}; for (var i = 0; i < rawtree.length; i++) { var n = rawtree[i].content; if(rawtree[i].dtype == 'cartridge'){ n.id = rawtree[i].id; n.parent_id = ((rawtree[i].parent == 'applicationId') ? 'applicationId': rawtree[i].parent); n.dtype =rawtree[i].dtype; }else if(rawtree[i].dtype == 'group'){ n.id = rawtree[i].id; n.parent_id = ((rawtree[i].parent == 'applicationId') ? 'applicationId': rawtree[i].parent); n.dtype =rawtree[i].dtype; n.groups = []; n.cartridges =[]; } lookupList[n.id] = n; nodes.push(n); if (n.parent_id == 'applicationId' && rawtree[i].dtype == 'cartridge') { collector['components']['cartridges'].push(n); }else if(n.parent_id == 'applicationId' && rawtree[i].dtype == 'group'){ collector['components']['groups'].push(n); } } //merge any root level stuffs for (var i = 0; i < nodes.length; i++) { var n = nodes[i]; if (!(n.parent_id == 'applicationId') && n.dtype == 'cartridge') { lookupList[n.parent_id]['cartridges'] = lookupList[n.parent_id]['cartridges'].concat([n]); }else if(!(n.parent_id == 'applicationId') && n.dtype == 'group'){ lookupList[n.parent_id]['groups'] = lookupList[n.parent_id]['groups'].concat([n]); } } //cleanup JSON, remove extra items added to object level function traverse(o) { for (var i in o) { if(i == 'id' || i == 'parent_id' || i == 'dtype'){ delete o[i]; }else if(i == 'groups' && o[i].length == 0){ delete o[i]; } if (o[i] !== null && typeof(o[i])=="object") { //going on step down in the object tree!! traverse(o[i]); } } } traverse(collector); return collector; } //UUID generator function uuid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } //setting up schema and defaults var cartridgeBlockTemplate = { "type":"object", "$schema": "http://json-schema.org/draft-03/schema", "id": "root", "format":"grid", "properties":{ "type": { "type":"string", "id": "root/type", "default": "name", "title": "Cartridge Type: ", "required":false }, "cartridgeMax": { "type":"number", "id": "root/cartridgeMax", "default":2, "title":"Cartridge Max", "required":false }, "cartridgeMin": { "type":"number", "id": "root/cartridgeMin", "title":"Cartridge Min", "default":1, "required":false }, "subscribableInfo": { "type":"object", "id": "root/subscribableInfo", "title":"Subscribable Info: ", "required":false, "properties":{ "alias": { "type":"string", "id": "root/subscribableInfo/alias", "default": "alias2", "title":"Alias: ", "required":false }, "autoscalingPolicy": { "type":"string", "id": "root/subscribableInfo/autoscalingPolicy", "default": "autoscale_policy_1", "title":"Auto-scaling Policy: ", "enum": [], "required":false }, "deploymentPolicy": { "type":"string", "id": "root/subscribableInfo/deploymentPolicy", "default": "deployment_policy_1", "title":"Deployment Policy: ", "enum": [], "required":false }, "artifactRepository": { "id": "root/subscribableInfo/artifactRepository", "type": "object", "properties": { "privateRepo": { "id": "root/subscribableInfo/artifactRepository/privateRepo", "title":"Private Repository: ", "type": "boolean" }, "repoUrl": { "id": "root/subscribableInfo/artifactRepository/repoUrl", "title":"Repository URL: ", "type": "string" }, "repoUsername": { "id": "root/subscribableInfo/artifactRepository/repoUsername", "title":"Repository Username: ", "type": "string" }, "repoPassword": { "id": "root/subscribableInfo/artifactRepository/repoPassword", "title":"Repository Password: ", "type": "string", "format":"password" } } } } } } }; var cartridgeBlockDefault = { "type":"tomcat", "cartridgeMin":1, "cartridgeMax":2, "subscribableInfo":{ "alias":"alias2", "autoscalingPolicy":"", "deploymentPolicy":"", "artifactRepository":{ "privateRepo":"true", "repoUrl":"http://xxx:10080/git/default.git", "repoUsername":"user", "repoPassword":"password", } } }; var groupBlockTemplate = { "type":"object", "$schema": "http://json-schema.org/draft-03/schema", "id": "root", "required":false, "properties":{ "name": { "type":"string", "id": "root/name", "default": "name", "required":false }, "alias": { "type":"string", "id": "root/alias", "default": "alias", "required":false }, "groupMaxInstances": { "type":"number", "id": "root/groupMaxInstances", "default":2, "required":false }, "groupMinInstances": { "type":"number", "id": "root/groupMinInstances", "default":1, "required":false } } }; var groupBlockDefault = { "name":"group2", "alias":"group2alias", "groupMinInstances":1, "groupMaxInstances":2 }; var applicationBlockTemplate = { "$schema": "http://json-schema.org/draft-04/schema#", "id": "root", "type": "object", "title":" ", "options":{ "disable_properties":true, "disable_collapse": true }, "properties": { "applicationId": { "id": "root/applicationId", "title": "Application Id", "name": "Application Id", "type": "string" }, "alias": { "id": "root/alias", "type": "string", "title": "Application Alias", "name": "Application Alias" }, "multiTenant": { "id": "root/multiTenant", "type": "boolean", "title": "Application Multi Tenancy", "name": "Application Multi Tenancy" }, "dependencies": { "id": "root/dependencies", "type": "object", "title": "Dependencies", "name": "Dependencies", "options": { "hidden": false, "disable_properties":true, "collapsed": true }, "properties": { "startupOrders": { "id": "root/dependencies/startupOrders", "type": "array", "title": "Startup Orders", "name": "Startup Orders", "format":"tabs", "items": { "id": "root/dependencies/startupOrders/0", "type": "string", "title": "Order", "name": "Order", "default":"group.my-group1,cartridge.my-c4" } }, "scalingDependents": { "id": "root/dependencies/scalingDependents", "type": "array", "title": "Scaling Dependents", "name": "Scaling Dependents", "format":"tabs", "items": { "id": "root/dependencies/scalingDependents/0", "type": "string", "title": "Dependent", "name": "Dependent", "default":"group.my-group1,cartridge.my-c4" } }, "terminationBehaviour": { "id": "root/dependencies/terminationBehaviour", "type": "string", "title": "Termination Behaviour", "name": "Termination Behaviour", "enum": ["terminate-none","terminate-dependents","terminate-all"], } } } } }; var applicationBlockDefault = { "applicationId": "", "alias": "", "multiTenant": false, "dependencies": { "startupOrders": [ ], "scalingDependents": [ ], "terminationBehaviour": "terminate-dependents" } }; //create cartridge list var cartridgeListHtml=''; function generateCartridges(data){ if(data == null || data.length == 0){ cartridgeListHtml = 'No Cartridges found..'; }else{ for(var cartridge in data){ var cartridgeData = data[cartridge]; cartridgeListHtml += '<div class="block-cartridge" ' + 'data-info="'+cartridgeData.description+ '"'+ 'data-toggle="tooltip" data-placement="bottom" title="Single Click to view details. Double click to add"'+ 'id="'+cartridgeData.type+'">' + cartridgeData.displayName+ '</div>' } } //append cartridge into html content $('#cartridge-list').append(cartridgeListHtml); } //create group list var groupListHtml=''; function generateGroups(data){ if(data == null || data.length == 0){ groupListHtml = 'No Groups found..'; }else { for (var group in data) { var groupData = data[group]; groupListHtml += '<div class="block-group" ' + ' data-info="' + encodeURIComponent(JSON.stringify(groupData)) + '"' + 'data-toggle="tooltip" data-placement="bottom" title="'+groupData.name+'"'+ 'id="' + groupData.name + '">' + groupData.name + '</div>' } } //append cartridge into html content $('#group-list').append(groupListHtml); } //node positioning algo with dagre js function dagrePosition(){ // construct dagre graph from JsPlumb graph var g = new dagre.graphlib.Graph(); g.setGraph({ranksep:'80'}); g.setDefaultEdgeLabel(function() { return {}; }); var nodes = $(".stepnode"); for (var i = 0; i < nodes.length; i++) { var n = nodes[i]; g.setNode(n.id, {width: 52, height: 52}); } var edges = jsPlumb.getAllConnections(); for (var i = 0; i < edges.length; i++) { var c = edges[i]; g.setEdge(c.source.id,c.target.id ); } // calculate the layout (i.e. node positions) dagre.layout(g); // Applying the calculated layout g.nodes().forEach(function(v) { $("#" + v).css("left", g.node(v).x + "px"); $("#" + v).css("top", g.node(v).y + "px"); }); jsPlumb.repaintEverything(); } // Document ready events $(document).ready(function(){ //handled Ajax base session expire issue $(document).ajaxError(function (e, xhr, settings) { window.location.href = '../'; }); $('#deploy').attr('disabled','disabled'); $('#deploy').on('click', function(){ var appJSON = generateJsplumbTree(applicationJson, jsPlumb.getConnections(), appeditor); var btn = $(this); var formtype = 'applications'; btn.html("<i class='fa fa-spinner fa-spin'></i> Adding..."); $.ajax({ type: "POST", url: caramel.context + "/controllers/applications/application_requests.jag", dataType: 'json', data: { "formPayload": JSON.stringify(appJSON), "formtype": formtype }, success: function (data) { if (data.status == 'error') { var n = noty({text: data.message, layout: 'bottomRight', type: 'error'}); } else if (data.status == 'warning') { var n = noty({text: data.message, layout: 'bottomRight', type: 'warning'}); } else { var n = noty({text: data.message, layout: 'bottomRight', type: 'success'}); window.setTimeout(function(){ window.location.href = '../'; }, 1500); } } }) .always(function () { btn.html('Add New Application Definition'); }); }); //*******************Adding JSON editor *************// JSONEditor.defaults.theme = 'bootstrap3'; JSONEditor.defaults.iconlib = 'fontawesome4'; JSONEditor.defaults.show_errors = "always"; var editor, blockId, appeditor; //set hidden UUID applicationBlockDefault.applicationId = uuid(); // Initialize the editor for main section appeditor = new JSONEditor(document.getElementById('general'), { ajax: false, disable_edit_json: true, schema: applicationBlockTemplate, format: "grid", startval: applicationBlockDefault }); DragEl(".stepnode"); Repaint(); $('#whiteboard').on('click', '.stepnode', function(){ tabData($(this)); }); $('#whiteboard').on('dblclick', '.stepnode', function(){ var target = $('#component-data'); if( target.length ) { event.preventDefault(); $('html, body').animate({ scrollTop: target.offset().top }, 1000); } }); function tabData(node){ //get tab activated if(node.attr('id') == 'applicationId'){ activateTab('general'); }else{ activateTab('components'); $('#component-info-update').prop("disabled", false); } blockId = node.attr('id'); var blockType = node.attr('data-type'); var startval; var ctype = node.attr('data-ctype'); if(blockType == 'cartridge' || blockType == 'group-cartridge'){ startval = cartridgeBlockDefault; startval['type'] = ctype; //get list of autosacles var policies = editorAutoscalePolicies; var policiesEnum = []; for(var i=0; i<policies.length; i++){ policiesEnum.push(policies[i].id); } cartridgeBlockTemplate['properties']['subscribableInfo']['properties']['autoscalingPolicy']['enum'] =policiesEnum; //get list of deploymentpolicies var dpolicies = editorDeploymentPolicies; var dpoliciesEnum = []; for(var i=0; i<dpolicies.length; i++){ dpoliciesEnum.push(dpolicies[i].id); } cartridgeBlockTemplate['properties']['subscribableInfo']['properties']['deploymentPolicy']['enum'] =dpoliciesEnum; }else{ startval = groupBlockDefault; startval['name'] = ctype; } if(node.attr('data-generated')) { startval = JSON.parse(decodeURIComponent(node.attr('data-generated'))); } $('#component-data').html(''); switch (blockType){ case 'cartridge': generateHtmlBlock(cartridgeBlockTemplate, startval); break; case 'group': generateHtmlBlock(groupBlockTemplate, startval); break; case 'group-cartridge': generateHtmlBlock(cartridgeBlockTemplate, startval); break; } } function generateHtmlBlock(schema, startval){ // Initialize the editor editor = new JSONEditor(document.getElementById('component-data'), { ajax: false, disable_edit_json: true, schema: schema, format: "grid", startval: startval }); if(editor.getEditor('root.type')){ editor.getEditor('root.type').disable(); }else{ editor.getEditor('root.name').disable(); } } //get component JSON data $('#component-info-update').on('click', function(){ $('#'+blockId).attr('data-generated', encodeURIComponent(JSON.stringify(editor.getValue()))); $('#'+blockId).removeClass('input-false'); $('#'+blockId).find('div>i').removeClass('fa-exclamation-circle').addClass('fa-check-circle-o').css('color','#2ecc71'); $('#deploy').prop("disabled", false); }); //get create cartridge list generateCartridges(cartridgeList); //get group JSON generateGroups(groupList); //handle single click for cartridge $('#cartridge-list').on('click', ".block-cartridge", function(){ $('.description-section').html($(this).attr('data-info')); }); //handle double click for cartridge $('#cartridge-list').on('dblclick', ".block-cartridge", function(){ addJsplumbCartridge($(this).attr('id'),cartridgeCounter); //reposition after cartridge add dagrePosition(); //increase global count for instances cartridgeCounter++; }); //handle single click for groups $('#group-list').on('click', ".block-group", function(){ var groupJSON = JSON.parse(decodeURIComponent($(this).attr('data-info'))); mydata = generateGroupTree(groupJSON); generateGroupPreview(mydata); }); //handle double click event for groups $('#group-list').on('dblclick', ".block-group", function(){ var groupJSON = JSON.parse(decodeURIComponent($(this).attr('data-info'))); addJsplumbGroup(groupJSON,cartridgeCounter); //reposition after group add dagrePosition(); //increase global count for instances cartridgeCounter++; }); //reposition on click event on editor $('.reposition').on('click', function(){ dagrePosition(); }); //genrate context menu for nodes $.contextMenu({ selector: '.stepnode', callback: function(key, options) { var m = "clicked: " + key + $(this); if(key == 'delete'){ deleteNode($(this)); }else if(key == 'edit'){ document.getElementById('component-data').scrollIntoView(); tabData($(this)); } }, items: { "edit": {name: "Edit", icon: "edit"}, "delete": {name: "Delete", icon: "delete"} } }); }); //bootstrap tooltip added $(function () { $('[data-toggle="tooltip"]').tooltip() }) // ************* Add context menu for nodes ****************** //remove nodes from workarea function deleteNode(endPoint){ if(endPoint.attr('id') != 'applicationId'){ var allnodes = $(".stepnode"); var superParent = endPoint.attr('id').split("-")[0]+endPoint.attr('id').split("-")[1]; var nodeName = endPoint.attr('data-ctype'); var nodeType = endPoint.attr('data-type'); var notyText = ''; if(nodeType == 'group'){ notyText = 'This will remove related nodes from the Editor. Are you sure you want to delete ' +nodeType + ': '+nodeName+'?'; }else{ notyText = 'Are you sure you want to delete '+nodeType + ': '+nodeName+'?'; } noty({ layout: 'bottomRight', type: 'warning', text: notyText, buttons: [ {addClass: 'btn btn-primary', text: 'Yes', onClick: function($noty) { $noty.close(); allnodes.each(function(){ var currentId = $(this).attr('id').split("-")[0]+$(this).attr('id').split("-")[1]; if(currentId == superParent){ var that=$(this); //get all of your DIV tags having endpoints for (var i=0;i<that.length;i++) { var endpoints = jsPlumb.getEndpoints($(that[i])); //get all endpoints of that DIV if(endpoints){ for (var m=0;m<endpoints.length;m++) { // if(endpoints[m].anchor.type=="TopCenter") //Endpoint on right side jsPlumb.deleteEndpoint(endpoints[m]); //remove endpoint } } } jsPlumb.detachAllConnections($(this)); $(this).remove(); } }); //clear html area $('#component-data').html(''); activateTab('general'); } }, {addClass: 'btn btn-danger', text: 'No', onClick: function($noty) { $noty.close(); } } ] }); }else{ var n = noty({text: 'Sorry you can\'t remove application node' , layout: 'bottomRight', type: 'warning'}); } }
components/org.apache.stratos.manager.console/console/themes/theme0/js/custom/applications-editor.js
// repaint function Repaint(){ $("#whiteboard").resize(function(){ jsPlumb.repaintEverything(); }); } // drag function DragEl(el){ jsPlumb.draggable($(el) ,{ containment:"#whiteboard" }); } // JsPlumb Config var color = "gray", exampleColor = "#00f", arrowCommon = { foldback:0.7, fillStyle:color, width:14 }; jsPlumb.importDefaults({ Connector : [ "Bezier", { curviness:63 } ], /*Overlays: [ [ "Arrow", { location:0.7 }, arrowCommon ], ]*/ }); var nodeDropOptions = { activeClass:"dragActive" }; var bottomConnectorOptions = { endpoint:"Rectangle", paintStyle:{ width:25, height:21, fillStyle:'#666' }, isSource:true, connectorStyle : { strokeStyle:"#666" }, isTarget:false, maxConnections:20 }; var endpointOptions = { isTarget:true, endpoint:"Dot", paintStyle:{ fillStyle:"gray" }, dropOptions: nodeDropOptions, maxConnections:1 }; var groupOptions = { isTarget:true, endpoint:"Dot", paintStyle:{ fillStyle:"gray" }, dropOptions: nodeDropOptions, maxConnections:1 }; var generatedCartridgeEndpointOptions = { isTarget:false, endpoint:"Dot", paintStyle:{ fillStyle:"gray" }, dropOptions: '', maxConnections:1 }; var generatedGroupOptions = { isTarget:false, endpoint:"Dot", paintStyle:{ fillStyle:"gray" }, dropOptions: nodeDropOptions, maxConnections:1 }; jsPlumb.ready(function() { //create application level block jsPlumb.addEndpoint('applicationId', { anchor:"BottomCenter" }, bottomConnectorOptions); }); var cartridgeCounter=0; //add cartridge to editor function addJsplumbCartridge(idname, cartridgeCounter) { var Div = $('<div>').attr({'id':cartridgeCounter+'-'+idname, 'data-type':'cartridge', 'data-ctype':idname } ) .addClass('input-false') .attr('data-toggle', 'tooltip') .attr('title',idname) .appendTo('#whiteboard'); $(Div).append('<span>'+idname+'</span>'); $(Div).addClass('stepnode'); jsPlumb.addEndpoint($(Div), { anchor: "TopCenter" }, endpointOptions); // jsPlumb.addEndpoint($(Div), sourceEndpoint); $(Div).append('<div class="notification"><i class="fa fa-exclamation-circle fa-2x"></i></div>'); DragEl($(Div)); Repaint(); } //add group to editor function addJsplumbGroup(groupJSON, cartridgeCounter){ var divRoot = $('<div>').attr({'id':cartridgeCounter+'-'+groupJSON.name,'data-type':'group','data-ctype':groupJSON.name}) .addClass('input-false') .attr('data-toggle', 'tooltip') .attr('title',groupJSON.name) .addClass('stepnode') .appendTo('#whiteboard'); $(divRoot).append('<span>'+groupJSON.name+'</span>'); $(divRoot).append('<div class="notification"><i class="fa fa-exclamation-circle fa-2x"></i></div>'); jsPlumb.addEndpoint($(divRoot), { anchor:"BottomCenter" }, bottomConnectorOptions); jsPlumb.addEndpoint($(divRoot), { anchor: "TopCenter" }, groupOptions); DragEl($(divRoot)); for (var prop in groupJSON) { if(prop == 'cartridges'){ genJsplumbCartridge(groupJSON[prop], divRoot, groupJSON.name) } if(prop == 'groups'){ genJsplumbGroups(groupJSON[prop], divRoot, groupJSON.name) } } function genJsplumbCartridge(item, currentParent, parentName){ for (var i = 0; i < item.length; i++) { var id = item[i]; var divCartridge = $('<div>').attr({'id':cartridgeCounter+'-'+parentName+'-'+item[i],'data-type':'cartridge','data-ctype':item[i]} ) .addClass('input-false') .attr('data-toggle', 'tooltip') .attr('title',item[i]) .addClass('stepnode') .appendTo('#whiteboard'); $(divCartridge).append('<span>'+item[i]+'</span>'); $(divCartridge).append('<div class="notification"><i class="fa fa-exclamation-circle fa-2x"></i></div>'); jsPlumb.addEndpoint($(divCartridge), { anchor: "TopCenter" }, generatedCartridgeEndpointOptions); //add connection options jsPlumb.connect({ source:$(currentParent), target:$(divCartridge), paintStyle:{strokeStyle:"blue", lineWidth:1 }, Connector : [ "Bezier", { curviness:63 } ], anchors:["BottomCenter", "TopCenter"], endpoint:"Dot" }); DragEl($(divCartridge)); } } function genJsplumbGroups(item, currentParent, parentName) { for (var prop in item) { var divGroup = $('<div>').attr({'id':cartridgeCounter+'-'+parentName+'-'+item[prop]['name'],'data-type':'group','data-ctype':item[prop]['name'] }) .addClass('stepnode') .attr('data-toggle', 'tooltip') .attr('title',item[prop]['name']) .addClass('input-false') .appendTo('#whiteboard'); $(divGroup).append('<span>'+item[prop]['name']+'</span>'); $(divGroup).append('<div class="notification"><i class="fa fa-exclamation-circle fa-2x"></i></div>'); jsPlumb.addEndpoint($(divGroup), { anchor:"BottomCenter" }, bottomConnectorOptions); jsPlumb.addEndpoint($(divGroup), { anchor: "TopCenter" }, generatedGroupOptions); //add connection options jsPlumb.connect({ source:$(currentParent), target:$(divGroup), paintStyle:{strokeStyle:"blue", lineWidth:1 }, Connector : [ "Bezier", { curviness:63 } ], anchors:["BottomCenter", "TopCenter"], endpoint:"Dot" }); DragEl($(divGroup)); if(item[prop].hasOwnProperty('cartridges')) { genJsplumbCartridge(item[prop].cartridges, divGroup, parentName+'-'+item[prop]['name'] ); } if(item[prop].hasOwnProperty('groups')) { genJsplumbGroups(item[prop].groups, divGroup, parentName+'-'+item[prop]['name']) } } } } //use to activate tab function activateTab(tab){ $('.nav-tabs a[href="#' + tab + '"]').tab('show'); }; //generate treefor Groups function generateGroupTree(groupJSON){ var rawout = []; //create initial node for tree var rootnode ={}; rootnode.name = groupJSON.name; rootnode.parent = null; rootnode.type = 'groups'; rawout.push(rootnode); for (var prop in groupJSON) { if(prop == 'cartridges'){ getCartridges(groupJSON[prop],rawout, rootnode.name) } if(prop == 'groups'){ getGroups(groupJSON[prop], rawout, rootnode.name) } } function getCartridges(item, collector, parent){ for (var i = 0; i < item.length; i++) { var type = 'cartridges'; var cur_name = item[i]; collector.push({"name": cur_name, "parent": parent, "type": type}); } } function getGroups(item, collector, parent){ for (var prop in item) { var cur_name = item[prop]['name']; var type = 'groups'; collector.push({"name": cur_name, "parent": parent, "type": type}); if(item[prop].hasOwnProperty('cartridges')) { getCartridges(item[prop].cartridges, collector, cur_name); } if(item[prop].hasOwnProperty('groups')) { getGroups(item[prop].groups, collector, cur_name) } } } return rawout; } // ************** Generate the tree diagram ***************** function generateGroupPreview(data) { //clean current graph and text $(".description-section").html(''); //mapping data var dataMap = data.reduce(function(map, node) { map[node.name] = node; return map; }, {}); var treeData = []; data.forEach(function(node) { // add to parent var parent = dataMap[node.parent]; if (parent) { // create child array if it doesn't exist (parent.children || (parent.children = [])) // add node to child array .push(node); } else { // parent is null or missing treeData.push(node); } }); var source = treeData[0]; //generate position for tree view var margin = {top: 25, right: 5, bottom: 5, left: 5}, width = 320 - margin.right - margin.left, height = 500 - margin.top - margin.bottom; var i = 0; var tree = d3.layout.tree() .size([height, width]); var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.x, d.y]; }); function redraw() { svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"); } var svg = d3.select(".description-section").append("svg") .attr("width", width) .attr("height", height) .call(d3.behavior.zoom().on("zoom", redraw)) .append("g") .attr("transform", "translate(" + -90+ "," + margin.top + ")"); // Compute the new tree layout. var nodes = tree.nodes(source).reverse(), links = tree.links(nodes); // Normalize for fixed-depth. nodes.forEach(function(d) { d.y = d.depth * 60; }); // Declare the nodes… var node = svg.selectAll("g.node") .data(nodes, function(d) { return d.id || (d.id = ++i); }); // Enter the nodes. var nodeEnter = node.enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); nodeEnter.append("rect") .attr("x", -10) .attr("y", -10) .attr("rx",2) .attr("ry",2) .attr("width", 20) .attr("height", 20) .attr("stroke-width", 1) .attr("stroke", "silver") .style("fill", "#fff"); nodeEnter.append("text") .attr("y", function(d) { return d.children || d._children ? -20 : 20; }) .attr("dy", ".35em") .attr("text-anchor", "middle") .text(function(d) { return d.name; }) .style("fill-opacity", 1); // Declare the links var link = svg.selectAll("path.link") .data(links, function(d) { return d.target.id; }); // Enter the links. link.enter().insert("path", "g") .attr("class", "link") .attr("d", diagonal); } var applicationJson = {}; //Definition JSON builder function generateJsplumbTree(collector, connections, appeditor){ collector = appeditor.getValue(); collector['components']={}; collector['components']['groups']=[]; collector['components']['cartridges']=[]; collector['components']['dependencies']= collector['dependencies']; delete collector['dependencies']; //generate raw data tree from connections var rawtree = []; $.each(jsPlumb.getConnections(), function (idx, connection) { var dataType = $('#'+connection.targetId).attr('data-type'); var jsonContent = JSON.parse(decodeURIComponent($('#'+connection.targetId).attr('data-generated'))); rawtree.push({ parent: connection.sourceId, content: jsonContent, dtype:dataType, id: connection.targetId }); }); //generate heirache by adding json and extra info var nodes = []; var toplevelNodes = []; var lookupList = {}; for (var i = 0; i < rawtree.length; i++) { var n = rawtree[i].content; if(rawtree[i].dtype == 'cartridge'){ n.id = rawtree[i].id; n.parent_id = ((rawtree[i].parent == 'applicationId') ? 'applicationId': rawtree[i].parent); n.dtype =rawtree[i].dtype; }else if(rawtree[i].dtype == 'group'){ n.id = rawtree[i].id; n.parent_id = ((rawtree[i].parent == 'applicationId') ? 'applicationId': rawtree[i].parent); n.dtype =rawtree[i].dtype; n.groups = []; n.cartridges =[]; } lookupList[n.id] = n; nodes.push(n); if (n.parent_id == 'applicationId' && rawtree[i].dtype == 'cartridge') { collector['components']['cartridges'].push(n); }else if(n.parent_id == 'applicationId' && rawtree[i].dtype == 'group'){ collector['components']['groups'].push(n); } } //merge any root level stuffs for (var i = 0; i < nodes.length; i++) { var n = nodes[i]; if (!(n.parent_id == 'applicationId') && n.dtype == 'cartridge') { lookupList[n.parent_id]['cartridges'] = lookupList[n.parent_id]['cartridges'].concat([n]); }else if(!(n.parent_id == 'applicationId') && n.dtype == 'group'){ lookupList[n.parent_id]['groups'] = lookupList[n.parent_id]['groups'].concat([n]); } } //cleanup JSON, remove extra items added to object level function traverse(o) { for (var i in o) { if(i == 'id' || i == 'parent_id' || i == 'dtype'){ delete o[i]; }else if(i == 'groups' && o[i].length == 0){ delete o[i]; } if (o[i] !== null && typeof(o[i])=="object") { //going on step down in the object tree!! traverse(o[i]); } } } traverse(collector); return collector; } //UUID generator function uuid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } //setting up schema and defaults var cartridgeBlockTemplate = { "type":"object", "$schema": "http://json-schema.org/draft-03/schema", "id": "root", "format":"grid", "properties":{ "type": { "type":"string", "id": "root/type", "default": "name", "title": "Cartridge Type: ", "required":false }, "cartridgeMax": { "type":"number", "id": "root/cartridgeMax", "default":2, "title":"Cartridge Max", "required":false }, "cartridgeMin": { "type":"number", "id": "root/cartridgeMin", "title":"Cartridge Min", "default":1, "required":false }, "subscribableInfo": { "type":"object", "id": "root/subscribableInfo", "title":"Subscribable Info: ", "required":false, "properties":{ "alias": { "type":"string", "id": "root/subscribableInfo/alias", "default": "alias2", "title":"Alias: ", "required":false }, "autoscalingPolicy": { "type":"string", "id": "root/subscribableInfo/autoscalingPolicy", "default": "autoscale_policy_1", "title":"Auto-scaling Policy: ", "enum": [], "required":false }, "deploymentPolicy": { "type":"string", "id": "root/subscribableInfo/deploymentPolicy", "default": "deployment_policy_1", "title":"Deployment Policy: ", "enum": [], "required":false }, "artifactRepository": { "id": "root/subscribableInfo/artifactRepository", "type": "object", "properties": { "privateRepo": { "id": "root/subscribableInfo/artifactRepository/privateRepo", "title":"Private Repository: ", "type": "boolean" }, "repoUrl": { "id": "root/subscribableInfo/artifactRepository/repoUrl", "title":"Repository URL: ", "type": "string" }, "repoUsername": { "id": "root/subscribableInfo/artifactRepository/repoUsername", "title":"Repository Username: ", "type": "string" }, "repoPassword": { "id": "root/subscribableInfo/artifactRepository/repoPassword", "title":"Repository Password: ", "type": "string", "format":"password" } } } } } } }; var cartridgeBlockDefault = { "type":"tomcat", "cartridgeMin":1, "cartridgeMax":2, "subscribableInfo":{ "alias":"alias2", "autoscalingPolicy":"", "deploymentPolicy":"", "artifactRepository":{ "privateRepo":"true", "repoUrl":"http://xxx:10080/git/default.git", "repoUsername":"user", "repoPassword":"password", } } }; var groupBlockTemplate = { "type":"object", "$schema": "http://json-schema.org/draft-03/schema", "id": "root", "required":false, "properties":{ "name": { "type":"string", "id": "root/name", "default": "name", "required":false }, "alias": { "type":"string", "id": "root/alias", "default": "alias", "required":false }, "groupMaxInstances": { "type":"number", "id": "root/groupMaxInstances", "default":2, "required":false }, "groupMinInstances": { "type":"number", "id": "root/groupMinInstances", "default":1, "required":false } } }; var groupBlockDefault = { "name":"group2", "alias":"group2alias", "groupMinInstances":1, "groupMaxInstances":2 }; var applicationBlockTemplate = { "$schema": "http://json-schema.org/draft-04/schema#", "id": "root", "type": "object", "title":" ", "options":{ "disable_properties":true, "disable_collapse": true }, "properties": { "applicationId": { "id": "root/applicationId", "title": "Application Id", "name": "Application Id", "type": "string" }, "alias": { "id": "root/alias", "type": "string", "title": "Application Alias", "name": "Application Alias" }, "multiTenant": { "id": "root/multiTenant", "type": "boolean", "title": "Application Multi Tenancy", "name": "Application Multi Tenancy" }, "dependencies": { "id": "root/dependencies", "type": "object", "title": "Dependencies", "name": "Dependencies", "options": { "hidden": false, "disable_properties":true, "collapsed": true }, "properties": { "startupOrders": { "id": "root/dependencies/startupOrders", "type": "array", "title": "Startup Orders", "name": "Startup Orders", "format":"tabs", "items": { "id": "root/dependencies/startupOrders/0", "type": "string", "title": "Order", "name": "Order" } }, "scalingDependents": { "id": "root/dependencies/scalingDependents", "type": "array", "title": "Scaling Dependents", "name": "Scaling Dependents", "format":"tabs", "items": { "id": "root/dependencies/scalingDependents/0", "type": "string", "title": "Dependent", "name": "Dependent" } }, "terminationBehaviour": { "id": "root/dependencies/terminationBehaviour", "type": "string", "title": "Termination Behaviour", "name": "Termination Behaviour", "enum": ["terminate-none","terminate-dependents","terminate-all"], } } } } }; var applicationBlockDefault = { "applicationId": "", "alias": "", "multiTenant": false, "dependencies": { "startupOrders": [ "group.my-group1,cartridge.my-c4" ], "scalingDependents": [ "group.my-group1,cartridge.my-c4" ], "terminationBehaviour": "terminate-dependents" } }; //create cartridge list var cartridgeListHtml=''; function generateCartridges(data){ if(data == null || data.length == 0){ cartridgeListHtml = 'No Cartridges found..'; }else{ for(var cartridge in data){ var cartridgeData = data[cartridge]; cartridgeListHtml += '<div class="block-cartridge" ' + 'data-info="'+cartridgeData.description+ '"'+ 'data-toggle="tooltip" data-placement="bottom" title="Single Click to view details. Double click to add"'+ 'id="'+cartridgeData.type+'">' + cartridgeData.displayName+ '</div>' } } //append cartridge into html content $('#cartridge-list').append(cartridgeListHtml); } //create group list var groupListHtml=''; function generateGroups(data){ if(data == null || data.length == 0){ groupListHtml = 'No Groups found..'; }else { for (var group in data) { var groupData = data[group]; groupListHtml += '<div class="block-group" ' + ' data-info="' + encodeURIComponent(JSON.stringify(groupData)) + '"' + 'data-toggle="tooltip" data-placement="bottom" title="'+groupData.name+'"'+ 'id="' + groupData.name + '">' + groupData.name + '</div>' } } //append cartridge into html content $('#group-list').append(groupListHtml); } //node positioning algo with dagre js function dagrePosition(){ // construct dagre graph from JsPlumb graph var g = new dagre.graphlib.Graph(); g.setGraph({ranksep:'80'}); g.setDefaultEdgeLabel(function() { return {}; }); var nodes = $(".stepnode"); for (var i = 0; i < nodes.length; i++) { var n = nodes[i]; g.setNode(n.id, {width: 52, height: 52}); } var edges = jsPlumb.getAllConnections(); for (var i = 0; i < edges.length; i++) { var c = edges[i]; g.setEdge(c.source.id,c.target.id ); } // calculate the layout (i.e. node positions) dagre.layout(g); // Applying the calculated layout g.nodes().forEach(function(v) { $("#" + v).css("left", g.node(v).x + "px"); $("#" + v).css("top", g.node(v).y + "px"); }); jsPlumb.repaintEverything(); } // Document ready events $(document).ready(function(){ //handled Ajax base session expire issue $(document).ajaxError(function (e, xhr, settings) { window.location.href = '../'; }); $('#deploy').attr('disabled','disabled'); $('#deploy').on('click', function(){ var appJSON = generateJsplumbTree(applicationJson, jsPlumb.getConnections(), appeditor); var btn = $(this); var formtype = 'applications'; btn.html("<i class='fa fa-spinner fa-spin'></i> Adding..."); $.ajax({ type: "POST", url: caramel.context + "/controllers/applications/application_requests.jag", dataType: 'json', data: { "formPayload": JSON.stringify(appJSON), "formtype": formtype }, success: function (data) { if (data.status == 'error') { var n = noty({text: data.message, layout: 'bottomRight', type: 'error'}); } else if (data.status == 'warning') { var n = noty({text: data.message, layout: 'bottomRight', type: 'warning'}); } else { var n = noty({text: data.message, layout: 'bottomRight', type: 'success'}); window.setTimeout(function(){ window.location.href = '../'; }, 1500); } } }) .always(function () { btn.html('Add New Application Definition'); }); }); //*******************Adding JSON editor *************// JSONEditor.defaults.theme = 'bootstrap3'; JSONEditor.defaults.iconlib = 'fontawesome4'; JSONEditor.defaults.show_errors = "always"; var editor, blockId, appeditor; //set hidden UUID applicationBlockDefault.applicationId = uuid(); // Initialize the editor for main section appeditor = new JSONEditor(document.getElementById('general'), { ajax: false, disable_edit_json: true, schema: applicationBlockTemplate, format: "grid", startval: applicationBlockDefault }); DragEl(".stepnode"); Repaint(); $('#whiteboard').on('click', '.stepnode', function(){ tabData($(this)); }); $('#whiteboard').on('dblclick', '.stepnode', function(){ var target = $('#component-data'); if( target.length ) { event.preventDefault(); $('html, body').animate({ scrollTop: target.offset().top }, 1000); } }); function tabData(node){ //get tab activated if(node.attr('id') == 'applicationId'){ activateTab('general'); }else{ activateTab('components'); $('#component-info-update').prop("disabled", false); } blockId = node.attr('id'); var blockType = node.attr('data-type'); var startval; var ctype = node.attr('data-ctype'); if(blockType == 'cartridge' || blockType == 'group-cartridge'){ startval = cartridgeBlockDefault; startval['type'] = ctype; //get list of autosacles var policies = editorAutoscalePolicies; var policiesEnum = []; for(var i=0; i<policies.length; i++){ policiesEnum.push(policies[i].id); } cartridgeBlockTemplate['properties']['subscribableInfo']['properties']['autoscalingPolicy']['enum'] =policiesEnum; //get list of deploymentpolicies var dpolicies = editorDeploymentPolicies; var dpoliciesEnum = []; for(var i=0; i<dpolicies.length; i++){ dpoliciesEnum.push(dpolicies[i].id); } cartridgeBlockTemplate['properties']['subscribableInfo']['properties']['deploymentPolicy']['enum'] =dpoliciesEnum; }else{ startval = groupBlockDefault; startval['name'] = ctype; } if(node.attr('data-generated')) { startval = JSON.parse(decodeURIComponent(node.attr('data-generated'))); } $('#component-data').html(''); switch (blockType){ case 'cartridge': generateHtmlBlock(cartridgeBlockTemplate, startval); break; case 'group': generateHtmlBlock(groupBlockTemplate, startval); break; case 'group-cartridge': generateHtmlBlock(cartridgeBlockTemplate, startval); break; } } function generateHtmlBlock(schema, startval){ // Initialize the editor editor = new JSONEditor(document.getElementById('component-data'), { ajax: false, disable_edit_json: true, schema: schema, format: "grid", startval: startval }); if(editor.getEditor('root.type')){ editor.getEditor('root.type').disable(); }else{ editor.getEditor('root.name').disable(); } } //get component JSON data $('#component-info-update').on('click', function(){ $('#'+blockId).attr('data-generated', encodeURIComponent(JSON.stringify(editor.getValue()))); $('#'+blockId).removeClass('input-false'); $('#'+blockId).find('div>i').removeClass('fa-exclamation-circle').addClass('fa-check-circle-o').css('color','#2ecc71'); $('#deploy').prop("disabled", false); }); //get create cartridge list generateCartridges(cartridgeList); //get group JSON generateGroups(groupList); //handle single click for cartridge $('#cartridge-list').on('click', ".block-cartridge", function(){ $('.description-section').html($(this).attr('data-info')); }); //handle double click for cartridge $('#cartridge-list').on('dblclick', ".block-cartridge", function(){ addJsplumbCartridge($(this).attr('id'),cartridgeCounter); //reposition after cartridge add dagrePosition(); //increase global count for instances cartridgeCounter++; }); //handle single click for groups $('#group-list').on('click', ".block-group", function(){ var groupJSON = JSON.parse(decodeURIComponent($(this).attr('data-info'))); mydata = generateGroupTree(groupJSON); generateGroupPreview(mydata); }); //handle double click event for groups $('#group-list').on('dblclick', ".block-group", function(){ var groupJSON = JSON.parse(decodeURIComponent($(this).attr('data-info'))); addJsplumbGroup(groupJSON,cartridgeCounter); //reposition after group add dagrePosition(); //increase global count for instances cartridgeCounter++; }); //reposition on click event on editor $('.reposition').on('click', function(){ dagrePosition(); }); //genrate context menu for nodes $.contextMenu({ selector: '.stepnode', callback: function(key, options) { var m = "clicked: " + key + $(this); if(key == 'delete'){ deleteNode($(this)); }else if(key == 'edit'){ document.getElementById('component-data').scrollIntoView(); tabData($(this)); } }, items: { "edit": {name: "Edit", icon: "edit"}, "delete": {name: "Delete", icon: "delete"} } }); }); //bootstrap tooltip added $(function () { $('[data-toggle="tooltip"]').tooltip() }) // ************* Add context menu for nodes ****************** //remove nodes from workarea function deleteNode(endPoint){ if(endPoint.attr('id') != 'applicationId'){ var allnodes = $(".stepnode"); var superParent = endPoint.attr('id').split("-")[0]+endPoint.attr('id').split("-")[1]; var nodeName = endPoint.attr('data-ctype'); var nodeType = endPoint.attr('data-type'); var notyText = ''; if(nodeType == 'group'){ notyText = 'This will remove related nodes from the Editor. Are you sure you want to delete ' +nodeType + ': '+nodeName+'?'; }else{ notyText = 'Are you sure you want to delete '+nodeType + ': '+nodeName+'?'; } noty({ layout: 'bottomRight', type: 'warning', text: notyText, buttons: [ {addClass: 'btn btn-primary', text: 'Yes', onClick: function($noty) { $noty.close(); allnodes.each(function(){ var currentId = $(this).attr('id').split("-")[0]+$(this).attr('id').split("-")[1]; if(currentId == superParent){ var that=$(this); //get all of your DIV tags having endpoints for (var i=0;i<that.length;i++) { var endpoints = jsPlumb.getEndpoints($(that[i])); //get all endpoints of that DIV if(endpoints){ for (var m=0;m<endpoints.length;m++) { // if(endpoints[m].anchor.type=="TopCenter") //Endpoint on right side jsPlumb.deleteEndpoint(endpoints[m]); //remove endpoint } } } jsPlumb.detachAllConnections($(this)); $(this).remove(); } }); //clear html area $('#component-data').html(''); activateTab('general'); } }, {addClass: 'btn btn-danger', text: 'No', onClick: function($noty) { $noty.close(); } } ] }); }else{ var n = noty({text: 'Sorry you can\'t remove application node' , layout: 'bottomRight', type: 'warning'}); } }
fix the cannot leave startup order in UI [STRATOS-1243]
components/org.apache.stratos.manager.console/console/themes/theme0/js/custom/applications-editor.js
fix the cannot leave startup order in UI [STRATOS-1243]
<ide><path>omponents/org.apache.stratos.manager.console/console/themes/theme0/js/custom/applications-editor.js <ide> "id": "root/dependencies/startupOrders/0", <ide> "type": "string", <ide> "title": "Order", <del> "name": "Order" <add> "name": "Order", <add> "default":"group.my-group1,cartridge.my-c4" <ide> } <ide> }, <ide> "scalingDependents": { <ide> "id": "root/dependencies/scalingDependents/0", <ide> "type": "string", <ide> "title": "Dependent", <del> "name": "Dependent" <add> "name": "Dependent", <add> "default":"group.my-group1,cartridge.my-c4" <ide> } <ide> }, <ide> "terminationBehaviour": { <ide> "multiTenant": false, <ide> "dependencies": { <ide> "startupOrders": [ <del> "group.my-group1,cartridge.my-c4" <add> <ide> ], <ide> "scalingDependents": [ <del> "group.my-group1,cartridge.my-c4" <add> <ide> ], <ide> "terminationBehaviour": "terminate-dependents" <ide> }
JavaScript
bsd-3-clause
044da363a1184ac60f3978d8f4029830530dc44b
0
MapCreatorEU/m4n-api,MapCreatorEU/m4n-api
/* * BSD 3-Clause License * * Copyright (c) 2017, MapCreator * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import fetchPonyfill from 'fetch-ponyfill'; export const {fetch, Request, Response, Headers} = fetchPonyfill({Promise}); /** * Encodes an object to a http query string with support for recursion * @param {object<string, *>} paramsObject - data to be encoded * @returns {string} - encoded http query string * * @protected */ export function encodeQueryString(paramsObject) { return _encodeQueryString(paramsObject).replace('&&', '&'); } /** * Encodes an object to a http query string with support for recursion * @param {Object<string, *>} paramsObject - data to be encoded * @param {Array<string>} _basePrefix - Used internally for tracking recursion * @returns {string} - encoded http query string * * @see http://stackoverflow.com/a/39828481 * @private */ function _encodeQueryString(paramsObject, _basePrefix = []) { return Object .keys(paramsObject) .sort() .map(key => { const prefix = _basePrefix.slice(0); if (typeof paramsObject[key] === 'object') { prefix.push(key); return _encodeQueryString(paramsObject[key], prefix); } prefix.push(key); let out = ''; out += encodeURIComponent(prefix.shift()); // main key out += prefix.map(item => `[${encodeURIComponent(item)}]`).join(''); // optional array keys out += '=' + encodeURIComponent(paramsObject[key]); // value return out; }).join('&'); }
src/utils/requests.js
/* * BSD 3-Clause License * * Copyright (c) 2017, MapCreator * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import fetchPonyfill from 'fetch-ponyfill'; export const {fetch, Request, Response, Headers} = fetchPonyfill({Promise}); /** * Makes a HTTP request and returns a promise. Promise will fail/reject if the * status code isn't 2XX. * @param {string} url - Target url * @param {string} method - HTTP method * @param {string|object<string, string>} body - raw body content or object to be json encoded * @param {object<string, string>} headers - headers * @param {string} responseType - XMLHttpRequest response type * * @returns {Promise} - resolves/rejects with {@link XMLHttpRequest} object. Rejects if status code != 2xx * @protected * @deprecated * @todo Better nodejs compatibility, maybe a requests library */ export function makeRequest(url, method = 'GET', body = '', headers = {}, responseType = '') { return new Promise((resolve, reject) => { method = method.toUpperCase(); const request = new XMLHttpRequest(); request.responseType = responseType; function hasHeader(h) { return Object.keys(headers) .filter(x => x.toLowerCase() === h.toLowerCase()) .length > 0; } request.open(method, url, true); // Apply headers for (const key of Object.keys(headers)) { request.setRequestHeader(key, headers[key]); } request.onreadystatechange = () => { // State 4 === Done if (request.readyState === XMLHttpRequest.DONE) { if (request.status >= 200 && request.status < 300) { resolve(request); } else { reject(request); } } }; if (body && method !== 'GET') { request.send(body); } else { request.send(); } }); } /** * Encodes an object to a http query string with support for recursion * @param {object<string, *>} paramsObject - data to be encoded * @returns {string} - encoded http query string * * @protected */ export function encodeQueryString(paramsObject) { return _encodeQueryString(paramsObject).replace('&&', '&'); } /** * Encodes an object to a http query string with support for recursion * @param {Object<string, *>} paramsObject - data to be encoded * @param {Array<string>} _basePrefix - Used internally for tracking recursion * @returns {string} - encoded http query string * * @see http://stackoverflow.com/a/39828481 * @private */ function _encodeQueryString(paramsObject, _basePrefix = []) { return Object .keys(paramsObject) .sort() .map(key => { const prefix = _basePrefix.slice(0); if (typeof paramsObject[key] === 'object') { prefix.push(key); return _encodeQueryString(paramsObject[key], prefix); } prefix.push(key); let out = ''; out += encodeURIComponent(prefix.shift()); // main key out += prefix.map(item => `[${encodeURIComponent(item)}]`).join(''); // optional array keys out += '=' + encodeURIComponent(paramsObject[key]); // value return out; }).join('&'); }
Remove makeRequest method
src/utils/requests.js
Remove makeRequest method
<ide><path>rc/utils/requests.js <ide> <ide> import fetchPonyfill from 'fetch-ponyfill'; <ide> export const {fetch, Request, Response, Headers} = fetchPonyfill({Promise}); <del> <del>/** <del> * Makes a HTTP request and returns a promise. Promise will fail/reject if the <del> * status code isn't 2XX. <del> * @param {string} url - Target url <del> * @param {string} method - HTTP method <del> * @param {string|object<string, string>} body - raw body content or object to be json encoded <del> * @param {object<string, string>} headers - headers <del> * @param {string} responseType - XMLHttpRequest response type <del> * <del> * @returns {Promise} - resolves/rejects with {@link XMLHttpRequest} object. Rejects if status code != 2xx <del> * @protected <del> * @deprecated <del> * @todo Better nodejs compatibility, maybe a requests library <del> */ <del>export function makeRequest(url, method = 'GET', body = '', headers = {}, responseType = '') { <del> return new Promise((resolve, reject) => { <del> method = method.toUpperCase(); <del> <del> const request = new XMLHttpRequest(); <del> <del> request.responseType = responseType; <del> <del> function hasHeader(h) { <del> return Object.keys(headers) <del> .filter(x => x.toLowerCase() === h.toLowerCase()) <del> .length > 0; <del> } <del> <del> request.open(method, url, true); <del> <del> <del> <del> // Apply headers <del> for (const key of Object.keys(headers)) { <del> request.setRequestHeader(key, headers[key]); <del> } <del> <del> request.onreadystatechange = () => { <del> // State 4 === Done <del> if (request.readyState === XMLHttpRequest.DONE) { <del> if (request.status >= 200 && request.status < 300) { <del> resolve(request); <del> } else { <del> reject(request); <del> } <del> } <del> }; <del> <del> if (body && method !== 'GET') { <del> request.send(body); <del> } else { <del> request.send(); <del> } <del> }); <del>} <del> <ide> <ide> /** <ide> * Encodes an object to a http query string with support for recursion
JavaScript
mit
ce5a87ae36956a08623c6530cc5860528dc22cc1
0
Bethhh/UCSDRentals,Bethhh/UCSDRentals,Bethhh/UCSDRentals
$(document).ready(function() { $.get("/user/get_name", update_name); }) function update_name(result){ if(result != ""){ if($(".user_name")[0] != undefined){ $(".user_name")[0].innerHTML = "Hello, "+result; } console.log("here"); } } function validateUser(){//originally use action="/login" method="post", successfully get the form data and to req.body, but no callback to call alert var email = document.getElementById('email').value; var password = document.getElementById('password').value; var json = { "email":email, "password":password }; $.post('/login', json, checkLogIn); } function checkLogIn(result){ var errorMsgs = ["nopwd","invalidemail","noaccount","wrongpwd"]; if(result == errorMsgs[0]){ alert("Please enter a password!"); }else if(result == errorMsgs[1]){ alert("Please enter a valid UCSD email address!"); }else if(result == errorMsgs[2]){ alert("Your account does not exist!\n Please sign up!"); }else if(result == errorMsgs[3]){ alert("Your password is incorrect!\n Please reenter your password!"); }else{ ga("send","event","login","click"); window.location='/menu';///'+result; } } /* function validateInfo() { var email = document.getElementById('email'); var filter = /^([a-zA-Z0-9_\.\-])+\@ucsd.edu+$/; var password = document.getElementById('password'); var errors = []; if (!filter.test(email.value)){ errors[errors.length] = "You must enter a valid UCSD email address!"; }else if (password.value == ''){ errors[errors.length] = "You must enter a password!"; }else{ window.location='/menu'; console.log("should go"); return true; } var msg = ""; if (errors.length > 0){ //var msg = "Please Enter Valid Data...\n"; for (var i = 0; i<errors.length; i++){ var numError = i+1; msg += "\n" + errors[i]; } alert(msg); return false; } }*/ function signupValidation(){ console.log("in checking sign up"); var email = document.getElementById('emaill').value; var password1 = document.getElementById('password1').value; var password2 = document.getElementById('password2').value; var json = { "email":email, "password1":password1, "password2":password2 }; $.post('/login/signup', json, checkSignUp); } function checkSignUp(result){ var errorMsgs = ["nopwd","invalidemail","accountexist","wrongpwd"]; if(result == errorMsgs[0]){ alert("Please enter your password!"); }else if(result == errorMsgs[1]){ alert("Please enter a valid UCSD email address!"); }else if(result == errorMsgs[2]){ alert("This account already exist!\n Please log in!"); }else if(result == errorMsgs[3]){ alert("Your passwords don't match!\n Please reenter your password!"); }else{ ga("send","event","login","click"); window.location='/setting'; //$.get('/setting', putEPBack); } } /*function putEPBack(){ $.get('/setting/set', setting_done); } function setting_done(result){ window.location="/setting"; console.log("the cookie"); console.log(result[0]); var e = document.getElementsByName("email"); e.value = result[0]; var p = document.getElementsByName("pwd"); p.value = result[1]; }*/ $("#signup").click(function() { //console.log("should gogogogo"); window.location='/signup'; }); /*$("#signup_btn").click(function() { //console.log("should gogogogo"); //window.location='/signup'; signupValidation(); });*/ $("#createNew").click(function() { // $.get("/oneProfile", getProfileForm); window.location='/newp'; }); /*function getProfileForm(result){ var copy_result = result; console.log("getprofileform"); console.log(copy_result); }*/ $("#viewExisting").click(function() { window.location='/existing'; }); $("#about").click(function() { window.location='/about'; }); //$("#logout").click(function() { // window.location='/'; //}); function grabTypeForm(){ } $("#contact").click(function(){ var msg=prompt("Enter your message here:"); }); $("#detail_back").click(function(){ window.location = '../matches'; }); $(".m").click(function(){ window.location = '../matches'; }); $("#update").click(function(f){ f.preventDefault(); var e = document.getElementById("existing_buttons"); e.style.display = 'none'; var e = document.getElementById("existing_list"); e.style.display = 'block'; }); $("#logout").click(function(f){ f.preventDefault(); ga("send","event","logout","click"); $.get('/login/logout', afterOut); }); $(".logoutgroup").click(function(f){ f.preventDefault(); ga("send","event","logout","click"); $.get('../login/logout', afterOut); }); function afterOut(result){ console.log(result); window.location="/"; }
public/js/ucsdrentals.js
$(document).ready(function() { $.get("/user/get_name", update_name); }) function update_name(result){ if(result != ""){ if($(".user_name")[0] != undefined){ $(".user_name")[0].innerHTML = "Hello, "+result; } console.log("here"); } } function validateUser(){//originally use action="/login" method="post", successfully get the form data and to req.body, but no callback to call alert var email = document.getElementById('email').value; var password = document.getElementById('password').value; var json = { "email":email, "password":password }; $.post('/login', json, checkLogIn); } function checkLogIn(result){ var errorMsgs = ["nopwd","invalidemail","noaccount","wrongpwd"]; if(result == errorMsgs[0]){ alert("Please enter a password!"); }else if(result == errorMsgs[1]){ alert("Please enter a valid UCSD email address!"); }else if(result == errorMsgs[2]){ alert("Your account does not exist!\n Please sign up!"); }else if(result == errorMsgs[3]){ alert("Your password is incorrect!\n Please reenter your password!"); }else{ window.location='/menu';///'+result; } } /* function validateInfo() { var email = document.getElementById('email'); var filter = /^([a-zA-Z0-9_\.\-])+\@ucsd.edu+$/; var password = document.getElementById('password'); var errors = []; if (!filter.test(email.value)){ errors[errors.length] = "You must enter a valid UCSD email address!"; }else if (password.value == ''){ errors[errors.length] = "You must enter a password!"; }else{ window.location='/menu'; console.log("should go"); return true; } var msg = ""; if (errors.length > 0){ //var msg = "Please Enter Valid Data...\n"; for (var i = 0; i<errors.length; i++){ var numError = i+1; msg += "\n" + errors[i]; } alert(msg); return false; } }*/ function signupValidation(){ console.log("in checking sign up"); var email = document.getElementById('emaill').value; var password1 = document.getElementById('password1').value; var password2 = document.getElementById('password2').value; var json = { "email":email, "password1":password1, "password2":password2 }; $.post('/login/signup', json, checkSignUp); } function checkSignUp(result){ var errorMsgs = ["nopwd","invalidemail","accountexist","wrongpwd"]; if(result == errorMsgs[0]){ alert("Please enter your password!"); }else if(result == errorMsgs[1]){ alert("Please enter a valid UCSD email address!"); }else if(result == errorMsgs[2]){ alert("This account already exist!\n Please log in!"); }else if(result == errorMsgs[3]){ alert("Your passwords don't match!\n Please reenter your password!"); }else{ window.location='/setting'; //$.get('/setting', putEPBack); } } /*function putEPBack(){ $.get('/setting/set', setting_done); } function setting_done(result){ window.location="/setting"; console.log("the cookie"); console.log(result[0]); var e = document.getElementsByName("email"); e.value = result[0]; var p = document.getElementsByName("pwd"); p.value = result[1]; }*/ $("#signup").click(function() { //console.log("should gogogogo"); window.location='/signup'; }); /*$("#signup_btn").click(function() { //console.log("should gogogogo"); //window.location='/signup'; signupValidation(); });*/ $("#createNew").click(function() { // $.get("/oneProfile", getProfileForm); window.location='/newp'; }); /*function getProfileForm(result){ var copy_result = result; console.log("getprofileform"); console.log(copy_result); }*/ $("#viewExisting").click(function() { window.location='/existing'; }); $("#about").click(function() { window.location='/about'; }); //$("#logout").click(function() { // window.location='/'; //}); function grabTypeForm(){ } $("#contact").click(function(){ var msg=prompt("Enter your message here:"); }); $("#detail_back").click(function(){ window.location = '../matches'; }); $(".m").click(function(){ window.location = '../matches'; }); $("#update").click(function(f){ f.preventDefault(); var e = document.getElementById("existing_buttons"); e.style.display = 'none'; var e = document.getElementById("existing_list"); e.style.display = 'block'; }); $("#logout").click(function(f){ f.preventDefault(); $.get('/login/logout', afterOut); }); $(".logoutgroup").click(function(f){ f.preventDefault(); $.get('../login/logout', afterOut); }); function afterOut(result){ console.log(result); window.location="/"; }
add pageview
public/js/ucsdrentals.js
add pageview
<ide><path>ublic/js/ucsdrentals.js <ide> }else if(result == errorMsgs[3]){ <ide> alert("Your password is incorrect!\n Please reenter your password!"); <ide> }else{ <add> ga("send","event","login","click"); <ide> window.location='/menu';///'+result; <ide> } <ide> } <ide> }else if(result == errorMsgs[3]){ <ide> alert("Your passwords don't match!\n Please reenter your password!"); <ide> }else{ <add> ga("send","event","login","click"); <ide> window.location='/setting'; <ide> //$.get('/setting', putEPBack); <ide> } <ide> <ide> $("#logout").click(function(f){ <ide> f.preventDefault(); <add> ga("send","event","logout","click"); <ide> $.get('/login/logout', afterOut); <ide> }); <ide> <ide> $(".logoutgroup").click(function(f){ <ide> f.preventDefault(); <add> ga("send","event","logout","click"); <ide> $.get('../login/logout', afterOut); <ide> }); <ide>
Java
mit
1354424fc80867ee2dafe73a5122072040650076
0
jxd134/java8-lambda-exercises
package com.insightfullogic.java8.test.chapter3; import static org.junit.Assert.*; import static java.util.Arrays.asList; import java.util.Collections; import java.util.List; import java.util.function.Function; import org.junit.Test; import com.insightfullogic.java8.answers.chapter3.*; public class MapUsingReduceTest { @Test public void emptyList() { assertMapped(Function.<Object> identity(), Collections.<Object> emptyList(), Collections.<Object> emptyList()); } @Test public void identityMapsToItself() { assertMapped((Integer x) -> x, asList(1, 2, 3), asList(1, 2, 3)); } @Test public void incrementingNumbers() { assertMapped((Integer x) -> x + 2, asList(1, 2, 3), asList(3, 4, 5)); } private <I, O> void assertMapped(Function<I, O> mapper, List<I> input, List<O> expectedOutput) { List<O> output = MapUsingReduce.map(input.stream(), mapper); assertEquals(expectedOutput, output); List<O> paralleOutPut = MapUsingReduce.map(input.parallelStream(), mapper); assertEquals(expectedOutput, paralleOutPut); } }
src/com/insightfullogic/java8/test/chapter3/MapUsingReduceTest.java
package com.insightfullogic.java8.test.chapter3; import static org.junit.Assert.*; import java.util.Collections; import java.util.List; import java.util.function.Function; import org.junit.Test; import com.insightfullogic.java8.answers.chapter3.*; public class MapUsingReduceTest { @Test public void emptyList(){ assertMapped(Function.<Object>identity(), Collections.<Object>emptyList(), Collections.<Object>emptyList()); } private <I,O> void assertMapped(Function<I,O> mapper,List<I> input,List<O> expectedOutput){ List<O> output=MapUsingReduce.map(input.stream(), mapper); assertEquals(expectedOutput, output); } }
complete test for MapUsingReduce in chapter3
src/com/insightfullogic/java8/test/chapter3/MapUsingReduceTest.java
complete test for MapUsingReduce in chapter3
<ide><path>rc/com/insightfullogic/java8/test/chapter3/MapUsingReduceTest.java <ide> package com.insightfullogic.java8.test.chapter3; <ide> <ide> import static org.junit.Assert.*; <add>import static java.util.Arrays.asList; <ide> <ide> import java.util.Collections; <ide> import java.util.List; <ide> import com.insightfullogic.java8.answers.chapter3.*; <ide> <ide> public class MapUsingReduceTest { <del> <add> <ide> @Test <del> public void emptyList(){ <del> assertMapped(Function.<Object>identity(), Collections.<Object>emptyList(), Collections.<Object>emptyList()); <add> public void emptyList() { <add> assertMapped(Function.<Object> identity(), Collections.<Object> emptyList(), Collections.<Object> emptyList()); <ide> } <ide> <del> private <I,O> void assertMapped(Function<I,O> mapper,List<I> input,List<O> expectedOutput){ <del> List<O> output=MapUsingReduce.map(input.stream(), mapper); <add> @Test <add> public void identityMapsToItself() { <add> assertMapped((Integer x) -> x, asList(1, 2, 3), asList(1, 2, 3)); <add> } <add> <add> @Test <add> public void incrementingNumbers() { <add> assertMapped((Integer x) -> x + 2, asList(1, 2, 3), asList(3, 4, 5)); <add> } <add> <add> private <I, O> void assertMapped(Function<I, O> mapper, List<I> input, List<O> expectedOutput) { <add> List<O> output = MapUsingReduce.map(input.stream(), mapper); <ide> assertEquals(expectedOutput, output); <add> <add> List<O> paralleOutPut = MapUsingReduce.map(input.parallelStream(), mapper); <add> assertEquals(expectedOutput, paralleOutPut); <ide> } <del> <add> <ide> }
Java
mpl-2.0
836f24498c3716b0c6e35c2e25d9cc355b1b1e2b
0
johan12345/substitution-schedule-parser,vertretungsplanme/substitution-schedule-parser,vertretungsplanme/substitution-schedule-parser,johan12345/substitution-schedule-parser
/* * substitution-schedule-parser - Java library for parsing schools' substitution schedules * Copyright (c) 2016 Johan v. Forstner * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package me.vertretungsplan.parser; import me.vertretungsplan.exception.CredentialInvalidException; import me.vertretungsplan.objects.Substitution; import me.vertretungsplan.objects.SubstitutionSchedule; import me.vertretungsplan.objects.SubstitutionScheduleData; import me.vertretungsplan.objects.SubstitutionScheduleDay; import org.jetbrains.annotations.NotNull; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormat; import org.json.JSONException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DaVinciParser extends BaseParser { private static final String ENCODING = "UTF-8"; public DaVinciParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) { super(scheduleData, cookieProvider); } static void parseDaVinciTable(Element table, SubstitutionScheduleDay day, ColorProvider colorProvider) { parseDaVinciTable(table, day, null, colorProvider); } static void parseDaVinciTable(Element table, SubstitutionScheduleDay day, String klasse, ColorProvider colorProvider) { List<String> headers = new ArrayList<>(); for (Element header : table.select("thead tr th, tr td[bgcolor=#9999FF]")) { headers.add(header.text()); } // These two variables can Set<String> classes = new HashSet<>(); String lesson = null; Pattern previousCurrentPattern = Pattern.compile("\\+([^\\s]+) \\(([^)]+)\\)"); for (Element row : table.select("tr:not(thead tr, tr:has(td[bgcolor=#9999FF]))")) { Substitution subst = new Substitution(); Elements columns = row.select("td"); for (int i = 0; i < headers.size(); i++) { String value = columns.get(i).text().replace("\u00a0", ""); String header = headers.get(i); if (value.isEmpty()) { if (header.equals("Klasse")) subst.setClasses(classes); if (header.equals("Pos") || header.equals("Stunde")) subst.setLesson(lesson); if (header.equals("Art") || header.equals("Merkmal")) subst.setType("Vertretung"); continue; } Matcher matcher = previousCurrentPattern.matcher(value); switch (header) { case "Klasse": classes = new HashSet<>(Arrays.asList(value.split(","))); subst.setClasses(classes); break; case "Pos": case "Stunde": lesson = value; subst.setLesson(lesson); break; case "VLehrer Kürzel": case "VLehrer": case "Vertreter": if (!value.startsWith("*")) { if (value.equals("Raumänderung")) { subst.setType(value); } else { subst.setTeacher(value); } } break; case "Lehrer": case "Lehrer Kürzel": if (matcher.find()) { subst.setTeacher(matcher.group(1)); subst.setPreviousTeacher(matcher.group(2)); } else { subst.setPreviousTeacher(value); } break; case "VFach": subst.setSubject(value); break; case "Fach": if (matcher.find()) { subst.setSubject(matcher.group(1)); subst.setPreviousSubject(matcher.group(2)); } else { subst.setPreviousSubject(value); } break; case "VRaum": subst.setRoom(value); break; case "Raum": if (matcher.find()) { subst.setRoom(matcher.group(1)); subst.setPreviousRoom(matcher.group(2)); } else { subst.setPreviousRoom(value); } break; case "Art": case "Merkmal": subst.setType(value); break; case "Info": case "Mitteilung": subst.setDesc(value); if (!headers.contains("Art") && !headers.contains("Merkmal")) { } break; } } if (klasse != null) { Set<String> fixedClasses = new HashSet<>(); fixedClasses.add(klasse); subst.setClasses(fixedClasses); } if (subst.getType() == null) { String recognizedType = null; if (subst.getDesc() != null) recognizedType = recognizeType(subst.getDesc()); subst.setType(recognizedType != null ? recognizedType : "Vertretung"); } subst.setColor(colorProvider.getColor(subst.getType())); day.addSubstitution(subst); } } @Override public SubstitutionSchedule getSubstitutionSchedule() throws IOException, JSONException, CredentialInvalidException { new LoginHandler(scheduleData, credential, cookieProvider).handleLogin(executor, cookieStore); SubstitutionSchedule schedule = SubstitutionSchedule.fromData(scheduleData); String url = scheduleData.getData().getString("url"); Document doc = Jsoup.parse(httpGet(url, ENCODING)); List<String> dayUrls = getDayUrls(url, doc); for (String dayUrl : dayUrls) { Document dayDoc; if (dayUrl.equals(url)) { dayDoc = doc; } else { dayDoc = Jsoup.parse(httpGet(dayUrl, ENCODING)); } schedule.addDay(parseDay(dayDoc)); } schedule.setWebsite(url); schedule.setClasses(getAllClasses()); schedule.setTeachers(getAllTeachers()); return schedule; } @NotNull static List<String> getDayUrls(String url, Document doc) throws IOException { List<String> dayUrls = new ArrayList<>(); if (doc.select("ul.classes").size() > 0) { // List of classes Elements classes = doc.select("ul.classes li a"); for (Element klasse : classes) { dayUrls.add(new URL(new URL(url), klasse.attr("href")).toString()); } } else if (doc.select("ul.month").size() > 0) { // List of days in calendar view Elements days = doc.select("ul.month li input[onclick]"); for (Element day : days) { String urlFromOnclick = urlFromOnclick(day.attr("onclick")); if (urlFromOnclick == null) continue; dayUrls.add(new URL(new URL(url), urlFromOnclick).toString()); } } else if (doc.select("ul.day-index").size() > 0) { // List of days in list view Elements days = doc.select("ul.day-index li a"); for (Element day : days) { dayUrls.add(new URL(new URL(url), day.attr("href")).toString()); } } else { // Single day dayUrls.add(url); } return dayUrls; } private static String urlFromOnclick(String onclick) { Pattern pattern = Pattern.compile("window\\.location\\.href='([^']+)'"); Matcher matcher = pattern.matcher(onclick); if (matcher.find()) { return matcher.group(1); } else { return null; } } @NotNull SubstitutionScheduleDay parseDay(Document doc) throws IOException { SubstitutionScheduleDay day = new SubstitutionScheduleDay(); String title = doc.select("h1.list-table-caption").first().text(); String klasse = null; // title can either be date or class if (title.matches("\\w+ \\d+\\.\\d+.\\d{4}")) { day.setDateString(title); day.setDate(ParserUtils.parseDate(title)); } else { klasse = title; String nextText = doc.select("h1.list-table-caption").first().nextElementSibling().text(); if (nextText.matches("\\w+ \\d+\\.\\d+.\\d{4}")) { day.setDateString(nextText); day.setDate(ParserUtils.parseDate(nextText)); } else { throw new IOException("Could not find date"); } } String lastChange = doc.select(".row.copyright div").first().ownText(); Pattern pattern = Pattern.compile("(\\d{2}-\\d{2}-\\d{4} \\d{2}:\\d{2}) \\|"); Matcher matcher = pattern.matcher(lastChange); if (matcher.find()) { LocalDateTime lastChangeTime = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm").parseLocalDateTime(matcher.group(1)); day.setLastChange(lastChangeTime); } if (doc.select(".list-table").size() > 0 || !doc.select(".callout").text().contains("Es liegen keine")) { Element table = doc.select(".list-table").first(); parseDaVinciTable(table, day, klasse, colorProvider); } return day; } @Override public List<String> getAllClasses() throws IOException, JSONException { if (scheduleData.getData().has("classesSource")) { Document doc = Jsoup.parse(httpGet(scheduleData.getData().getString("classesSource"), ENCODING)); List<String> classes = new ArrayList<>(); for (Element li : doc.select("li.Class")) { classes.add(li.text()); } return classes; } else { return getClassesFromJson(); } } @Override public List<String> getAllTeachers() { return null; } }
parser/src/main/java/me/vertretungsplan/parser/DaVinciParser.java
/* * substitution-schedule-parser - Java library for parsing schools' substitution schedules * Copyright (c) 2016 Johan v. Forstner * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package me.vertretungsplan.parser; import me.vertretungsplan.exception.CredentialInvalidException; import me.vertretungsplan.objects.Substitution; import me.vertretungsplan.objects.SubstitutionSchedule; import me.vertretungsplan.objects.SubstitutionScheduleData; import me.vertretungsplan.objects.SubstitutionScheduleDay; import org.jetbrains.annotations.NotNull; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormat; import org.json.JSONException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DaVinciParser extends BaseParser { private static final String ENCODING = "UTF-8"; public DaVinciParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) { super(scheduleData, cookieProvider); } static void parseDaVinciTable(Element table, SubstitutionScheduleDay day, ColorProvider colorProvider) { parseDaVinciTable(table, day, null, colorProvider); } static void parseDaVinciTable(Element table, SubstitutionScheduleDay day, String klasse, ColorProvider colorProvider) { List<String> headers = new ArrayList<>(); for (Element header : table.select("thead tr th, tr td[bgcolor=#9999FF]")) { headers.add(header.text()); } // These two variables can Set<String> classes = new HashSet<>(); String lesson = null; Pattern previousCurrentPattern = Pattern.compile("\\+([^\\s]+) \\(([^)]+)\\)"); for (Element row : table.select("tr:not(thead tr, tr:has(td[bgcolor=#9999FF]))")) { Substitution subst = new Substitution(); Elements columns = row.select("td"); for (int i = 0; i < headers.size(); i++) { String value = columns.get(i).text().replace("\u00a0", ""); String header = headers.get(i); if (value.isEmpty()) { if (header.equals("Klasse")) subst.setClasses(classes); if (header.equals("Pos") || header.equals("Stunde")) subst.setLesson(lesson); if (header.equals("Art") || header.equals("Merkmal")) subst.setType("Vertretung"); continue; } Matcher matcher = previousCurrentPattern.matcher(value); switch (header) { case "Klasse": classes = new HashSet<>(Arrays.asList(value.split(","))); subst.setClasses(classes); break; case "Pos": case "Stunde": lesson = value; subst.setLesson(lesson); break; case "VLehrer Kürzel": case "VLehrer": case "Vertreter": if (!value.startsWith("*")) { if (value.equals("Raumänderung")) { subst.setType(value); } else { subst.setTeacher(value); } } break; case "Lehrer": case "Lehrer Kürzel": if (matcher.find()) { subst.setTeacher(matcher.group(1)); subst.setPreviousTeacher(matcher.group(2)); } else { subst.setPreviousTeacher(value); } break; case "VFach": subst.setSubject(value); break; case "Fach": if (matcher.find()) { subst.setSubject(matcher.group(1)); subst.setPreviousSubject(matcher.group(2)); } else { subst.setPreviousSubject(value); } break; case "VRaum": subst.setRoom(value); break; case "Raum": if (matcher.find()) { subst.setRoom(matcher.group(1)); subst.setPreviousRoom(matcher.group(2)); } else { subst.setPreviousRoom(value); } break; case "Art": case "Merkmal": subst.setType(value); break; case "Info": case "Mitteilung": subst.setDesc(value); if (!headers.contains("Art") && !headers.contains("Merkmal")) { } break; } } if (klasse != null) { Set<String> fixedClasses = new HashSet<>(); fixedClasses.add(klasse); subst.setClasses(fixedClasses); } if (subst.getType() == null) { String recognizedType = null; if (subst.getDesc() != null) recognizedType = recognizeType(subst.getDesc()); subst.setType(recognizedType != null ? recognizedType : "Vertretung"); } subst.setColor(colorProvider.getColor(subst.getType())); day.addSubstitution(subst); } } @Override public SubstitutionSchedule getSubstitutionSchedule() throws IOException, JSONException, CredentialInvalidException { SubstitutionSchedule schedule = SubstitutionSchedule.fromData(scheduleData); String url = scheduleData.getData().getString("url"); Document doc = Jsoup.parse(httpGet(url, ENCODING)); List<String> dayUrls = getDayUrls(url, doc); for (String dayUrl : dayUrls) { Document dayDoc; if (dayUrl.equals(url)) { dayDoc = doc; } else { dayDoc = Jsoup.parse(httpGet(dayUrl, ENCODING)); } schedule.addDay(parseDay(dayDoc)); } schedule.setWebsite(url); schedule.setClasses(getAllClasses()); schedule.setTeachers(getAllTeachers()); return schedule; } @NotNull static List<String> getDayUrls(String url, Document doc) throws IOException { List<String> dayUrls = new ArrayList<>(); if (doc.select("ul.classes").size() > 0) { // List of classes Elements classes = doc.select("ul.classes li a"); for (Element klasse : classes) { dayUrls.add(new URL(new URL(url), klasse.attr("href")).toString()); } } else if (doc.select("ul.month").size() > 0) { // List of days in calendar view Elements days = doc.select("ul.month li input[onclick]"); for (Element day : days) { String urlFromOnclick = urlFromOnclick(day.attr("onclick")); if (urlFromOnclick == null) continue; dayUrls.add(new URL(new URL(url), urlFromOnclick).toString()); } } else if (doc.select("ul.day-index").size() > 0) { // List of days in list view Elements days = doc.select("ul.day-index li a"); for (Element day : days) { dayUrls.add(new URL(new URL(url), day.attr("href")).toString()); } } else { // Single day dayUrls.add(url); } return dayUrls; } private static String urlFromOnclick(String onclick) { Pattern pattern = Pattern.compile("window\\.location\\.href='([^']+)'"); Matcher matcher = pattern.matcher(onclick); if (matcher.find()) { return matcher.group(1); } else { return null; } } @NotNull SubstitutionScheduleDay parseDay(Document doc) throws IOException { SubstitutionScheduleDay day = new SubstitutionScheduleDay(); String title = doc.select("h1.list-table-caption").first().text(); String klasse = null; // title can either be date or class if (title.matches("\\w+ \\d+\\.\\d+.\\d{4}")) { day.setDateString(title); day.setDate(ParserUtils.parseDate(title)); } else { klasse = title; String nextText = doc.select("h1.list-table-caption").first().nextElementSibling().text(); if (nextText.matches("\\w+ \\d+\\.\\d+.\\d{4}")) { day.setDateString(nextText); day.setDate(ParserUtils.parseDate(nextText)); } else { throw new IOException("Could not find date"); } } String lastChange = doc.select(".row.copyright div").first().ownText(); Pattern pattern = Pattern.compile("(\\d{2}-\\d{2}-\\d{4} \\d{2}:\\d{2}) \\|"); Matcher matcher = pattern.matcher(lastChange); if (matcher.find()) { LocalDateTime lastChangeTime = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm").parseLocalDateTime(matcher.group(1)); day.setLastChange(lastChangeTime); } if (doc.select(".list-table").size() > 0 || !doc.select(".callout").text().contains("Es liegen keine")) { Element table = doc.select(".list-table").first(); parseDaVinciTable(table, day, klasse, colorProvider); } return day; } @Override public List<String> getAllClasses() throws IOException, JSONException { if (scheduleData.getData().has("classesSource")) { Document doc = Jsoup.parse(httpGet(scheduleData.getData().getString("classesSource"), ENCODING)); List<String> classes = new ArrayList<>(); for (Element li : doc.select("li.Class")) { classes.add(li.text()); } return classes; } else { return getClassesFromJson(); } } @Override public List<String> getAllTeachers() { return null; } }
DaVinciParser: add LoginHandler call
parser/src/main/java/me/vertretungsplan/parser/DaVinciParser.java
DaVinciParser: add LoginHandler call
<ide><path>arser/src/main/java/me/vertretungsplan/parser/DaVinciParser.java <ide> <ide> @Override <ide> public SubstitutionSchedule getSubstitutionSchedule() throws IOException, JSONException, CredentialInvalidException { <add> new LoginHandler(scheduleData, credential, cookieProvider).handleLogin(executor, cookieStore); <add> <ide> SubstitutionSchedule schedule = SubstitutionSchedule.fromData(scheduleData); <ide> <ide> String url = scheduleData.getData().getString("url");
Java
apache-2.0
ce190a2f8d706dcebc647e138dac442d2cb107be
0
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
package br.net.mirante.singular.dao; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.Period; import java.time.ZoneId; import java.time.temporal.Temporal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.transform.Transformers; import org.hibernate.type.FloatType; import org.hibernate.type.IntegerType; import org.hibernate.type.LongType; import org.hibernate.type.StringType; import org.hibernate.type.TimestampType; import org.springframework.stereotype.Repository; import br.net.mirante.singular.dto.StatusDTO; import br.net.mirante.singular.flow.core.TaskType; @Repository public class InstanceDAO extends BaseDAO{ public static final int MAX_FEED_SIZE = 30; private enum Columns { description("DESCRICAO"), delta("DELTA"), date("DIN"), deltas("DELTAS"), dates("DS"), user("USUARIO"); private String code; Columns(String code) { this.code = code; } @Override public String toString() { return code; } } @SuppressWarnings("unchecked") public List<Object[]> retrieveAll(int first, int size, String orderByProperty, boolean asc, Long id) { StringBuilder orderByStatement = new StringBuilder(""); if (orderByProperty != null) { orderByStatement.append("ORDER BY ").append(Columns.valueOf(orderByProperty)).append(" "); orderByStatement.append(asc ? "ASC" : "DESC"); } String sql = "SELECT DISTINCT INS.CO_INSTANCIA_PROCESSO AS CODIGO, INS.DS_INSTANCIA_PROCESSO AS DESCRICAO," + " DATEDIFF(SECOND, DT_INICIO, GETDATE()) AS DELTA, DT_INICIO AS DIN," + " DATEDIFF(SECOND, data_situacao_atual, GETDATE()) AS DELTAS, data_situacao_atual AS DS," + " PES.nome_guerra AS USUARIO" + " FROM TB_INSTANCIA_PROCESSO INS" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN CAD_PESSOA PES ON PES.cod_pessoa = INS.cod_pessoa_alocada" + " WHERE INS.DT_FIM IS NULL AND PRO.CO_DEFINICAO_PROCESSO = :id " + orderByStatement.toString(); Query query = getSession().createSQLQuery(sql) .addScalar("CODIGO", LongType.INSTANCE) .addScalar("DESCRICAO", StringType.INSTANCE) .addScalar("DELTA", LongType.INSTANCE) .addScalar("DIN", TimestampType.INSTANCE) .addScalar("DELTAS", LongType.INSTANCE) .addScalar("DS", TimestampType.INSTANCE) .addScalar("USUARIO", LongType.INSTANCE) .setParameter("id", id); query.setFirstResult(first); query.setMaxResults(size); return (List<Object[]>) query.list(); } public int countAll(Long id) { return ((Number) getSession().createSQLQuery( "SELECT COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO)" + " FROM TB_INSTANCIA_PROCESSO INS" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN TB_DEFINICAO_TAREFA DFT ON DFT.CO_DEFINICAO_PROCESSO = DEF.CO_DEFINICAO_PROCESSO" + " WHERE INS.DT_FIM IS NULL AND PRO.CO_DEFINICAO_PROCESSO = :id") .setParameter("id", id) .uniqueResult()).intValue(); } public List<Map<String, String>> retrieveTransactionQuantityLastYear(String processCode, Set<String> processCodeWithAccess) { List<Map<String, String>> newTransactions = retrieveNewQuantityLastYear(processCode, processCodeWithAccess); List<Map<String, String>> finishedTransations = retrieveFinishedQuantityLastYear(processCode, processCodeWithAccess); List<Map<String, String>> transactions = newTransactions.stream().collect(Collectors.toList()); for (Map<String, String> map : finishedTransations) { Map<String, String> m = retrieveResultMap(map, transactions); if (m == null) { transactions.add(map); } else { m.put("QTD_CLS", map.get("QTD_CLS")); } } return transactions; } private Map<String, String> retrieveResultMap(Map<String, String> map, List<Map<String, String>> list) { for (Map<String, String> m : list) { if (m.get("POS").equals(map.get("POS"))) { return m; } } return null; } @SuppressWarnings("unchecked") private List<Map<String, String>> retrieveNewQuantityLastYear(String processCode, Set<String> processCodeWithAccess) { String sql = "SET LANGUAGE Portuguese;" + "SELECT RIGHT('00' + CAST(MONTH(DT_INICIO) AS VARCHAR(2)), 2) + SUBSTRING(DATENAME(YEAR, DT_INICIO), 3, 4) AS POS," + " UPPER(SUBSTRING(DATENAME(MONTH, DT_INICIO), 0, 4)) + '/' + SUBSTRING(DATENAME(YEAR, DT_INICIO), 3, 4) AS MES," + " COUNT(CO_INSTANCIA_PROCESSO) AS QTD_NEW" + " FROM TB_INSTANCIA_PROCESSO INS" + " LEFT JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " WHERE DT_INICIO >= CAST(FLOOR(CAST(GETDATE() - 364 - DAY(GETDATE()) AS FLOAT)) AS DATETIME)" + " AND SG_PROCESSO in(:processCodeWithAccess)" + (processCode != null ? " AND SG_PROCESSO = :processCode" : "") + " GROUP BY MONTH(DT_INICIO), YEAR(DT_INICIO), DATENAME(MONTH, DT_INICIO), DATENAME(YEAR, DT_INICIO)" + " ORDER BY YEAR(DT_INICIO), MONTH(DT_INICIO)"; Query query = getSession().createSQLQuery(sql) .addScalar("POS", StringType.INSTANCE) .addScalar("MES", StringType.INSTANCE) .addScalar("QTD_NEW", StringType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); if (processCode != null) { query.setParameter("processCode", processCode); } query.setParameterList("processCodeWithAccess", processCodeWithAccess); return (List<Map<String, String>>) query.list(); } @SuppressWarnings("unchecked") private List<Map<String, String>> retrieveFinishedQuantityLastYear(String processCode, Set<String> processCodeWithAccess) { String sql = "SET LANGUAGE Portuguese;" + "SELECT RIGHT('00' + CAST(MONTH(DT_FIM) AS VARCHAR(2)), 2) + SUBSTRING(DATENAME(YEAR, DT_FIM), 3, 4) AS POS," + " UPPER(SUBSTRING(DATENAME(MONTH, DT_FIM), 0, 4)) + '/' + SUBSTRING(DATENAME(YEAR, DT_FIM), 3, 4) AS MES," + " COUNT(CO_INSTANCIA_PROCESSO) AS QTD_CLS" + " FROM TB_INSTANCIA_PROCESSO INS" + " LEFT JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " WHERE DT_FIM >= CAST(FLOOR(CAST(GETDATE() - 364 - DAY(GETDATE()) AS FLOAT)) AS DATETIME)" + " AND SG_PROCESSO in(:processCodeWithAccess)" + (processCode != null ? " AND SG_PROCESSO = :processCode" : "") + " GROUP BY MONTH(DT_FIM), YEAR(DT_FIM), DATENAME(MONTH, DT_FIM), DATENAME(YEAR, DT_FIM)" + " ORDER BY YEAR(DT_FIM), MONTH(DT_FIM)"; Query query = getSession().createSQLQuery(sql) .addScalar("POS", StringType.INSTANCE) .addScalar("MES", StringType.INSTANCE) .addScalar("QTD_CLS", StringType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); if (processCode != null) { query.setParameter("processCode", processCode); } query.setParameterList("processCodeWithAccess", processCodeWithAccess); return (List<Map<String, String>>) query.list(); } @SuppressWarnings("unchecked") public List<Map<String, String>> retrieveEndStatusQuantityByPeriod(Period period, String processCod) { String sql = "SELECT SIT.NO_TAREFA AS SITUACAO, COUNT(DEM.CO_INSTANCIA_PROCESSO) AS QUANTIDADE" + " FROM TB_INSTANCIA_PROCESSO DEM" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = DEM.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN TB_VERSAO_TAREFA SIT ON SIT.CO_VERSAO_TAREFA = DEM.cod_situacao" + " WHERE DEM.data_situacao_atual >= :startPeriod AND DEF.SG_PROCESSO = :processCod" + " AND SIT.CO_TIPO_TAREFA = " + TaskType.End.ordinal() + " GROUP BY SIT.NO_TAREFA"; Query query = getSession().createSQLQuery(sql) .addScalar("SITUACAO", StringType.INSTANCE) .addScalar("QUANTIDADE", LongType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); query.setParameter("processCod", processCod); query.setParameter("startPeriod", periodFromNow(period)); return (List<Map<String, String>>) query.list(); } @SuppressWarnings("unchecked") public List<Map<String, String>> retrieveAllDelayedBySigla(String sigla, BigDecimal media) { String sql = "SELECT INS.DS_INSTANCIA_PROCESSO AS DESCRICAO," + " ROUND(ISNULL(CAST(DATEDIFF(SECOND, INS.DT_INICIO, GETDATE()) AS FLOAT), 0) / (24 * 60 * 60), 2) AS DIAS" + " FROM TB_DEFINICAO_PROCESSO DEF" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " INNER JOIN TB_INSTANCIA_PROCESSO INS ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " WHERE INS.DT_FIM IS NULL AND DEF.SG_PROCESSO = :sigla" + " AND ROUND(ISNULL(CAST(DATEDIFF(SECOND, INS.DT_INICIO, GETDATE()) AS FLOAT), 0) / (24 * 60 * 60), 2) > :media"; Query query = getSession().createSQLQuery(sql) .addScalar("DESCRICAO", StringType.INSTANCE) .addScalar("DIAS", StringType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); query.setParameter("media", media); query.setParameter("sigla", sigla); query.setMaxResults(MAX_FEED_SIZE); return (List<Map<String, String>>) query.list(); } private Date periodFromNow(Period period) { Temporal temporal = period.addTo(LocalDateTime.now()); LocalDateTime localDateTime = LocalDateTime.from(temporal); return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); } public StatusDTO retrieveActiveInstanceStatus(String processCode) { String sql = "SELECT '" + processCode + "' AS processCode," + " COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO) AS amount," + " AVG(DATEDIFF(DAY, INS.DT_INICIO, GETDATE())) AS averageTimeInDays" + " FROM TB_INSTANCIA_PROCESSO INS" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " WHERE INS.DT_FIM IS NULL AND DEF.se_ativo = 1" + (processCode != null ? " AND DEF.SG_PROCESSO = :processCode" : ""); Query query = getSession().createSQLQuery(sql) .addScalar("processCode", StringType.INSTANCE) .addScalar("amount", IntegerType.INSTANCE) .addScalar("averageTimeInDays", IntegerType.INSTANCE); if (processCode != null) { query.setParameter("processCode", processCode); } query.setResultTransformer(Transformers.aliasToBean(StatusDTO.class)); StatusDTO status = (StatusDTO) query.uniqueResult(); status.setOpenedInstancesLast30Days(countOpenedInstancesLast30Days(processCode)); status.setFinishedInstancesLast30Days(countFinishedInstancesLast30Days(processCode)); return status; } public Integer countOpenedInstancesLast30Days(String processCode) { String sql = "SELECT COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO) AS QUANTIDADE" + " FROM TB_DEFINICAO_PROCESSO DEF" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN TB_INSTANCIA_PROCESSO INS ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " WHERE INS.DT_INICIO >= (GETDATE() - 30) AND DEF.se_ativo = 1" + (processCode != null ? " AND DEF.SG_PROCESSO = :processCode" : ""); Query query = getSession().createSQLQuery(sql) .addScalar("QUANTIDADE", LongType.INSTANCE); if (processCode != null) { query.setParameter("processCode", processCode); } return ((Number) query.uniqueResult()).intValue(); } public Integer countFinishedInstancesLast30Days(String processCode) { String sql = "SELECT COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO) AS QUANTIDADE" + " FROM TB_DEFINICAO_PROCESSO DEF" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN TB_INSTANCIA_PROCESSO INS ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " LEFT JOIN TB_VERSAO_TAREFA TAR ON PRO.CO_VERSAO_PROCESSO = TAR.CO_VERSAO_PROCESSO" + " WHERE INS.DT_FIM >= (GETDATE() - 30) AND DEF.se_ativo = 1" + (processCode != null ? " AND DEF.SG_PROCESSO = :processCode" : ""); Query query = getSession().createSQLQuery(sql) .addScalar("QUANTIDADE", LongType.INSTANCE); if (processCode != null) { query.setParameter("processCode", processCode); } return ((Number) query.uniqueResult()).intValue(); } private static final String ACTIVE_DATE_DIST_SQL = "SELECT %d AS POS, UPPER(SUBSTRING(DATENAME(MONTH, CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)), 0, 4))%n" + " + '/' + SUBSTRING(DATENAME(YEAR, CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)), 3, 4) AS MES,%n" + "%s%n" + "FROM TB_INSTANCIA_PROCESSO INS%n" + " LEFT JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO%n" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO%n" + "WHERE DT_INICIO < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)%n" + " AND (DT_FIM > CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) OR DT_FIM IS NULL)%s"; private static final String FINISHED_DATE_DIST_SQL = "SELECT %d AS POS, UPPER(SUBSTRING(DATENAME(MONTH, CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)), 0, 4))%n" + " + '/' + SUBSTRING(DATENAME(YEAR, CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)), 3, 4) AS MES,%n" + "%s%n" + "FROM TB_INSTANCIA_PROCESSO INS%n" + " LEFT JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO%n" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO%n" + "WHERE DT_FIM >= CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)%n" + " AND DT_FIM < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)%s"; private static final String PROCESS_CODE_FILTER_SQL = " AND SG_PROCESSO = :processCode"; private static final String SELECT_AVERAGE_TIME_SQL = " ROUND(ISNULL(AVG(CAST(DATEDIFF(SECOND, INS.DT_INICIO, (CASE WHEN ISNULL(INS.DT_FIM, GETDATE()) < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) THEN ISNULL(INS.DT_FIM, GETDATE()) ELSE CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) END)) AS FLOAT)), 0) / (24 * 60 * 60), 2) AS TEMPO"; private static final String SELECT_AVERAGE_2_TIME_SQL = " CAST(YEAR(CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)) AS VARCHAR) + '-' + RIGHT('00' + CAST(MONTH(CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)) AS VARCHAR(2)), 2) AS DATA,%n" + " ROUND(ISNULL(AVG(CAST(DATEDIFF(SECOND, INS.DT_INICIO, (CASE WHEN ISNULL(INS.DT_FIM, GETDATE()) < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) THEN ISNULL(INS.DT_FIM, GETDATE()) ELSE CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) END)) AS FLOAT)), 0) / (24 * 60 * 60), 2) AS TEMPO,%n" + " ROUND(ISNULL(AVG(CAST(DATEDIFF(SECOND, INS.DT_INICIO, (CASE WHEN ISNULL(INS.DT_FIM, GETDATE()) < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) THEN ISNULL(INS.DT_FIM, GETDATE()) ELSE CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) END)) AS FLOAT)), 0) / (24 * 60 * 60), 2) AS TEMPO2"; private static final String SELECT_COUNT_SQL = " COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO) AS QUANTIDADE"; private String mountDateDistSQL(boolean active, boolean processCodeFilter) { return mountDateDistSQL(active, false, processCodeFilter); } private String mountDateDistSQL(boolean active, boolean count, boolean processCodeFilter) { return mountDateDistSQL(active, count, false, processCodeFilter); } private String mountDateDistSQL(boolean active, boolean count, boolean move, boolean processCodeFilter) { List<String> sqls = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); for (int pos = 13; pos > 0; pos--) { int monthPlus1 = calendar.get(Calendar.MONTH) + 1; int yearPlus1 = calendar.get(Calendar.YEAR); calendar.add(Calendar.MONTH, -1); int month = calendar.get(Calendar.MONTH) + 1; int year = calendar.get(Calendar.YEAR); formatDateDistSQL(sqls, pos, month, year, monthPlus1, yearPlus1, active, count, move, processCodeFilter); } int pos = 13; StringBuilder result = new StringBuilder("SET LANGUAGE Portuguese;"); for (String sql : sqls) { result.append(String.format("%s%n%s%n", sql, pos-- == 1 ? "ORDER BY POS" : "UNION")); } return result.toString(); } private String formatDateDistMoveSQL(int month, int year, int yearPlus1, int monthPlus1) { int yearPlus3; int monthPlus3; int yearPlus6; int monthPlus6; Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, yearPlus1); calendar.set(Calendar.MONTH, monthPlus1 - 1); calendar.add(Calendar.MONTH, 2); yearPlus3 = calendar.get(Calendar.YEAR); monthPlus3 = calendar.get(Calendar.MONTH) + 1; calendar.add(Calendar.MONTH, 3); yearPlus6 = calendar.get(Calendar.YEAR); monthPlus6 = calendar.get(Calendar.MONTH) + 1; return String.format(SELECT_AVERAGE_2_TIME_SQL, year, month, year, month, yearPlus3, monthPlus3, yearPlus3, monthPlus3, yearPlus6, monthPlus6, yearPlus6, monthPlus6); } private void formatDateDistSQL(List<String> sqls, int pos, int month, int year, int monthPlus1, int yearPlus1, boolean active, boolean count, boolean move, boolean processCodeFilter) { if (active) { if (count) { sqls.add(String.format(ACTIVE_DATE_DIST_SQL, pos, year, month, year, month, SELECT_COUNT_SQL, yearPlus1, monthPlus1, yearPlus1, monthPlus1, (processCodeFilter ? PROCESS_CODE_FILTER_SQL : ""))); } else { sqls.add(String.format(ACTIVE_DATE_DIST_SQL, pos, year, month, year, month, (move ? formatDateDistMoveSQL(month, year, yearPlus1, monthPlus1) : String.format(SELECT_AVERAGE_TIME_SQL, yearPlus1, monthPlus1, yearPlus1, monthPlus1) ), yearPlus1, monthPlus1, yearPlus1, monthPlus1, (processCodeFilter ? PROCESS_CODE_FILTER_SQL : ""))); } } else { if (count) { sqls.add(String.format(FINISHED_DATE_DIST_SQL, pos, year, month, year, month, SELECT_COUNT_SQL, year, month, yearPlus1, monthPlus1, (processCodeFilter ? PROCESS_CODE_FILTER_SQL : ""))); } else { sqls.add(String.format(FINISHED_DATE_DIST_SQL, pos, year, month, year, month, String.format(SELECT_AVERAGE_TIME_SQL, yearPlus1, monthPlus1, yearPlus1, monthPlus1), year, month, yearPlus1, monthPlus1, (processCodeFilter ? PROCESS_CODE_FILTER_SQL : ""))); } } } private List<Map<String, String>> retrieveMeanTimeInstances(String sql, String processCode, boolean count, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(sql, processCode, count, false, processCodeWithAccess); } @SuppressWarnings("unchecked") private List<Map<String, String>> retrieveMeanTimeInstances(String sql, String processCode, boolean count, boolean move, Set<String> processCodeWithAccess) { Query query = getSession().createSQLQuery(sql) .addScalar("POS", IntegerType.INSTANCE) .addScalar("MES", StringType.INSTANCE) .addScalar(count ? "QUANTIDADE" : "TEMPO", count ? IntegerType.INSTANCE : FloatType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); if (move) { ((SQLQuery) query).addScalar("DATA", StringType.INSTANCE).addScalar("TEMPO2", FloatType.INSTANCE); } if (processCode != null) { query.setParameter("processCode", processCode); } return (List<Map<String, String>>) query.list(); } public List<Map<String, String>> retrieveMeanTimeActiveInstances(String processCode, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(mountDateDistSQL(true, processCode != null), processCode, false, processCodeWithAccess); } public List<Map<String, String>> retrieveAverageTimesActiveInstances(String processCode, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(mountDateDistSQL(true, false, true, true), processCode, false, true, processCodeWithAccess); } public List<Map<String, String>> retrieveMeanTimeFinishedInstances(String processCode, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(mountDateDistSQL(false, processCode != null), processCode, false, processCodeWithAccess); } public List<Map<String, String>> retrieveCounterActiveInstances(String processCode, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(mountDateDistSQL(true, true, processCode != null), processCode, true, processCodeWithAccess); } }
flow/ui-admin/src/main/java/br/net/mirante/singular/dao/InstanceDAO.java
package br.net.mirante.singular.dao; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.Period; import java.time.ZoneId; import java.time.temporal.Temporal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.transform.Transformers; import org.hibernate.type.FloatType; import org.hibernate.type.IntegerType; import org.hibernate.type.LongType; import org.hibernate.type.StringType; import org.hibernate.type.TimestampType; import org.springframework.stereotype.Repository; import br.net.mirante.singular.dto.StatusDTO; import br.net.mirante.singular.flow.core.TaskType; @Repository public class InstanceDAO extends BaseDAO{ public static final int MAX_FEED_SIZE = 30; private enum Columns { description("DESCRICAO"), delta("DELTA"), date("DIN"), deltas("DELTAS"), dates("DS"), user("USUARIO"); private String code; Columns(String code) { this.code = code; } @Override public String toString() { return code; } } @SuppressWarnings("unchecked") public List<Object[]> retrieveAll(int first, int size, String orderByProperty, boolean asc, Long id) { StringBuilder orderByStatement = new StringBuilder(""); if (orderByProperty != null) { orderByStatement.append("ORDER BY ").append(Columns.valueOf(orderByProperty)).append(" "); orderByStatement.append(asc ? "ASC" : "DESC"); } String sql = "SELECT DISTINCT INS.CO_INSTANCIA_PROCESSO AS CODIGO, INS.DS_INSTANCIA_PROCESSO AS DESCRICAO," + " DATEDIFF(SECOND, DT_INICIO, GETDATE()) AS DELTA, DT_INICIO AS DIN," + " DATEDIFF(SECOND, data_situacao_atual, GETDATE()) AS DELTAS, data_situacao_atual AS DS," + " PES.nome_guerra AS USUARIO" + " FROM TB_INSTANCIA_PROCESSO INS" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN CAD_PESSOA PES ON PES.cod_pessoa = INS.cod_pessoa_alocada" + " WHERE INS.DT_FIM IS NULL AND PRO.CO_DEFINICAO_PROCESSO = :id " + orderByStatement.toString(); Query query = getSession().createSQLQuery(sql) .addScalar("CODIGO", LongType.INSTANCE) .addScalar("DESCRICAO", StringType.INSTANCE) .addScalar("DELTA", LongType.INSTANCE) .addScalar("DIN", TimestampType.INSTANCE) .addScalar("DELTAS", LongType.INSTANCE) .addScalar("DS", TimestampType.INSTANCE) .addScalar("USUARIO", LongType.INSTANCE) .setParameter("id", id); query.setFirstResult(first); query.setMaxResults(size); return (List<Object[]>) query.list(); } public int countAll(Long id) { return ((Number) getSession().createSQLQuery( "SELECT COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO)" + " FROM TB_INSTANCIA_PROCESSO INS" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN TB_DEFINICAO_TAREFA DFT ON DFT.CO_DEFINICAO_PROCESSO = DEF.CO_DEFINICAO_PROCESSO" + " WHERE INS.DT_FIM IS NULL AND PRO.CO_DEFINICAO_PROCESSO = :id") .setParameter("id", id) .uniqueResult()).intValue(); } public List<Map<String, String>> retrieveTransactionQuantityLastYear(String processCode, Set<String> processCodeWithAccess) { List<Map<String, String>> newTransactions = retrieveNewQuantityLastYear(processCode, processCodeWithAccess); List<Map<String, String>> finishedTransations = retrieveFinishedQuantityLastYear(processCode, processCodeWithAccess); List<Map<String, String>> transactions = newTransactions.stream().collect(Collectors.toList()); for (Map<String, String> map : finishedTransations) { Map<String, String> m = retrieveResultMap(map, transactions); if (m == null) { transactions.add(map); } else { m.put("QTD_CLS", map.get("QTD_CLS")); } } return transactions; } private Map<String, String> retrieveResultMap(Map<String, String> map, List<Map<String, String>> list) { for (Map<String, String> m : list) { if (m.get("POS").equals(map.get("POS"))) { return m; } } return null; } @SuppressWarnings("unchecked") private List<Map<String, String>> retrieveNewQuantityLastYear(String processCode, Set<String> processCodeWithAccess) { String sql = "SET LANGUAGE Portuguese;" + "SELECT RIGHT('00' + CAST(MONTH(DT_INICIO) AS VARCHAR(2)), 2) + SUBSTRING(DATENAME(YEAR, DT_INICIO), 3, 4) AS POS," + " UPPER(SUBSTRING(DATENAME(MONTH, DT_INICIO), 0, 4)) + '/' + SUBSTRING(DATENAME(YEAR, DT_INICIO), 3, 4) AS MES," + " COUNT(CO_INSTANCIA_PROCESSO) AS QTD_NEW" + " FROM TB_INSTANCIA_PROCESSO INS" + " LEFT JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " WHERE DT_INICIO >= CAST(FLOOR(CAST(GETDATE() - 364 - DAY(GETDATE()) AS FLOAT)) AS DATETIME)" + " AND SG_PROCESSO in(:processCodeWithAccess)" + (processCode != null ? " AND SG_PROCESSO = :processCode" : "") + " GROUP BY MONTH(DT_INICIO), YEAR(DT_INICIO), DATENAME(MONTH, DT_INICIO), DATENAME(YEAR, DT_INICIO)" + " ORDER BY YEAR(DT_INICIO), MONTH(DT_INICIO)"; Query query = getSession().createSQLQuery(sql) .addScalar("POS", StringType.INSTANCE) .addScalar("MES", StringType.INSTANCE) .addScalar("QTD_NEW", StringType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); if (processCode != null) { query.setParameter("processCode", processCode); } query.setParameterList("processCodeWithAccess", processCodeWithAccess); return (List<Map<String, String>>) query.list(); } @SuppressWarnings("unchecked") private List<Map<String, String>> retrieveFinishedQuantityLastYear(String processCode, Set<String> processCodeWithAccess) { String sql = "SET LANGUAGE Portuguese;" + "SELECT RIGHT('00' + CAST(MONTH(DT_FIM) AS VARCHAR(2)), 2) + SUBSTRING(DATENAME(YEAR, DT_FIM), 3, 4) AS POS," + " UPPER(SUBSTRING(DATENAME(MONTH, DT_FIM), 0, 4)) + '/' + SUBSTRING(DATENAME(YEAR, DT_FIM), 3, 4) AS MES," + " COUNT(CO_INSTANCIA_PROCESSO) AS QTD_CLS" + " FROM TB_INSTANCIA_PROCESSO INS" + " LEFT JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " WHERE DT_FIM >= CAST(FLOOR(CAST(GETDATE() - 364 - DAY(GETDATE()) AS FLOAT)) AS DATETIME)" + " AND SG_PROCESSO in(:processCodeWithAccess)" + (processCode != null ? " AND SG_PROCESSO = :processCode" : "") + " GROUP BY MONTH(DT_FIM), YEAR(DT_FIM), DATENAME(MONTH, DT_FIM), DATENAME(YEAR, DT_FIM)" + " ORDER BY YEAR(DT_FIM), MONTH(DT_FIM)"; Query query = getSession().createSQLQuery(sql) .addScalar("POS", StringType.INSTANCE) .addScalar("MES", StringType.INSTANCE) .addScalar("QTD_CLS", StringType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); if (processCode != null) { query.setParameter("processCode", processCode); } query.setParameterList("processCodeWithAccess", processCodeWithAccess); return (List<Map<String, String>>) query.list(); } @SuppressWarnings("unchecked") public List<Map<String, String>> retrieveEndStatusQuantityByPeriod(Period period, String processCod) { String sql = "SELECT SIT.NO_TAREFA AS SITUACAO, COUNT(DEM.CO_INSTANCIA_PROCESSO) AS QUANTIDADE" + " FROM TB_INSTANCIA_PROCESSO DEM" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = DEM.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN TB_VERSAO_TAREFA SIT ON SIT.CO_VERSAO_TAREFA = DEM.cod_situacao" + " WHERE DEM.data_situacao_atual >= :startPeriod AND DEF.SG_PROCESSO = :processCod" + " AND DEF.SG_PROCESSO = in(:processCodeWithAccess)" + " AND SIT.CO_TIPO_TAREFA = " + TaskType.End.ordinal() + " GROUP BY SIT.NO_TAREFA"; Query query = getSession().createSQLQuery(sql) .addScalar("SITUACAO", StringType.INSTANCE) .addScalar("QUANTIDADE", LongType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); query.setParameter("processCod", processCod); query.setParameter("startPeriod", periodFromNow(period)); return (List<Map<String, String>>) query.list(); } @SuppressWarnings("unchecked") public List<Map<String, String>> retrieveAllDelayedBySigla(String sigla, BigDecimal media) { String sql = "SELECT INS.DS_INSTANCIA_PROCESSO AS DESCRICAO," + " ROUND(ISNULL(CAST(DATEDIFF(SECOND, INS.DT_INICIO, GETDATE()) AS FLOAT), 0) / (24 * 60 * 60), 2) AS DIAS" + " FROM TB_DEFINICAO_PROCESSO DEF" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " INNER JOIN TB_INSTANCIA_PROCESSO INS ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " WHERE INS.DT_FIM IS NULL AND DEF.SG_PROCESSO = :sigla" + " AND ROUND(ISNULL(CAST(DATEDIFF(SECOND, INS.DT_INICIO, GETDATE()) AS FLOAT), 0) / (24 * 60 * 60), 2) > :media"; Query query = getSession().createSQLQuery(sql) .addScalar("DESCRICAO", StringType.INSTANCE) .addScalar("DIAS", StringType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); query.setParameter("media", media); query.setParameter("sigla", sigla); query.setMaxResults(MAX_FEED_SIZE); return (List<Map<String, String>>) query.list(); } private Date periodFromNow(Period period) { Temporal temporal = period.addTo(LocalDateTime.now()); LocalDateTime localDateTime = LocalDateTime.from(temporal); return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); } public StatusDTO retrieveActiveInstanceStatus(String processCode) { String sql = "SELECT '" + processCode + "' AS processCode," + " COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO) AS amount," + " AVG(DATEDIFF(DAY, INS.DT_INICIO, GETDATE())) AS averageTimeInDays" + " FROM TB_INSTANCIA_PROCESSO INS" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " WHERE INS.DT_FIM IS NULL AND DEF.se_ativo = 1" + (processCode != null ? " AND DEF.SG_PROCESSO = :processCode" : ""); Query query = getSession().createSQLQuery(sql) .addScalar("processCode", StringType.INSTANCE) .addScalar("amount", IntegerType.INSTANCE) .addScalar("averageTimeInDays", IntegerType.INSTANCE); if (processCode != null) { query.setParameter("processCode", processCode); } query.setResultTransformer(Transformers.aliasToBean(StatusDTO.class)); StatusDTO status = (StatusDTO) query.uniqueResult(); status.setOpenedInstancesLast30Days(countOpenedInstancesLast30Days(processCode)); status.setFinishedInstancesLast30Days(countFinishedInstancesLast30Days(processCode)); return status; } public Integer countOpenedInstancesLast30Days(String processCode) { String sql = "SELECT COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO) AS QUANTIDADE" + " FROM TB_DEFINICAO_PROCESSO DEF" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN TB_INSTANCIA_PROCESSO INS ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " WHERE INS.DT_INICIO >= (GETDATE() - 30) AND DEF.se_ativo = 1" + (processCode != null ? " AND DEF.SG_PROCESSO = :processCode" : ""); Query query = getSession().createSQLQuery(sql) .addScalar("QUANTIDADE", LongType.INSTANCE); if (processCode != null) { query.setParameter("processCode", processCode); } return ((Number) query.uniqueResult()).intValue(); } public Integer countFinishedInstancesLast30Days(String processCode) { String sql = "SELECT COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO) AS QUANTIDADE" + " FROM TB_DEFINICAO_PROCESSO DEF" + " INNER JOIN TB_VERSAO_PROCESSO PRO ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" + " LEFT JOIN TB_INSTANCIA_PROCESSO INS ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO" + " LEFT JOIN TB_VERSAO_TAREFA TAR ON PRO.CO_VERSAO_PROCESSO = TAR.CO_VERSAO_PROCESSO" + " WHERE INS.DT_FIM >= (GETDATE() - 30) AND DEF.se_ativo = 1" + (processCode != null ? " AND DEF.SG_PROCESSO = :processCode" : ""); Query query = getSession().createSQLQuery(sql) .addScalar("QUANTIDADE", LongType.INSTANCE); if (processCode != null) { query.setParameter("processCode", processCode); } return ((Number) query.uniqueResult()).intValue(); } private static final String ACTIVE_DATE_DIST_SQL = "SELECT %d AS POS, UPPER(SUBSTRING(DATENAME(MONTH, CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)), 0, 4))%n" + " + '/' + SUBSTRING(DATENAME(YEAR, CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)), 3, 4) AS MES,%n" + "%s%n" + "FROM TB_INSTANCIA_PROCESSO INS%n" + " LEFT JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO%n" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO%n" + "WHERE DT_INICIO < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)%n" + " AND (DT_FIM > CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) OR DT_FIM IS NULL)%s"; private static final String FINISHED_DATE_DIST_SQL = "SELECT %d AS POS, UPPER(SUBSTRING(DATENAME(MONTH, CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)), 0, 4))%n" + " + '/' + SUBSTRING(DATENAME(YEAR, CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)), 3, 4) AS MES,%n" + "%s%n" + "FROM TB_INSTANCIA_PROCESSO INS%n" + " LEFT JOIN TB_VERSAO_PROCESSO PRO ON PRO.CO_VERSAO_PROCESSO = INS.CO_VERSAO_PROCESSO%n" + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO%n" + "WHERE DT_FIM >= CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)%n" + " AND DT_FIM < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)%s"; private static final String PROCESS_CODE_FILTER_SQL = " AND SG_PROCESSO = :processCode"; private static final String SELECT_AVERAGE_TIME_SQL = " ROUND(ISNULL(AVG(CAST(DATEDIFF(SECOND, INS.DT_INICIO, (CASE WHEN ISNULL(INS.DT_FIM, GETDATE()) < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) THEN ISNULL(INS.DT_FIM, GETDATE()) ELSE CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) END)) AS FLOAT)), 0) / (24 * 60 * 60), 2) AS TEMPO"; private static final String SELECT_AVERAGE_2_TIME_SQL = " CAST(YEAR(CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)) AS VARCHAR) + '-' + RIGHT('00' + CAST(MONTH(CAST('%04d-%02d-01T00:00:00.000' AS DATETIME)) AS VARCHAR(2)), 2) AS DATA,%n" + " ROUND(ISNULL(AVG(CAST(DATEDIFF(SECOND, INS.DT_INICIO, (CASE WHEN ISNULL(INS.DT_FIM, GETDATE()) < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) THEN ISNULL(INS.DT_FIM, GETDATE()) ELSE CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) END)) AS FLOAT)), 0) / (24 * 60 * 60), 2) AS TEMPO,%n" + " ROUND(ISNULL(AVG(CAST(DATEDIFF(SECOND, INS.DT_INICIO, (CASE WHEN ISNULL(INS.DT_FIM, GETDATE()) < CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) THEN ISNULL(INS.DT_FIM, GETDATE()) ELSE CAST('%04d-%02d-01T00:00:00.000' AS DATETIME) END)) AS FLOAT)), 0) / (24 * 60 * 60), 2) AS TEMPO2"; private static final String SELECT_COUNT_SQL = " COUNT(DISTINCT INS.CO_INSTANCIA_PROCESSO) AS QUANTIDADE"; private String mountDateDistSQL(boolean active, boolean processCodeFilter) { return mountDateDistSQL(active, false, processCodeFilter); } private String mountDateDistSQL(boolean active, boolean count, boolean processCodeFilter) { return mountDateDistSQL(active, count, false, processCodeFilter); } private String mountDateDistSQL(boolean active, boolean count, boolean move, boolean processCodeFilter) { List<String> sqls = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); for (int pos = 13; pos > 0; pos--) { int monthPlus1 = calendar.get(Calendar.MONTH) + 1; int yearPlus1 = calendar.get(Calendar.YEAR); calendar.add(Calendar.MONTH, -1); int month = calendar.get(Calendar.MONTH) + 1; int year = calendar.get(Calendar.YEAR); formatDateDistSQL(sqls, pos, month, year, monthPlus1, yearPlus1, active, count, move, processCodeFilter); } int pos = 13; StringBuilder result = new StringBuilder("SET LANGUAGE Portuguese;"); for (String sql : sqls) { result.append(String.format("%s%n%s%n", sql, pos-- == 1 ? "ORDER BY POS" : "UNION")); } return result.toString(); } private String formatDateDistMoveSQL(int month, int year, int yearPlus1, int monthPlus1) { int yearPlus3; int monthPlus3; int yearPlus6; int monthPlus6; Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, yearPlus1); calendar.set(Calendar.MONTH, monthPlus1 - 1); calendar.add(Calendar.MONTH, 2); yearPlus3 = calendar.get(Calendar.YEAR); monthPlus3 = calendar.get(Calendar.MONTH) + 1; calendar.add(Calendar.MONTH, 3); yearPlus6 = calendar.get(Calendar.YEAR); monthPlus6 = calendar.get(Calendar.MONTH) + 1; return String.format(SELECT_AVERAGE_2_TIME_SQL, year, month, year, month, yearPlus3, monthPlus3, yearPlus3, monthPlus3, yearPlus6, monthPlus6, yearPlus6, monthPlus6); } private void formatDateDistSQL(List<String> sqls, int pos, int month, int year, int monthPlus1, int yearPlus1, boolean active, boolean count, boolean move, boolean processCodeFilter) { if (active) { if (count) { sqls.add(String.format(ACTIVE_DATE_DIST_SQL, pos, year, month, year, month, SELECT_COUNT_SQL, yearPlus1, monthPlus1, yearPlus1, monthPlus1, (processCodeFilter ? PROCESS_CODE_FILTER_SQL : ""))); } else { sqls.add(String.format(ACTIVE_DATE_DIST_SQL, pos, year, month, year, month, (move ? formatDateDistMoveSQL(month, year, yearPlus1, monthPlus1) : String.format(SELECT_AVERAGE_TIME_SQL, yearPlus1, monthPlus1, yearPlus1, monthPlus1) ), yearPlus1, monthPlus1, yearPlus1, monthPlus1, (processCodeFilter ? PROCESS_CODE_FILTER_SQL : ""))); } } else { if (count) { sqls.add(String.format(FINISHED_DATE_DIST_SQL, pos, year, month, year, month, SELECT_COUNT_SQL, year, month, yearPlus1, monthPlus1, (processCodeFilter ? PROCESS_CODE_FILTER_SQL : ""))); } else { sqls.add(String.format(FINISHED_DATE_DIST_SQL, pos, year, month, year, month, String.format(SELECT_AVERAGE_TIME_SQL, yearPlus1, monthPlus1, yearPlus1, monthPlus1), year, month, yearPlus1, monthPlus1, (processCodeFilter ? PROCESS_CODE_FILTER_SQL : ""))); } } } private List<Map<String, String>> retrieveMeanTimeInstances(String sql, String processCode, boolean count, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(sql, processCode, count, false, processCodeWithAccess); } @SuppressWarnings("unchecked") private List<Map<String, String>> retrieveMeanTimeInstances(String sql, String processCode, boolean count, boolean move, Set<String> processCodeWithAccess) { Query query = getSession().createSQLQuery(sql) .addScalar("POS", IntegerType.INSTANCE) .addScalar("MES", StringType.INSTANCE) .addScalar(count ? "QUANTIDADE" : "TEMPO", count ? IntegerType.INSTANCE : FloatType.INSTANCE) .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); if (move) { ((SQLQuery) query).addScalar("DATA", StringType.INSTANCE).addScalar("TEMPO2", FloatType.INSTANCE); } if (processCode != null) { query.setParameter("processCode", processCode); } return (List<Map<String, String>>) query.list(); } public List<Map<String, String>> retrieveMeanTimeActiveInstances(String processCode, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(mountDateDistSQL(true, processCode != null), processCode, false, processCodeWithAccess); } public List<Map<String, String>> retrieveAverageTimesActiveInstances(String processCode, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(mountDateDistSQL(true, false, true, true), processCode, false, true, processCodeWithAccess); } public List<Map<String, String>> retrieveMeanTimeFinishedInstances(String processCode, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(mountDateDistSQL(false, processCode != null), processCode, false, processCodeWithAccess); } public List<Map<String, String>> retrieveCounterActiveInstances(String processCode, Set<String> processCodeWithAccess) { return retrieveMeanTimeInstances(mountDateDistSQL(true, true, processCode != null), processCode, true, processCodeWithAccess); } }
correções
flow/ui-admin/src/main/java/br/net/mirante/singular/dao/InstanceDAO.java
correções
<ide><path>low/ui-admin/src/main/java/br/net/mirante/singular/dao/InstanceDAO.java <ide> + " INNER JOIN TB_DEFINICAO_PROCESSO DEF ON DEF.CO_DEFINICAO_PROCESSO = PRO.CO_DEFINICAO_PROCESSO" <ide> + " LEFT JOIN TB_VERSAO_TAREFA SIT ON SIT.CO_VERSAO_TAREFA = DEM.cod_situacao" <ide> + " WHERE DEM.data_situacao_atual >= :startPeriod AND DEF.SG_PROCESSO = :processCod" <del> + " AND DEF.SG_PROCESSO = in(:processCodeWithAccess)" <ide> + " AND SIT.CO_TIPO_TAREFA = " + TaskType.End.ordinal() <ide> + " GROUP BY SIT.NO_TAREFA"; <ide> Query query = getSession().createSQLQuery(sql)
Java
apache-2.0
66973006861b232c37c7f1da713b564f792e78ee
0
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
// Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.notedb.rebuild; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.gerrit.reviewdb.server.ReviewDbUtil.unwrapDb; import static com.google.gerrit.server.notedb.NotesMigration.SECTION_NOTE_DB; import static com.google.gerrit.server.notedb.NotesMigrationState.NOTE_DB; import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_NO_SEQUENCE; import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY; import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY; import static com.google.gerrit.server.notedb.NotesMigrationState.WRITE; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Comparator.comparing; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.MultimapBuilder; import com.google.common.collect.Ordering; import com.google.common.collect.SetMultimap; import com.google.common.collect.Streams; import com.google.common.flogger.FluentLogger; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.gerrit.common.FormatUtil; import com.google.gerrit.common.Nullable; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.reviewdb.server.ReviewDbWrapper; import com.google.gerrit.server.GerritPersonIdent; import com.google.gerrit.server.InternalUser; import com.google.gerrit.server.Sequences; import com.google.gerrit.server.config.AllProjectsName; import com.google.gerrit.server.config.AllUsersName; import com.google.gerrit.server.config.GerritServerConfigProvider; import com.google.gerrit.server.config.SitePaths; import com.google.gerrit.server.extensions.events.GitReferenceUpdated; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.git.LockFailureException; import com.google.gerrit.server.git.WorkQueue; import com.google.gerrit.server.notedb.ChangeBundleReader; import com.google.gerrit.server.notedb.ChangeNotes; import com.google.gerrit.server.notedb.MutableNotesMigration; import com.google.gerrit.server.notedb.NoteDbTable; import com.google.gerrit.server.notedb.NoteDbUpdateManager; import com.google.gerrit.server.notedb.NotesMigrationState; import com.google.gerrit.server.notedb.PrimaryStorageMigrator; import com.google.gerrit.server.notedb.PrimaryStorageMigrator.NoNoteDbStateException; import com.google.gerrit.server.notedb.RepoSequence; import com.google.gerrit.server.notedb.rebuild.ChangeRebuilder.NoPatchSetsException; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.update.ChainedReceiveCommands; import com.google.gerrit.server.update.RefUpdateUtil; import com.google.gerrit.server.util.ManualRequestContext; import com.google.gerrit.server.util.ThreadLocalRequestContext; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.SchemaFactory; import com.google.inject.Inject; import com.google.inject.Provider; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Predicate; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.internal.storage.file.PackInserter; import org.eclipse.jgit.lib.BatchRefUpdate; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.ProgressMonitor; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.TextProgressMonitor; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.transport.ReceiveCommand; import org.eclipse.jgit.util.FS; /** One stop shop for migrating a site's change storage from ReviewDb to NoteDb. */ public class NoteDbMigrator implements AutoCloseable { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String AUTO_MIGRATE = "autoMigrate"; private static final String TRIAL = "trial"; public static boolean getAutoMigrate(Config cfg) { return cfg.getBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), AUTO_MIGRATE, false); } private static void setAutoMigrate(Config cfg, boolean autoMigrate) { cfg.setBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), AUTO_MIGRATE, autoMigrate); } public static boolean getTrialMode(Config cfg) { return cfg.getBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), TRIAL, false); } public static void setTrialMode(Config cfg, boolean trial) { cfg.setBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), TRIAL, trial); } private static class NoteDbMigrationLoggerOut extends OutputStream { private StringBuilder outputBuffer = new StringBuilder(); @Override public synchronized void write(int b) throws IOException { if (b == '\r' || b == '\n') { logger.atInfo().log(outputBuffer.toString()); outputBuffer = new StringBuilder(); } else { outputBuffer.append(Character.toChars(b)); } } } public static class Builder { private final Config cfg; private final SitePaths sitePaths; private final Provider<PersonIdent> serverIdent; private final AllUsersName allUsers; private final SchemaFactory<ReviewDb> schemaFactory; private final GitRepositoryManager repoManager; private final NoteDbUpdateManager.Factory updateManagerFactory; private final ChangeBundleReader bundleReader; private final AllProjectsName allProjects; private final InternalUser.Factory userFactory; private final ThreadLocalRequestContext requestContext; private final ChangeRebuilderImpl rebuilder; private final WorkQueue workQueue; private final MutableNotesMigration globalNotesMigration; private final PrimaryStorageMigrator primaryStorageMigrator; private final DynamicSet<NotesMigrationStateListener> listeners; private final ProjectCache projectCache; private int threads; private ImmutableList<Project.NameKey> projects = ImmutableList.of(); private ImmutableList<Project.NameKey> skipProjects = ImmutableList.of(); private ImmutableList<Change.Id> changes = ImmutableList.of(); private OutputStream progressOut = new NoteDbMigrationLoggerOut(); private NotesMigrationState stopAtState; private boolean trial; private boolean forceRebuild; private int sequenceGap = -1; private boolean autoMigrate; @Inject Builder( GerritServerConfigProvider configProvider, SitePaths sitePaths, @GerritPersonIdent Provider<PersonIdent> serverIdent, AllUsersName allUsers, SchemaFactory<ReviewDb> schemaFactory, GitRepositoryManager repoManager, NoteDbUpdateManager.Factory updateManagerFactory, ChangeBundleReader bundleReader, AllProjectsName allProjects, ThreadLocalRequestContext requestContext, InternalUser.Factory userFactory, ChangeRebuilderImpl rebuilder, WorkQueue workQueue, MutableNotesMigration globalNotesMigration, PrimaryStorageMigrator primaryStorageMigrator, DynamicSet<NotesMigrationStateListener> listeners, ProjectCache projectCache) { // Reload gerrit.config/notedb.config on each migrator invocation, in case a previous // migration in the same process modified the on-disk contents. This ensures the defaults for // trial/autoMigrate get set correctly below. this.cfg = configProvider.loadConfig(); this.sitePaths = sitePaths; this.serverIdent = serverIdent; this.allUsers = allUsers; this.schemaFactory = schemaFactory; this.repoManager = repoManager; this.updateManagerFactory = updateManagerFactory; this.bundleReader = bundleReader; this.allProjects = allProjects; this.requestContext = requestContext; this.userFactory = userFactory; this.rebuilder = rebuilder; this.workQueue = workQueue; this.globalNotesMigration = globalNotesMigration; this.primaryStorageMigrator = primaryStorageMigrator; this.listeners = listeners; this.projectCache = projectCache; this.trial = getTrialMode(cfg); this.autoMigrate = getAutoMigrate(cfg); } /** * Set the number of threads used by parallelizable phases of the migration, such as rebuilding * all changes. * * <p>Not all phases are parallelizable, and calling {@link #rebuild()} directly will do * substantial work in the calling thread regardless of the number of threads configured. * * <p>By default, all work is done in the calling thread. * * @param threads thread count; if less than 2, all work happens in the calling thread. * @return this. */ public Builder setThreads(int threads) { this.threads = threads; return this; } /** * Limit the set of projects that are processed. * * <p>Incompatible with {@link #setChanges(Collection)}. * * <p>By default, all projects will be processed. * * @param projects set of projects; if null or empty, all projects will be processed. * @return this. */ public Builder setProjects(@Nullable Collection<Project.NameKey> projects) { this.projects = projects != null ? ImmutableList.copyOf(projects) : ImmutableList.of(); return this; } /** * Process all projects except these * * <p>Incompatible with {@link #setProjects(Collection)} and {@link #setChanges(Collection)} * * <p>By default, all projects will be processed. * * @param skipProjects set of projects; if null or empty all project will be processed * @return this. */ public Builder setSkipProjects(@Nullable Collection<Project.NameKey> skipProjects) { this.skipProjects = skipProjects != null ? ImmutableList.copyOf(skipProjects) : ImmutableList.of(); return this; } /** * Limit the set of changes that are processed. * * <p>Incompatible with {@link #setProjects(Collection)}. * * <p>By default, all changes will be processed. * * @param changes set of changes; if null or empty, all changes will be processed. * @return this. */ public Builder setChanges(@Nullable Collection<Change.Id> changes) { this.changes = changes != null ? ImmutableList.copyOf(changes) : ImmutableList.of(); return this; } /** * Set output stream for progress monitors. * * <p>By default, there is no progress monitor output (although there may be other logs). * * @param progressOut output stream. * @return this. */ public Builder setProgressOut(OutputStream progressOut) { this.progressOut = requireNonNull(progressOut); return this; } /** * Stop at a specific migration state, for testing only. * * @param stopAtState state to stop at. * @return this. */ @VisibleForTesting public Builder setStopAtStateForTesting(NotesMigrationState stopAtState) { this.stopAtState = stopAtState; return this; } /** * Rebuild in "trial mode": configure Gerrit to write to and read from NoteDb, but leave * ReviewDb as the source of truth for all changes. * * <p>By default, trial mode is off, and NoteDb is the source of truth for all changes following * the migration. * * @param trial whether to rebuild in trial mode. * @return this. */ public Builder setTrialMode(boolean trial) { this.trial = trial; return this; } /** * Rebuild all changes in NoteDb from ReviewDb, even if Gerrit is currently configured to read * from NoteDb. * * <p>Only supported if ReviewDb is still the source of truth for all changes. * * <p>By default, force rebuilding is off. * * @param forceRebuild whether to force rebuilding. * @return this. */ public Builder setForceRebuild(boolean forceRebuild) { this.forceRebuild = forceRebuild; return this; } /** * Gap between ReviewDb change sequence numbers and NoteDb. * * <p>If NoteDb sequences are enabled in a running server, there is a race between the migration * step that calls {@code nextChangeId()} to seed the ref, and other threads that call {@code * nextChangeId()} to create new changes. In order to prevent these operations stepping on one * another, we use this value to skip some predefined sequence numbers. This is strongly * recommended in a running server. * * <p>If the migration takes place offline, there is no race with other threads, and this option * may be set to 0. However, admins may still choose to use a gap, for example to make it easier * to distinguish changes that were created before and after the NoteDb migration. * * <p>By default, uses the value from {@code noteDb.changes.initialSequenceGap} in {@code * gerrit.config}, which defaults to 1000. * * @param sequenceGap sequence gap size; if negative, use the default. * @return this. */ public Builder setSequenceGap(int sequenceGap) { this.sequenceGap = sequenceGap; return this; } /** * Enable auto-migration on subsequent daemon launches. * * <p>If true, prior to running any migration steps, sets the necessary configuration in {@code * gerrit.config} to make {@code gerrit.war daemon} retry the migration on next startup, if it * fails. * * @param autoMigrate whether to set auto-migration config. * @return this. */ public Builder setAutoMigrate(boolean autoMigrate) { this.autoMigrate = autoMigrate; return this; } public NoteDbMigrator build() throws MigrationException { return new NoteDbMigrator( sitePaths, schemaFactory, serverIdent, allUsers, repoManager, updateManagerFactory, bundleReader, allProjects, requestContext, userFactory, rebuilder, globalNotesMigration, primaryStorageMigrator, listeners, threads > 1 ? MoreExecutors.listeningDecorator( workQueue.createQueue(threads, "RebuildChange", true)) : MoreExecutors.newDirectExecutorService(), projects, skipProjects, changes, progressOut, stopAtState, projectCache, trial, forceRebuild, sequenceGap >= 0 ? sequenceGap : Sequences.getChangeSequenceGap(cfg), autoMigrate); } } private final FileBasedConfig gerritConfig; private final FileBasedConfig noteDbConfig; private final SchemaFactory<ReviewDb> schemaFactory; private final Provider<PersonIdent> serverIdent; private final AllUsersName allUsers; private final GitRepositoryManager repoManager; private final NoteDbUpdateManager.Factory updateManagerFactory; private final ChangeBundleReader bundleReader; private final AllProjectsName allProjects; private final ThreadLocalRequestContext requestContext; private final InternalUser.Factory userFactory; private final ChangeRebuilderImpl rebuilder; private final MutableNotesMigration globalNotesMigration; private final PrimaryStorageMigrator primaryStorageMigrator; private final DynamicSet<NotesMigrationStateListener> listeners; private final ListeningExecutorService executor; private final ImmutableList<Project.NameKey> projects; private final ImmutableList<Project.NameKey> skipProjects; private final ImmutableList<Change.Id> changes; private final OutputStream progressOut; private final NotesMigrationState stopAtState; private final ProjectCache projectCache; private final boolean trial; private final boolean forceRebuild; private final int sequenceGap; private final boolean autoMigrate; private NoteDbMigrator( SitePaths sitePaths, SchemaFactory<ReviewDb> schemaFactory, Provider<PersonIdent> serverIdent, AllUsersName allUsers, GitRepositoryManager repoManager, NoteDbUpdateManager.Factory updateManagerFactory, ChangeBundleReader bundleReader, AllProjectsName allProjects, ThreadLocalRequestContext requestContext, InternalUser.Factory userFactory, ChangeRebuilderImpl rebuilder, MutableNotesMigration globalNotesMigration, PrimaryStorageMigrator primaryStorageMigrator, DynamicSet<NotesMigrationStateListener> listeners, ListeningExecutorService executor, ImmutableList<Project.NameKey> projects, ImmutableList<Project.NameKey> skipProjects, ImmutableList<Change.Id> changes, OutputStream progressOut, NotesMigrationState stopAtState, ProjectCache projectCache, boolean trial, boolean forceRebuild, int sequenceGap, boolean autoMigrate) throws MigrationException { if (ImmutableList.of(!changes.isEmpty(), !projects.isEmpty(), !skipProjects.isEmpty()).stream() .filter(e -> e) .count() > 1) { throw new MigrationException("Cannot combine changes, projects and skipProjects"); } if (sequenceGap < 0) { throw new MigrationException("Sequence gap must be non-negative: " + sequenceGap); } this.schemaFactory = schemaFactory; this.serverIdent = serverIdent; this.allUsers = allUsers; this.rebuilder = rebuilder; this.repoManager = repoManager; this.updateManagerFactory = updateManagerFactory; this.bundleReader = bundleReader; this.allProjects = allProjects; this.requestContext = requestContext; this.userFactory = userFactory; this.globalNotesMigration = globalNotesMigration; this.primaryStorageMigrator = primaryStorageMigrator; this.listeners = listeners; this.executor = executor; this.projects = projects; this.skipProjects = skipProjects; this.changes = changes; this.progressOut = progressOut; this.stopAtState = stopAtState; this.projectCache = projectCache; this.trial = trial; this.forceRebuild = forceRebuild; this.sequenceGap = sequenceGap; this.autoMigrate = autoMigrate; // Stack notedb.config over gerrit.config, in the same way as GerritServerConfigProvider. this.gerritConfig = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.detect()); this.noteDbConfig = new FileBasedConfig(gerritConfig, sitePaths.notedb_config.toFile(), FS.detect()); } @Override public void close() { executor.shutdownNow(); } public void migrate() throws OrmException, IOException { if (!changes.isEmpty() || !projects.isEmpty() || !skipProjects.isEmpty()) { throw new MigrationException( "Cannot set changes or projects or skipProjects during full migration; call rebuild()" + " instead"); } Optional<NotesMigrationState> maybeState = loadState(); if (!maybeState.isPresent()) { throw new MigrationException("Could not determine initial migration state"); } NotesMigrationState state = maybeState.get(); if (trial && state.compareTo(READ_WRITE_NO_SEQUENCE) > 0) { throw new MigrationException( "Migration has already progressed past the endpoint of the \"trial mode\" state;" + " NoteDb is already the primary storage for some changes"); } if (forceRebuild && state.compareTo(READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY) > 0) { throw new MigrationException( "Cannot force rebuild changes; NoteDb is already the primary storage for some changes"); } setControlFlags(); boolean rebuilt = false; while (state.compareTo(NOTE_DB) < 0) { if (state.equals(stopAtState)) { return; } boolean stillNeedsRebuild = forceRebuild && !rebuilt; if (trial && state.compareTo(READ_WRITE_NO_SEQUENCE) >= 0) { if (stillNeedsRebuild && state == READ_WRITE_NO_SEQUENCE) { // We're at the end state of trial mode, but still need a rebuild due to forceRebuild. Let // the loop go one more time. } else { return; } } switch (state) { case REVIEW_DB: state = turnOnWrites(state); break; case WRITE: state = rebuildAndEnableReads(state); rebuilt = true; break; case READ_WRITE_NO_SEQUENCE: if (stillNeedsRebuild) { state = rebuildAndEnableReads(state); rebuilt = true; } else { state = enableSequences(state); } break; case READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY: if (stillNeedsRebuild) { state = rebuildAndEnableReads(state); rebuilt = true; } else { state = setNoteDbPrimary(state); } break; case READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY: // The only way we can get here is if there was a failure on a previous run of // setNoteDbPrimary, since that method moves to NOTE_DB if it completes // successfully. Assume that not all changes were converted and re-run the step. // migrateToNoteDbPrimary is a relatively fast no-op for already-migrated changes, so this // isn't actually repeating work. state = setNoteDbPrimary(state); break; case NOTE_DB: // Done! break; default: throw new MigrationException( "Migration out of the following state is not supported:\n" + state.toText()); } } } private NotesMigrationState turnOnWrites(NotesMigrationState prev) throws IOException { return saveState(prev, WRITE); } private NotesMigrationState rebuildAndEnableReads(NotesMigrationState prev) throws OrmException, IOException { rebuild(); return saveState(prev, READ_WRITE_NO_SEQUENCE); } private NotesMigrationState enableSequences(NotesMigrationState prev) throws OrmException, IOException { try (ReviewDb db = schemaFactory.open()) { @SuppressWarnings("deprecation") final int nextChangeId = db.nextChangeId(); RepoSequence seq = new RepoSequence( repoManager, GitReferenceUpdated.DISABLED, allProjects, Sequences.NAME_CHANGES, // If sequenceGap is 0, this writes into the sequence ref the same ID that is returned // by the call to seq.next() below. If we actually used this as a change ID, that // would be a problem, but we just discard it, so this is safe. () -> nextChangeId + sequenceGap - 1, 1, nextChangeId); seq.next(); } return saveState(prev, READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY); } private NotesMigrationState setNoteDbPrimary(NotesMigrationState prev) throws MigrationException, OrmException, IOException { checkState( projects.isEmpty() && changes.isEmpty() && skipProjects.isEmpty(), "Should not have attempted setNoteDbPrimary with a subset of changes"); checkState( prev == READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY || prev == READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY, "Unexpected start state for setNoteDbPrimary: %s", prev); // Before changing the primary storage of old changes, ensure new changes are created with // NoteDb primary. prev = saveState(prev, READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY); Stopwatch sw = Stopwatch.createStarted(); logger.atInfo().log("Setting primary storage to NoteDb"); List<Change.Id> allChanges; try (ReviewDb db = unwrapDb(schemaFactory.open())) { allChanges = Streams.stream(db.changes().all()).map(Change::getId).collect(toList()); } try (ContextHelper contextHelper = new ContextHelper()) { List<ListenableFuture<Boolean>> futures = allChanges.stream() .map( id -> executor.submit( () -> { try (ManualRequestContext ctx = contextHelper.open()) { try { primaryStorageMigrator.migrateToNoteDbPrimary(id); } catch (NoNoteDbStateException e) { if (canSkipPrimaryStorageMigration( ctx.getReviewDbProvider().get(), id)) { logger.atWarning().withCause(e).log( "Change %s previously failed to rebuild;" + " skipping primary storage migration", id); } else { throw e; } } return true; } catch (Exception e) { logger.atSevere().withCause(e).log( "Error migrating primary storage for %s", id); return false; } })) .collect(toList()); boolean ok = futuresToBoolean(futures, "Error migrating primary storage"); double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d; logger.atInfo().log( "Migrated primary storage of %d changes in %.01fs (%.01f/s)\n", allChanges.size(), t, allChanges.size() / t); if (!ok) { throw new MigrationException("Migrating primary storage for some changes failed, see log"); } } return disableReviewDb(prev); } /** * Checks whether a change is so corrupt that it can be completely skipped by the primary storage * migration step. * * <p>To get to the point where this method is called from {@link #setNoteDbPrimary}, it means we * attempted to rebuild it, and encountered an error that was then caught in {@link * #rebuildProject} and skipped. As a result, there is no {@code noteDbState} field in the change * by the time we get to {@link #setNoteDbPrimary}, so {@code migrateToNoteDbPrimary} throws an * exception. * * <p>We have to do this hacky double-checking because we don't have a way for the rebuilding * phase to communicate to the primary storage migration phase that the change is skippable. It * would be possible to store this info in some field in this class, but there is no guarantee * that the rebuild and primary storage migration phases are run in the same JVM invocation. * * <p>In an ideal world, we could do this through the {@link * com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage} enum, having a separate value * for errors. However, that would be an invasive change touching many non-migration-related parts * of the NoteDb migration code, which is too risky to attempt in the stable branch where this bug * had to be fixed. * * <p>As of this writing, there are only two cases where this happens: when a change has no patch * sets, or the project doesn't exist. */ private boolean canSkipPrimaryStorageMigration(ReviewDb db, Change.Id id) { try { return Iterables.isEmpty(unwrapDb(db).patchSets().byChange(id)) || projectCache.get(unwrapDb(db).changes().get(id).getProject()) == null; } catch (Exception e) { logger.atSevere().withCause(e).log( "Error checking if change %s can be skipped, assuming no", id); return false; } } private NotesMigrationState disableReviewDb(NotesMigrationState prev) throws IOException { return saveState(prev, NOTE_DB, c -> setAutoMigrate(c, false)); } private Optional<NotesMigrationState> loadState() throws IOException { try { gerritConfig.load(); noteDbConfig.load(); return NotesMigrationState.forConfig(noteDbConfig); } catch (ConfigInvalidException | IllegalArgumentException e) { logger.atWarning().withCause(e).log( "error reading NoteDb migration options from %s", noteDbConfig.getFile()); return Optional.empty(); } } private NotesMigrationState saveState( NotesMigrationState expectedOldState, NotesMigrationState newState) throws IOException { return saveState(expectedOldState, newState, c -> {}); } private NotesMigrationState saveState( NotesMigrationState expectedOldState, NotesMigrationState newState, Consumer<Config> additionalUpdates) throws IOException { synchronized (globalNotesMigration) { // This read-modify-write is racy. We're counting on the fact that no other Gerrit operation // modifies gerrit.config, and hoping that admins don't either. Optional<NotesMigrationState> actualOldState = loadState(); if (!actualOldState.equals(Optional.of(expectedOldState))) { throw new MigrationException( "Cannot move to new state:\n" + newState.toText() + "\n\n" + "Expected this state in gerrit.config:\n" + expectedOldState.toText() + "\n\n" + (actualOldState.isPresent() ? "But found this state:\n" + actualOldState.get().toText() : "But could not parse the current state")); } preStateChange(expectedOldState, newState); newState.setConfigValues(noteDbConfig); additionalUpdates.accept(noteDbConfig); noteDbConfig.save(); // Only set in-memory state once it's been persisted to storage. globalNotesMigration.setFrom(newState); logger.atInfo().log("Migration state: %s => %s", expectedOldState, newState); return newState; } } private void preStateChange(NotesMigrationState oldState, NotesMigrationState newState) throws IOException { for (NotesMigrationStateListener listener : listeners) { listener.preStateChange(oldState, newState); } } private void setControlFlags() throws MigrationException { synchronized (globalNotesMigration) { try { noteDbConfig.load(); setAutoMigrate(noteDbConfig, autoMigrate); setTrialMode(noteDbConfig, trial); noteDbConfig.save(); } catch (ConfigInvalidException | IOException e) { throw new MigrationException("Error saving auto-migration config", e); } } } public void rebuild() throws MigrationException, OrmException { if (!globalNotesMigration.commitChangeWrites()) { throw new MigrationException("Cannot rebuild without noteDb.changes.write=true"); } Stopwatch sw = Stopwatch.createStarted(); logger.atInfo().log("Rebuilding changes in NoteDb"); ImmutableListMultimap<Project.NameKey, Change.Id> changesByProject = getChangesByProject(); List<ListenableFuture<Boolean>> futures = new ArrayList<>(); try (ContextHelper contextHelper = new ContextHelper()) { List<Project.NameKey> projectNames = Ordering.usingToString().sortedCopy(changesByProject.keySet()); for (Project.NameKey project : projectNames) { ListenableFuture<Boolean> future = executor.submit( () -> { try { return rebuildProject(contextHelper.getReviewDb(), changesByProject, project); } catch (Exception e) { logger.atSevere().withCause(e).log("Error rebuilding project %s", project); return false; } }); futures.add(future); } boolean ok = futuresToBoolean(futures, "Error rebuilding projects"); double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d; logger.atInfo().log( "Rebuilt %d changes in %.01fs (%.01f/s)\n", changesByProject.size(), t, changesByProject.size() / t); if (!ok) { throw new MigrationException("Rebuilding some changes failed, see log"); } } } private ImmutableListMultimap<Project.NameKey, Change.Id> getChangesByProject() throws OrmException { // Memoize all changes so we can close the db connection and allow other threads to use the full // connection pool. SetMultimap<Project.NameKey, Change.Id> out = MultimapBuilder.treeKeys(comparing(Project.NameKey::get)) .treeSetValues(comparing(Change.Id::get)) .build(); try (ReviewDb db = unwrapDb(schemaFactory.open())) { if (!projects.isEmpty()) { return byProject(db.changes().all(), c -> projects.contains(c.getProject()), out); } if (!skipProjects.isEmpty()) { return byProject(db.changes().all(), c -> !skipProjects.contains(c.getProject()), out); } if (!changes.isEmpty()) { return byProject(db.changes().get(changes), c -> true, out); } return byProject(db.changes().all(), c -> true, out); } } private static ImmutableListMultimap<Project.NameKey, Change.Id> byProject( Iterable<Change> changes, Predicate<Change> pred, SetMultimap<Project.NameKey, Change.Id> out) { Streams.stream(changes).filter(pred).forEach(c -> out.put(c.getProject(), c.getId())); return ImmutableListMultimap.copyOf(out); } private static ObjectInserter newPackInserter(Repository repo) { if (!(repo instanceof FileRepository)) { return repo.newObjectInserter(); } PackInserter ins = ((FileRepository) repo).getObjectDatabase().newPackInserter(); ins.checkExisting(false); return ins; } private boolean rebuildProject( ReviewDb db, ImmutableListMultimap<Project.NameKey, Change.Id> allChanges, Project.NameKey project) { checkArgument(allChanges.containsKey(project)); boolean ok = true; ProgressMonitor pm = new TextProgressMonitor( new PrintWriter(new BufferedWriter(new OutputStreamWriter(progressOut, UTF_8)))); try (Repository changeRepo = repoManager.openRepository(project); // Only use a PackInserter for the change repo, not All-Users. // // It's not possible to share a single inserter for All-Users across all project tasks, and // we don't want to add one pack per project to All-Users. Adding many loose objects is // preferable to many packs. // // Anyway, the number of objects inserted into All-Users is proportional to the number // of pending draft comments, which should not be high (relative to the total number of // changes), so the number of loose objects shouldn't be too unreasonable. ObjectInserter changeIns = newPackInserter(changeRepo); ObjectReader changeReader = changeIns.newReader(); RevWalk changeRw = new RevWalk(changeReader); Repository allUsersRepo = repoManager.openRepository(allUsers); ObjectInserter allUsersIns = allUsersRepo.newObjectInserter(); ObjectReader allUsersReader = allUsersIns.newReader(); RevWalk allUsersRw = new RevWalk(allUsersReader)) { ChainedReceiveCommands changeCmds = new ChainedReceiveCommands(changeRepo); ChainedReceiveCommands allUsersCmds = new ChainedReceiveCommands(allUsersRepo); Collection<Change.Id> changes = allChanges.get(project); pm.beginTask(FormatUtil.elide("Rebuilding " + project.get(), 50), changes.size()); int toSave = 0; try { for (Change.Id changeId : changes) { // NoteDbUpdateManager assumes that all commands in its OpenRepo were added by itself, so // we can't share the top-level ChainedReceiveCommands. Use a new set of commands sharing // the same underlying repo, and copy commands back to the top-level // ChainedReceiveCommands later. This also assumes that each ref in the final list of // commands was only modified by a single NoteDbUpdateManager; since we use one manager // per change, and each ref corresponds to exactly one change, this assumption should be // safe. ChainedReceiveCommands tmpChangeCmds = new ChainedReceiveCommands(changeCmds.getRepoRefCache()); ChainedReceiveCommands tmpAllUsersCmds = new ChainedReceiveCommands(allUsersCmds.getRepoRefCache()); try (NoteDbUpdateManager manager = updateManagerFactory .create(project) .setAtomicRefUpdates(false) .setSaveObjects(false) .setChangeRepo(changeRepo, changeRw, changeIns, tmpChangeCmds) .setAllUsersRepo(allUsersRepo, allUsersRw, allUsersIns, tmpAllUsersCmds)) { rebuild(db, changeId, manager); // Executing with dryRun=true writes all objects to the underlying inserters and adds // commands to the ChainedReceiveCommands. Afterwards, we can discard the manager, so we // don't keep using any memory beyond what may be buffered in the PackInserter. manager.execute(true); tmpChangeCmds.getCommands().values().forEach(c -> addCommand(changeCmds, c)); tmpAllUsersCmds.getCommands().values().forEach(c -> addCommand(allUsersCmds, c)); toSave++; } catch (NoPatchSetsException e) { logger.atWarning().log(e.getMessage()); } catch (ConflictingUpdateException ex) { logger.atWarning().log( "Rebuilding detected a conflicting ReviewDb update for change %s;" + " will be auto-rebuilt at runtime", changeId); } catch (Throwable t) { logger.atSevere().withCause(t).log("Failed to rebuild change %s", changeId); ok = false; } pm.update(1); } } finally { pm.endTask(); } pm.beginTask(FormatUtil.elide("Saving " + project.get(), 50), ProgressMonitor.UNKNOWN); try { save(changeRepo, changeRw, changeIns, changeCmds); save(allUsersRepo, allUsersRw, allUsersIns, allUsersCmds); // This isn't really useful progress. If we passed a real ProgressMonitor to // BatchRefUpdate#execute we might get something more incremental, but that doesn't allow us // to specify the repo name in the task text. pm.update(toSave); } catch (LockFailureException e) { logger.atWarning().log( "Rebuilding detected a conflicting NoteDb update for the following refs, which will" + " be auto-rebuilt at runtime: %s", e.getFailedRefs().stream().distinct().sorted().collect(joining(", "))); } catch (IOException e) { logger.atSevere().withCause(e).log("Failed to save NoteDb state for %s", project); } finally { pm.endTask(); } } catch (RepositoryNotFoundException e) { logger.atWarning().log("Repository %s not found", project); } catch (IOException e) { logger.atSevere().withCause(e).log("Failed to rebuild project %s", project); } return ok; } private void rebuild(ReviewDb db, Change.Id changeId, NoteDbUpdateManager manager) throws OrmException, IOException { // Match ChangeRebuilderImpl#stage, but without calling manager.stage(), since that can only be // called after building updates for all changes. Change change = ChangeRebuilderImpl.checkNoteDbState(ChangeNotes.readOneReviewDbChange(db, changeId)); if (change == null) { // Could log here instead, but this matches the behavior of ChangeRebuilderImpl#stage. throw new NoSuchChangeException(changeId); } rebuilder.buildUpdates(manager, bundleReader.fromReviewDb(db, changeId)); rebuilder.execute(db, changeId, manager, true, false); } private static void addCommand(ChainedReceiveCommands cmds, ReceiveCommand cmd) { // ChainedReceiveCommands doesn't allow no-ops, but these occur when rebuilding a // previously-rebuilt change. if (!cmd.getOldId().equals(cmd.getNewId())) { cmds.add(cmd); } } private void save(Repository repo, RevWalk rw, ObjectInserter ins, ChainedReceiveCommands cmds) throws IOException { if (cmds.isEmpty()) { return; } ins.flush(); BatchRefUpdate bru = repo.getRefDatabase().newBatchUpdate(); bru.setRefLogMessage("Migrate changes to NoteDb", false); bru.setRefLogIdent(serverIdent.get()); bru.setAtomic(false); bru.setAllowNonFastForwards(true); cmds.addTo(bru); RefUpdateUtil.executeChecked(bru, rw); } private static boolean futuresToBoolean(List<ListenableFuture<Boolean>> futures, String errMsg) { try { return Futures.allAsList(futures).get().stream().allMatch(b -> b); } catch (InterruptedException | ExecutionException e) { logger.atSevere().withCause(e).log(errMsg); return false; } } private class ContextHelper implements AutoCloseable { private final Thread callingThread; private ReviewDb db; private Runnable closeDb; ContextHelper() { callingThread = Thread.currentThread(); } ManualRequestContext open() throws OrmException { return new ManualRequestContext( userFactory.create(), // Reuse the same lazily-opened ReviewDb on the original calling thread, otherwise open // SchemaFactory in the normal way. Thread.currentThread().equals(callingThread) ? this::getReviewDb : schemaFactory, requestContext); } synchronized ReviewDb getReviewDb() throws OrmException { if (db == null) { ReviewDb actual = schemaFactory.open(); closeDb = actual::close; db = new ReviewDbWrapper(unwrapDb(actual)) { @Override public void close() { // Closed by ContextHelper#close. } }; } return db; } @Override public synchronized void close() { if (db != null) { closeDb.run(); db = null; closeDb = null; } } } }
java/com/google/gerrit/server/notedb/rebuild/NoteDbMigrator.java
// Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.notedb.rebuild; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.gerrit.reviewdb.server.ReviewDbUtil.unwrapDb; import static com.google.gerrit.server.notedb.NotesMigration.SECTION_NOTE_DB; import static com.google.gerrit.server.notedb.NotesMigrationState.NOTE_DB; import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_NO_SEQUENCE; import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY; import static com.google.gerrit.server.notedb.NotesMigrationState.READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY; import static com.google.gerrit.server.notedb.NotesMigrationState.WRITE; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Comparator.comparing; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.MultimapBuilder; import com.google.common.collect.Ordering; import com.google.common.collect.SetMultimap; import com.google.common.collect.Streams; import com.google.common.flogger.FluentLogger; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.gerrit.common.FormatUtil; import com.google.gerrit.common.Nullable; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.reviewdb.server.ReviewDbWrapper; import com.google.gerrit.server.GerritPersonIdent; import com.google.gerrit.server.InternalUser; import com.google.gerrit.server.Sequences; import com.google.gerrit.server.config.AllProjectsName; import com.google.gerrit.server.config.AllUsersName; import com.google.gerrit.server.config.GerritServerConfigProvider; import com.google.gerrit.server.config.SitePaths; import com.google.gerrit.server.extensions.events.GitReferenceUpdated; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.git.LockFailureException; import com.google.gerrit.server.git.WorkQueue; import com.google.gerrit.server.notedb.ChangeBundleReader; import com.google.gerrit.server.notedb.ChangeNotes; import com.google.gerrit.server.notedb.MutableNotesMigration; import com.google.gerrit.server.notedb.NoteDbTable; import com.google.gerrit.server.notedb.NoteDbUpdateManager; import com.google.gerrit.server.notedb.NotesMigrationState; import com.google.gerrit.server.notedb.PrimaryStorageMigrator; import com.google.gerrit.server.notedb.PrimaryStorageMigrator.NoNoteDbStateException; import com.google.gerrit.server.notedb.RepoSequence; import com.google.gerrit.server.notedb.rebuild.ChangeRebuilder.NoPatchSetsException; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.update.ChainedReceiveCommands; import com.google.gerrit.server.update.RefUpdateUtil; import com.google.gerrit.server.util.ManualRequestContext; import com.google.gerrit.server.util.ThreadLocalRequestContext; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.SchemaFactory; import com.google.inject.Inject; import com.google.inject.Provider; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Predicate; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.internal.storage.file.PackInserter; import org.eclipse.jgit.lib.BatchRefUpdate; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.ProgressMonitor; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.TextProgressMonitor; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.transport.ReceiveCommand; import org.eclipse.jgit.util.FS; /** One stop shop for migrating a site's change storage from ReviewDb to NoteDb. */ public class NoteDbMigrator implements AutoCloseable { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String AUTO_MIGRATE = "autoMigrate"; private static final String TRIAL = "trial"; public static boolean getAutoMigrate(Config cfg) { return cfg.getBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), AUTO_MIGRATE, false); } private static void setAutoMigrate(Config cfg, boolean autoMigrate) { cfg.setBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), AUTO_MIGRATE, autoMigrate); } public static boolean getTrialMode(Config cfg) { return cfg.getBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), TRIAL, false); } public static void setTrialMode(Config cfg, boolean trial) { cfg.setBoolean(SECTION_NOTE_DB, NoteDbTable.CHANGES.key(), TRIAL, trial); } private static class NoteDbMigrationLoggerOut extends OutputStream { private StringBuilder outputBuffer = new StringBuilder(); @Override public synchronized void write(int b) throws IOException { if (b == '\r' || b == '\n') { logger.atInfo().log(outputBuffer.toString()); outputBuffer = new StringBuilder(); } else { outputBuffer.append(Character.toChars(b)); } } } public static class Builder { private final Config cfg; private final SitePaths sitePaths; private final Provider<PersonIdent> serverIdent; private final AllUsersName allUsers; private final SchemaFactory<ReviewDb> schemaFactory; private final GitRepositoryManager repoManager; private final NoteDbUpdateManager.Factory updateManagerFactory; private final ChangeBundleReader bundleReader; private final AllProjectsName allProjects; private final InternalUser.Factory userFactory; private final ThreadLocalRequestContext requestContext; private final ChangeRebuilderImpl rebuilder; private final WorkQueue workQueue; private final MutableNotesMigration globalNotesMigration; private final PrimaryStorageMigrator primaryStorageMigrator; private final DynamicSet<NotesMigrationStateListener> listeners; private final ProjectCache projectCache; private int threads; private ImmutableList<Project.NameKey> projects = ImmutableList.of(); private ImmutableList<Project.NameKey> skipProjects = ImmutableList.of(); private ImmutableList<Change.Id> changes = ImmutableList.of(); private OutputStream progressOut = new NoteDbMigrationLoggerOut(); private NotesMigrationState stopAtState; private boolean trial; private boolean forceRebuild; private int sequenceGap = -1; private boolean autoMigrate; @Inject Builder( GerritServerConfigProvider configProvider, SitePaths sitePaths, @GerritPersonIdent Provider<PersonIdent> serverIdent, AllUsersName allUsers, SchemaFactory<ReviewDb> schemaFactory, GitRepositoryManager repoManager, NoteDbUpdateManager.Factory updateManagerFactory, ChangeBundleReader bundleReader, AllProjectsName allProjects, ThreadLocalRequestContext requestContext, InternalUser.Factory userFactory, ChangeRebuilderImpl rebuilder, WorkQueue workQueue, MutableNotesMigration globalNotesMigration, PrimaryStorageMigrator primaryStorageMigrator, DynamicSet<NotesMigrationStateListener> listeners, ProjectCache projectCache) { // Reload gerrit.config/notedb.config on each migrator invocation, in case a previous // migration in the same process modified the on-disk contents. This ensures the defaults for // trial/autoMigrate get set correctly below. this.cfg = configProvider.loadConfig(); this.sitePaths = sitePaths; this.serverIdent = serverIdent; this.allUsers = allUsers; this.schemaFactory = schemaFactory; this.repoManager = repoManager; this.updateManagerFactory = updateManagerFactory; this.bundleReader = bundleReader; this.allProjects = allProjects; this.requestContext = requestContext; this.userFactory = userFactory; this.rebuilder = rebuilder; this.workQueue = workQueue; this.globalNotesMigration = globalNotesMigration; this.primaryStorageMigrator = primaryStorageMigrator; this.listeners = listeners; this.projectCache = projectCache; this.trial = getTrialMode(cfg); this.autoMigrate = getAutoMigrate(cfg); } /** * Set the number of threads used by parallelizable phases of the migration, such as rebuilding * all changes. * * <p>Not all phases are parallelizable, and calling {@link #rebuild()} directly will do * substantial work in the calling thread regardless of the number of threads configured. * * <p>By default, all work is done in the calling thread. * * @param threads thread count; if less than 2, all work happens in the calling thread. * @return this. */ public Builder setThreads(int threads) { this.threads = threads; return this; } /** * Limit the set of projects that are processed. * * <p>Incompatible with {@link #setChanges(Collection)}. * * <p>By default, all projects will be processed. * * @param projects set of projects; if null or empty, all projects will be processed. * @return this. */ public Builder setProjects(@Nullable Collection<Project.NameKey> projects) { this.projects = projects != null ? ImmutableList.copyOf(projects) : ImmutableList.of(); return this; } /** * Process all projects except these * * <p>Incompatible with {@link #setProjects(Collection)} and {@link #setChanges(Collection)} * * <p>By default, all projects will be processed. * * @param skipProjects set of projects; if null or empty all project will be processed * @return this. */ public Builder setSkipProjects(@Nullable Collection<Project.NameKey> skipProjects) { this.skipProjects = skipProjects != null ? ImmutableList.copyOf(skipProjects) : ImmutableList.of(); return this; } /** * Limit the set of changes that are processed. * * <p>Incompatible with {@link #setProjects(Collection)}. * * <p>By default, all changes will be processed. * * @param changes set of changes; if null or empty, all changes will be processed. * @return this. */ public Builder setChanges(@Nullable Collection<Change.Id> changes) { this.changes = changes != null ? ImmutableList.copyOf(changes) : ImmutableList.of(); return this; } /** * Set output stream for progress monitors. * * <p>By default, there is no progress monitor output (although there may be other logs). * * @param progressOut output stream. * @return this. */ public Builder setProgressOut(OutputStream progressOut) { this.progressOut = requireNonNull(progressOut); return this; } /** * Stop at a specific migration state, for testing only. * * @param stopAtState state to stop at. * @return this. */ @VisibleForTesting public Builder setStopAtStateForTesting(NotesMigrationState stopAtState) { this.stopAtState = stopAtState; return this; } /** * Rebuild in "trial mode": configure Gerrit to write to and read from NoteDb, but leave * ReviewDb as the source of truth for all changes. * * <p>By default, trial mode is off, and NoteDb is the source of truth for all changes following * the migration. * * @param trial whether to rebuild in trial mode. * @return this. */ public Builder setTrialMode(boolean trial) { this.trial = trial; return this; } /** * Rebuild all changes in NoteDb from ReviewDb, even if Gerrit is currently configured to read * from NoteDb. * * <p>Only supported if ReviewDb is still the source of truth for all changes. * * <p>By default, force rebuilding is off. * * @param forceRebuild whether to force rebuilding. * @return this. */ public Builder setForceRebuild(boolean forceRebuild) { this.forceRebuild = forceRebuild; return this; } /** * Gap between ReviewDb change sequence numbers and NoteDb. * * <p>If NoteDb sequences are enabled in a running server, there is a race between the migration * step that calls {@code nextChangeId()} to seed the ref, and other threads that call {@code * nextChangeId()} to create new changes. In order to prevent these operations stepping on one * another, we use this value to skip some predefined sequence numbers. This is strongly * recommended in a running server. * * <p>If the migration takes place offline, there is no race with other threads, and this option * may be set to 0. However, admins may still choose to use a gap, for example to make it easier * to distinguish changes that were created before and after the NoteDb migration. * * <p>By default, uses the value from {@code noteDb.changes.initialSequenceGap} in {@code * gerrit.config}, which defaults to 1000. * * @param sequenceGap sequence gap size; if negative, use the default. * @return this. */ public Builder setSequenceGap(int sequenceGap) { this.sequenceGap = sequenceGap; return this; } /** * Enable auto-migration on subsequent daemon launches. * * <p>If true, prior to running any migration steps, sets the necessary configuration in {@code * gerrit.config} to make {@code gerrit.war daemon} retry the migration on next startup, if it * fails. * * @param autoMigrate whether to set auto-migration config. * @return this. */ public Builder setAutoMigrate(boolean autoMigrate) { this.autoMigrate = autoMigrate; return this; } public NoteDbMigrator build() throws MigrationException { return new NoteDbMigrator( sitePaths, schemaFactory, serverIdent, allUsers, repoManager, updateManagerFactory, bundleReader, allProjects, requestContext, userFactory, rebuilder, globalNotesMigration, primaryStorageMigrator, listeners, threads > 1 ? MoreExecutors.listeningDecorator( workQueue.createQueue(threads, "RebuildChange", true)) : MoreExecutors.newDirectExecutorService(), projects, skipProjects, changes, progressOut, stopAtState, projectCache, trial, forceRebuild, sequenceGap >= 0 ? sequenceGap : Sequences.getChangeSequenceGap(cfg), autoMigrate); } } private final FileBasedConfig gerritConfig; private final FileBasedConfig noteDbConfig; private final SchemaFactory<ReviewDb> schemaFactory; private final Provider<PersonIdent> serverIdent; private final AllUsersName allUsers; private final GitRepositoryManager repoManager; private final NoteDbUpdateManager.Factory updateManagerFactory; private final ChangeBundleReader bundleReader; private final AllProjectsName allProjects; private final ThreadLocalRequestContext requestContext; private final InternalUser.Factory userFactory; private final ChangeRebuilderImpl rebuilder; private final MutableNotesMigration globalNotesMigration; private final PrimaryStorageMigrator primaryStorageMigrator; private final DynamicSet<NotesMigrationStateListener> listeners; private final ListeningExecutorService executor; private final ImmutableList<Project.NameKey> projects; private final ImmutableList<Project.NameKey> skipProjects; private final ImmutableList<Change.Id> changes; private final OutputStream progressOut; private final NotesMigrationState stopAtState; private final ProjectCache projectCache; private final boolean trial; private final boolean forceRebuild; private final int sequenceGap; private final boolean autoMigrate; private NoteDbMigrator( SitePaths sitePaths, SchemaFactory<ReviewDb> schemaFactory, Provider<PersonIdent> serverIdent, AllUsersName allUsers, GitRepositoryManager repoManager, NoteDbUpdateManager.Factory updateManagerFactory, ChangeBundleReader bundleReader, AllProjectsName allProjects, ThreadLocalRequestContext requestContext, InternalUser.Factory userFactory, ChangeRebuilderImpl rebuilder, MutableNotesMigration globalNotesMigration, PrimaryStorageMigrator primaryStorageMigrator, DynamicSet<NotesMigrationStateListener> listeners, ListeningExecutorService executor, ImmutableList<Project.NameKey> projects, ImmutableList<Project.NameKey> skipProjects, ImmutableList<Change.Id> changes, OutputStream progressOut, NotesMigrationState stopAtState, ProjectCache projectCache, boolean trial, boolean forceRebuild, int sequenceGap, boolean autoMigrate) throws MigrationException { if (ImmutableList.of(!changes.isEmpty(), !projects.isEmpty(), !skipProjects.isEmpty()).stream() .filter(e -> e) .count() > 1) { throw new MigrationException("Cannot combine changes, projects and skipProjects"); } if (sequenceGap < 0) { throw new MigrationException("Sequence gap must be non-negative: " + sequenceGap); } this.schemaFactory = schemaFactory; this.serverIdent = serverIdent; this.allUsers = allUsers; this.rebuilder = rebuilder; this.repoManager = repoManager; this.updateManagerFactory = updateManagerFactory; this.bundleReader = bundleReader; this.allProjects = allProjects; this.requestContext = requestContext; this.userFactory = userFactory; this.globalNotesMigration = globalNotesMigration; this.primaryStorageMigrator = primaryStorageMigrator; this.listeners = listeners; this.executor = executor; this.projects = projects; this.skipProjects = skipProjects; this.changes = changes; this.progressOut = progressOut; this.stopAtState = stopAtState; this.projectCache = projectCache; this.trial = trial; this.forceRebuild = forceRebuild; this.sequenceGap = sequenceGap; this.autoMigrate = autoMigrate; // Stack notedb.config over gerrit.config, in the same way as GerritServerConfigProvider. this.gerritConfig = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.detect()); this.noteDbConfig = new FileBasedConfig(gerritConfig, sitePaths.notedb_config.toFile(), FS.detect()); } @Override public void close() { executor.shutdownNow(); } public void migrate() throws OrmException, IOException { if (!changes.isEmpty() || !projects.isEmpty() || !skipProjects.isEmpty()) { throw new MigrationException( "Cannot set changes or projects or skipProjects during full migration; call rebuild() instead"); } Optional<NotesMigrationState> maybeState = loadState(); if (!maybeState.isPresent()) { throw new MigrationException("Could not determine initial migration state"); } NotesMigrationState state = maybeState.get(); if (trial && state.compareTo(READ_WRITE_NO_SEQUENCE) > 0) { throw new MigrationException( "Migration has already progressed past the endpoint of the \"trial mode\" state;" + " NoteDb is already the primary storage for some changes"); } if (forceRebuild && state.compareTo(READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY) > 0) { throw new MigrationException( "Cannot force rebuild changes; NoteDb is already the primary storage for some changes"); } setControlFlags(); boolean rebuilt = false; while (state.compareTo(NOTE_DB) < 0) { if (state.equals(stopAtState)) { return; } boolean stillNeedsRebuild = forceRebuild && !rebuilt; if (trial && state.compareTo(READ_WRITE_NO_SEQUENCE) >= 0) { if (stillNeedsRebuild && state == READ_WRITE_NO_SEQUENCE) { // We're at the end state of trial mode, but still need a rebuild due to forceRebuild. Let // the loop go one more time. } else { return; } } switch (state) { case REVIEW_DB: state = turnOnWrites(state); break; case WRITE: state = rebuildAndEnableReads(state); rebuilt = true; break; case READ_WRITE_NO_SEQUENCE: if (stillNeedsRebuild) { state = rebuildAndEnableReads(state); rebuilt = true; } else { state = enableSequences(state); } break; case READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY: if (stillNeedsRebuild) { state = rebuildAndEnableReads(state); rebuilt = true; } else { state = setNoteDbPrimary(state); } break; case READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY: // The only way we can get here is if there was a failure on a previous run of // setNoteDbPrimary, since that method moves to NOTE_DB if it completes // successfully. Assume that not all changes were converted and re-run the step. // migrateToNoteDbPrimary is a relatively fast no-op for already-migrated changes, so this // isn't actually repeating work. state = setNoteDbPrimary(state); break; case NOTE_DB: // Done! break; default: throw new MigrationException( "Migration out of the following state is not supported:\n" + state.toText()); } } } private NotesMigrationState turnOnWrites(NotesMigrationState prev) throws IOException { return saveState(prev, WRITE); } private NotesMigrationState rebuildAndEnableReads(NotesMigrationState prev) throws OrmException, IOException { rebuild(); return saveState(prev, READ_WRITE_NO_SEQUENCE); } private NotesMigrationState enableSequences(NotesMigrationState prev) throws OrmException, IOException { try (ReviewDb db = schemaFactory.open()) { @SuppressWarnings("deprecation") final int nextChangeId = db.nextChangeId(); RepoSequence seq = new RepoSequence( repoManager, GitReferenceUpdated.DISABLED, allProjects, Sequences.NAME_CHANGES, // If sequenceGap is 0, this writes into the sequence ref the same ID that is returned // by the call to seq.next() below. If we actually used this as a change ID, that // would be a problem, but we just discard it, so this is safe. () -> nextChangeId + sequenceGap - 1, 1, nextChangeId); seq.next(); } return saveState(prev, READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY); } private NotesMigrationState setNoteDbPrimary(NotesMigrationState prev) throws MigrationException, OrmException, IOException { checkState( projects.isEmpty() && changes.isEmpty() && skipProjects.isEmpty(), "Should not have attempted setNoteDbPrimary with a subset of changes"); checkState( prev == READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY || prev == READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY, "Unexpected start state for setNoteDbPrimary: %s", prev); // Before changing the primary storage of old changes, ensure new changes are created with // NoteDb primary. prev = saveState(prev, READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY); Stopwatch sw = Stopwatch.createStarted(); logger.atInfo().log("Setting primary storage to NoteDb"); List<Change.Id> allChanges; try (ReviewDb db = unwrapDb(schemaFactory.open())) { allChanges = Streams.stream(db.changes().all()).map(Change::getId).collect(toList()); } try (ContextHelper contextHelper = new ContextHelper()) { List<ListenableFuture<Boolean>> futures = allChanges.stream() .map( id -> executor.submit( () -> { try (ManualRequestContext ctx = contextHelper.open()) { try { primaryStorageMigrator.migrateToNoteDbPrimary(id); } catch (NoNoteDbStateException e) { if (canSkipPrimaryStorageMigration( ctx.getReviewDbProvider().get(), id)) { logger.atWarning().withCause(e).log( "Change %s previously failed to rebuild;" + " skipping primary storage migration", id); } else { throw e; } } return true; } catch (Exception e) { logger.atSevere().withCause(e).log( "Error migrating primary storage for %s", id); return false; } })) .collect(toList()); boolean ok = futuresToBoolean(futures, "Error migrating primary storage"); double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d; logger.atInfo().log( "Migrated primary storage of %d changes in %.01fs (%.01f/s)\n", allChanges.size(), t, allChanges.size() / t); if (!ok) { throw new MigrationException("Migrating primary storage for some changes failed, see log"); } } return disableReviewDb(prev); } /** * Checks whether a change is so corrupt that it can be completely skipped by the primary storage * migration step. * * <p>To get to the point where this method is called from {@link #setNoteDbPrimary}, it means we * attempted to rebuild it, and encountered an error that was then caught in {@link * #rebuildProject} and skipped. As a result, there is no {@code noteDbState} field in the change * by the time we get to {@link #setNoteDbPrimary}, so {@code migrateToNoteDbPrimary} throws an * exception. * * <p>We have to do this hacky double-checking because we don't have a way for the rebuilding * phase to communicate to the primary storage migration phase that the change is skippable. It * would be possible to store this info in some field in this class, but there is no guarantee * that the rebuild and primary storage migration phases are run in the same JVM invocation. * * <p>In an ideal world, we could do this through the {@link * com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage} enum, having a separate value * for errors. However, that would be an invasive change touching many non-migration-related parts * of the NoteDb migration code, which is too risky to attempt in the stable branch where this bug * had to be fixed. * * <p>As of this writing, there are only two cases where this happens: when a change has no patch * sets, or the project doesn't exist. */ private boolean canSkipPrimaryStorageMigration(ReviewDb db, Change.Id id) { try { return Iterables.isEmpty(unwrapDb(db).patchSets().byChange(id)) || projectCache.get(unwrapDb(db).changes().get(id).getProject()) == null; } catch (Exception e) { logger.atSevere().withCause(e).log( "Error checking if change %s can be skipped, assuming no", id); return false; } } private NotesMigrationState disableReviewDb(NotesMigrationState prev) throws IOException { return saveState(prev, NOTE_DB, c -> setAutoMigrate(c, false)); } private Optional<NotesMigrationState> loadState() throws IOException { try { gerritConfig.load(); noteDbConfig.load(); return NotesMigrationState.forConfig(noteDbConfig); } catch (ConfigInvalidException | IllegalArgumentException e) { logger.atWarning().withCause(e).log( "error reading NoteDb migration options from %s", noteDbConfig.getFile()); return Optional.empty(); } } private NotesMigrationState saveState( NotesMigrationState expectedOldState, NotesMigrationState newState) throws IOException { return saveState(expectedOldState, newState, c -> {}); } private NotesMigrationState saveState( NotesMigrationState expectedOldState, NotesMigrationState newState, Consumer<Config> additionalUpdates) throws IOException { synchronized (globalNotesMigration) { // This read-modify-write is racy. We're counting on the fact that no other Gerrit operation // modifies gerrit.config, and hoping that admins don't either. Optional<NotesMigrationState> actualOldState = loadState(); if (!actualOldState.equals(Optional.of(expectedOldState))) { throw new MigrationException( "Cannot move to new state:\n" + newState.toText() + "\n\n" + "Expected this state in gerrit.config:\n" + expectedOldState.toText() + "\n\n" + (actualOldState.isPresent() ? "But found this state:\n" + actualOldState.get().toText() : "But could not parse the current state")); } preStateChange(expectedOldState, newState); newState.setConfigValues(noteDbConfig); additionalUpdates.accept(noteDbConfig); noteDbConfig.save(); // Only set in-memory state once it's been persisted to storage. globalNotesMigration.setFrom(newState); logger.atInfo().log("Migration state: %s => %s", expectedOldState, newState); return newState; } } private void preStateChange(NotesMigrationState oldState, NotesMigrationState newState) throws IOException { for (NotesMigrationStateListener listener : listeners) { listener.preStateChange(oldState, newState); } } private void setControlFlags() throws MigrationException { synchronized (globalNotesMigration) { try { noteDbConfig.load(); setAutoMigrate(noteDbConfig, autoMigrate); setTrialMode(noteDbConfig, trial); noteDbConfig.save(); } catch (ConfigInvalidException | IOException e) { throw new MigrationException("Error saving auto-migration config", e); } } } public void rebuild() throws MigrationException, OrmException { if (!globalNotesMigration.commitChangeWrites()) { throw new MigrationException("Cannot rebuild without noteDb.changes.write=true"); } Stopwatch sw = Stopwatch.createStarted(); logger.atInfo().log("Rebuilding changes in NoteDb"); ImmutableListMultimap<Project.NameKey, Change.Id> changesByProject = getChangesByProject(); List<ListenableFuture<Boolean>> futures = new ArrayList<>(); try (ContextHelper contextHelper = new ContextHelper()) { List<Project.NameKey> projectNames = Ordering.usingToString().sortedCopy(changesByProject.keySet()); for (Project.NameKey project : projectNames) { ListenableFuture<Boolean> future = executor.submit( () -> { try { return rebuildProject(contextHelper.getReviewDb(), changesByProject, project); } catch (Exception e) { logger.atSevere().withCause(e).log("Error rebuilding project %s", project); return false; } }); futures.add(future); } boolean ok = futuresToBoolean(futures, "Error rebuilding projects"); double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d; logger.atInfo().log( "Rebuilt %d changes in %.01fs (%.01f/s)\n", changesByProject.size(), t, changesByProject.size() / t); if (!ok) { throw new MigrationException("Rebuilding some changes failed, see log"); } } } private ImmutableListMultimap<Project.NameKey, Change.Id> getChangesByProject() throws OrmException { // Memoize all changes so we can close the db connection and allow other threads to use the full // connection pool. SetMultimap<Project.NameKey, Change.Id> out = MultimapBuilder.treeKeys(comparing(Project.NameKey::get)) .treeSetValues(comparing(Change.Id::get)) .build(); try (ReviewDb db = unwrapDb(schemaFactory.open())) { if (!projects.isEmpty()) { return byProject(db.changes().all(), c -> projects.contains(c.getProject()), out); } if (!skipProjects.isEmpty()) { return byProject(db.changes().all(), c -> !skipProjects.contains(c.getProject()), out); } if (!changes.isEmpty()) { return byProject(db.changes().get(changes), c -> true, out); } return byProject(db.changes().all(), c -> true, out); } } private static ImmutableListMultimap<Project.NameKey, Change.Id> byProject( Iterable<Change> changes, Predicate<Change> pred, SetMultimap<Project.NameKey, Change.Id> out) { Streams.stream(changes).filter(pred).forEach(c -> out.put(c.getProject(), c.getId())); return ImmutableListMultimap.copyOf(out); } private static ObjectInserter newPackInserter(Repository repo) { if (!(repo instanceof FileRepository)) { return repo.newObjectInserter(); } PackInserter ins = ((FileRepository) repo).getObjectDatabase().newPackInserter(); ins.checkExisting(false); return ins; } private boolean rebuildProject( ReviewDb db, ImmutableListMultimap<Project.NameKey, Change.Id> allChanges, Project.NameKey project) { checkArgument(allChanges.containsKey(project)); boolean ok = true; ProgressMonitor pm = new TextProgressMonitor( new PrintWriter(new BufferedWriter(new OutputStreamWriter(progressOut, UTF_8)))); try (Repository changeRepo = repoManager.openRepository(project); // Only use a PackInserter for the change repo, not All-Users. // // It's not possible to share a single inserter for All-Users across all project tasks, and // we don't want to add one pack per project to All-Users. Adding many loose objects is // preferable to many packs. // // Anyway, the number of objects inserted into All-Users is proportional to the number // of pending draft comments, which should not be high (relative to the total number of // changes), so the number of loose objects shouldn't be too unreasonable. ObjectInserter changeIns = newPackInserter(changeRepo); ObjectReader changeReader = changeIns.newReader(); RevWalk changeRw = new RevWalk(changeReader); Repository allUsersRepo = repoManager.openRepository(allUsers); ObjectInserter allUsersIns = allUsersRepo.newObjectInserter(); ObjectReader allUsersReader = allUsersIns.newReader(); RevWalk allUsersRw = new RevWalk(allUsersReader)) { ChainedReceiveCommands changeCmds = new ChainedReceiveCommands(changeRepo); ChainedReceiveCommands allUsersCmds = new ChainedReceiveCommands(allUsersRepo); Collection<Change.Id> changes = allChanges.get(project); pm.beginTask(FormatUtil.elide("Rebuilding " + project.get(), 50), changes.size()); int toSave = 0; try { for (Change.Id changeId : changes) { // NoteDbUpdateManager assumes that all commands in its OpenRepo were added by itself, so // we can't share the top-level ChainedReceiveCommands. Use a new set of commands sharing // the same underlying repo, and copy commands back to the top-level // ChainedReceiveCommands later. This also assumes that each ref in the final list of // commands was only modified by a single NoteDbUpdateManager; since we use one manager // per change, and each ref corresponds to exactly one change, this assumption should be // safe. ChainedReceiveCommands tmpChangeCmds = new ChainedReceiveCommands(changeCmds.getRepoRefCache()); ChainedReceiveCommands tmpAllUsersCmds = new ChainedReceiveCommands(allUsersCmds.getRepoRefCache()); try (NoteDbUpdateManager manager = updateManagerFactory .create(project) .setAtomicRefUpdates(false) .setSaveObjects(false) .setChangeRepo(changeRepo, changeRw, changeIns, tmpChangeCmds) .setAllUsersRepo(allUsersRepo, allUsersRw, allUsersIns, tmpAllUsersCmds)) { rebuild(db, changeId, manager); // Executing with dryRun=true writes all objects to the underlying inserters and adds // commands to the ChainedReceiveCommands. Afterwards, we can discard the manager, so we // don't keep using any memory beyond what may be buffered in the PackInserter. manager.execute(true); tmpChangeCmds.getCommands().values().forEach(c -> addCommand(changeCmds, c)); tmpAllUsersCmds.getCommands().values().forEach(c -> addCommand(allUsersCmds, c)); toSave++; } catch (NoPatchSetsException e) { logger.atWarning().log(e.getMessage()); } catch (ConflictingUpdateException ex) { logger.atWarning().log( "Rebuilding detected a conflicting ReviewDb update for change %s;" + " will be auto-rebuilt at runtime", changeId); } catch (Throwable t) { logger.atSevere().withCause(t).log("Failed to rebuild change %s", changeId); ok = false; } pm.update(1); } } finally { pm.endTask(); } pm.beginTask(FormatUtil.elide("Saving " + project.get(), 50), ProgressMonitor.UNKNOWN); try { save(changeRepo, changeRw, changeIns, changeCmds); save(allUsersRepo, allUsersRw, allUsersIns, allUsersCmds); // This isn't really useful progress. If we passed a real ProgressMonitor to // BatchRefUpdate#execute we might get something more incremental, but that doesn't allow us // to specify the repo name in the task text. pm.update(toSave); } catch (LockFailureException e) { logger.atWarning().log( "Rebuilding detected a conflicting NoteDb update for the following refs, which will" + " be auto-rebuilt at runtime: %s", e.getFailedRefs().stream().distinct().sorted().collect(joining(", "))); } catch (IOException e) { logger.atSevere().withCause(e).log("Failed to save NoteDb state for %s", project); } finally { pm.endTask(); } } catch (RepositoryNotFoundException e) { logger.atWarning().log("Repository %s not found", project); } catch (IOException e) { logger.atSevere().withCause(e).log("Failed to rebuild project %s", project); } return ok; } private void rebuild(ReviewDb db, Change.Id changeId, NoteDbUpdateManager manager) throws OrmException, IOException { // Match ChangeRebuilderImpl#stage, but without calling manager.stage(), since that can only be // called after building updates for all changes. Change change = ChangeRebuilderImpl.checkNoteDbState(ChangeNotes.readOneReviewDbChange(db, changeId)); if (change == null) { // Could log here instead, but this matches the behavior of ChangeRebuilderImpl#stage. throw new NoSuchChangeException(changeId); } rebuilder.buildUpdates(manager, bundleReader.fromReviewDb(db, changeId)); rebuilder.execute(db, changeId, manager, true, false); } private static void addCommand(ChainedReceiveCommands cmds, ReceiveCommand cmd) { // ChainedReceiveCommands doesn't allow no-ops, but these occur when rebuilding a // previously-rebuilt change. if (!cmd.getOldId().equals(cmd.getNewId())) { cmds.add(cmd); } } private void save(Repository repo, RevWalk rw, ObjectInserter ins, ChainedReceiveCommands cmds) throws IOException { if (cmds.isEmpty()) { return; } ins.flush(); BatchRefUpdate bru = repo.getRefDatabase().newBatchUpdate(); bru.setRefLogMessage("Migrate changes to NoteDb", false); bru.setRefLogIdent(serverIdent.get()); bru.setAtomic(false); bru.setAllowNonFastForwards(true); cmds.addTo(bru); RefUpdateUtil.executeChecked(bru, rw); } private static boolean futuresToBoolean(List<ListenableFuture<Boolean>> futures, String errMsg) { try { return Futures.allAsList(futures).get().stream().allMatch(b -> b); } catch (InterruptedException | ExecutionException e) { logger.atSevere().withCause(e).log(errMsg); return false; } } private class ContextHelper implements AutoCloseable { private final Thread callingThread; private ReviewDb db; private Runnable closeDb; ContextHelper() { callingThread = Thread.currentThread(); } ManualRequestContext open() throws OrmException { return new ManualRequestContext( userFactory.create(), // Reuse the same lazily-opened ReviewDb on the original calling thread, otherwise open // SchemaFactory in the normal way. Thread.currentThread().equals(callingThread) ? this::getReviewDb : schemaFactory, requestContext); } synchronized ReviewDb getReviewDb() throws OrmException { if (db == null) { ReviewDb actual = schemaFactory.open(); closeDb = actual::close; db = new ReviewDbWrapper(unwrapDb(actual)) { @Override public void close() { // Closed by ContextHelper#close. } }; } return db; } @Override public synchronized void close() { if (db != null) { closeDb.run(); db = null; closeDb = null; } } } }
NoteDbMigrator: fix formatting Change-Id: I82b7a1feedf5faa0edbeb235079e74b1ee4793f1
java/com/google/gerrit/server/notedb/rebuild/NoteDbMigrator.java
NoteDbMigrator: fix formatting
<ide><path>ava/com/google/gerrit/server/notedb/rebuild/NoteDbMigrator.java <ide> public void migrate() throws OrmException, IOException { <ide> if (!changes.isEmpty() || !projects.isEmpty() || !skipProjects.isEmpty()) { <ide> throw new MigrationException( <del> "Cannot set changes or projects or skipProjects during full migration; call rebuild() instead"); <add> "Cannot set changes or projects or skipProjects during full migration; call rebuild()" <add> + " instead"); <ide> } <ide> Optional<NotesMigrationState> maybeState = loadState(); <ide> if (!maybeState.isPresent()) {
Java
bsd-3-clause
5a5e91e98d412cad37bb6fa7eb6d396eb992ce67
0
interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl
// @@@ msg combining AND lrmc at the same time is not supported // @@@ TODO? LRMC echt een ring maken, zodat je weet dat de mcast klaar is -> // handig als een node om updates/object vraagt /* * Created on Apr 26, 2006 by rob */ package ibis.satin.impl.sharedObjects; import ibis.ipl.IbisIdentifier; import ibis.ipl.PortType; import ibis.ipl.ReadMessage; import ibis.ipl.ReceivePort; import ibis.ipl.ReceivePortIdentifier; import ibis.ipl.SendPort; import ibis.ipl.WriteMessage; import ibis.satin.SharedObject; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.communication.Communication; import ibis.satin.impl.communication.Protocol; import ibis.satin.impl.loadBalancing.Victim; import ibis.satin.impl.spawnSync.InvocationRecord; import ibis.util.DeepCopy; import ibis.util.Timer; import ibis.util.TypedProperties; import ibis.util.messagecombining.MessageCombiner; import ibis.util.messagecombining.MessageSplitter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import mcast.object.ObjectMulticaster; import mcast.object.SendDoneUpcaller; class OmcInfo implements Config { HashMap<Integer, Timer> map = new HashMap<Integer, Timer>(); Timer total = Timer.createTimer(); Satin s; public OmcInfo(Satin s) { this.s = s; } synchronized void registerSend(int id) { Timer t = Timer.createTimer(); map.put(id, t); t.start(); } public synchronized void sendDone(int id) { Timer t = map.remove(id); if (t == null) { soLogger.info("SATIN '" + s.ident + "': got upcall for unknow id: " + id); return; } t.stop(); total.add(t); soLogger.info("SATIN '" + s.ident + "': broadcast " + id + " took " + t.totalTime()); } void end() { soLogger.info("SATIN '" + s.ident + "': total broadcast time was: " + total.totalTime()); } } final class SOCommunication implements Config, Protocol, SendDoneUpcaller { private static final boolean ASYNC_SO_BCAST = false; private final static int WAIT_FOR_UPDATES_TIME = 60000; public static final boolean DISABLE_SO_BCAST = false; private Satin s; /** the current size of the accumulated so messages */ private long soCurrTotalMessageSize = 0; private long soInvocationsDelayTimer = -1; /** used to broadcast shared object invocations */ private SendPort soSendPort; private PortType soPortType; /** used to do message combining on soSendPort */ private MessageCombiner soMessageCombiner; /** a list of ibis identifiers that we still need to connect to */ private ArrayList<IbisIdentifier> toConnect = new ArrayList<IbisIdentifier>(); private HashMap<IbisIdentifier, ReceivePortIdentifier> ports = new HashMap<IbisIdentifier, ReceivePortIdentifier>(); private ObjectMulticaster omc; private SharedObject sharedObject = null; private boolean receivedNack = false; private OmcInfo omcInfo; protected SOCommunication(Satin s) { this.s = s; } protected void init() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { try { omc = new ObjectMulticaster(s.comm.ibis, true /* efficient multi-cluster */, false, "satinSO", this); omcInfo = new OmcInfo(s); } catch (Exception e) { System.err.println("cannot create OMC: " + e); e.printStackTrace(); System.exit(1); } new SOInvocationReceiver(s, omc).start(); } else { try { soPortType = createSOPortType(); // Create a multicast port to bcast shared object invocations. // Connections are established later. soSendPort = s.comm.ibis.createSendPort(soPortType, "satin so port on " + s.ident); if (SO_MAX_INVOCATION_DELAY > 0) { TypedProperties props = new TypedProperties(); props.setProperty("ibis.serialization", "ibis"); soMessageCombiner = new MessageCombiner(props, soSendPort); } } catch (Exception e) { commLogger.fatal("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } } private PortType createSOPortType() throws IOException { return new PortType( PortType.CONNECTION_ONE_TO_MANY, PortType.CONNECTION_UPCALLS, PortType.CONNECTION_DOWNCALLS, PortType.RECEIVE_EXPLICIT, PortType.RECEIVE_AUTO_UPCALLS, PortType.SERIALIZATION_OBJECT); } /** * Creates SO receive ports for new Satin instances. Do this first, to make * them available as soon as possible. */ protected void handleJoins(IbisIdentifier[] joiners) { if(DISABLE_SO_BCAST) return; // lrmc uses its own ports if (LABEL_ROUTING_MCAST) { for (int i = 0; i < joiners.length; i++) { omc.addIbis(joiners[i]); } // Set the destination for the multicast. // The victimtable does not contain the new joiners yet. IbisIdentifier[] victims; synchronized (s) { victims = s.victims.getIbises(); } HashSet<IbisIdentifier> destinations = new HashSet<IbisIdentifier>(); for (IbisIdentifier id : victims) { destinations.add(id); } for (IbisIdentifier id : joiners) { destinations.add(id); } omc.setDestination(destinations.toArray(new IbisIdentifier[destinations.size()])); return; } for (int i = 0; i < joiners.length; i++) { // create a receive port for this guy try { SOInvocationHandler soInvocationHandler = new SOInvocationHandler(s); ReceivePort rec; rec = s.comm.ibis.createReceivePort(soPortType, "satin so receive port for " + joiners[i], soInvocationHandler, s.ft .getReceivePortConnectHandler(), null); if (SO_MAX_INVOCATION_DELAY > 0) { TypedProperties s = new TypedProperties(); s.setProperty("ibis.serialization", "ibis"); soInvocationHandler.setMessageSplitter(new MessageSplitter( s, rec)); } rec.enableConnections(); rec.enableMessageUpcalls(); } catch (Exception e) { commLogger.fatal("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } /** Add new connections to the soSendPort */ synchronized (s) { for (int i = 0; i < joiners.length; i++) { toConnect.add(joiners[i]); } } } protected void sendAccumulatedSOInvocations() { if (SO_MAX_INVOCATION_DELAY <= 0) return; long currTime = System.currentTimeMillis(); long elapsed = currTime - soInvocationsDelayTimer; if (soInvocationsDelayTimer > 0 && (elapsed > SO_MAX_INVOCATION_DELAY || soCurrTotalMessageSize > SO_MAX_MESSAGE_SIZE)) { try { s.stats.broadcastSOInvocationsTimer.start(); soMessageCombiner.sendAccumulatedMessages(); } catch (IOException e) { System.err.println("SATIN '" + s.ident + "': unable to broadcast shared object invocations " + e); } s.stats.soRealMessageCount++; soCurrTotalMessageSize = 0; soInvocationsDelayTimer = -1; s.stats.broadcastSOInvocationsTimer.stop(); } } protected void broadcastSOInvocation(SOInvocationRecord r) { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { doBroadcastSOInvocationLRMC(r); } else { if (ASYNC_SO_BCAST) { // We have to make a copy of the object first, the caller might modify it. SOInvocationRecord copy = (SOInvocationRecord) DeepCopy.deepCopy(r); new AsyncBcaster(this, copy).start(); } else { doBroadcastSOInvocation(r); } } } public void sendDone(int id) { if (soLogger.isDebugEnabled()) { soLogger.debug("SATIN '" + s.ident + "': got ACK for send " + id); } omcInfo.sendDone(id); } /** Broadcast an so invocation */ protected void doBroadcastSOInvocationLRMC(SOInvocationRecord r) { IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); if (tmp.length == 0) return; } soLogger.debug("SATIN '" + s.ident + "': broadcasting so invocation for: " + r.getObjectId()); s.stats.broadcastSOInvocationsTimer.start(); s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp); try { int id = omc.send(r); omcInfo.registerSend(id); } catch (Exception e) { soLogger.warn("SOI mcast failed: " + e + " msg: " + e.getMessage()); } s.stats.soInvocations++; s.stats.soRealMessageCount++; s.stats.soInvocationsBytes += omc.lastSize(); s.stats.broadcastSOInvocationsTimer.stop(); } /** Broadcast an so invocation */ protected void doBroadcastSOInvocation(SOInvocationRecord r) { long byteCount = 0; WriteMessage w = null; s.stats.broadcastSOInvocationsTimer.start(); connectSendPortToNewReceivers(); IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); } s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp); if (soSendPort != null && soSendPort.connectedTo().length > 0) { try { if (SO_MAX_INVOCATION_DELAY > 0) { // do message combining w = soMessageCombiner.newMessage(); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } } else { w = soSendPort.newMessage(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); } catch (IOException e) { if (w != null) { w.finish(e); } System.err .println("SATIN '" + s.ident + "': unable to broadcast a shared object invocation: " + e); } if (SO_MAX_INVOCATION_DELAY > 0) { soCurrTotalMessageSize += byteCount; } else { s.stats.soRealMessageCount++; } } s.stats.soInvocations++; s.stats.soInvocationsBytes += byteCount; s.stats.broadcastSOInvocationsTimer.stop(); // Try to send immediately if needed. // We might not reach a safe point for a considerable time. if (SO_MAX_INVOCATION_DELAY > 0) { sendAccumulatedSOInvocations(); } } /** * This basicaly is optional, if nodes don't have the object, they will * retrieve it. However, one broadcast is more efficient (serialization is * done only once). We MUST use message combining here, we use the same receiveport * as the SO invocation messages. This is only called by exportObject. */ protected void broadcastSharedObject(SharedObject object) { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { doBroadcastSharedObjectLRMC(object); } else { doBroadcastSharedObject(object); } } protected void doBroadcastSharedObject(SharedObject object) { WriteMessage w = null; long size = 0; s.stats.soBroadcastTransferTimer.start(); connectSendPortToNewReceivers(); if (soSendPort == null) { s.stats.soBroadcastTransferTimer.stop(); return; } IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); } s.so.registerMulticast(s.so.getSOReference(object.getObjectId()), tmp); try { if (SO_MAX_INVOCATION_DELAY > 0) { //do message combining w = soMessageCombiner.newMessage(); } else { w = soSendPort.newMessage(); } w.writeByte(SO_TRANSFER); s.stats.soBroadcastSerializationTimer.start(); w.writeObject(object); s.stats.soBroadcastSerializationTimer.stop(); size = w.finish(); w = null; if (SO_MAX_INVOCATION_DELAY > 0) { soMessageCombiner.sendAccumulatedMessages(); } } catch (IOException e) { if (w != null) { w.finish(e); } System.err.println("SATIN '" + s.ident + "': unable to broadcast a shared object: " + e); } s.stats.soBcasts++; s.stats.soBcastBytes += size; s.stats.soBroadcastTransferTimer.stop(); } /** Broadcast an so invocation */ protected void doBroadcastSharedObjectLRMC(SharedObject object) { IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); if (tmp.length == 0) return; } soLogger.debug("SATIN '" + s.ident + "': broadcasting object: " + object.getObjectId()); s.stats.soBroadcastTransferTimer.start(); s.so.registerMulticast(object, tmp); try { s.stats.soBroadcastSerializationTimer.start(); int id = omc.send(object); omcInfo.registerSend(id); s.stats.soBroadcastSerializationTimer.stop(); } catch (Exception e) { System.err.println("WARNING, SO mcast failed: " + e + " msg: " + e.getMessage()); e.printStackTrace(); } s.stats.soBcasts++; s.stats.soBcastBytes += omc.lastSize(); s.stats.soBroadcastTransferTimer.stop(); } /** Remove a connection to the soSendPort */ protected void removeSOConnection(IbisIdentifier id) { Satin.assertLocked(s); ReceivePortIdentifier r = ports.remove(id); if (r != null) { Communication.disconnect(soSendPort, r); } } /** Fetch a shared object from another node. * If the Invocation record is null, any version is OK, we just test that we have a * version of the object. If it is not null, we try to satisfy the guard of the * invocation record. It might not be satisfied when this method returns, the * guard might depend on more than one shared object. */ protected void fetchObject(String objectId, IbisIdentifier source, InvocationRecord r) throws SOReferenceSourceCrashedException { /* soLogger.debug("SATIN '" + s.ident + "': sending SO request " + (r == null ? "FIRST TIME" : "GUARD")); // first, ask for the object sendSORequest(objectId, source, false); boolean gotIt = waitForSOReply(); if (gotIt) { soLogger.debug("SATIN '" + s.ident + "': received the object after requesting it"); return; } soLogger .debug("SATIN '" + s.ident + "': received NACK, the object is probably already being broadcast to me, WAITING"); */ // got a nack back, the source thinks it sent it to me. // wait for the object to arrive. If it doesn't, demand the object. long start = System.currentTimeMillis(); while (true) { if (System.currentTimeMillis() - start > WAIT_FOR_UPDATES_TIME) break; synchronized (s) { try { s.wait(500); } catch (InterruptedException e) { // Ignore } } s.handleDelayedMessages(); if (r == null) { if (s.so.getSOInfo(objectId) != null) { soLogger.debug("SATIN '" + s.ident + "': received new object from a bcast"); return; // got it! } } else { if (r.guard()) { soLogger.debug("SATIN '" + s.ident + "': received object, guard satisfied"); return; } } } soLogger.debug("SATIN '" + s.ident + "': did not receive object in time, demanding it now"); // haven't got it, demand it now. sendSORequest(objectId, source, true); boolean gotIt = waitForSOReply(); if (gotIt) { soLogger.debug("SATIN '" + s.ident + "': received demanded object"); return; } soLogger .fatal("SATIN '" + s.ident + "': internal error: did not receive shared object after I demanded it. "); } private void sendSORequest(String objectId, IbisIdentifier source, boolean demand) throws SOReferenceSourceCrashedException { // request the shared object from the source WriteMessage w = null; try { s.lb.setCurrentVictim(source); Victim v; synchronized (s) { v = s.victims.getVictim(source); } if (v == null) { // hm we've got a problem here // push the job somewhere else? soLogger.error("SATIN '" + s.ident + "': could not " + "write shared-object request"); throw new SOReferenceSourceCrashedException(); } w = v.newMessage(); if (demand) { w.writeByte(SO_DEMAND); } else { w.writeByte(SO_REQUEST); } w.writeString(objectId); v.finish(w); } catch (IOException e) { if (w != null) { w.finish(e); } // hm we've got a problem here // push the job somewhere else? soLogger.error("SATIN '" + s.ident + "': could not " + "write shared-object request", e); throw new SOReferenceSourceCrashedException(); } } private boolean waitForSOReply() throws SOReferenceSourceCrashedException { // wait for the reply // there are three possibilities: // 1. we get the object back -> return true // 2. we get a nack back -> return false // 3. the source crashed -> exception while (true) { synchronized (s) { if (sharedObject != null) { s.so.addObject(sharedObject); sharedObject = null; s.currentVictimCrashed = false; soLogger.info("SATIN '" + s.ident + "': received shared object"); return true; } if (s.currentVictimCrashed) { s.currentVictimCrashed = false; // the source has crashed, abort the job soLogger.info("SATIN '" + s.ident + "': source crashed while waiting for SO reply"); throw new SOReferenceSourceCrashedException(); } if (receivedNack) { receivedNack = false; s.currentVictimCrashed = false; soLogger.info("SATIN '" + s.ident + "': received shared object NACK"); return false; } try { s.wait(); } catch (Exception e) { // ignore } } } } boolean broadcastInProgress(SharedObjectInfo info, IbisIdentifier dest) { if (System.currentTimeMillis() - info.lastBroadcastTime > WAIT_FOR_UPDATES_TIME) { return false; } for (int i = 0; i < info.destinations.length; i++) { if (info.destinations[i].equals(dest)) return true; } return false; } protected void handleSORequests() { WriteMessage wm = null; IbisIdentifier origin; String objid; boolean demand; while (true) { Victim v; synchronized (s) { if (s.so.SORequestList.getCount() == 0) { s.so.gotSORequests = false; return; } origin = s.so.SORequestList.getRequester(0); objid = s.so.SORequestList.getobjID(0); demand = s.so.SORequestList.isDemand(0); s.so.SORequestList.removeIndex(0); v = s.victims.getVictim(origin); } if (v == null) { soLogger.debug("SATIN '" + s.ident + "': vicim crached in handleSORequest"); continue; // node might have crashed } SharedObjectInfo info = s.so.getSOInfo(objid); if (ASSERTS && info == null) { soLogger.fatal("SATIN '" + s.ident + "': EEEK, requested shared object: " + objid + " not found! Exiting.."); System.exit(1); // Failed assertion } if (!demand && broadcastInProgress(info, v.getIdent())) { soLogger.debug("SATIN '" + s.ident + "': send NACK back in handleSORequest"); // send NACK back try { wm = v.newMessage(); wm.writeByte(SO_NACK); v.finish(wm); } catch (IOException e) { if (wm != null) { wm.finish(e); } soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object NACK", e); } continue; } soLogger.debug("SATIN '" + s.ident + "': send object back in handleSORequest"); sendObjectBack(v, info); } } private void sendObjectBack(Victim v, SharedObjectInfo info) { WriteMessage wm = null; long size; // No need to hold the lock while writing the object. // Updates cannot change the state of the object during the send, // they are delayed until safe a point. s.stats.soTransferTimer.start(); SharedObject so = info.sharedObject; try { wm = v.newMessage(); wm.writeByte(SO_TRANSFER); } catch (IOException e) { s.stats.soTransferTimer.stop(); if (wm != null) { wm.finish(e); } soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); return; } s.stats.soSerializationTimer.start(); try { wm.writeObject(so); } catch (IOException e) { s.stats.soSerializationTimer.stop(); s.stats.soTransferTimer.stop(); wm.finish(e); soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); return; } s.stats.soSerializationTimer.stop(); try { size = v.finish(wm); } catch (IOException e) { s.stats.soTransferTimer.stop(); wm.finish(e); soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); return; } s.stats.soTransfers++; s.stats.soTransfersBytes += size; s.stats.soTransferTimer.stop(); } protected void handleSORequest(ReadMessage m, boolean demand) { String objid = null; IbisIdentifier origin = m.origin().ibisIdentifier(); soLogger.info("SATIN '" + s.ident + "': got so request"); try { objid = m.readString(); // no need to finish the message. We don't do any communication } catch (IOException e) { soLogger.warn("SATIN '" + s.ident + "': got exception while reading" + " shared object request: " + e.getMessage()); } synchronized (s) { s.so.addToSORequestList(origin, objid, demand); } } /** * Receive a shared object from another node (called by the MessageHandler */ protected void handleSOTransfer(ReadMessage m) { // normal so transfer (not exportObject) SharedObject obj = null; s.stats.soDeserializationTimer.start(); try { obj = (SharedObject) m.readObject(); } catch (IOException e) { soLogger.error("SATIN '" + s.ident + "': got exception while reading" + " shared object", e); } catch (ClassNotFoundException e) { soLogger.error("SATIN '" + s.ident + "': got exception while reading" + " shared object", e); } s.stats.soDeserializationTimer.stop(); // no need to finish the read message here. // We don't block and don't do any communication synchronized (s) { sharedObject = obj; s.notifyAll(); } } protected void handleSONack(ReadMessage m) { synchronized (s) { receivedNack = true; s.notifyAll(); } } private void connectSOSendPort(IbisIdentifier ident) { ReceivePortIdentifier r = Communication.connect(soSendPort, ident, "satin so receiveport for " + s.ident, Satin.CONNECT_TIMEOUT); if (r != null) { synchronized (s) { ports.put(ident, r); } } else { soLogger.warn("SATIN '" + s.ident + "': unable to connect to SO receive port "); // We won't broadcast the object to this receiver. // This is not really a problem, it will get the object if it // needs it. But the node has probably crashed anyway. return; } } private void connectSendPortToNewReceivers() { IbisIdentifier[] tmp; synchronized (s) { tmp = new IbisIdentifier[toConnect.size()]; for (int i = 0; i < toConnect.size(); i++) { tmp[i] = toConnect.get(i); } toConnect.clear(); } // do not keep the lock during connection setup for (int i = 0; i < tmp.length; i++) { connectSOSendPort(tmp[i]); } } public void handleMyOwnJoin() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { omc.addIbis(s.ident); } } public void handleCrash(IbisIdentifier id) { if (LABEL_ROUTING_MCAST) { omc.removeIbis(id); omc.setDestination(s.victims.getIbises()); } } protected void exit() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { omc.done(); omcInfo.end(); } } static class AsyncBcaster extends Thread { private SOCommunication c; private SOInvocationRecord r; AsyncBcaster(SOCommunication c, SOInvocationRecord r) { this.c = c; this.r = r; } public void run() { c.doBroadcastSOInvocation(r); } } }
src/ibis/satin/impl/sharedObjects/SOCommunication.java
// @@@ msg combining AND lrmc at the same time is not supported // @@@ TODO? LRMC echt een ring maken, zodat je weet dat de mcast klaar is -> // handig als een node om updates/object vraagt /* * Created on Apr 26, 2006 by rob */ package ibis.satin.impl.sharedObjects; import ibis.ipl.IbisIdentifier; import ibis.ipl.PortType; import ibis.ipl.ReadMessage; import ibis.ipl.ReceivePort; import ibis.ipl.ReceivePortIdentifier; import ibis.ipl.SendPort; import ibis.ipl.WriteMessage; import ibis.satin.SharedObject; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.communication.Communication; import ibis.satin.impl.communication.Protocol; import ibis.satin.impl.loadBalancing.Victim; import ibis.satin.impl.spawnSync.InvocationRecord; import ibis.util.DeepCopy; import ibis.util.Timer; import ibis.util.TypedProperties; import ibis.util.messagecombining.MessageCombiner; import ibis.util.messagecombining.MessageSplitter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import mcast.object.ObjectMulticaster; import mcast.object.SendDoneUpcaller; class OmcInfo implements Config { HashMap<Integer, Timer> map = new HashMap<Integer, Timer>(); Timer total = Timer.createTimer(); Satin s; public OmcInfo(Satin s) { this.s = s; } synchronized void registerSend(int id) { Timer t = Timer.createTimer(); map.put(id, t); t.start(); } public synchronized void sendDone(int id) { Timer t = map.remove(id); if (t == null) { soLogger.info("SATIN '" + s.ident + "': got upcall for unknow id: " + id); return; } t.stop(); total.add(t); soLogger.info("SATIN '" + s.ident + "': broadcast " + id + " took " + t.totalTime()); } void end() { soLogger.info("SATIN '" + s.ident + "': total broadcast time was: " + total.totalTime()); } } final class SOCommunication implements Config, Protocol, SendDoneUpcaller { private static final boolean ASYNC_SO_BCAST = false; private final static int WAIT_FOR_UPDATES_TIME = 60000; public static final boolean DISABLE_SO_BCAST = false; private Satin s; /** the current size of the accumulated so messages */ private long soCurrTotalMessageSize = 0; private long soInvocationsDelayTimer = -1; /** used to broadcast shared object invocations */ private SendPort soSendPort; private PortType soPortType; /** used to do message combining on soSendPort */ private MessageCombiner soMessageCombiner; /** a list of ibis identifiers that we still need to connect to */ private ArrayList<IbisIdentifier> toConnect = new ArrayList<IbisIdentifier>(); private HashMap<IbisIdentifier, ReceivePortIdentifier> ports = new HashMap<IbisIdentifier, ReceivePortIdentifier>(); private ObjectMulticaster omc; private SharedObject sharedObject = null; private boolean receivedNack = false; private OmcInfo omcInfo; protected SOCommunication(Satin s) { this.s = s; } protected void init() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { try { omc = new ObjectMulticaster(s.comm.ibis, true /* efficient multi-cluster */, false, "satinSO", this); omcInfo = new OmcInfo(s); } catch (Exception e) { System.err.println("cannot create OMC: " + e); e.printStackTrace(); System.exit(1); } new SOInvocationReceiver(s, omc).start(); } else { try { soPortType = createSOPortType(); // Create a multicast port to bcast shared object invocations. // Connections are established later. soSendPort = s.comm.ibis.createSendPort(soPortType, "satin so port on " + s.ident); if (SO_MAX_INVOCATION_DELAY > 0) { TypedProperties props = new TypedProperties(); props.setProperty("ibis.serialization", "ibis"); soMessageCombiner = new MessageCombiner(props, soSendPort); } } catch (Exception e) { commLogger.fatal("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } } private PortType createSOPortType() throws IOException { return new PortType( PortType.CONNECTION_ONE_TO_MANY, PortType.CONNECTION_UPCALLS, PortType.CONNECTION_DOWNCALLS, PortType.RECEIVE_EXPLICIT, PortType.RECEIVE_AUTO_UPCALLS, PortType.SERIALIZATION_OBJECT); } /** * Creates SO receive ports for new Satin instances. Do this first, to make * them available as soon as possible. */ protected void handleJoins(IbisIdentifier[] joiners) { if(DISABLE_SO_BCAST) return; // lrmc uses its own ports if (LABEL_ROUTING_MCAST) { for (int i = 0; i < joiners.length; i++) { omc.addIbis(joiners[i]); } // Set the destination for the multicast. // The victimtable does not contain the new joiners yet. IbisIdentifier[] victims; synchronized (s) { victims = s.victims.getIbises(); } HashSet<IbisIdentifier> destinations = new HashSet<IbisIdentifier>(); for (IbisIdentifier id : victims) { destinations.add(id); } for (IbisIdentifier id : joiners) { destinations.add(id); } omc.setDestination(destinations.toArray(new IbisIdentifier[destinations.size()])); return; } for (int i = 0; i < joiners.length; i++) { // create a receive port for this guy try { SOInvocationHandler soInvocationHandler = new SOInvocationHandler(s); ReceivePort rec; rec = s.comm.ibis.createReceivePort(soPortType, "satin so receive port for " + joiners[i], soInvocationHandler, s.ft .getReceivePortConnectHandler(), null); if (SO_MAX_INVOCATION_DELAY > 0) { TypedProperties s = new TypedProperties(); s.setProperty("ibis.serialization", "ibis"); soInvocationHandler.setMessageSplitter(new MessageSplitter( s, rec)); } rec.enableConnections(); rec.enableMessageUpcalls(); } catch (Exception e) { commLogger.fatal("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } /** Add new connections to the soSendPort */ synchronized (s) { for (int i = 0; i < joiners.length; i++) { toConnect.add(joiners[i]); } } } protected void sendAccumulatedSOInvocations() { if (SO_MAX_INVOCATION_DELAY <= 0) return; long currTime = System.currentTimeMillis(); long elapsed = currTime - soInvocationsDelayTimer; if (soInvocationsDelayTimer > 0 && (elapsed > SO_MAX_INVOCATION_DELAY || soCurrTotalMessageSize > SO_MAX_MESSAGE_SIZE)) { try { s.stats.broadcastSOInvocationsTimer.start(); soMessageCombiner.sendAccumulatedMessages(); } catch (IOException e) { System.err.println("SATIN '" + s.ident + "': unable to broadcast shared object invocations " + e); } s.stats.soRealMessageCount++; soCurrTotalMessageSize = 0; soInvocationsDelayTimer = -1; s.stats.broadcastSOInvocationsTimer.stop(); } } protected void broadcastSOInvocation(SOInvocationRecord r) { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { doBroadcastSOInvocationLRMC(r); } else { if (ASYNC_SO_BCAST) { // We have to make a copy of the object first, the caller might modify it. SOInvocationRecord copy = (SOInvocationRecord) DeepCopy.deepCopy(r); new AsyncBcaster(this, copy).start(); } else { doBroadcastSOInvocation(r); } } } public void sendDone(int id) { if (soLogger.isDebugEnabled()) { soLogger.debug("SATIN '" + s.ident + "': got ACK for send " + id); } omcInfo.sendDone(id); } /** Broadcast an so invocation */ protected void doBroadcastSOInvocationLRMC(SOInvocationRecord r) { IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); if (tmp.length == 0) return; } soLogger.debug("SATIN '" + s.ident + "': broadcasting so invocation for: " + r.getObjectId()); s.stats.broadcastSOInvocationsTimer.start(); s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp); try { int id = omc.send(r); omcInfo.registerSend(id); } catch (Exception e) { soLogger.warn("SOI mcast failed: " + e + " msg: " + e.getMessage()); } s.stats.soInvocations++; s.stats.soRealMessageCount++; s.stats.soInvocationsBytes += omc.lastSize(); s.stats.broadcastSOInvocationsTimer.stop(); } /** Broadcast an so invocation */ protected void doBroadcastSOInvocation(SOInvocationRecord r) { long byteCount = 0; WriteMessage w = null; s.stats.broadcastSOInvocationsTimer.start(); connectSendPortToNewReceivers(); IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); } s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp); if (soSendPort != null && soSendPort.connectedTo().length > 0) { try { if (SO_MAX_INVOCATION_DELAY > 0) { // do message combining w = soMessageCombiner.newMessage(); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } } else { w = soSendPort.newMessage(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); } catch (IOException e) { if (w != null) { w.finish(e); } System.err .println("SATIN '" + s.ident + "': unable to broadcast a shared object invocation: " + e); } if (SO_MAX_INVOCATION_DELAY > 0) { soCurrTotalMessageSize += byteCount; } else { s.stats.soRealMessageCount++; } } s.stats.soInvocations++; s.stats.soInvocationsBytes += byteCount; s.stats.broadcastSOInvocationsTimer.stop(); // Try to send immediately if needed. // We might not reach a safe point for a considerable time. if (SO_MAX_INVOCATION_DELAY > 0) { sendAccumulatedSOInvocations(); } } /** * This basicaly is optional, if nodes don't have the object, they will * retrieve it. However, one broadcast is more efficient (serialization is * done only once). We MUST use message combining here, we use the same receiveport * as the SO invocation messages. This is only called by exportObject. */ protected void broadcastSharedObject(SharedObject object) { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { doBroadcastSharedObjectLRMC(object); } else { doBroadcastSharedObject(object); } } protected void doBroadcastSharedObject(SharedObject object) { WriteMessage w = null; long size = 0; s.stats.soBroadcastTransferTimer.start(); connectSendPortToNewReceivers(); if (soSendPort == null) { s.stats.soBroadcastTransferTimer.stop(); return; } IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); } s.so.registerMulticast(s.so.getSOReference(object.getObjectId()), tmp); try { if (SO_MAX_INVOCATION_DELAY > 0) { //do message combining w = soMessageCombiner.newMessage(); } else { w = soSendPort.newMessage(); } w.writeByte(SO_TRANSFER); s.stats.soBroadcastSerializationTimer.start(); w.writeObject(object); s.stats.soBroadcastSerializationTimer.stop(); size = w.finish(); w = null; if (SO_MAX_INVOCATION_DELAY > 0) { soMessageCombiner.sendAccumulatedMessages(); } } catch (IOException e) { if (w != null) { w.finish(e); } System.err.println("SATIN '" + s.ident + "': unable to broadcast a shared object: " + e); } s.stats.soBcasts++; s.stats.soBcastBytes += size; s.stats.soBroadcastTransferTimer.stop(); } /** Broadcast an so invocation */ protected void doBroadcastSharedObjectLRMC(SharedObject object) { IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); if (tmp.length == 0) return; } soLogger.debug("SATIN '" + s.ident + "': broadcasting object: " + object.getObjectId()); s.stats.soBroadcastTransferTimer.start(); s.so.registerMulticast(object, tmp); try { s.stats.soBroadcastSerializationTimer.start(); int id = omc.send(object); omcInfo.registerSend(id); s.stats.soBroadcastSerializationTimer.stop(); } catch (Exception e) { System.err.println("WARNING, SO mcast failed: " + e + " msg: " + e.getMessage()); e.printStackTrace(); } s.stats.soBcasts++; s.stats.soBcastBytes += omc.lastSize(); s.stats.soBroadcastTransferTimer.stop(); } /** Remove a connection to the soSendPort */ protected void removeSOConnection(IbisIdentifier id) { Satin.assertLocked(s); ReceivePortIdentifier r = ports.remove(id); if (r != null) { Communication.disconnect(soSendPort, r); } } /** Fetch a shared object from another node. * If the Invocation record is null, any version is OK, we just test that we have a * version of the object. If it is not null, we try to satisfy the guard of the * invocation record. It might not be satisfied when this method returns, the * guard might depend on more than one shared object. */ protected void fetchObject(String objectId, IbisIdentifier source, InvocationRecord r) throws SOReferenceSourceCrashedException { /* soLogger.debug("SATIN '" + s.ident + "': sending SO request " + (r == null ? "FIRST TIME" : "GUARD")); // first, ask for the object sendSORequest(objectId, source, false); boolean gotIt = waitForSOReply(); if (gotIt) { soLogger.debug("SATIN '" + s.ident + "': received the object after requesting it"); return; } soLogger .debug("SATIN '" + s.ident + "': received NACK, the object is probably already being broadcast to me, WAITING"); */ // got a nack back, the source thinks it sent it to me. // wait for the object to arrive. If it doesn't, demand the object. long start = System.currentTimeMillis(); while (true) { if (System.currentTimeMillis() - start > WAIT_FOR_UPDATES_TIME) break; synchronized (s) { try { s.wait(500); } catch (InterruptedException e) { // Ignore } } s.handleDelayedMessages(); if (r == null) { if (s.so.getSOInfo(objectId) != null) { soLogger.debug("SATIN '" + s.ident + "': received new object from a bcast"); return; // got it! } } else { if (r.guard()) { soLogger.debug("SATIN '" + s.ident + "': received object, guard satisfied"); return; } } } soLogger.debug("SATIN '" + s.ident + "': did not receive object in time, demanding it now"); // haven't got it, demand it now. sendSORequest(objectId, source, true); boolean gotIt = waitForSOReply(); if (gotIt) { soLogger.debug("SATIN '" + s.ident + "': received demanded object"); return; } soLogger .fatal("SATIN '" + s.ident + "': internal error: did not receive shared object after I demanded it. "); } private void sendSORequest(String objectId, IbisIdentifier source, boolean demand) throws SOReferenceSourceCrashedException { // request the shared object from the source WriteMessage w = null; try { s.lb.setCurrentVictim(source); Victim v; synchronized (s) { v = s.victims.getVictim(source); } if (v == null) { // hm we've got a problem here // push the job somewhere else? soLogger.error("SATIN '" + s.ident + "': could not " + "write shared-object request"); throw new SOReferenceSourceCrashedException(); } w = v.newMessage(); if (demand) { w.writeByte(SO_DEMAND); } else { w.writeByte(SO_REQUEST); } w.writeString(objectId); v.finish(w); } catch (IOException e) { if (w != null) { w.finish(e); } // hm we've got a problem here // push the job somewhere else? soLogger.error("SATIN '" + s.ident + "': could not " + "write shared-object request", e); throw new SOReferenceSourceCrashedException(); } } private boolean waitForSOReply() throws SOReferenceSourceCrashedException { // wait for the reply // there are three possibilities: // 1. we get the object back -> return true // 2. we get a nack back -> return false // 3. the source crashed -> exception while (true) { synchronized (s) { if (sharedObject != null) { s.so.addObject(sharedObject); sharedObject = null; s.currentVictimCrashed = false; soLogger.info("SATIN '" + s.ident + "': received shared object"); return true; } if (s.currentVictimCrashed) { s.currentVictimCrashed = false; // the source has crashed, abort the job soLogger.info("SATIN '" + s.ident + "': source crashed while waiting for SO reply"); throw new SOReferenceSourceCrashedException(); } if (receivedNack) { receivedNack = false; s.currentVictimCrashed = false; soLogger.info("SATIN '" + s.ident + "': received shared object NACK"); return false; } try { s.wait(); } catch (Exception e) { // ignore } } } } boolean broadcastInProgress(SharedObjectInfo info, IbisIdentifier dest) { if (System.currentTimeMillis() - info.lastBroadcastTime > WAIT_FOR_UPDATES_TIME) { return false; } for (int i = 0; i < info.destinations.length; i++) { if (info.destinations[i].equals(dest)) return true; } return false; } protected void handleSORequests() { WriteMessage wm = null; IbisIdentifier origin; String objid; boolean demand; while (true) { Victim v; synchronized (s) { if (s.so.SORequestList.getCount() == 0) { s.so.gotSORequests = false; return; } origin = s.so.SORequestList.getRequester(0); objid = s.so.SORequestList.getobjID(0); demand = s.so.SORequestList.isDemand(0); s.so.SORequestList.removeIndex(0); v = s.victims.getVictim(origin); } if (v == null) { soLogger.debug("SATIN '" + s.ident + "': vicim crached in handleSORequest"); continue; // node might have crashed } SharedObjectInfo info = s.so.getSOInfo(objid); if (ASSERTS && info == null) { soLogger.fatal("SATIN '" + s.ident + "': EEEK, requested shared object: " + objid + " not found! Exiting.."); System.exit(1); // Failed assertion } if (!demand && broadcastInProgress(info, v.getIdent())) { soLogger.debug("SATIN '" + s.ident + "': send NACK back in handleSORequest"); // send NACK back try { wm = v.newMessage(); wm.writeByte(SO_NACK); v.finish(wm); } catch (IOException e) { if (wm != null) { wm.finish(e); } soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object NACK", e); } continue; } soLogger.debug("SATIN '" + s.ident + "': send object back in handleSORequest"); sendObjectBack(v, info); } } private void sendObjectBack(Victim v, SharedObjectInfo info) { WriteMessage wm = null; long size; // No need to hold the lock while writing the object. // Updates cannot change the state of the object during the send, // they are delayed until safe a point. s.stats.soTransferTimer.start(); SharedObject so = info.sharedObject; try { wm = v.newMessage(); wm.writeByte(SO_TRANSFER); } catch (IOException e) { if (wm != null) { wm.finish(e); } soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); s.stats.soTransferTimer.stop(); return; } s.stats.soSerializationTimer.start(); try { wm.writeObject(so); } catch (IOException e) { wm.finish(e); soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); s.stats.soSerializationTimer.stop(); s.stats.soTransferTimer.stop(); return; } s.stats.soSerializationTimer.stop(); try { size = v.finish(wm); } catch (IOException e) { wm.finish(e); soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); s.stats.soTransferTimer.stop(); return; } s.stats.soTransfers++; s.stats.soTransfersBytes += size; s.stats.soTransferTimer.stop(); } protected void handleSORequest(ReadMessage m, boolean demand) { String objid = null; IbisIdentifier origin = m.origin().ibisIdentifier(); soLogger.info("SATIN '" + s.ident + "': got so request"); try { objid = m.readString(); // no need to finish the message. We don't do any communication } catch (IOException e) { soLogger.warn("SATIN '" + s.ident + "': got exception while reading" + " shared object request: " + e.getMessage()); } synchronized (s) { s.so.addToSORequestList(origin, objid, demand); } } /** * Receive a shared object from another node (called by the MessageHandler */ protected void handleSOTransfer(ReadMessage m) { // normal so transfer (not exportObject) SharedObject obj = null; s.stats.soDeserializationTimer.start(); try { obj = (SharedObject) m.readObject(); } catch (IOException e) { soLogger.error("SATIN '" + s.ident + "': got exception while reading" + " shared object", e); } catch (ClassNotFoundException e) { soLogger.error("SATIN '" + s.ident + "': got exception while reading" + " shared object", e); } s.stats.soDeserializationTimer.stop(); // no need to finish the read message here. // We don't block and don't do any communication synchronized (s) { sharedObject = obj; s.notifyAll(); } } protected void handleSONack(ReadMessage m) { synchronized (s) { receivedNack = true; s.notifyAll(); } } private void connectSOSendPort(IbisIdentifier ident) { ReceivePortIdentifier r = Communication.connect(soSendPort, ident, "satin so receiveport for " + s.ident, Satin.CONNECT_TIMEOUT); if (r != null) { synchronized (s) { ports.put(ident, r); } } else { soLogger.warn("SATIN '" + s.ident + "': unable to connect to SO receive port "); // We won't broadcast the object to this receiver. // This is not really a problem, it will get the object if it // needs it. But the node has probably crashed anyway. return; } } private void connectSendPortToNewReceivers() { IbisIdentifier[] tmp; synchronized (s) { tmp = new IbisIdentifier[toConnect.size()]; for (int i = 0; i < toConnect.size(); i++) { tmp[i] = toConnect.get(i); } toConnect.clear(); } // do not keep the lock during connection setup for (int i = 0; i < tmp.length; i++) { connectSOSendPort(tmp[i]); } } public void handleMyOwnJoin() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { omc.addIbis(s.ident); } } public void handleCrash(IbisIdentifier id) { if (LABEL_ROUTING_MCAST) { omc.removeIbis(id); omc.setDestination(s.victims.getIbises()); } } protected void exit() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { omc.done(); omcInfo.end(); } } static class AsyncBcaster extends Thread { private SOCommunication c; private SOInvocationRecord r; AsyncBcaster(SOCommunication c, SOInvocationRecord r) { this.c = c; this.r = r; } public void run() { c.doBroadcastSOInvocation(r); } } }
git-svn-id: http://gforge.cs.vu.nl/svn/ibis/ibis/trunk@5875 aaf88347-d911-0410-b711-e54d386773bb
src/ibis/satin/impl/sharedObjects/SOCommunication.java
<ide><path>rc/ibis/satin/impl/sharedObjects/SOCommunication.java <ide> wm = v.newMessage(); <ide> wm.writeByte(SO_TRANSFER); <ide> } catch (IOException e) { <add> s.stats.soTransferTimer.stop(); <ide> if (wm != null) { <ide> wm.finish(e); <ide> } <ide> soLogger.error("SATIN '" + s.ident <ide> + "': got exception while sending" + " shared object", e); <del> s.stats.soTransferTimer.stop(); <ide> return; <ide> } <ide> <ide> try { <ide> wm.writeObject(so); <ide> } catch (IOException e) { <add> s.stats.soSerializationTimer.stop(); <add> s.stats.soTransferTimer.stop(); <ide> wm.finish(e); <ide> soLogger.error("SATIN '" + s.ident <ide> + "': got exception while sending" + " shared object", e); <del> s.stats.soSerializationTimer.stop(); <del> s.stats.soTransferTimer.stop(); <ide> return; <ide> } <ide> s.stats.soSerializationTimer.stop(); <ide> try { <ide> size = v.finish(wm); <ide> } catch (IOException e) { <add> s.stats.soTransferTimer.stop(); <ide> wm.finish(e); <ide> soLogger.error("SATIN '" + s.ident <ide> + "': got exception while sending" + " shared object", e); <del> s.stats.soTransferTimer.stop(); <ide> return; <ide> } <ide>
Java
bsd-2-clause
812304f86924ea663c512c2061aefbcba76e5537
0
MinELenI/CBSviewer,mprins/CBSviewer,mprins/CBSviewer,mprins/CBSviewer,MinELenI/CBSviewer,MinELenI/CBSviewer
/* * Copyright (c) 2012, Dienst Landelijk Gebied - Ministerie van Economische Zaken * * Gepubliceerd onder de BSD 2-clause licentie, * zie https://github.com/MinELenI/CBSviewer/blob/master/LICENSE.md voor de volledige licentie. */ package nl.mineleni.cbsviewer.servlet.wms; import static nl.mineleni.cbsviewer.util.StringConstants.MAP_CACHE_DIR; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_BGMAP; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_CACHEDIR; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_FEATUREINFO; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_KAART; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_LEGENDAS; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_MAPID; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.RescaleOp; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.imageio.ImageIO; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import nl.mineleni.cbsviewer.servlet.AbstractWxSServlet; import nl.mineleni.cbsviewer.servlet.wms.cache.BboxLayerCacheKey; import nl.mineleni.cbsviewer.servlet.wms.cache.CachableString; import nl.mineleni.cbsviewer.servlet.wms.cache.Cache; import nl.mineleni.cbsviewer.servlet.wms.cache.CacheImage; import nl.mineleni.cbsviewer.servlet.wms.cache.WMSCache; import nl.mineleni.cbsviewer.util.AvailableLayersBean; import nl.mineleni.cbsviewer.util.SpatialUtil; import nl.mineleni.cbsviewer.util.xml.LayerDescriptor; import org.geotools.data.ows.Layer; import org.geotools.data.ows.WMSCapabilities; import org.geotools.data.wms.WMSUtils; import org.geotools.data.wms.WebMapServer; import org.geotools.data.wms.request.GetFeatureInfoRequest; import org.geotools.data.wms.request.GetLegendGraphicRequest; import org.geotools.data.wms.request.GetMapRequest; import org.geotools.data.wms.response.GetFeatureInfoResponse; import org.geotools.data.wms.response.GetLegendGraphicResponse; import org.geotools.data.wms.response.GetMapResponse; import org.geotools.ows.ServiceException; import org.opengis.geometry.BoundingBox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * WMS client voor de applicatie. * * @author prinsmc */ public class WMSClientServlet extends AbstractWxSServlet { /** maximum aantal elementen per cache. {@value} */ private static final int NUMBER_CACHE_ELEMENTS = 1000; /** logger. */ private static final Logger LOGGER = LoggerFactory .getLogger(WMSClientServlet.class); /** * vaste afmeting van de kaart (hoogte en breedte). {@value} * * @see #MAP_DIMENSION_MIDDLE */ private static final int MAP_DIMENSION = 440; /** * helft van de afmeting van de kaart (hoogte en breedte). {@value} * * @see #MAP_DIMENSION */ private static final int MAP_DIMENSION_MIDDLE = MAP_DIMENSION / 2; /** time-to-live voor cache elementen. {@value} */ private static final long SECONDS_TO_CACHE_ELEMENTS = 60 * 60/* 1 uur */; /** time-to-live voor cache elementen. {@value} */ private static final long MILLISECONDS_TO_CACHE_ELEMENTS = SECONDS_TO_CACHE_ELEMENTS * 1000; /** serialVersionUID. */ private static final long serialVersionUID = 4958212343847516071L; /** De achtergrond kaart WMS. */ private transient WebMapServer bgWMS = null; /** cache voor legenda afbeeldingen. */ private transient Cache<String, CacheImage, BufferedImage> legendCache = null; /** cache voor voorgrond WMS afbeeldingen. */ private transient Cache<BboxLayerCacheKey, CacheImage, BufferedImage> fgWMSCache = null; /** cache voor feature info. */ private transient Cache<BboxLayerCacheKey, CachableString, String> featInfoCache = null; /** verzameling lagen voor de achtergrondkaart. */ private String[] bgWMSlayers = null; /** * voorgrond wms request. * * @todo refactor naar lokale variabele */ private transient GetMapRequest getMapRequest = null; /** layers bean. */ private final transient AvailableLayersBean layers = new AvailableLayersBean(); /** cache voor achtergrond kaartjes. */ private transient WMSCache bgWMSCache = null; /** De achtergrond luchtfoto WMS. */ private transient WebMapServer lufoWMS = null; /** cache voor achtergrond kaartjes. */ private transient WMSCache bgWMSLuFoCache = null; /** verzameling lagen voor de achtergrondkaart. */ private String[] lufoWMSlayers = null; /** * de verzameling met (voorgrond) WMSsen die we benaderen. Het opstarten van * een WMS duurt lang vanwege de capabilities uitvraag en versie * onderhandeling. */ private transient Map<String, WebMapServer> wmsServersCache = null; /* * (non-Javadoc) * * @see javax.servlet.GenericServlet#destroy() */ @Override public void destroy() { this.bgWMSCache.clear(); this.bgWMS = null; this.bgWMSLuFoCache.clear(); this.lufoWMS = null; this.wmsServersCache.clear(); this.legendCache.clear(); this.legendCache = null; this.fgWMSCache.clear(); this.fgWMSCache = null; this.featInfoCache.clear(); this.featInfoCache = null; this.getMapRequest = null; super.destroy(); } /** * Achtergrondkaart ophalen en opslaan in de cache. * * @param bbox * the bbox * @param type * the type * @return background/basemap image * @throws ServletException * Geeft aan dat er een fout is opgetreden bij het benaderen van * de achtergrondgrond WMS service */ private BufferedImage getBackGroundMap(final BoundingBox bbox, final BasemapType type) throws ServletException { GetMapRequest map; switch (type) { case luchtfoto: if (this.bgWMSLuFoCache.containsKey(bbox)) { // ophalen uit cache LOGGER.debug("Achtergrond " + type + " afbeelding uit de cache serveren."); return this.bgWMSLuFoCache.getImage(bbox); } map = this.lufoWMS.createGetMapRequest(); if (this.lufoWMSlayers != null) { for (final String lyr : this.lufoWMSlayers) { // per laag toevoegen met de default style map.addLayer(lyr, ""); } } else { // alle lagen toevoegen for (final Layer layer : WMSUtils.getNamedLayers(this.lufoWMS .getCapabilities())) { map.addLayer(layer); } } break; case topografie: // implicit fall thru naar default default: if (this.bgWMSCache.containsKey(bbox)) { // ophalen uit cache LOGGER.debug("Achtergrond " + type + " afbeelding uit de cache serveren."); return this.bgWMSCache.getImage(bbox); } map = this.bgWMS.createGetMapRequest(); if (this.bgWMSlayers != null) { for (final String lyr : this.bgWMSlayers) { // per laag toevoegen met de default style map.addLayer(lyr, ""); } } else { // alle lagen toevoegen for (final Layer layer : WMSUtils.getNamedLayers(this.bgWMS .getCapabilities())) { map.addLayer(layer); } } } map.setFormat("image/png"); map.setDimensions(MAP_DIMENSION, MAP_DIMENSION); map.setTransparent(true); map.setBGColour("0xffffff"); map.setExceptions("application/vnd.ogc.se_inimage"); map.setSRS("EPSG:28992"); map.setBBox(bbox); LOGGER.debug("Achtergrond WMS url is: " + map.getFinalURL()); try { final GetMapResponse response = this.bgWMS.issueRequest(map); final BufferedImage image = ImageIO.read(response.getInputStream()); switch (type) { case luchtfoto: this.bgWMSLuFoCache.put(bbox, image, SECONDS_TO_CACHE_ELEMENTS); break; case topografie: default: this.bgWMSCache.put(bbox, image, SECONDS_TO_CACHE_ELEMENTS); break; } if (LOGGER.isDebugEnabled()) { // achtergrond plaatje bewaren in debug modus final File temp = File.createTempFile( "bgwms", ".png", new File(this.getServletContext().getRealPath( MAP_CACHE_DIR.code))); temp.deleteOnExit(); ImageIO.write(image, "png", temp); } return image; } catch (ServiceException | IOException e) { LOGGER.error( "Er is een fout opgetreden bij het benaderen van de achtergrond WMS service.", e); throw new ServletException(e); } } /** * zoekt of maakt de gevraagde WebMapServer. * * @param lyrDesc * de layerdescriptor met de WMS informatie * @return the cached wms * @throws ServiceException * the service exception * @throws IOException * Signals that an I/O exception has occurred. */ private WebMapServer getCachedWMS(final LayerDescriptor lyrDesc) throws ServiceException, IOException { if (this.wmsServersCache.containsKey(lyrDesc.getUrl())) { LOGGER.debug("WMS gevonden in cache."); return this.wmsServersCache.get(lyrDesc.getUrl()); } else { LOGGER.debug("Aanmaken van nieuwe WMS (inclusief versie onderhandeling)."); final WebMapServer fgWMS = new WebMapServer(new URL( lyrDesc.getUrl())); this.wmsServersCache.put(lyrDesc.getUrl(), fgWMS); return fgWMS; } } /** * Haalt de feature info op. * * @param bbox * the bbox * @param lyrDesc * de layerdescriptor met de WMS informatie * @return Een string met feature info * @throws ServiceException * Geeft aan dat er een fout is opgetreden tijden het benaderen * van de WMS * @throws IOException * Signals that an I/O exception has occurred. */ private String getFeatureInfo(final BoundingBox bbox, final LayerDescriptor lyrDesc) throws ServiceException, IOException { final BboxLayerCacheKey key = new BboxLayerCacheKey(bbox, lyrDesc); if (this.featInfoCache.containsKey(key)) { // ophalen uit cache final String fInfo = this.featInfoCache.get(key).getItem(); if (null != fInfo) { // dit kan null zijn in het geval het item verlopen is LOGGER.debug("FeatureInfo uit de cache serveren."); return fInfo; } } try { final GetFeatureInfoRequest getFeatureInfoRequest = this .getCachedWMS(lyrDesc).createGetFeatureInfoRequest( this.getMapRequest); final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); final Set<Layer> queryLayers = new HashSet<Layer>(); final WMSCapabilities caps = this.getCachedWMS(lyrDesc) .getCapabilities(); for (final Layer wmsLyr : caps.getLayerList()) { if ((wmsLyr.getName() != null) && (wmsLyr.getName().length() != 0)) { for (final String layerName : layerNames) { if (wmsLyr.getName().equalsIgnoreCase(layerName)) { queryLayers.add(wmsLyr); } } } } getFeatureInfoRequest.setQueryLayers(queryLayers); getFeatureInfoRequest.setInfoFormat("application/vnd.ogc.gml"); getFeatureInfoRequest.setFeatureCount(10); getFeatureInfoRequest.setQueryPoint(MAP_DIMENSION_MIDDLE, MAP_DIMENSION_MIDDLE); LOGGER.debug("WMS feature info request url is: " + getFeatureInfoRequest.getFinalURL()); final GetFeatureInfoResponse response = this.getCachedWMS(lyrDesc) .issueRequest(getFeatureInfoRequest); final String html = FeatureInfoResponseConverter .convertToHTMLTable(response.getInputStream(), FeatureInfoResponseConverter.Type.GMLTYPE, lyrDesc .getAttributes().split(",\\s*")); this.featInfoCache.put(key, new CachableString(html, System.currentTimeMillis() + MILLISECONDS_TO_CACHE_ELEMENTS)); return html; } catch (final UnsupportedOperationException u) { LOGGER.warn("De WMS server (" + this.getCachedWMS(lyrDesc).getInfo().getTitle() + ") ondersteund geen GetFeatureInfoRequest.", u); return ""; } } /** * voorgrondkaart ophalen. * * @param bbox * the bbox * @param lyrDesc * de layerdescriptor met de WMS informatie * @return voorgrond afbeelding * @throws ServletException * Geeft aan dat er een fout is opgetreden bij het benaderen van * de voorgrond WMS service */ private BufferedImage getForeGroundMap(final BoundingBox bbox, final LayerDescriptor lyrDesc) throws ServletException { final BboxLayerCacheKey key = new BboxLayerCacheKey(bbox, lyrDesc); if (this.fgWMSCache.containsKey(key)) { // ophalen uit cache final BufferedImage image = this.fgWMSCache.get(key).getImage(); if (null != image) { LOGGER.debug("Voorgrond afbeelding uit de cache serveren."); return image; } } // wms request doen try { this.getMapRequest = this.getCachedWMS(lyrDesc) .createGetMapRequest(); final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); final String[] styleNames = lyrDesc.getStyles().split(",\\s*"); for (int l = 0; l < layerNames.length; l++) { this.getMapRequest.addLayer(layerNames[l], styleNames[l]); } this.getMapRequest.setFormat("image/png"); this.getMapRequest.setDimensions(MAP_DIMENSION, MAP_DIMENSION); this.getMapRequest.setTransparent(true); this.getMapRequest.setSRS("EPSG:28992"); this.getMapRequest.setBBox(bbox); this.getMapRequest.setExceptions("application/vnd.ogc.se_inimage"); this.getMapRequest.setBGColour("0xffffff"); LOGGER.debug("Voorgrond WMS url is: " + this.getMapRequest.getFinalURL()); // thema/voorgrond ophalen final GetMapResponse response = this.getCachedWMS(lyrDesc) .issueRequest(this.getMapRequest); final BufferedImage image = ImageIO.read(response.getInputStream()); this.fgWMSCache.put(key, new CacheImage(image, SECONDS_TO_CACHE_ELEMENTS)); if (LOGGER.isDebugEnabled()) { // voorgrond plaatje bewaren in debug modus final File temp = File.createTempFile( "fgwms", ".png", new File(this.getServletContext().getRealPath( MAP_CACHE_DIR.code))); temp.deleteOnExit(); ImageIO.write(image, "png", temp); } return image; } catch (ServiceException | IOException e) { LOGGER.error( "Er is een fout opgetreden bij het benaderen van de voorgrond WMS service.", e); throw new ServletException(e); } } /** * Haalt de legenda op voor de thema laag. * * @param lyrDesc * de layerdescriptor met de WMS informatie * @return een array met legenda afbeeldings bestanden * @throws ServiceException * Geeft aan dat er een fout is opgetreden tijden het benaderen * van de WMS * @throws IOException * Signals that an I/O exception has occurred. */ private File[] getLegends(final LayerDescriptor lyrDesc) throws ServiceException, IOException { final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); final String[] styleNames = lyrDesc.getStyles().split(",\\s*"); final File[] legends = new File[layerNames.length]; try { final GetLegendGraphicRequest legend = this.getCachedWMS(lyrDesc) .createGetLegendGraphicRequest(); BufferedImage image; for (int l = 0; l < layerNames.length; l++) { final String key = layerNames[l] + "::" + styleNames[l]; if (this.legendCache.containsKey(key)) { // in de cache kijken of we deze legenda afbeelding al // hebben final String fname = this.legendCache.get(key).getName(); if (null != fname) { legends[l] = new File(fname); if (!legends[l].exists()) { // (mogelijk) is het bestand gewist.. ImageIO.write(this.legendCache.get(key).getImage(), "png", legends[l]); } LOGGER.debug("Legenda bestand uit cache: " + legends[l].getAbsolutePath()); } } else { // legenda opvragen legend.setLayer(layerNames[l]); legend.setStyle(styleNames[l]); legend.setFormat("image/png"); legend.setExceptions("application/vnd.ogc.se_inimage"); LOGGER.debug("Voorgrond WMS legenda url is: " + legend.getFinalURL()); final GetLegendGraphicResponse response = this .getCachedWMS(lyrDesc).issueRequest(legend); image = ImageIO.read(response.getInputStream()); legends[l] = File.createTempFile( "legenda", ".png", new File(this.getServletContext().getRealPath( MAP_CACHE_DIR.code))); legends[l].deleteOnExit(); this.legendCache .put(key, new CacheImage( image, legends[l].getAbsolutePath(), System.currentTimeMillis() + (MILLISECONDS_TO_CACHE_ELEMENTS * 24))); LOGGER.debug("Legenda bestand: " + legends[l].getAbsolutePath()); ImageIO.write(image, "png", legends[l]); } } } catch (final UnsupportedOperationException u) { LOGGER.warn("De WMS server (" + this.getCachedWMS(lyrDesc).getInfo().getTitle() + ") ondersteund geen GetLegendGraphicRequest.", u); return null; } return legends; } /** * kaart maken op basis van de opgehaalde afbeeldingen. * * @param imageVoorgrond * de voorgrondkaart * @param imageAchtergrond * de achtergrondgrondkaart * @return de file met de afbeelding * @throws IOException * Signals that an I/O exception has occurred. */ private File getMap(final BufferedImage imageVoorgrond, final BufferedImage imageAchtergrond) throws IOException { final BufferedImage composite = new BufferedImage(MAP_DIMENSION, MAP_DIMENSION, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = composite.createGraphics(); g.drawImage(imageAchtergrond, 0, 0, null); if (imageVoorgrond != null) { final float[] scales = { 1f, 1f, 1f, 0.8f }; final RescaleOp rop = new RescaleOp(scales, new float[4], null); g.drawImage(imageVoorgrond, rop, 0, 0); // zoeklocatie intekenen met plaatje final BufferedImage infoImage = ImageIO.read(new File(this .getClass().getClassLoader().getResource("info.png") .getFile())); // CHECKSTYLE.OFF: MagicNumber - dit zijn midden en hoogte van het // plaatje "info.png" g.drawImage(infoImage, MAP_DIMENSION_MIDDLE - 16, MAP_DIMENSION_MIDDLE - 37, null); // CHECKSTYLE.ON: MagicNumber } // opslaan van plaatje zodat de browser het op kan halen final File kaartAfbeelding = File.createTempFile( "wmscombined", ".png", new File(this.getServletContext().getRealPath( MAP_CACHE_DIR.code))); kaartAfbeelding.deleteOnExit(); ImageIO.write(composite, "png", kaartAfbeelding); g.dispose(); return kaartAfbeelding; } /* * (non-Javadoc) * * @see * nl.mineleni.cbsviewer.servlet.AbstractBaseServlet#init(javax.servlet. * ServletConfig) */ @Override public void init(final ServletConfig config) throws ServletException { super.init(config); try { this.bgWMSCache = new WMSCache(this.getServletContext() .getRealPath(MAP_CACHE_DIR.code), NUMBER_CACHE_ELEMENTS); } catch (final IOException e) { LOGGER.error( "Inititalisatie fout voor de achtergrond topografie cache.", e); } try { this.bgWMSLuFoCache = new WMSCache(this.getServletContext() .getRealPath(MAP_CACHE_DIR.code), NUMBER_CACHE_ELEMENTS); } catch (final IOException e) { LOGGER.error( "Inititalisatie fout voor de achtergrond luchtfoto cache.", e); } this.legendCache = new Cache<String, CacheImage, BufferedImage>( NUMBER_CACHE_ELEMENTS); this.featInfoCache = new Cache<BboxLayerCacheKey, CachableString, String>( NUMBER_CACHE_ELEMENTS); this.fgWMSCache = new Cache<BboxLayerCacheKey, CacheImage, BufferedImage>( NUMBER_CACHE_ELEMENTS); // achtergrond kaart final String bgCapabilitiesURL = config .getInitParameter("bgCapabilitiesURL"); LOGGER.debug("WMS capabilities url van achtergrond kaart: " + bgCapabilitiesURL); try { this.bgWMS = new WebMapServer(new URL(bgCapabilitiesURL)); } catch (final MalformedURLException e) { LOGGER.error( "Een url die gebruikt wordt voor de topografie WMS capabilities is misvormd", e); throw new ServletException(e); } catch (final ServiceException e) { LOGGER.error( "Er is een service exception (WMS server fout) opgetreden bij het ophalen van de topografie WMS capabilities", e); throw new ServletException(e); } catch (final IOException e) { LOGGER.error( "Er is een I/O fout opgetreden bij benaderen van de topografie WMS services", e); throw new ServletException(e); } final String bgWMSlyrs = config.getInitParameter("bgWMSlayers"); LOGGER.debug("Achtergrond kaartlagen topografie: " + bgWMSlyrs); if ((bgWMSlyrs != null) && (bgWMSlyrs.length() > 0)) { this.bgWMSlayers = bgWMSlyrs.split("[,]\\s*"); } // achtergrond luchtfoto final String lufoCapabilitiesURL = config .getInitParameter("lufoCapabilitiesURL"); LOGGER.debug("WMS capabilities url van achtergrond luchtfoto: " + lufoCapabilitiesURL); try { this.lufoWMS = new WebMapServer(new URL(lufoCapabilitiesURL)); } catch (final MalformedURLException e) { LOGGER.error( "De url die gebruikt wordt voor de luchtfoto WMS capabilities is misvormd", e); throw new ServletException(e); } catch (final ServiceException e) { LOGGER.error( "Er is een service exception (WMS server fout) opgetreden bij het ophalen van de luchtfoto WMS capabilities", e); throw new ServletException(e); } catch (final IOException e) { LOGGER.error( "Er is een I/O fout opgetreden bij benaderen van de luchtfoto WMS services", e); throw new ServletException(e); } final String lufoWMSlyrs = config.getInitParameter("lufoWMSlayers"); LOGGER.debug("Achtergrond kaartlagen luchtfoto: " + lufoWMSlyrs); if ((lufoWMSlyrs != null) && (lufoWMSlyrs.length() > 0)) { this.lufoWMSlayers = lufoWMSlyrs.split("[,]\\s*"); } // init servers cache this.wmsServersCache = new ConcurrentHashMap<String, WebMapServer>(); } /* * (non-Javadoc) * * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest, * javax.servlet.ServletResponse) */ @Override protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final int[] dXcoordYCoordStraal = this.parseLocation(request); final int xcoord = dXcoordYCoordStraal[0]; final int ycoord = dXcoordYCoordStraal[1]; final int straal = dXcoordYCoordStraal[2]; final BoundingBox bbox = SpatialUtil.calcRDBBOX(xcoord, ycoord, straal); BasemapType basemaptype = BasemapType.topografie; final String mType = request.getParameter(REQ_PARAM_BGMAP.code); if (this.isNotNullNotEmptyNotWhiteSpaceOnly(mType)) { try { basemaptype = BasemapType.valueOf(mType); } catch (final IllegalArgumentException e) { LOGGER.debug("Ongeldige waarde gebruikt voor basemap type, de default wordt gebruikt."); } } final BufferedImage bg = this.getBackGroundMap(bbox, basemaptype); BufferedImage fg = null; final String mapId = request.getParameter(REQ_PARAM_MAPID.code); if (this.isNotNullNotEmptyNotWhiteSpaceOnly(mapId)) { final LayerDescriptor layer = this.layers.getLayerByID(mapId); request.setAttribute("mapname", layer.getName()); LOGGER.debug("LayerDescriptor::Name is: " + layer.getName()); final String fgCapabilitiesURL = layer.getUrl(); LOGGER.debug("WMS capabilities url van voorgrond kaart: " + fgCapabilitiesURL); try { fg = this.getForeGroundMap(bbox, layer); final File[] legendas = this.getLegends(layer); final String fInfo = this.getFeatureInfo(bbox, layer); request.setAttribute(REQ_PARAM_MAPID.code, mapId); request.setAttribute(REQ_PARAM_LEGENDAS.code, legendas); request.setAttribute(REQ_PARAM_FEATUREINFO.code, fInfo); } catch (final ServiceException e) { LOGGER.error( "Er is een service exception opgetreden bij benaderen van de voorgrond WMS", e); throw new ServletException(e); } catch (final MalformedURLException e) { LOGGER.error( "De url die gebruikt wordt voor de WMS capabilities is misvormd.", e); throw new ServletException(e); } } final File kaart = this.getMap(fg, bg); request.setAttribute(REQ_PARAM_CACHEDIR.code, MAP_CACHE_DIR.code); request.setAttribute(REQ_PARAM_KAART.code, kaart); request.setAttribute(REQ_PARAM_BGMAP.code, basemaptype); } }
src/main/java/nl/mineleni/cbsviewer/servlet/wms/WMSClientServlet.java
/* * Copyright (c) 2012, Dienst Landelijk Gebied - Ministerie van Economische Zaken * * Gepubliceerd onder de BSD 2-clause licentie, * zie https://github.com/MinELenI/CBSviewer/blob/master/LICENSE.md voor de volledige licentie. */ package nl.mineleni.cbsviewer.servlet.wms; import static nl.mineleni.cbsviewer.util.StringConstants.MAP_CACHE_DIR; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_BGMAP; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_CACHEDIR; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_FEATUREINFO; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_KAART; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_LEGENDAS; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_MAPID; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.RescaleOp; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.imageio.ImageIO; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import nl.mineleni.cbsviewer.servlet.AbstractWxSServlet; import nl.mineleni.cbsviewer.servlet.wms.cache.BboxLayerCacheKey; import nl.mineleni.cbsviewer.servlet.wms.cache.CachableString; import nl.mineleni.cbsviewer.servlet.wms.cache.Cache; import nl.mineleni.cbsviewer.servlet.wms.cache.CacheImage; import nl.mineleni.cbsviewer.servlet.wms.cache.WMSCache; import nl.mineleni.cbsviewer.util.AvailableLayersBean; import nl.mineleni.cbsviewer.util.SpatialUtil; import nl.mineleni.cbsviewer.util.xml.LayerDescriptor; import org.geotools.data.ows.Layer; import org.geotools.data.ows.WMSCapabilities; import org.geotools.data.wms.WMSUtils; import org.geotools.data.wms.WebMapServer; import org.geotools.data.wms.request.GetFeatureInfoRequest; import org.geotools.data.wms.request.GetLegendGraphicRequest; import org.geotools.data.wms.request.GetMapRequest; import org.geotools.data.wms.response.GetFeatureInfoResponse; import org.geotools.data.wms.response.GetLegendGraphicResponse; import org.geotools.data.wms.response.GetMapResponse; import org.geotools.ows.ServiceException; import org.opengis.geometry.BoundingBox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * WMS client voor de applicatie. * * @author prinsmc */ public class WMSClientServlet extends AbstractWxSServlet { /** maximum aantal elementen per cache. {@value} */ private static final int NUMBER_CACHE_ELEMENTS = 1000; /** logger. */ private static final Logger LOGGER = LoggerFactory .getLogger(WMSClientServlet.class); /** * vaste afmeting van de kaart (hoogte en breedte). {@value} * * @see #MAP_DIMENSION_MIDDLE */ private static final int MAP_DIMENSION = 440; /** * helft van de afmeting van de kaart (hoogte en breedte). {@value} * * @see #MAP_DIMENSION */ private static final int MAP_DIMENSION_MIDDLE = MAP_DIMENSION / 2; /** time-to-live voor cache elementen. {@value} */ private static final long SECONDS_TO_CACHE_ELEMENTS = 60 * 60/* 1 uur */; /** time-to-live voor cache elementen. {@value} */ private static final long MILLISECONDS_TO_CACHE_ELEMENTS = SECONDS_TO_CACHE_ELEMENTS * 1000; /** serialVersionUID. */ private static final long serialVersionUID = 4958212343847516071L; /** De achtergrond kaart WMS. */ private transient WebMapServer bgWMS = null; /** cache voor legenda afbeeldingen. */ private transient Cache<String, CacheImage, BufferedImage> legendCache = null; /** cache voor voorgrond WMS afbeeldingen. */ private transient Cache<BboxLayerCacheKey, CacheImage, BufferedImage> fgWMSCache = null; /** cache voor feature info. */ private transient Cache<BboxLayerCacheKey, CachableString, String> featInfoCache = null; /** verzameling lagen voor de achtergrondkaart. */ private String[] bgWMSlayers = null; /** * voorgrond wms request. * * @todo refactor naar lokale variabele */ private transient GetMapRequest getMapRequest = null; /** layers bean. */ private final transient AvailableLayersBean layers = new AvailableLayersBean(); /** cache voor achtergrond kaartjes. */ private transient WMSCache bgWMSCache = null; /** De achtergrond luchtfoto WMS. */ private transient WebMapServer lufoWMS = null; /** cache voor achtergrond kaartjes. */ private transient WMSCache bgWMSLuFoCache = null; /** verzameling lagen voor de achtergrondkaart. */ private String[] lufoWMSlayers = null; /** * de verzameling met (voorgrond) WMSsen die we benaderen. Het opstarten van * een WMS duurt lang vanwege de capabilities uitvraag en versie * onderhandeling. */ private transient Map<String, WebMapServer> wmsServersCache = null; /* * (non-Javadoc) * * @see javax.servlet.GenericServlet#destroy() */ @Override public void destroy() { this.bgWMSCache.clear(); this.bgWMS = null; this.bgWMSLuFoCache.clear(); this.lufoWMS = null; this.wmsServersCache.clear(); this.legendCache.clear(); this.legendCache = null; this.fgWMSCache.clear(); this.fgWMSCache = null; this.featInfoCache.clear(); this.featInfoCache = null; this.getMapRequest = null; super.destroy(); } /** * Achtergrondkaart ophalen en opslaan in de cache. * * @param bbox * the bbox * @param type * the type * @return background/basemap image * @throws ServletException * Geeft aan dat er een fout is opgetreden bij het benaderen van * de achtergrondgrond WMS service */ private BufferedImage getBackGroundMap(final BoundingBox bbox, final BasemapType type) throws ServletException { GetMapRequest map; switch (type) { case luchtfoto: if (this.bgWMSLuFoCache.containsKey(bbox)) { // ophalen uit cache LOGGER.debug("Achtergrond " + type + " afbeelding uit de cache serveren."); return this.bgWMSLuFoCache.getImage(bbox); } map = this.lufoWMS.createGetMapRequest(); if (this.lufoWMSlayers != null) { for (final String lyr : this.lufoWMSlayers) { // per laag toevoegen met de default style map.addLayer(lyr, ""); } } else { // alle lagen toevoegen for (final Layer layer : WMSUtils.getNamedLayers(this.lufoWMS .getCapabilities())) { map.addLayer(layer); } } break; case topografie: // implicit fall thru naar default default: if (this.bgWMSCache.containsKey(bbox)) { // ophalen uit cache LOGGER.debug("Achtergrond " + type + " afbeelding uit de cache serveren."); return this.bgWMSCache.getImage(bbox); } map = this.bgWMS.createGetMapRequest(); if (this.bgWMSlayers != null) { for (final String lyr : this.bgWMSlayers) { // per laag toevoegen met de default style map.addLayer(lyr, ""); } } else { // alle lagen toevoegen for (final Layer layer : WMSUtils.getNamedLayers(this.bgWMS .getCapabilities())) { map.addLayer(layer); } } } map.setFormat("image/png"); map.setDimensions(MAP_DIMENSION, MAP_DIMENSION); map.setTransparent(true); map.setBGColour("0xffffff"); map.setExceptions("application/vnd.ogc.se_inimage"); map.setSRS("EPSG:28992"); map.setBBox(bbox); LOGGER.debug("Achtergrond WMS url is: " + map.getFinalURL()); try { final GetMapResponse response = this.bgWMS.issueRequest(map); final BufferedImage image = ImageIO.read(response.getInputStream()); switch (type) { case luchtfoto: this.bgWMSLuFoCache.put(bbox, image, SECONDS_TO_CACHE_ELEMENTS); break; case topografie: default: this.bgWMSCache.put(bbox, image, SECONDS_TO_CACHE_ELEMENTS); break; } if (LOGGER.isDebugEnabled()) { // achtergrond plaatje bewaren in debug modus final File temp = File.createTempFile( "bgwms", ".png", new File(this.getServletContext().getRealPath( MAP_CACHE_DIR.code))); temp.deleteOnExit(); ImageIO.write(image, "png", temp); } return image; } catch (ServiceException | IOException e) { LOGGER.error( "Er is een fout opgetreden bij het benaderen van de achtergrond WMS service.", e); throw new ServletException(e); } } /** * zoekt of maakt de gevraagde WebMapServer. * * @param lyrDesc * de layerdescriptor met de WMS informatie * @return the cached wms * @throws ServiceException * the service exception * @throws IOException * Signals that an I/O exception has occurred. */ private WebMapServer getCachedWMS(final LayerDescriptor lyrDesc) throws ServiceException, IOException { if (this.wmsServersCache.containsKey(lyrDesc.getUrl())) { LOGGER.debug("WMS gevonden in cache."); return this.wmsServersCache.get(lyrDesc.getUrl()); } else { LOGGER.debug("Aanmaken van nieuwe WMS (inclusief versie onderhandeling)."); final WebMapServer fgWMS = new WebMapServer(new URL( lyrDesc.getUrl())); this.wmsServersCache.put(lyrDesc.getUrl(), fgWMS); return fgWMS; } } /** * Haalt de feature info op. * * @param bbox * the bbox * @param lyrDesc * de layerdescriptor met de WMS informatie * @return Een string met feature info * @throws ServiceException * Geeft aan dat er een fout is opgetreden tijden het benaderen * van de WMS * @throws IOException * Signals that an I/O exception has occurred. */ private String getFeatureInfo(final BoundingBox bbox, final LayerDescriptor lyrDesc) throws ServiceException, IOException { final BboxLayerCacheKey key = new BboxLayerCacheKey(bbox, lyrDesc); if (this.featInfoCache.containsKey(key)) { // ophalen uit cache final String fInfo = this.featInfoCache.get(key).getItem(); if (null != fInfo) { // dit kan null zijn in het geval het item verlopen is LOGGER.debug("FeatureInfo uit de cache serveren."); return fInfo; } } try { final GetFeatureInfoRequest getFeatureInfoRequest = this .getCachedWMS(lyrDesc).createGetFeatureInfoRequest( this.getMapRequest); final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); final Set<Layer> queryLayers = new HashSet<Layer>(); final WMSCapabilities caps = this.getCachedWMS(lyrDesc) .getCapabilities(); for (final Layer wmsLyr : caps.getLayerList()) { if ((wmsLyr.getName() != null) && (wmsLyr.getName().length() != 0)) { for (final String layerName : layerNames) { if (wmsLyr.getName().equalsIgnoreCase(layerName)) { queryLayers.add(wmsLyr); } } } } getFeatureInfoRequest.setQueryLayers(queryLayers); getFeatureInfoRequest.setInfoFormat("application/vnd.ogc.gml"); getFeatureInfoRequest.setFeatureCount(10); getFeatureInfoRequest.setQueryPoint(MAP_DIMENSION_MIDDLE, MAP_DIMENSION_MIDDLE); LOGGER.debug("WMS feature info request url is: " + getFeatureInfoRequest.getFinalURL()); final GetFeatureInfoResponse response = this.getCachedWMS(lyrDesc) .issueRequest(getFeatureInfoRequest); final String html = FeatureInfoResponseConverter .convertToHTMLTable(response.getInputStream(), FeatureInfoResponseConverter.Type.GMLTYPE, lyrDesc .getAttributes().split(",\\s*")); this.featInfoCache.put(key, new CachableString(html, System.currentTimeMillis() + MILLISECONDS_TO_CACHE_ELEMENTS)); return html; } catch (final UnsupportedOperationException u) { LOGGER.warn("De WMS server (" + this.getCachedWMS(lyrDesc).getInfo().getTitle() + ") ondersteund geen GetFeatureInfoRequest.", u); return ""; } } /** * voorgrondkaart ophalen. * * @param bbox * the bbox * @param lyrDesc * de layerdescriptor met de WMS informatie * @return voorgrond afbeelding * @throws ServletException * Geeft aan dat er een fout is opgetreden bij het benaderen van * de voorgrond WMS service */ private BufferedImage getForeGroundMap(final BoundingBox bbox, final LayerDescriptor lyrDesc) throws ServletException { final BboxLayerCacheKey key = new BboxLayerCacheKey(bbox, lyrDesc); if (this.fgWMSCache.containsKey(key)) { // ophalen uit cache final BufferedImage image = this.fgWMSCache.get(key).getImage(); if (null != image) { LOGGER.debug("Voorgrond afbeelding uit de cache serveren."); return image; } } // wms request doen try { this.getMapRequest = this.getCachedWMS(lyrDesc) .createGetMapRequest(); final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); final String[] styleNames = lyrDesc.getStyles().split(",\\s*"); for (int l = 0; l < layerNames.length; l++) { this.getMapRequest.addLayer(layerNames[l], styleNames[l]); } this.getMapRequest.setFormat("image/png"); this.getMapRequest.setDimensions(MAP_DIMENSION, MAP_DIMENSION); this.getMapRequest.setTransparent(true); this.getMapRequest.setSRS("EPSG:28992"); this.getMapRequest.setBBox(bbox); this.getMapRequest.setExceptions("application/vnd.ogc.se_inimage"); this.getMapRequest.setBGColour("0xffffff"); LOGGER.debug("Voorgrond WMS url is: " + this.getMapRequest.getFinalURL()); // thema/voorgrond ophalen final GetMapResponse response = this.getCachedWMS(lyrDesc) .issueRequest(this.getMapRequest); final BufferedImage image = ImageIO.read(response.getInputStream()); this.fgWMSCache.put(key, new CacheImage(image, SECONDS_TO_CACHE_ELEMENTS)); if (LOGGER.isDebugEnabled()) { // voorgrond plaatje bewaren in debug modus final File temp = File.createTempFile( "fgwms", ".png", new File(this.getServletContext().getRealPath( MAP_CACHE_DIR.code))); temp.deleteOnExit(); ImageIO.write(image, "png", temp); } return image; } catch (ServiceException | IOException e) { LOGGER.error( "Er is een fout opgetreden bij het benaderen van de achtergrond WMS service.", e); throw new ServletException(e); } } /** * Haalt de legenda op voor de thema laag. * * @param lyrDesc * de layerdescriptor met de WMS informatie * @return een array met legenda afbeeldings bestanden * @throws ServiceException * Geeft aan dat er een fout is opgetreden tijden het benaderen * van de WMS * @throws IOException * Signals that an I/O exception has occurred. */ private File[] getLegends(final LayerDescriptor lyrDesc) throws ServiceException, IOException { final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); final String[] styleNames = lyrDesc.getStyles().split(",\\s*"); final File[] legends = new File[layerNames.length]; try { final GetLegendGraphicRequest legend = this.getCachedWMS(lyrDesc) .createGetLegendGraphicRequest(); BufferedImage image; for (int l = 0; l < layerNames.length; l++) { final String key = layerNames[l] + "::" + styleNames[l]; if (this.legendCache.containsKey(key)) { // in de cache kijken of we deze legenda afbeelding al // hebben String fname = this.legendCache.get(key).getName(); if (null != fname) { legends[l] = new File(fname); if (!legends[l].exists()) { // (mogelijk) is het bestand gewist.. ImageIO.write(this.legendCache.get(key).getImage(), "png", legends[l]); } LOGGER.debug("Legenda bestand uit cache: " + legends[l].getAbsolutePath()); } } else { // legenda opvragen legend.setLayer(layerNames[l]); legend.setStyle(styleNames[l]); legend.setFormat("image/png"); legend.setExceptions("application/vnd.ogc.se_inimage"); LOGGER.debug("Voorgrond WMS legenda url is: " + legend.getFinalURL()); final GetLegendGraphicResponse response = this .getCachedWMS(lyrDesc).issueRequest(legend); image = ImageIO.read(response.getInputStream()); legends[l] = File.createTempFile( "legenda", ".png", new File(this.getServletContext().getRealPath( MAP_CACHE_DIR.code))); legends[l].deleteOnExit(); this.legendCache .put(key, new CacheImage( image, legends[l].getAbsolutePath(), System.currentTimeMillis() + (MILLISECONDS_TO_CACHE_ELEMENTS * 24))); LOGGER.debug("Legenda bestand: " + legends[l].getAbsolutePath()); ImageIO.write(image, "png", legends[l]); } } } catch (final UnsupportedOperationException u) { LOGGER.warn("De WMS server (" + this.getCachedWMS(lyrDesc).getInfo().getTitle() + ") ondersteund geen GetLegendGraphicRequest.", u); return null; } return legends; } /** * kaart maken op basis van de opgehaalde afbeeldingen. * * @param imageVoorgrond * de voorgrondkaart * @param imageAchtergrond * de achtergrondgrondkaart * @return de file met de afbeelding * @throws IOException * Signals that an I/O exception has occurred. */ private File getMap(final BufferedImage imageVoorgrond, final BufferedImage imageAchtergrond) throws IOException { final BufferedImage composite = new BufferedImage(MAP_DIMENSION, MAP_DIMENSION, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = composite.createGraphics(); g.drawImage(imageAchtergrond, 0, 0, null); if (imageVoorgrond != null) { final float[] scales = { 1f, 1f, 1f, 0.8f }; final RescaleOp rop = new RescaleOp(scales, new float[4], null); g.drawImage(imageVoorgrond, rop, 0, 0); // zoeklocatie intekenen met plaatje final BufferedImage infoImage = ImageIO.read(new File(this .getClass().getClassLoader().getResource("info.png") .getFile())); // CHECKSTYLE.OFF: MagicNumber - dit zijn midden en hoogte van het // plaatje "info.png" g.drawImage(infoImage, MAP_DIMENSION_MIDDLE - 16, MAP_DIMENSION_MIDDLE - 37, null); // CHECKSTYLE.ON: MagicNumber } // opslaan van plaatje zodat de browser het op kan halen final File kaartAfbeelding = File.createTempFile( "wmscombined", ".png", new File(this.getServletContext().getRealPath( MAP_CACHE_DIR.code))); kaartAfbeelding.deleteOnExit(); ImageIO.write(composite, "png", kaartAfbeelding); g.dispose(); return kaartAfbeelding; } /* * (non-Javadoc) * * @see * nl.mineleni.cbsviewer.servlet.AbstractBaseServlet#init(javax.servlet. * ServletConfig) */ @Override public void init(final ServletConfig config) throws ServletException { super.init(config); try { this.bgWMSCache = new WMSCache(this.getServletContext() .getRealPath(MAP_CACHE_DIR.code), NUMBER_CACHE_ELEMENTS); } catch (final IOException e) { LOGGER.error( "Inititalisatie fout voor de achtergrond topografie cache.", e); } try { this.bgWMSLuFoCache = new WMSCache(this.getServletContext() .getRealPath(MAP_CACHE_DIR.code), NUMBER_CACHE_ELEMENTS); } catch (final IOException e) { LOGGER.error( "Inititalisatie fout voor de achtergrond luchtfoto cache.", e); } this.legendCache = new Cache<String, CacheImage, BufferedImage>( NUMBER_CACHE_ELEMENTS); this.featInfoCache = new Cache<BboxLayerCacheKey, CachableString, String>( NUMBER_CACHE_ELEMENTS); this.fgWMSCache = new Cache<BboxLayerCacheKey, CacheImage, BufferedImage>( NUMBER_CACHE_ELEMENTS); // achtergrond kaart final String bgCapabilitiesURL = config .getInitParameter("bgCapabilitiesURL"); LOGGER.debug("WMS capabilities url van achtergrond kaart: " + bgCapabilitiesURL); try { this.bgWMS = new WebMapServer(new URL(bgCapabilitiesURL)); } catch (final MalformedURLException e) { LOGGER.error( "Een url die gebruikt wordt voor de topografie WMS capabilities is misvormd", e); throw new ServletException(e); } catch (final ServiceException e) { LOGGER.error( "Er is een service exception (WMS server fout) opgetreden bij het ophalen van de topografie WMS capabilities", e); throw new ServletException(e); } catch (final IOException e) { LOGGER.error( "Er is een I/O fout opgetreden bij benaderen van de topografie WMS services", e); throw new ServletException(e); } final String bgWMSlyrs = config.getInitParameter("bgWMSlayers"); LOGGER.debug("Achtergrond kaartlagen topografie: " + bgWMSlyrs); if ((bgWMSlyrs != null) && (bgWMSlyrs.length() > 0)) { this.bgWMSlayers = bgWMSlyrs.split("[,]\\s*"); } // achtergrond luchtfoto final String lufoCapabilitiesURL = config .getInitParameter("lufoCapabilitiesURL"); LOGGER.debug("WMS capabilities url van achtergrond luchtfoto: " + lufoCapabilitiesURL); try { this.lufoWMS = new WebMapServer(new URL(lufoCapabilitiesURL)); } catch (final MalformedURLException e) { LOGGER.error( "De url die gebruikt wordt voor de luchtfoto WMS capabilities is misvormd", e); throw new ServletException(e); } catch (final ServiceException e) { LOGGER.error( "Er is een service exception (WMS server fout) opgetreden bij het ophalen van de luchtfoto WMS capabilities", e); throw new ServletException(e); } catch (final IOException e) { LOGGER.error( "Er is een I/O fout opgetreden bij benaderen van de luchtfoto WMS services", e); throw new ServletException(e); } final String lufoWMSlyrs = config.getInitParameter("lufoWMSlayers"); LOGGER.debug("Achtergrond kaartlagen luchtfoto: " + lufoWMSlyrs); if ((lufoWMSlyrs != null) && (lufoWMSlyrs.length() > 0)) { this.lufoWMSlayers = lufoWMSlyrs.split("[,]\\s*"); } // init servers cache this.wmsServersCache = new ConcurrentHashMap<String, WebMapServer>(); } /* * (non-Javadoc) * * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest, * javax.servlet.ServletResponse) */ @Override protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final int[] dXcoordYCoordStraal = this.parseLocation(request); final int xcoord = dXcoordYCoordStraal[0]; final int ycoord = dXcoordYCoordStraal[1]; final int straal = dXcoordYCoordStraal[2]; final BoundingBox bbox = SpatialUtil.calcRDBBOX(xcoord, ycoord, straal); BasemapType basemaptype = BasemapType.topografie; final String mType = request.getParameter(REQ_PARAM_BGMAP.code); if (this.isNotNullNotEmptyNotWhiteSpaceOnly(mType)) { try { basemaptype = BasemapType.valueOf(mType); } catch (final IllegalArgumentException e) { LOGGER.debug("Ongeldige waarde gebruikt voor basemap type, de default wordt gebruikt."); } } final BufferedImage bg = this.getBackGroundMap(bbox, basemaptype); BufferedImage fg = null; final String mapId = request.getParameter(REQ_PARAM_MAPID.code); if (this.isNotNullNotEmptyNotWhiteSpaceOnly(mapId)) { final LayerDescriptor layer = this.layers.getLayerByID(mapId); request.setAttribute("mapname", layer.getName()); LOGGER.debug("LayerDescriptor::Name is: " + layer.getName()); final String fgCapabilitiesURL = layer.getUrl(); LOGGER.debug("WMS capabilities url van voorgrond kaart: " + fgCapabilitiesURL); try { fg = this.getForeGroundMap(bbox, layer); final File[] legendas = this.getLegends(layer); final String fInfo = this.getFeatureInfo(bbox, layer); request.setAttribute(REQ_PARAM_MAPID.code, mapId); request.setAttribute(REQ_PARAM_LEGENDAS.code, legendas); request.setAttribute(REQ_PARAM_FEATUREINFO.code, fInfo); } catch (final ServiceException e) { LOGGER.error( "Er is een service exception opgetreden bij benaderen van de voorgrond WMS", e); throw new ServletException(e); } catch (final MalformedURLException e) { LOGGER.error( "De url die gebruikt wordt voor de WMS capabilities is misvormd.", e); throw new ServletException(e); } } final File kaart = this.getMap(fg, bg); request.setAttribute(REQ_PARAM_CACHEDIR.code, MAP_CACHE_DIR.code); request.setAttribute(REQ_PARAM_KAART.code, kaart); request.setAttribute(REQ_PARAM_BGMAP.code, basemaptype); } }
fix typo in logging
src/main/java/nl/mineleni/cbsviewer/servlet/wms/WMSClientServlet.java
fix typo in logging
<ide><path>rc/main/java/nl/mineleni/cbsviewer/servlet/wms/WMSClientServlet.java <ide> */ <ide> public class WMSClientServlet extends AbstractWxSServlet { <ide> <del> /** maximum aantal elementen per cache. {@value} */ <del> private static final int NUMBER_CACHE_ELEMENTS = 1000; <del> <del> /** logger. */ <del> private static final Logger LOGGER = LoggerFactory <del> .getLogger(WMSClientServlet.class); <del> <del> /** <del> * vaste afmeting van de kaart (hoogte en breedte). {@value} <del> * <del> * @see #MAP_DIMENSION_MIDDLE <del> */ <del> private static final int MAP_DIMENSION = 440; <del> <del> /** <del> * helft van de afmeting van de kaart (hoogte en breedte). {@value} <del> * <del> * @see #MAP_DIMENSION <del> */ <del> private static final int MAP_DIMENSION_MIDDLE = MAP_DIMENSION / 2; <del> <del> /** time-to-live voor cache elementen. {@value} */ <del> private static final long SECONDS_TO_CACHE_ELEMENTS = 60 * 60/* 1 uur */; <del> <del> /** time-to-live voor cache elementen. {@value} */ <del> private static final long MILLISECONDS_TO_CACHE_ELEMENTS = SECONDS_TO_CACHE_ELEMENTS * 1000; <del> <del> /** serialVersionUID. */ <del> private static final long serialVersionUID = 4958212343847516071L; <del> <del> /** De achtergrond kaart WMS. */ <del> private transient WebMapServer bgWMS = null; <del> <del> /** cache voor legenda afbeeldingen. */ <del> private transient Cache<String, CacheImage, BufferedImage> legendCache = null; <del> <del> /** cache voor voorgrond WMS afbeeldingen. */ <del> private transient Cache<BboxLayerCacheKey, CacheImage, BufferedImage> fgWMSCache = null; <del> <del> /** cache voor feature info. */ <del> private transient Cache<BboxLayerCacheKey, CachableString, String> featInfoCache = null; <del> <del> /** verzameling lagen voor de achtergrondkaart. */ <del> private String[] bgWMSlayers = null; <del> <del> /** <del> * voorgrond wms request. <del> * <del> * @todo refactor naar lokale variabele <del> */ <del> private transient GetMapRequest getMapRequest = null; <del> <del> /** layers bean. */ <del> private final transient AvailableLayersBean layers = new AvailableLayersBean(); <del> <del> /** cache voor achtergrond kaartjes. */ <del> private transient WMSCache bgWMSCache = null; <del> /** De achtergrond luchtfoto WMS. */ <del> private transient WebMapServer lufoWMS = null; <del> <del> /** cache voor achtergrond kaartjes. */ <del> private transient WMSCache bgWMSLuFoCache = null; <del> /** verzameling lagen voor de achtergrondkaart. */ <del> private String[] lufoWMSlayers = null; <del> <del> /** <del> * de verzameling met (voorgrond) WMSsen die we benaderen. Het opstarten van <del> * een WMS duurt lang vanwege de capabilities uitvraag en versie <del> * onderhandeling. <del> */ <del> private transient Map<String, WebMapServer> wmsServersCache = null; <del> <del> /* <del> * (non-Javadoc) <del> * <del> * @see javax.servlet.GenericServlet#destroy() <del> */ <del> @Override <del> public void destroy() { <del> this.bgWMSCache.clear(); <del> this.bgWMS = null; <del> this.bgWMSLuFoCache.clear(); <del> this.lufoWMS = null; <del> this.wmsServersCache.clear(); <del> this.legendCache.clear(); <del> this.legendCache = null; <del> this.fgWMSCache.clear(); <del> this.fgWMSCache = null; <del> this.featInfoCache.clear(); <del> this.featInfoCache = null; <del> this.getMapRequest = null; <del> super.destroy(); <del> } <del> <del> /** <del> * Achtergrondkaart ophalen en opslaan in de cache. <del> * <del> * @param bbox <del> * the bbox <del> * @param type <del> * the type <del> * @return background/basemap image <del> * @throws ServletException <del> * Geeft aan dat er een fout is opgetreden bij het benaderen van <del> * de achtergrondgrond WMS service <del> */ <del> private BufferedImage getBackGroundMap(final BoundingBox bbox, <del> final BasemapType type) throws ServletException { <del> <del> GetMapRequest map; <del> switch (type) { <del> case luchtfoto: <del> if (this.bgWMSLuFoCache.containsKey(bbox)) { <del> // ophalen uit cache <del> LOGGER.debug("Achtergrond " + type <del> + " afbeelding uit de cache serveren."); <del> return this.bgWMSLuFoCache.getImage(bbox); <del> } <del> map = this.lufoWMS.createGetMapRequest(); <del> if (this.lufoWMSlayers != null) { <del> for (final String lyr : this.lufoWMSlayers) { <del> // per laag toevoegen met de default style <del> map.addLayer(lyr, ""); <del> } <del> } else { <del> // alle lagen toevoegen <del> for (final Layer layer : WMSUtils.getNamedLayers(this.lufoWMS <del> .getCapabilities())) { <del> map.addLayer(layer); <del> } <del> } <del> break; <del> case topografie: <del> // implicit fall thru naar default <del> default: <del> if (this.bgWMSCache.containsKey(bbox)) { <del> // ophalen uit cache <del> LOGGER.debug("Achtergrond " + type <del> + " afbeelding uit de cache serveren."); <del> return this.bgWMSCache.getImage(bbox); <del> } <del> map = this.bgWMS.createGetMapRequest(); <del> if (this.bgWMSlayers != null) { <del> for (final String lyr : this.bgWMSlayers) { <del> // per laag toevoegen met de default style <del> map.addLayer(lyr, ""); <del> } <del> } else { <del> // alle lagen toevoegen <del> for (final Layer layer : WMSUtils.getNamedLayers(this.bgWMS <del> .getCapabilities())) { <del> map.addLayer(layer); <del> } <del> } <del> } <del> <del> map.setFormat("image/png"); <del> map.setDimensions(MAP_DIMENSION, MAP_DIMENSION); <del> map.setTransparent(true); <del> map.setBGColour("0xffffff"); <del> map.setExceptions("application/vnd.ogc.se_inimage"); <del> map.setSRS("EPSG:28992"); <del> map.setBBox(bbox); <del> <del> LOGGER.debug("Achtergrond WMS url is: " + map.getFinalURL()); <del> <del> try { <del> final GetMapResponse response = this.bgWMS.issueRequest(map); <del> final BufferedImage image = ImageIO.read(response.getInputStream()); <del> switch (type) { <del> case luchtfoto: <del> this.bgWMSLuFoCache.put(bbox, image, SECONDS_TO_CACHE_ELEMENTS); <del> <del> break; <del> case topografie: <del> default: <del> this.bgWMSCache.put(bbox, image, SECONDS_TO_CACHE_ELEMENTS); <del> break; <del> } <del> <del> if (LOGGER.isDebugEnabled()) { <del> // achtergrond plaatje bewaren in debug modus <del> final File temp = File.createTempFile( <del> "bgwms", <del> ".png", <del> new File(this.getServletContext().getRealPath( <del> MAP_CACHE_DIR.code))); <del> temp.deleteOnExit(); <del> ImageIO.write(image, "png", temp); <del> } <del> <del> return image; <del> } catch (ServiceException | IOException e) { <del> LOGGER.error( <del> "Er is een fout opgetreden bij het benaderen van de achtergrond WMS service.", <del> e); <del> throw new ServletException(e); <del> } <del> <del> } <del> <del> /** <del> * zoekt of maakt de gevraagde WebMapServer. <del> * <del> * @param lyrDesc <del> * de layerdescriptor met de WMS informatie <del> * @return the cached wms <del> * @throws ServiceException <del> * the service exception <del> * @throws IOException <del> * Signals that an I/O exception has occurred. <del> */ <del> private WebMapServer getCachedWMS(final LayerDescriptor lyrDesc) <del> throws ServiceException, IOException { <del> if (this.wmsServersCache.containsKey(lyrDesc.getUrl())) { <del> LOGGER.debug("WMS gevonden in cache."); <del> return this.wmsServersCache.get(lyrDesc.getUrl()); <del> } else { <del> LOGGER.debug("Aanmaken van nieuwe WMS (inclusief versie onderhandeling)."); <del> final WebMapServer fgWMS = new WebMapServer(new URL( <del> lyrDesc.getUrl())); <del> this.wmsServersCache.put(lyrDesc.getUrl(), fgWMS); <del> return fgWMS; <del> } <del> } <del> <del> /** <del> * Haalt de feature info op. <del> * <del> * @param bbox <del> * the bbox <del> * @param lyrDesc <del> * de layerdescriptor met de WMS informatie <del> * @return Een string met feature info <del> * @throws ServiceException <del> * Geeft aan dat er een fout is opgetreden tijden het benaderen <del> * van de WMS <del> * @throws IOException <del> * Signals that an I/O exception has occurred. <del> */ <del> private String getFeatureInfo(final BoundingBox bbox, <del> final LayerDescriptor lyrDesc) throws ServiceException, IOException { <del> final BboxLayerCacheKey key = new BboxLayerCacheKey(bbox, lyrDesc); <del> if (this.featInfoCache.containsKey(key)) { <del> // ophalen uit cache <del> final String fInfo = this.featInfoCache.get(key).getItem(); <del> if (null != fInfo) { <del> // dit kan null zijn in het geval het item verlopen is <del> LOGGER.debug("FeatureInfo uit de cache serveren."); <del> return fInfo; <del> } <del> } <del> <del> try { <del> final GetFeatureInfoRequest getFeatureInfoRequest = this <del> .getCachedWMS(lyrDesc).createGetFeatureInfoRequest( <del> this.getMapRequest); <del> <del> final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); <del> final Set<Layer> queryLayers = new HashSet<Layer>(); <del> final WMSCapabilities caps = this.getCachedWMS(lyrDesc) <del> .getCapabilities(); <del> <del> for (final Layer wmsLyr : caps.getLayerList()) { <del> if ((wmsLyr.getName() != null) <del> && (wmsLyr.getName().length() != 0)) { <del> for (final String layerName : layerNames) { <del> if (wmsLyr.getName().equalsIgnoreCase(layerName)) { <del> queryLayers.add(wmsLyr); <del> } <del> } <del> } <del> } <del> getFeatureInfoRequest.setQueryLayers(queryLayers); <del> getFeatureInfoRequest.setInfoFormat("application/vnd.ogc.gml"); <del> getFeatureInfoRequest.setFeatureCount(10); <del> getFeatureInfoRequest.setQueryPoint(MAP_DIMENSION_MIDDLE, <del> MAP_DIMENSION_MIDDLE); <del> LOGGER.debug("WMS feature info request url is: " <del> + getFeatureInfoRequest.getFinalURL()); <del> final GetFeatureInfoResponse response = this.getCachedWMS(lyrDesc) <del> .issueRequest(getFeatureInfoRequest); <del> <del> final String html = FeatureInfoResponseConverter <del> .convertToHTMLTable(response.getInputStream(), <del> FeatureInfoResponseConverter.Type.GMLTYPE, lyrDesc <del> .getAttributes().split(",\\s*")); <del> this.featInfoCache.put(key, <del> new CachableString(html, System.currentTimeMillis() <del> + MILLISECONDS_TO_CACHE_ELEMENTS)); <del> return html; <del> <del> } catch (final UnsupportedOperationException u) { <del> LOGGER.warn("De WMS server (" <del> + this.getCachedWMS(lyrDesc).getInfo().getTitle() <del> + ") ondersteund geen GetFeatureInfoRequest.", u); <del> return ""; <del> } <del> } <del> <del> /** <del> * voorgrondkaart ophalen. <del> * <del> * @param bbox <del> * the bbox <del> * @param lyrDesc <del> * de layerdescriptor met de WMS informatie <del> * @return voorgrond afbeelding <del> * @throws ServletException <del> * Geeft aan dat er een fout is opgetreden bij het benaderen van <del> * de voorgrond WMS service <del> */ <del> private BufferedImage getForeGroundMap(final BoundingBox bbox, <del> final LayerDescriptor lyrDesc) throws ServletException { <del> <del> final BboxLayerCacheKey key = new BboxLayerCacheKey(bbox, lyrDesc); <del> if (this.fgWMSCache.containsKey(key)) { <del> // ophalen uit cache <del> final BufferedImage image = this.fgWMSCache.get(key).getImage(); <del> if (null != image) { <del> LOGGER.debug("Voorgrond afbeelding uit de cache serveren."); <del> return image; <del> } <del> } <del> <del> // wms request doen <del> try { <del> this.getMapRequest = this.getCachedWMS(lyrDesc) <del> .createGetMapRequest(); <del> final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); <del> final String[] styleNames = lyrDesc.getStyles().split(",\\s*"); <del> <del> for (int l = 0; l < layerNames.length; l++) { <del> this.getMapRequest.addLayer(layerNames[l], styleNames[l]); <del> } <del> this.getMapRequest.setFormat("image/png"); <del> this.getMapRequest.setDimensions(MAP_DIMENSION, MAP_DIMENSION); <del> this.getMapRequest.setTransparent(true); <del> this.getMapRequest.setSRS("EPSG:28992"); <del> this.getMapRequest.setBBox(bbox); <del> this.getMapRequest.setExceptions("application/vnd.ogc.se_inimage"); <del> this.getMapRequest.setBGColour("0xffffff"); <del> LOGGER.debug("Voorgrond WMS url is: " <del> + this.getMapRequest.getFinalURL()); <del> <del> // thema/voorgrond ophalen <del> final GetMapResponse response = this.getCachedWMS(lyrDesc) <del> .issueRequest(this.getMapRequest); <del> final BufferedImage image = ImageIO.read(response.getInputStream()); <del> <del> this.fgWMSCache.put(key, new CacheImage(image, <del> SECONDS_TO_CACHE_ELEMENTS)); <del> <del> if (LOGGER.isDebugEnabled()) { <del> // voorgrond plaatje bewaren in debug modus <del> final File temp = File.createTempFile( <del> "fgwms", <del> ".png", <del> new File(this.getServletContext().getRealPath( <del> MAP_CACHE_DIR.code))); <del> temp.deleteOnExit(); <del> ImageIO.write(image, "png", temp); <del> } <del> return image; <del> } catch (ServiceException | IOException e) { <del> LOGGER.error( <del> "Er is een fout opgetreden bij het benaderen van de achtergrond WMS service.", <del> e); <del> throw new ServletException(e); <del> } <del> } <del> <del> /** <del> * Haalt de legenda op voor de thema laag. <del> * <del> * @param lyrDesc <del> * de layerdescriptor met de WMS informatie <del> * @return een array met legenda afbeeldings bestanden <del> * @throws ServiceException <del> * Geeft aan dat er een fout is opgetreden tijden het benaderen <del> * van de WMS <del> * @throws IOException <del> * Signals that an I/O exception has occurred. <del> */ <del> private File[] getLegends(final LayerDescriptor lyrDesc) <del> throws ServiceException, IOException { <del> <del> final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); <del> final String[] styleNames = lyrDesc.getStyles().split(",\\s*"); <del> <del> final File[] legends = new File[layerNames.length]; <del> try { <del> final GetLegendGraphicRequest legend = this.getCachedWMS(lyrDesc) <del> .createGetLegendGraphicRequest(); <del> BufferedImage image; <del> for (int l = 0; l < layerNames.length; l++) { <del> final String key = layerNames[l] + "::" + styleNames[l]; <del> if (this.legendCache.containsKey(key)) { <del> // in de cache kijken of we deze legenda afbeelding al <del> // hebben <del> String fname = this.legendCache.get(key).getName(); <del> if (null != fname) { <del> legends[l] = new File(fname); <del> if (!legends[l].exists()) { <del> // (mogelijk) is het bestand gewist.. <del> ImageIO.write(this.legendCache.get(key).getImage(), <del> "png", legends[l]); <del> } <del> LOGGER.debug("Legenda bestand uit cache: " <del> + legends[l].getAbsolutePath()); <del> } <del> } else { <del> // legenda opvragen <del> legend.setLayer(layerNames[l]); <del> legend.setStyle(styleNames[l]); <del> legend.setFormat("image/png"); <del> legend.setExceptions("application/vnd.ogc.se_inimage"); <del> <del> LOGGER.debug("Voorgrond WMS legenda url is: " <del> + legend.getFinalURL()); <del> final GetLegendGraphicResponse response = this <del> .getCachedWMS(lyrDesc).issueRequest(legend); <del> image = ImageIO.read(response.getInputStream()); <del> legends[l] = File.createTempFile( <del> "legenda", <del> ".png", <del> new File(this.getServletContext().getRealPath( <del> MAP_CACHE_DIR.code))); <del> legends[l].deleteOnExit(); <del> this.legendCache <del> .put(key, <del> new CacheImage( <del> image, <del> legends[l].getAbsolutePath(), <del> System.currentTimeMillis() <del> + (MILLISECONDS_TO_CACHE_ELEMENTS * 24))); <del> LOGGER.debug("Legenda bestand: " <del> + legends[l].getAbsolutePath()); <del> ImageIO.write(image, "png", legends[l]); <del> } <del> } <del> } catch (final UnsupportedOperationException u) { <del> LOGGER.warn("De WMS server (" <del> + this.getCachedWMS(lyrDesc).getInfo().getTitle() <del> + ") ondersteund geen GetLegendGraphicRequest.", u); <del> return null; <del> } <del> return legends; <del> } <del> <del> /** <del> * kaart maken op basis van de opgehaalde afbeeldingen. <del> * <del> * @param imageVoorgrond <del> * de voorgrondkaart <del> * @param imageAchtergrond <del> * de achtergrondgrondkaart <del> * @return de file met de afbeelding <del> * @throws IOException <del> * Signals that an I/O exception has occurred. <del> */ <del> private File getMap(final BufferedImage imageVoorgrond, <del> final BufferedImage imageAchtergrond) throws IOException { <del> <del> final BufferedImage composite = new BufferedImage(MAP_DIMENSION, <del> MAP_DIMENSION, BufferedImage.TYPE_INT_ARGB); <del> final Graphics2D g = composite.createGraphics(); <del> <del> g.drawImage(imageAchtergrond, 0, 0, null); <del> if (imageVoorgrond != null) { <del> final float[] scales = { 1f, 1f, 1f, 0.8f }; <del> final RescaleOp rop = new RescaleOp(scales, new float[4], null); <del> g.drawImage(imageVoorgrond, rop, 0, 0); <del> // zoeklocatie intekenen met plaatje <del> final BufferedImage infoImage = ImageIO.read(new File(this <del> .getClass().getClassLoader().getResource("info.png") <del> .getFile())); <del> // CHECKSTYLE.OFF: MagicNumber - dit zijn midden en hoogte van het <del> // plaatje "info.png" <del> g.drawImage(infoImage, MAP_DIMENSION_MIDDLE - 16, <del> MAP_DIMENSION_MIDDLE - 37, null); <del> // CHECKSTYLE.ON: MagicNumber <del> } <del> // opslaan van plaatje zodat de browser het op kan halen <del> final File kaartAfbeelding = File.createTempFile( <del> "wmscombined", <del> ".png", <del> new File(this.getServletContext().getRealPath( <del> MAP_CACHE_DIR.code))); <del> kaartAfbeelding.deleteOnExit(); <del> ImageIO.write(composite, "png", kaartAfbeelding); <del> g.dispose(); <del> return kaartAfbeelding; <del> } <del> <del> /* <del> * (non-Javadoc) <del> * <del> * @see <del> * nl.mineleni.cbsviewer.servlet.AbstractBaseServlet#init(javax.servlet. <del> * ServletConfig) <del> */ <del> @Override <del> public void init(final ServletConfig config) throws ServletException { <del> super.init(config); <del> try { <del> this.bgWMSCache = new WMSCache(this.getServletContext() <del> .getRealPath(MAP_CACHE_DIR.code), NUMBER_CACHE_ELEMENTS); <del> } catch (final IOException e) { <del> LOGGER.error( <del> "Inititalisatie fout voor de achtergrond topografie cache.", <del> e); <del> } <del> <del> try { <del> this.bgWMSLuFoCache = new WMSCache(this.getServletContext() <del> .getRealPath(MAP_CACHE_DIR.code), NUMBER_CACHE_ELEMENTS); <del> } catch (final IOException e) { <del> LOGGER.error( <del> "Inititalisatie fout voor de achtergrond luchtfoto cache.", <del> e); <del> } <del> <del> this.legendCache = new Cache<String, CacheImage, BufferedImage>( <del> NUMBER_CACHE_ELEMENTS); <del> <del> this.featInfoCache = new Cache<BboxLayerCacheKey, CachableString, String>( <del> NUMBER_CACHE_ELEMENTS); <del> <del> this.fgWMSCache = new Cache<BboxLayerCacheKey, CacheImage, BufferedImage>( <del> NUMBER_CACHE_ELEMENTS); <del> <del> // achtergrond kaart <del> final String bgCapabilitiesURL = config <del> .getInitParameter("bgCapabilitiesURL"); <del> LOGGER.debug("WMS capabilities url van achtergrond kaart: " <del> + bgCapabilitiesURL); <del> try { <del> this.bgWMS = new WebMapServer(new URL(bgCapabilitiesURL)); <del> } catch (final MalformedURLException e) { <del> LOGGER.error( <del> "Een url die gebruikt wordt voor de topografie WMS capabilities is misvormd", <del> e); <del> throw new ServletException(e); <del> } catch (final ServiceException e) { <del> LOGGER.error( <del> "Er is een service exception (WMS server fout) opgetreden bij het ophalen van de topografie WMS capabilities", <del> e); <del> throw new ServletException(e); <del> } catch (final IOException e) { <del> LOGGER.error( <del> "Er is een I/O fout opgetreden bij benaderen van de topografie WMS services", <del> e); <del> throw new ServletException(e); <del> } <del> final String bgWMSlyrs = config.getInitParameter("bgWMSlayers"); <del> LOGGER.debug("Achtergrond kaartlagen topografie: " + bgWMSlyrs); <del> if ((bgWMSlyrs != null) && (bgWMSlyrs.length() > 0)) { <del> this.bgWMSlayers = bgWMSlyrs.split("[,]\\s*"); <del> } <del> <del> // achtergrond luchtfoto <del> final String lufoCapabilitiesURL = config <del> .getInitParameter("lufoCapabilitiesURL"); <del> LOGGER.debug("WMS capabilities url van achtergrond luchtfoto: " <del> + lufoCapabilitiesURL); <del> try { <del> this.lufoWMS = new WebMapServer(new URL(lufoCapabilitiesURL)); <del> } catch (final MalformedURLException e) { <del> LOGGER.error( <del> "De url die gebruikt wordt voor de luchtfoto WMS capabilities is misvormd", <del> e); <del> throw new ServletException(e); <del> } catch (final ServiceException e) { <del> LOGGER.error( <del> "Er is een service exception (WMS server fout) opgetreden bij het ophalen van de luchtfoto WMS capabilities", <del> e); <del> throw new ServletException(e); <del> } catch (final IOException e) { <del> LOGGER.error( <del> "Er is een I/O fout opgetreden bij benaderen van de luchtfoto WMS services", <del> e); <del> throw new ServletException(e); <del> } <del> final String lufoWMSlyrs = config.getInitParameter("lufoWMSlayers"); <del> LOGGER.debug("Achtergrond kaartlagen luchtfoto: " + lufoWMSlyrs); <del> if ((lufoWMSlyrs != null) && (lufoWMSlyrs.length() > 0)) { <del> this.lufoWMSlayers = lufoWMSlyrs.split("[,]\\s*"); <del> } <del> <del> // init servers cache <del> this.wmsServersCache = new ConcurrentHashMap<String, WebMapServer>(); <del> } <del> <del> /* <del> * (non-Javadoc) <del> * <del> * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest, <del> * javax.servlet.ServletResponse) <del> */ <del> @Override <del> protected void service(final HttpServletRequest request, <del> final HttpServletResponse response) throws ServletException, <del> IOException { <del> <del> final int[] dXcoordYCoordStraal = this.parseLocation(request); <del> final int xcoord = dXcoordYCoordStraal[0]; <del> final int ycoord = dXcoordYCoordStraal[1]; <del> final int straal = dXcoordYCoordStraal[2]; <del> final BoundingBox bbox = SpatialUtil.calcRDBBOX(xcoord, ycoord, straal); <del> <del> BasemapType basemaptype = BasemapType.topografie; <del> final String mType = request.getParameter(REQ_PARAM_BGMAP.code); <del> if (this.isNotNullNotEmptyNotWhiteSpaceOnly(mType)) { <del> try { <del> basemaptype = BasemapType.valueOf(mType); <del> } catch (final IllegalArgumentException e) { <del> LOGGER.debug("Ongeldige waarde gebruikt voor basemap type, de default wordt gebruikt."); <del> } <del> } <del> final BufferedImage bg = this.getBackGroundMap(bbox, basemaptype); <del> <del> BufferedImage fg = null; <del> final String mapId = request.getParameter(REQ_PARAM_MAPID.code); <del> if (this.isNotNullNotEmptyNotWhiteSpaceOnly(mapId)) { <del> final LayerDescriptor layer = this.layers.getLayerByID(mapId); <del> request.setAttribute("mapname", layer.getName()); <del> LOGGER.debug("LayerDescriptor::Name is: " + layer.getName()); <del> <del> final String fgCapabilitiesURL = layer.getUrl(); <del> LOGGER.debug("WMS capabilities url van voorgrond kaart: " <del> + fgCapabilitiesURL); <del> try { <del> fg = this.getForeGroundMap(bbox, layer); <del> final File[] legendas = this.getLegends(layer); <del> final String fInfo = this.getFeatureInfo(bbox, layer); <del> request.setAttribute(REQ_PARAM_MAPID.code, mapId); <del> request.setAttribute(REQ_PARAM_LEGENDAS.code, legendas); <del> request.setAttribute(REQ_PARAM_FEATUREINFO.code, fInfo); <del> } catch (final ServiceException e) { <del> LOGGER.error( <del> "Er is een service exception opgetreden bij benaderen van de voorgrond WMS", <del> e); <del> throw new ServletException(e); <del> } catch (final MalformedURLException e) { <del> LOGGER.error( <del> "De url die gebruikt wordt voor de WMS capabilities is misvormd.", <del> e); <del> throw new ServletException(e); <del> } <del> } <del> <del> final File kaart = this.getMap(fg, bg); <del> <del> request.setAttribute(REQ_PARAM_CACHEDIR.code, MAP_CACHE_DIR.code); <del> request.setAttribute(REQ_PARAM_KAART.code, kaart); <del> request.setAttribute(REQ_PARAM_BGMAP.code, basemaptype); <del> } <add> /** maximum aantal elementen per cache. {@value} */ <add> private static final int NUMBER_CACHE_ELEMENTS = 1000; <add> <add> /** logger. */ <add> private static final Logger LOGGER = LoggerFactory <add> .getLogger(WMSClientServlet.class); <add> <add> /** <add> * vaste afmeting van de kaart (hoogte en breedte). {@value} <add> * <add> * @see #MAP_DIMENSION_MIDDLE <add> */ <add> private static final int MAP_DIMENSION = 440; <add> <add> /** <add> * helft van de afmeting van de kaart (hoogte en breedte). {@value} <add> * <add> * @see #MAP_DIMENSION <add> */ <add> private static final int MAP_DIMENSION_MIDDLE = MAP_DIMENSION / 2; <add> <add> /** time-to-live voor cache elementen. {@value} */ <add> private static final long SECONDS_TO_CACHE_ELEMENTS = 60 * 60/* 1 uur */; <add> <add> /** time-to-live voor cache elementen. {@value} */ <add> private static final long MILLISECONDS_TO_CACHE_ELEMENTS = SECONDS_TO_CACHE_ELEMENTS * 1000; <add> <add> /** serialVersionUID. */ <add> private static final long serialVersionUID = 4958212343847516071L; <add> <add> /** De achtergrond kaart WMS. */ <add> private transient WebMapServer bgWMS = null; <add> <add> /** cache voor legenda afbeeldingen. */ <add> private transient Cache<String, CacheImage, BufferedImage> legendCache = null; <add> <add> /** cache voor voorgrond WMS afbeeldingen. */ <add> private transient Cache<BboxLayerCacheKey, CacheImage, BufferedImage> fgWMSCache = null; <add> <add> /** cache voor feature info. */ <add> private transient Cache<BboxLayerCacheKey, CachableString, String> featInfoCache = null; <add> <add> /** verzameling lagen voor de achtergrondkaart. */ <add> private String[] bgWMSlayers = null; <add> <add> /** <add> * voorgrond wms request. <add> * <add> * @todo refactor naar lokale variabele <add> */ <add> private transient GetMapRequest getMapRequest = null; <add> <add> /** layers bean. */ <add> private final transient AvailableLayersBean layers = new AvailableLayersBean(); <add> <add> /** cache voor achtergrond kaartjes. */ <add> private transient WMSCache bgWMSCache = null; <add> /** De achtergrond luchtfoto WMS. */ <add> private transient WebMapServer lufoWMS = null; <add> <add> /** cache voor achtergrond kaartjes. */ <add> private transient WMSCache bgWMSLuFoCache = null; <add> /** verzameling lagen voor de achtergrondkaart. */ <add> private String[] lufoWMSlayers = null; <add> <add> /** <add> * de verzameling met (voorgrond) WMSsen die we benaderen. Het opstarten van <add> * een WMS duurt lang vanwege de capabilities uitvraag en versie <add> * onderhandeling. <add> */ <add> private transient Map<String, WebMapServer> wmsServersCache = null; <add> <add> /* <add> * (non-Javadoc) <add> * <add> * @see javax.servlet.GenericServlet#destroy() <add> */ <add> @Override <add> public void destroy() { <add> this.bgWMSCache.clear(); <add> this.bgWMS = null; <add> this.bgWMSLuFoCache.clear(); <add> this.lufoWMS = null; <add> this.wmsServersCache.clear(); <add> this.legendCache.clear(); <add> this.legendCache = null; <add> this.fgWMSCache.clear(); <add> this.fgWMSCache = null; <add> this.featInfoCache.clear(); <add> this.featInfoCache = null; <add> this.getMapRequest = null; <add> super.destroy(); <add> } <add> <add> /** <add> * Achtergrondkaart ophalen en opslaan in de cache. <add> * <add> * @param bbox <add> * the bbox <add> * @param type <add> * the type <add> * @return background/basemap image <add> * @throws ServletException <add> * Geeft aan dat er een fout is opgetreden bij het benaderen van <add> * de achtergrondgrond WMS service <add> */ <add> private BufferedImage getBackGroundMap(final BoundingBox bbox, <add> final BasemapType type) throws ServletException { <add> <add> GetMapRequest map; <add> switch (type) { <add> case luchtfoto: <add> if (this.bgWMSLuFoCache.containsKey(bbox)) { <add> // ophalen uit cache <add> LOGGER.debug("Achtergrond " + type <add> + " afbeelding uit de cache serveren."); <add> return this.bgWMSLuFoCache.getImage(bbox); <add> } <add> map = this.lufoWMS.createGetMapRequest(); <add> if (this.lufoWMSlayers != null) { <add> for (final String lyr : this.lufoWMSlayers) { <add> // per laag toevoegen met de default style <add> map.addLayer(lyr, ""); <add> } <add> } else { <add> // alle lagen toevoegen <add> for (final Layer layer : WMSUtils.getNamedLayers(this.lufoWMS <add> .getCapabilities())) { <add> map.addLayer(layer); <add> } <add> } <add> break; <add> case topografie: <add> // implicit fall thru naar default <add> default: <add> if (this.bgWMSCache.containsKey(bbox)) { <add> // ophalen uit cache <add> LOGGER.debug("Achtergrond " + type <add> + " afbeelding uit de cache serveren."); <add> return this.bgWMSCache.getImage(bbox); <add> } <add> map = this.bgWMS.createGetMapRequest(); <add> if (this.bgWMSlayers != null) { <add> for (final String lyr : this.bgWMSlayers) { <add> // per laag toevoegen met de default style <add> map.addLayer(lyr, ""); <add> } <add> } else { <add> // alle lagen toevoegen <add> for (final Layer layer : WMSUtils.getNamedLayers(this.bgWMS <add> .getCapabilities())) { <add> map.addLayer(layer); <add> } <add> } <add> } <add> <add> map.setFormat("image/png"); <add> map.setDimensions(MAP_DIMENSION, MAP_DIMENSION); <add> map.setTransparent(true); <add> map.setBGColour("0xffffff"); <add> map.setExceptions("application/vnd.ogc.se_inimage"); <add> map.setSRS("EPSG:28992"); <add> map.setBBox(bbox); <add> <add> LOGGER.debug("Achtergrond WMS url is: " + map.getFinalURL()); <add> <add> try { <add> final GetMapResponse response = this.bgWMS.issueRequest(map); <add> final BufferedImage image = ImageIO.read(response.getInputStream()); <add> switch (type) { <add> case luchtfoto: <add> this.bgWMSLuFoCache.put(bbox, image, SECONDS_TO_CACHE_ELEMENTS); <add> <add> break; <add> case topografie: <add> default: <add> this.bgWMSCache.put(bbox, image, SECONDS_TO_CACHE_ELEMENTS); <add> break; <add> } <add> <add> if (LOGGER.isDebugEnabled()) { <add> // achtergrond plaatje bewaren in debug modus <add> final File temp = File.createTempFile( <add> "bgwms", <add> ".png", <add> new File(this.getServletContext().getRealPath( <add> MAP_CACHE_DIR.code))); <add> temp.deleteOnExit(); <add> ImageIO.write(image, "png", temp); <add> } <add> <add> return image; <add> } catch (ServiceException | IOException e) { <add> LOGGER.error( <add> "Er is een fout opgetreden bij het benaderen van de achtergrond WMS service.", <add> e); <add> throw new ServletException(e); <add> } <add> <add> } <add> <add> /** <add> * zoekt of maakt de gevraagde WebMapServer. <add> * <add> * @param lyrDesc <add> * de layerdescriptor met de WMS informatie <add> * @return the cached wms <add> * @throws ServiceException <add> * the service exception <add> * @throws IOException <add> * Signals that an I/O exception has occurred. <add> */ <add> private WebMapServer getCachedWMS(final LayerDescriptor lyrDesc) <add> throws ServiceException, IOException { <add> if (this.wmsServersCache.containsKey(lyrDesc.getUrl())) { <add> LOGGER.debug("WMS gevonden in cache."); <add> return this.wmsServersCache.get(lyrDesc.getUrl()); <add> } else { <add> LOGGER.debug("Aanmaken van nieuwe WMS (inclusief versie onderhandeling)."); <add> final WebMapServer fgWMS = new WebMapServer(new URL( <add> lyrDesc.getUrl())); <add> this.wmsServersCache.put(lyrDesc.getUrl(), fgWMS); <add> return fgWMS; <add> } <add> } <add> <add> /** <add> * Haalt de feature info op. <add> * <add> * @param bbox <add> * the bbox <add> * @param lyrDesc <add> * de layerdescriptor met de WMS informatie <add> * @return Een string met feature info <add> * @throws ServiceException <add> * Geeft aan dat er een fout is opgetreden tijden het benaderen <add> * van de WMS <add> * @throws IOException <add> * Signals that an I/O exception has occurred. <add> */ <add> private String getFeatureInfo(final BoundingBox bbox, <add> final LayerDescriptor lyrDesc) throws ServiceException, IOException { <add> final BboxLayerCacheKey key = new BboxLayerCacheKey(bbox, lyrDesc); <add> if (this.featInfoCache.containsKey(key)) { <add> // ophalen uit cache <add> final String fInfo = this.featInfoCache.get(key).getItem(); <add> if (null != fInfo) { <add> // dit kan null zijn in het geval het item verlopen is <add> LOGGER.debug("FeatureInfo uit de cache serveren."); <add> return fInfo; <add> } <add> } <add> <add> try { <add> final GetFeatureInfoRequest getFeatureInfoRequest = this <add> .getCachedWMS(lyrDesc).createGetFeatureInfoRequest( <add> this.getMapRequest); <add> <add> final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); <add> final Set<Layer> queryLayers = new HashSet<Layer>(); <add> final WMSCapabilities caps = this.getCachedWMS(lyrDesc) <add> .getCapabilities(); <add> <add> for (final Layer wmsLyr : caps.getLayerList()) { <add> if ((wmsLyr.getName() != null) <add> && (wmsLyr.getName().length() != 0)) { <add> for (final String layerName : layerNames) { <add> if (wmsLyr.getName().equalsIgnoreCase(layerName)) { <add> queryLayers.add(wmsLyr); <add> } <add> } <add> } <add> } <add> getFeatureInfoRequest.setQueryLayers(queryLayers); <add> getFeatureInfoRequest.setInfoFormat("application/vnd.ogc.gml"); <add> getFeatureInfoRequest.setFeatureCount(10); <add> getFeatureInfoRequest.setQueryPoint(MAP_DIMENSION_MIDDLE, <add> MAP_DIMENSION_MIDDLE); <add> LOGGER.debug("WMS feature info request url is: " <add> + getFeatureInfoRequest.getFinalURL()); <add> final GetFeatureInfoResponse response = this.getCachedWMS(lyrDesc) <add> .issueRequest(getFeatureInfoRequest); <add> <add> final String html = FeatureInfoResponseConverter <add> .convertToHTMLTable(response.getInputStream(), <add> FeatureInfoResponseConverter.Type.GMLTYPE, lyrDesc <add> .getAttributes().split(",\\s*")); <add> this.featInfoCache.put(key, <add> new CachableString(html, System.currentTimeMillis() <add> + MILLISECONDS_TO_CACHE_ELEMENTS)); <add> return html; <add> <add> } catch (final UnsupportedOperationException u) { <add> LOGGER.warn("De WMS server (" <add> + this.getCachedWMS(lyrDesc).getInfo().getTitle() <add> + ") ondersteund geen GetFeatureInfoRequest.", u); <add> return ""; <add> } <add> } <add> <add> /** <add> * voorgrondkaart ophalen. <add> * <add> * @param bbox <add> * the bbox <add> * @param lyrDesc <add> * de layerdescriptor met de WMS informatie <add> * @return voorgrond afbeelding <add> * @throws ServletException <add> * Geeft aan dat er een fout is opgetreden bij het benaderen van <add> * de voorgrond WMS service <add> */ <add> private BufferedImage getForeGroundMap(final BoundingBox bbox, <add> final LayerDescriptor lyrDesc) throws ServletException { <add> <add> final BboxLayerCacheKey key = new BboxLayerCacheKey(bbox, lyrDesc); <add> if (this.fgWMSCache.containsKey(key)) { <add> // ophalen uit cache <add> final BufferedImage image = this.fgWMSCache.get(key).getImage(); <add> if (null != image) { <add> LOGGER.debug("Voorgrond afbeelding uit de cache serveren."); <add> return image; <add> } <add> } <add> <add> // wms request doen <add> try { <add> this.getMapRequest = this.getCachedWMS(lyrDesc) <add> .createGetMapRequest(); <add> final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); <add> final String[] styleNames = lyrDesc.getStyles().split(",\\s*"); <add> <add> for (int l = 0; l < layerNames.length; l++) { <add> this.getMapRequest.addLayer(layerNames[l], styleNames[l]); <add> } <add> this.getMapRequest.setFormat("image/png"); <add> this.getMapRequest.setDimensions(MAP_DIMENSION, MAP_DIMENSION); <add> this.getMapRequest.setTransparent(true); <add> this.getMapRequest.setSRS("EPSG:28992"); <add> this.getMapRequest.setBBox(bbox); <add> this.getMapRequest.setExceptions("application/vnd.ogc.se_inimage"); <add> this.getMapRequest.setBGColour("0xffffff"); <add> LOGGER.debug("Voorgrond WMS url is: " <add> + this.getMapRequest.getFinalURL()); <add> <add> // thema/voorgrond ophalen <add> final GetMapResponse response = this.getCachedWMS(lyrDesc) <add> .issueRequest(this.getMapRequest); <add> final BufferedImage image = ImageIO.read(response.getInputStream()); <add> <add> this.fgWMSCache.put(key, new CacheImage(image, <add> SECONDS_TO_CACHE_ELEMENTS)); <add> <add> if (LOGGER.isDebugEnabled()) { <add> // voorgrond plaatje bewaren in debug modus <add> final File temp = File.createTempFile( <add> "fgwms", <add> ".png", <add> new File(this.getServletContext().getRealPath( <add> MAP_CACHE_DIR.code))); <add> temp.deleteOnExit(); <add> ImageIO.write(image, "png", temp); <add> } <add> return image; <add> } catch (ServiceException | IOException e) { <add> LOGGER.error( <add> "Er is een fout opgetreden bij het benaderen van de voorgrond WMS service.", <add> e); <add> throw new ServletException(e); <add> } <add> } <add> <add> /** <add> * Haalt de legenda op voor de thema laag. <add> * <add> * @param lyrDesc <add> * de layerdescriptor met de WMS informatie <add> * @return een array met legenda afbeeldings bestanden <add> * @throws ServiceException <add> * Geeft aan dat er een fout is opgetreden tijden het benaderen <add> * van de WMS <add> * @throws IOException <add> * Signals that an I/O exception has occurred. <add> */ <add> private File[] getLegends(final LayerDescriptor lyrDesc) <add> throws ServiceException, IOException { <add> <add> final String[] layerNames = lyrDesc.getLayers().split(",\\s*"); <add> final String[] styleNames = lyrDesc.getStyles().split(",\\s*"); <add> <add> final File[] legends = new File[layerNames.length]; <add> try { <add> final GetLegendGraphicRequest legend = this.getCachedWMS(lyrDesc) <add> .createGetLegendGraphicRequest(); <add> BufferedImage image; <add> for (int l = 0; l < layerNames.length; l++) { <add> final String key = layerNames[l] + "::" + styleNames[l]; <add> if (this.legendCache.containsKey(key)) { <add> // in de cache kijken of we deze legenda afbeelding al <add> // hebben <add> final String fname = this.legendCache.get(key).getName(); <add> if (null != fname) { <add> legends[l] = new File(fname); <add> if (!legends[l].exists()) { <add> // (mogelijk) is het bestand gewist.. <add> ImageIO.write(this.legendCache.get(key).getImage(), <add> "png", legends[l]); <add> } <add> LOGGER.debug("Legenda bestand uit cache: " <add> + legends[l].getAbsolutePath()); <add> } <add> } else { <add> // legenda opvragen <add> legend.setLayer(layerNames[l]); <add> legend.setStyle(styleNames[l]); <add> legend.setFormat("image/png"); <add> legend.setExceptions("application/vnd.ogc.se_inimage"); <add> <add> LOGGER.debug("Voorgrond WMS legenda url is: " <add> + legend.getFinalURL()); <add> final GetLegendGraphicResponse response = this <add> .getCachedWMS(lyrDesc).issueRequest(legend); <add> image = ImageIO.read(response.getInputStream()); <add> legends[l] = File.createTempFile( <add> "legenda", <add> ".png", <add> new File(this.getServletContext().getRealPath( <add> MAP_CACHE_DIR.code))); <add> legends[l].deleteOnExit(); <add> this.legendCache <add> .put(key, <add> new CacheImage( <add> image, <add> legends[l].getAbsolutePath(), <add> System.currentTimeMillis() <add> + (MILLISECONDS_TO_CACHE_ELEMENTS * 24))); <add> LOGGER.debug("Legenda bestand: " <add> + legends[l].getAbsolutePath()); <add> ImageIO.write(image, "png", legends[l]); <add> } <add> } <add> } catch (final UnsupportedOperationException u) { <add> LOGGER.warn("De WMS server (" <add> + this.getCachedWMS(lyrDesc).getInfo().getTitle() <add> + ") ondersteund geen GetLegendGraphicRequest.", u); <add> return null; <add> } <add> return legends; <add> } <add> <add> /** <add> * kaart maken op basis van de opgehaalde afbeeldingen. <add> * <add> * @param imageVoorgrond <add> * de voorgrondkaart <add> * @param imageAchtergrond <add> * de achtergrondgrondkaart <add> * @return de file met de afbeelding <add> * @throws IOException <add> * Signals that an I/O exception has occurred. <add> */ <add> private File getMap(final BufferedImage imageVoorgrond, <add> final BufferedImage imageAchtergrond) throws IOException { <add> <add> final BufferedImage composite = new BufferedImage(MAP_DIMENSION, <add> MAP_DIMENSION, BufferedImage.TYPE_INT_ARGB); <add> final Graphics2D g = composite.createGraphics(); <add> <add> g.drawImage(imageAchtergrond, 0, 0, null); <add> if (imageVoorgrond != null) { <add> final float[] scales = { 1f, 1f, 1f, 0.8f }; <add> final RescaleOp rop = new RescaleOp(scales, new float[4], null); <add> g.drawImage(imageVoorgrond, rop, 0, 0); <add> // zoeklocatie intekenen met plaatje <add> final BufferedImage infoImage = ImageIO.read(new File(this <add> .getClass().getClassLoader().getResource("info.png") <add> .getFile())); <add> // CHECKSTYLE.OFF: MagicNumber - dit zijn midden en hoogte van het <add> // plaatje "info.png" <add> g.drawImage(infoImage, MAP_DIMENSION_MIDDLE - 16, <add> MAP_DIMENSION_MIDDLE - 37, null); <add> // CHECKSTYLE.ON: MagicNumber <add> } <add> // opslaan van plaatje zodat de browser het op kan halen <add> final File kaartAfbeelding = File.createTempFile( <add> "wmscombined", <add> ".png", <add> new File(this.getServletContext().getRealPath( <add> MAP_CACHE_DIR.code))); <add> kaartAfbeelding.deleteOnExit(); <add> ImageIO.write(composite, "png", kaartAfbeelding); <add> g.dispose(); <add> return kaartAfbeelding; <add> } <add> <add> /* <add> * (non-Javadoc) <add> * <add> * @see <add> * nl.mineleni.cbsviewer.servlet.AbstractBaseServlet#init(javax.servlet. <add> * ServletConfig) <add> */ <add> @Override <add> public void init(final ServletConfig config) throws ServletException { <add> super.init(config); <add> try { <add> this.bgWMSCache = new WMSCache(this.getServletContext() <add> .getRealPath(MAP_CACHE_DIR.code), NUMBER_CACHE_ELEMENTS); <add> } catch (final IOException e) { <add> LOGGER.error( <add> "Inititalisatie fout voor de achtergrond topografie cache.", <add> e); <add> } <add> <add> try { <add> this.bgWMSLuFoCache = new WMSCache(this.getServletContext() <add> .getRealPath(MAP_CACHE_DIR.code), NUMBER_CACHE_ELEMENTS); <add> } catch (final IOException e) { <add> LOGGER.error( <add> "Inititalisatie fout voor de achtergrond luchtfoto cache.", <add> e); <add> } <add> <add> this.legendCache = new Cache<String, CacheImage, BufferedImage>( <add> NUMBER_CACHE_ELEMENTS); <add> <add> this.featInfoCache = new Cache<BboxLayerCacheKey, CachableString, String>( <add> NUMBER_CACHE_ELEMENTS); <add> <add> this.fgWMSCache = new Cache<BboxLayerCacheKey, CacheImage, BufferedImage>( <add> NUMBER_CACHE_ELEMENTS); <add> <add> // achtergrond kaart <add> final String bgCapabilitiesURL = config <add> .getInitParameter("bgCapabilitiesURL"); <add> LOGGER.debug("WMS capabilities url van achtergrond kaart: " <add> + bgCapabilitiesURL); <add> try { <add> this.bgWMS = new WebMapServer(new URL(bgCapabilitiesURL)); <add> } catch (final MalformedURLException e) { <add> LOGGER.error( <add> "Een url die gebruikt wordt voor de topografie WMS capabilities is misvormd", <add> e); <add> throw new ServletException(e); <add> } catch (final ServiceException e) { <add> LOGGER.error( <add> "Er is een service exception (WMS server fout) opgetreden bij het ophalen van de topografie WMS capabilities", <add> e); <add> throw new ServletException(e); <add> } catch (final IOException e) { <add> LOGGER.error( <add> "Er is een I/O fout opgetreden bij benaderen van de topografie WMS services", <add> e); <add> throw new ServletException(e); <add> } <add> final String bgWMSlyrs = config.getInitParameter("bgWMSlayers"); <add> LOGGER.debug("Achtergrond kaartlagen topografie: " + bgWMSlyrs); <add> if ((bgWMSlyrs != null) && (bgWMSlyrs.length() > 0)) { <add> this.bgWMSlayers = bgWMSlyrs.split("[,]\\s*"); <add> } <add> <add> // achtergrond luchtfoto <add> final String lufoCapabilitiesURL = config <add> .getInitParameter("lufoCapabilitiesURL"); <add> LOGGER.debug("WMS capabilities url van achtergrond luchtfoto: " <add> + lufoCapabilitiesURL); <add> try { <add> this.lufoWMS = new WebMapServer(new URL(lufoCapabilitiesURL)); <add> } catch (final MalformedURLException e) { <add> LOGGER.error( <add> "De url die gebruikt wordt voor de luchtfoto WMS capabilities is misvormd", <add> e); <add> throw new ServletException(e); <add> } catch (final ServiceException e) { <add> LOGGER.error( <add> "Er is een service exception (WMS server fout) opgetreden bij het ophalen van de luchtfoto WMS capabilities", <add> e); <add> throw new ServletException(e); <add> } catch (final IOException e) { <add> LOGGER.error( <add> "Er is een I/O fout opgetreden bij benaderen van de luchtfoto WMS services", <add> e); <add> throw new ServletException(e); <add> } <add> final String lufoWMSlyrs = config.getInitParameter("lufoWMSlayers"); <add> LOGGER.debug("Achtergrond kaartlagen luchtfoto: " + lufoWMSlyrs); <add> if ((lufoWMSlyrs != null) && (lufoWMSlyrs.length() > 0)) { <add> this.lufoWMSlayers = lufoWMSlyrs.split("[,]\\s*"); <add> } <add> <add> // init servers cache <add> this.wmsServersCache = new ConcurrentHashMap<String, WebMapServer>(); <add> } <add> <add> /* <add> * (non-Javadoc) <add> * <add> * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest, <add> * javax.servlet.ServletResponse) <add> */ <add> @Override <add> protected void service(final HttpServletRequest request, <add> final HttpServletResponse response) throws ServletException, <add> IOException { <add> <add> final int[] dXcoordYCoordStraal = this.parseLocation(request); <add> final int xcoord = dXcoordYCoordStraal[0]; <add> final int ycoord = dXcoordYCoordStraal[1]; <add> final int straal = dXcoordYCoordStraal[2]; <add> final BoundingBox bbox = SpatialUtil.calcRDBBOX(xcoord, ycoord, straal); <add> <add> BasemapType basemaptype = BasemapType.topografie; <add> final String mType = request.getParameter(REQ_PARAM_BGMAP.code); <add> if (this.isNotNullNotEmptyNotWhiteSpaceOnly(mType)) { <add> try { <add> basemaptype = BasemapType.valueOf(mType); <add> } catch (final IllegalArgumentException e) { <add> LOGGER.debug("Ongeldige waarde gebruikt voor basemap type, de default wordt gebruikt."); <add> } <add> } <add> final BufferedImage bg = this.getBackGroundMap(bbox, basemaptype); <add> <add> BufferedImage fg = null; <add> final String mapId = request.getParameter(REQ_PARAM_MAPID.code); <add> if (this.isNotNullNotEmptyNotWhiteSpaceOnly(mapId)) { <add> final LayerDescriptor layer = this.layers.getLayerByID(mapId); <add> request.setAttribute("mapname", layer.getName()); <add> LOGGER.debug("LayerDescriptor::Name is: " + layer.getName()); <add> <add> final String fgCapabilitiesURL = layer.getUrl(); <add> LOGGER.debug("WMS capabilities url van voorgrond kaart: " <add> + fgCapabilitiesURL); <add> try { <add> fg = this.getForeGroundMap(bbox, layer); <add> final File[] legendas = this.getLegends(layer); <add> final String fInfo = this.getFeatureInfo(bbox, layer); <add> request.setAttribute(REQ_PARAM_MAPID.code, mapId); <add> request.setAttribute(REQ_PARAM_LEGENDAS.code, legendas); <add> request.setAttribute(REQ_PARAM_FEATUREINFO.code, fInfo); <add> } catch (final ServiceException e) { <add> LOGGER.error( <add> "Er is een service exception opgetreden bij benaderen van de voorgrond WMS", <add> e); <add> throw new ServletException(e); <add> } catch (final MalformedURLException e) { <add> LOGGER.error( <add> "De url die gebruikt wordt voor de WMS capabilities is misvormd.", <add> e); <add> throw new ServletException(e); <add> } <add> } <add> <add> final File kaart = this.getMap(fg, bg); <add> <add> request.setAttribute(REQ_PARAM_CACHEDIR.code, MAP_CACHE_DIR.code); <add> request.setAttribute(REQ_PARAM_KAART.code, kaart); <add> request.setAttribute(REQ_PARAM_BGMAP.code, basemaptype); <add> } <ide> }
Java
epl-1.0
c9d232ee7ef4bb893b8603e8aa967bb9c0d8ab7f
0
qgears/opensource-utils,qgears/opensource-utils,qgears/opensource-utils,qgears/opensource-utils,qgears/opensource-utils
package hu.qgears.opengl.commons.example; import hu.qgears.opengl.commons.Camera; import hu.qgears.opengl.commons.TargetRectangle; import hu.qgears.opengl.commons.UtilGl; import hu.qgears.opengl.commons.context.RGlContext; import hu.qgears.opengl.glut.Glut; import hu.qgears.opengl.glut.GlutInstance; import lwjgl.standalone.BaseAccessor; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GLContext; import org.lwjgl.util.vector.Vector2f; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; public class GlutExample02 { private static Camera camera=new Camera(); private static final int WIDTH=1024; private static final int HEIGHT=768; public static void main(String[] args) throws LWJGLException { GlutInstance.getInstance(); BaseAccessor.initLwjglNatives(); Glut glut=new Glut(); glut.init(); glut.openWindow(false, WIDTH, HEIGHT, "example 2"); GLContext.useContext(glut); doBunchOfLoop(glut); glut.setFullScreen(true, WIDTH, HEIGHT); doBunchOfLoop(glut); glut.setFullScreen(false, WIDTH, HEIGHT); doBunchOfLoop(glut); } private static void doBunchOfLoop(Glut glut) { int ctr=0; while(ctr<200) { glut.mainLoopEvent(); drawScene(); glut.swapBuffers(); ctr++; } } private static void drawScene() { // A kép rajzolásának elkezdését jelezzük ezzel a paranccsal GL11.glRenderMode(GL11.GL_RENDER); // Beállítjuk a kamera pozícióját. // Innentől mindent úgy rajzol az OpenGL, hogy a megadott // Pozícióba képzeli a kamerát UtilGl.init3D(WIDTH, HEIGHT, 30.0f, 1.0f); camera.setCamera(); // háttér törlése GL11.glClearColor(0,0,1,1); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); // fehér háromszög rajzolása renderVideo(); } private static void renderVideo() { RGlContext glContext=new RGlContext(); // háttér törlése GL11.glClearColor(0,1,0,.3f); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); float sizeX=1024; float sizeY=768; float scale=.2f; UtilGl.setColor(new Vector3f(1,0,0)); UtilGl.translate(GL11.GL_MODELVIEW, new Vector3f(0,0,-10)); TargetRectangle rect=new TargetRectangle( (Vector2f)new Vector2f(-sizeX/2,sizeY/2).scale(scale), (Vector2f)new Vector2f(sizeX-sizeX/2, -sizeY+sizeY/2).scale(scale) ); UtilGl.drawRectangle(glContext, rect, new Vector4f(1,0,0,.5f)); rect=new TargetRectangle( (Vector2f)new Vector2f(-sizeX/2+sizeX/2,sizeY/2).scale(scale), (Vector2f)new Vector2f(sizeX-sizeX/2, -sizeY+sizeY/2).scale(scale) ); UtilGl.drawRectangle(glContext, rect, new Vector4f(1,0,0,1f)); } }
commons/hu.qgears.opengl.commons/src/hu/qgears/opengl/commons/example/GlutExample02.java
package hu.qgears.opengl.commons.example; import hu.qgears.opengl.commons.Camera; import hu.qgears.opengl.commons.TargetRectangle; import hu.qgears.opengl.commons.UtilGl; import hu.qgears.opengl.commons.context.RGlContext; import hu.qgears.opengl.glut.Glut; import hu.qgears.opengl.glut.GlutInstance; import lwjgl.standalone.BaseAccessor; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GLContext; import org.lwjgl.util.vector.Vector2f; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; public class GlutExample02 { static Camera camera=new Camera(); private static int width=1024; private static int height=768; public static void main(String[] args) throws LWJGLException { GlutInstance.getInstance(); BaseAccessor.initLwjglNatives(); Glut glut=new Glut(); glut.init(); glut.openWindow(false, width, height, "example 2"); GLContext.useContext(glut); doBunchOfLoop(glut); glut.setFullScreen(true, width, height); int w=glut.getScreenWidth(); int h=glut.getScreenHeight(); doBunchOfLoop(glut); glut.setFullScreen(false, width, height); doBunchOfLoop(glut); System.out.println("Fullscreen width and height: ["+w+", "+h+"]"); } private static void doBunchOfLoop(Glut glut) { int ctr=0; while(ctr<200) { glut.mainLoopEvent(); drawScene(); glut.swapBuffers(); ctr++; } } private static void drawScene() { // A kép rajzolásának elkezdését jelezzük ezzel a paranccsal GL11.glRenderMode(GL11.GL_RENDER); // Beállítjuk a kamera pozícióját. // Innentől mindent úgy rajzol az OpenGL, hogy a megadott // Pozícióba képzeli a kamerát UtilGl.init3D(width, height, 30.0f, 1.0f); camera.setCamera(); // háttér törlése GL11.glClearColor(0,0,1,1); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); // fehér háromszög rajzolása renderVideo(); } private static void renderVideo() { RGlContext glContext=new RGlContext(); // háttér törlése GL11.glClearColor(0,1,0,.3f); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); int sizeX=1024; int sizeY=768; float scale=.2f; UtilGl.setColor(new Vector3f(1,0,0)); UtilGl.translate(GL11.GL_MODELVIEW, new Vector3f(0,0,-10)); TargetRectangle rect=new TargetRectangle( (Vector2f)new Vector2f(-sizeX/2,sizeY/2).scale(scale), (Vector2f)new Vector2f(sizeX-sizeX/2, -sizeY+sizeY/2).scale(scale) ); UtilGl.drawRectangle(glContext, rect, new Vector4f(1,0,0,.5f)); rect=new TargetRectangle( (Vector2f)new Vector2f(-sizeX/2+sizeX/2,sizeY/2).scale(scale), (Vector2f)new Vector2f(sizeX-sizeX/2, -sizeY+sizeY/2).scale(scale) ); UtilGl.drawRectangle(glContext, rect, new Vector4f(1,0,0,1f)); } }
Fix major and critical Sonar issues in GlutExample02.java
commons/hu.qgears.opengl.commons/src/hu/qgears/opengl/commons/example/GlutExample02.java
Fix major and critical Sonar issues in GlutExample02.java
<ide><path>ommons/hu.qgears.opengl.commons/src/hu/qgears/opengl/commons/example/GlutExample02.java <ide> import org.lwjgl.util.vector.Vector4f; <ide> <ide> public class GlutExample02 { <del> static Camera camera=new Camera(); <del> private static int width=1024; <del> private static int height=768; <add> private static Camera camera=new Camera(); <add> private static final int WIDTH=1024; <add> private static final int HEIGHT=768; <ide> public static void main(String[] args) throws LWJGLException { <ide> GlutInstance.getInstance(); <ide> BaseAccessor.initLwjglNatives(); <ide> Glut glut=new Glut(); <ide> glut.init(); <del> glut.openWindow(false, width, height, "example 2"); <add> glut.openWindow(false, WIDTH, HEIGHT, "example 2"); <ide> GLContext.useContext(glut); <ide> doBunchOfLoop(glut); <del> glut.setFullScreen(true, width, height); <del> int w=glut.getScreenWidth(); <del> int h=glut.getScreenHeight(); <add> glut.setFullScreen(true, WIDTH, HEIGHT); <ide> doBunchOfLoop(glut); <del> glut.setFullScreen(false, width, height); <add> glut.setFullScreen(false, WIDTH, HEIGHT); <ide> doBunchOfLoop(glut); <del> System.out.println("Fullscreen width and height: ["+w+", "+h+"]"); <ide> } <ide> <ide> private static void doBunchOfLoop(Glut glut) { <ide> // Beállítjuk a kamera pozícióját. <ide> // Innentől mindent úgy rajzol az OpenGL, hogy a megadott <ide> // Pozícióba képzeli a kamerát <del> UtilGl.init3D(width, height, 30.0f, 1.0f); <add> UtilGl.init3D(WIDTH, HEIGHT, 30.0f, 1.0f); <ide> camera.setCamera(); <ide> // háttér törlése <ide> GL11.glClearColor(0,0,1,1); <ide> GL11.glClearColor(0,1,0,.3f); <ide> GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); <ide> <del> int sizeX=1024; <del> int sizeY=768; <add> float sizeX=1024; <add> float sizeY=768; <ide> float scale=.2f; <ide> UtilGl.setColor(new Vector3f(1,0,0)); <ide> UtilGl.translate(GL11.GL_MODELVIEW, new Vector3f(0,0,-10));
JavaScript
isc
90e7d471fe928c0697ed68a8732160a3586b0b00
0
Alhadis/PPJSON
#!/usr/bin/env node "use strict"; const ChildProcess = require("child_process"); const getOpts = require("get-options"); const fs = require("fs"); // Read CLI args const {options, argv} = getOpts(process.argv.slice(2), { "-?, -h, --help": "", "-m, --mutilate": "<bool>", "-u, --underline-urls": "<bool>", "-i, --indent": "<size>", "-c, --colour, --colours, --colourise": "<bool>", "-p, --paged": "", "-a, --alphabetise": "" }); // Print help and bail if that's what the user wanted if(options.help){ const path = require("path"); const name = path.basename(process.argv[1]); const help = ` Usage: ${name} [options] <filename> Pretty-print JSON data for terminal output. Options: -m, --mutilate <bool=1> Unquote property identifiers -u, --underline-urls <bool=1> Add underlines to URLs -c, --colour <bool=1> Colourise the prettified output -i, --indent <size=4> Indentation width, expressed in spaces -a, --alphabetise Order properties alphabetically -p, --paged Show content in pager if longer than screen Run \`man ppjson' for full documentation. `.replace(/\t+/g, " "); process.stdout.write(help + "\n"); process.exit(0); } // Parse our options and normalise their defaults const mutilate = undefined === options.m ? true : bool(options.m); const underlineURLs = undefined === options.u ? true : bool(options.u); const colourise = undefined === options.c ? true : bool(options.c); const pagedView = undefined === options.p ? false : bool(options.p); const indentSize = undefined === options.i ? 4 : options.indent; const alphabetise = undefined === options.a ? false : options.alphabetise; const indent = Array(Math.max(1, indentSize) + 1).join(" "); // Configure colour palette const {env} = process; const SGR = { reset: "\x1B[0m", bold: "\x1B[1m", unbold: "\x1B[22m", underline: "\x1B[4m", noUnderline: "\x1B[24m", colours: { strings: `\x1B[38;5;${ +env.PPJSON_COLOUR_STRINGS || 2 }m`, numbers: `\x1B[38;5;${ +env.PPJSON_COLOUR_NUMBERS || 2 }m`, true: `\x1B[38;5;${ +env.PPJSON_COLOUR_TRUE || 6 }m`, false: `\x1B[38;5;${ +env.PPJSON_COLOUR_FALSE || 6 }m`, null: `\x1B[38;5;${ +env.PPJSON_COLOUR_NULL || 6 }m`, punct: `\x1B[38;5;${ +env.PPJSON_COLOUR_PUNCT || 8 }m`, error: `\x1B[38;5;${ +env.PPJSON_COLOUR_ERROR || 1 }m`, }, }; let input = ""; let output = ""; // An input file was specified on command-line if(argv.length){ let separator = ""; // Cycle through each file and prettify their contents for(const path of argv){ // Make sure there' s enough whitespace between files output += separator; separator = "\n\n"; try{ fs.accessSync(path); } catch(error){ // If there was an access error, hit eject process.stderr.write(SGR.colours.error); process.stderr.write(SGR.bold + "ERROR" + SGR.unbold + error.message); process.stderr.write(SGR.reset); process.exit(2); } // Otherwise, go for it output += prettifyJSON(fs.readFileSync(path, {encoding: "utf8"})); } // Send the compiled result to STDOUT print(output); } // No file specified, just read from STDIN instead else{ process.stdin.setEncoding("utf8"); process.stdin.on("readable", () => { const chunk = process.stdin.read(); if(null !== chunk) input += chunk; }); process.stdin.on("end", () => { print(prettifyJSON(input)); }); } /** * Interpret a string as a boolean value. * * @param {String} input * @return {Boolean} */ function bool(input){ const num = +input; // NaN: String was supplied, check for keywords equating to "false" if(num !== num) return !/^(?:false|off|no?|disabled?|nah)$/i.test(input); return !!num; } /** * Recursively alphabetise the enumerable properties of an object. * * This function returns a copy of the original object with all properties * listed in alphabetic order, rather than enumeration order. The original * object is unmodified. * * @param {Object} input * @param {Boolean} strictCase - If TRUE, will order case-sensitively (capitals first) * @return {Object} */ function alphabetiseProperties(input, strictCase = false){ const stringTag = Object.prototype.toString.call(input); // Regular JavaScript object; enumerate properties if("[object Object]" === stringTag){ let keys = Object.keys(input); keys = strictCase ? keys.sort() : keys.sort((a, b) => { const A = a.toLowerCase(); const B = b.toLowerCase(); if(A < B) return -1; if(A > B) return 1; return 0; }); const result = {}; for(const key of keys) result[key] = alphabetiseProperties(input[key]); return result; } // This is an array; make sure the properties of its values are sorted too else if(Array.isArray(input)) return input.map(e => alphabetiseProperties(e)); // Just return it untouched return input; } /** * Parse JSON or JSON-like data. * * @param {String} * @return {Object} */ function parseJSON(input = ""){ if(!input) return undefined; input = input.trim() .replace(/;$|^\s*"use strict"\s*(?:;\s*)?$/g, "") .replace(/^(module\s*\.\s*)?exports\s*=\s*/g, "") .replace(/^export(\s+default)?\s*/, ""); return require("vm").runInNewContext(`(${input})`); } /** * Spruce up JSON for console display. * * @param {String} * @return {String} */ function prettifyJSON(input){ let output = parseJSON(input); // Order the properties of objects by alphabetical order, not enumeration order if(alphabetise) output = alphabetiseProperties(output); output = JSON.stringify(output, null, indent); // Unquote property identifiers in object literals if(mutilate){ const pattern = new RegExp(indent + '"([\\w\\$]+)":', "g"); output = output.replace(pattern, indent + "$1:"); } // Colourise the output if(colourise){ const bracketsPattern = new RegExp("^((?:" + indent + ")*)([\\[\\{\\}\\]],?)", "gm"); const {colours, reset} = SGR; const {strings} = colours; output = output .replace(/("([^\\"]|\\.)*")/g, colours.strings + "$1" + SGR.reset) // Strings .replace(/(\d+,)$/gm, colours.numbers + "$1" + SGR.reset) // Numerals // Constants .replace(/true(,)?$/gm, colours.true + "true" + SGR.reset + "$1") .replace(/false(,)?$/gm, colours.false + "false" + SGR.reset + "$1") .replace(/null(,)?$/gm, colours.null + "null" + SGR.reset + "$1") // Greyed-out unimportant bits .replace(bracketsPattern, "$1" + colours.punct + "$2" + SGR.reset) .replace(/((?:\[\]|\{\})?,)$/gm, colours.punct + "$1" + SGR.reset) .replace(/(\[|\{)$/gm, colours.punct + "$1" + SGR.reset); } // Underline URLs if(underlineURLs){ const rURL = /(\s*(https?:)?\/\/([^:]+:[^@]+@)?([\w-]+)(\.[\w-]+)*(:\d+)?(\/\S+)?\s*(?="))/gm; output = output.replace(rURL, SGR.underline + "$1" + SGR.noUnderline); } return output + "\n"; } /** * Send a string to STDOUT. * * The content is sent through to the less program if it's too long to * show without scrolling, unless the --paged option's been disabled. * * @param {String} input */ function print(input){ // Determine if the output should be piped through to a pager if(pagedView && input.match(/\n/g).length > process.stdout.rows){ const less = ChildProcess.spawn("less", ["-Ri"], { stdio: ["pipe", process.stdout, process.stderr] }); less.stdin.write(input); less.stdin.end(); } else process.stdout.write(input); }
index.js
#!/usr/bin/env node "use strict"; const ChildProcess = require("child_process"); const getOpts = require("get-options"); const fs = require("fs"); // Read CLI args const {options, argv} = getOpts(process.argv.slice(2), { "-?, -h, --help": "", "-m, --mutilate": "<bool>", "-u, --underline-urls": "<bool>", "-i, --indent": "<size>", "-c, --colour, --colours, --colourise": "<bool>", "-p, --paged": "", "-a, --alphabetise": "" }); // Print help and bail if that's what the user wanted if(options.help){ const path = require("path"); const name = path.basename(process.argv[1]); const help = ` Usage: ${name} [options] <filename> Pretty-print JSON data for terminal output. Options: -m, --mutilate <bool=1> Unquote property identifiers -u, --underline-urls <bool=1> Add underlines to URLs -c, --colour <bool=1> Colourise the prettified output -i, --indent <size=4> Indentation width, expressed in spaces -a, --alphabetise Order properties alphabetically -p, --paged Show content in pager if longer than screen Run \`man ppjson' for full documentation. `.replace(/\t+/g, " "); process.stdout.write(help + "\n"); process.exit(0); } // Parse our options and normalise their defaults const mutilate = undefined === options.m ? true : bool(options.m); const underlineURLs = undefined === options.u ? true : bool(options.u); const colourise = undefined === options.c ? true : bool(options.c); const pagedView = undefined === options.p ? false : bool(options.p); const indentSize = undefined === options.i ? 4 : options.indent; const alphabetise = undefined === options.a ? false : options.alphabetise; const indent = Array(Math.max(1, indentSize) + 1).join(" "); // Configure colour palette const {env} = process; const SGR = { reset: "\x1B[0m", bold: "\x1B[1m", unbold: "\x1B[22m", underline: "\x1B[4m", noUnderline: "\x1B[24m", colours: { strings: `\x1B[38;5;${ +env.PPJSON_COLOUR_STRINGS || 2 }m`, numbers: `\x1B[38;5;${ +env.PPJSON_COLOUR_NUMBERS || 2 }m`, true: `\x1B[38;5;${ +env.PPJSON_COLOUR_TRUE || 6 }m`, false: `\x1B[38;5;${ +env.PPJSON_COLOUR_FALSE || 6 }m`, null: `\x1B[38;5;${ +env.PPJSON_COLOUR_NULL || 6 }m`, punct: `\x1B[38;5;${ +env.PPJSON_COLOUR_PUNCT || 8 }m`, error: `\x1B[38;5;${ +env.PPJSON_COLOUR_ERROR || 1 }m`, }, }; let input = ""; let output = ""; // An input file was specified on command-line if(argv.length){ let separator = ""; // Cycle through each file and prettify their contents for(const path of argv){ // Make sure there' s enough whitespace between files output += separator; separator = "\n\n"; try{ fs.accessSync(path); } catch(error){ // If there was an access error, hit eject process.stderr.write(SGR.colours.error); process.stderr.write(SGR.bold + "ERROR" + SGR.unbold + error.message); process.stderr.write(SGR.reset); process.exit(2); } // Otherwise, go for it output += prettifyJSON(fs.readFileSync(path, {encoding: "utf8"})); } // Send the compiled result to STDOUT print(output); } // No file specified, just read from STDIN instead else{ process.stdin.setEncoding("utf8"); process.stdin.on("readable", () => { const chunk = process.stdin.read(); if(null !== chunk) input += chunk; }); process.stdin.on("end", () => { print(prettifyJSON(input)); }); } /** * Interpret a string as a boolean value. * * @param {String} input * @return {Boolean} */ function bool(input){ const num = +input; // NaN: String was supplied, check for keywords equating to "false" if(num !== num) return !/^(?:false|off|no?|disabled?|nah)$/i.test(input); return !!num; } /** * Recursively alphabetise the enumerable properties of an object. * * This function returns a copy of the original object with all properties * listed in alphabetic order, rather than enumeration order. The original * object is unmodified. * * @param {Object} input * @param {Boolean} strictCase - If TRUE, will order case-sensitively (capitals first) * @return {Object} */ function alphabetiseProperties(input, strictCase = false){ const stringTag = Object.prototype.toString.call(input); // Regular JavaScript object; enumerate properties if("[object Object]" === stringTag){ let keys = Object.keys(input); keys = strictCase ? keys.sort() : keys.sort((a, b) => { const A = a.toLowerCase(); const B = b.toLowerCase(); if(A < B) return -1; if(A > B) return 1; return 0; }); const result = {}; for(const key of keys) result[key] = alphabetiseProperties(input[key]); return result; } // This is an array; make sure the properties of its values are sorted too else if(Array.isArray(input)) return input.map(e => alphabetiseProperties(e)); // Just return it untouched return input; } /** * Spruce up JSON for console display. * * @param {String} * @return {String} */ function prettifyJSON(input){ let output = JSON.parse(input); // Order the properties of objects by alphabetical order, not enumeration order if(alphabetise) output = alphabetiseProperties(output); output = JSON.stringify(output, null, indent); // Unquote property identifiers in object literals if(mutilate){ const pattern = new RegExp(indent + '"([\\w\\$]+)":', "g"); output = output.replace(pattern, indent + "$1:"); } // Colourise the output if(colourise){ const bracketsPattern = new RegExp("^((?:" + indent + ")*)([\\[\\{\\}\\]],?)", "gm"); const {colours, reset} = SGR; const {strings} = colours; output = output .replace(/("([^\\"]|\\.)*")/g, colours.strings + "$1" + SGR.reset) // Strings .replace(/(\d+,)$/gm, colours.numbers + "$1" + SGR.reset) // Numerals // Constants .replace(/true(,)?$/gm, colours.true + "true" + SGR.reset + "$1") .replace(/false(,)?$/gm, colours.false + "false" + SGR.reset + "$1") .replace(/null(,)?$/gm, colours.null + "null" + SGR.reset + "$1") // Greyed-out unimportant bits .replace(bracketsPattern, "$1" + colours.punct + "$2" + SGR.reset) .replace(/((?:\[\]|\{\})?,)$/gm, colours.punct + "$1" + SGR.reset) .replace(/(\[|\{)$/gm, colours.punct + "$1" + SGR.reset); } // Underline URLs if(underlineURLs){ const rURL = /(\s*(https?:)?\/\/([^:]+:[^@]+@)?([\w-]+)(\.[\w-]+)*(:\d+)?(\/\S+)?\s*(?="))/gm; output = output.replace(rURL, SGR.underline + "$1" + SGR.noUnderline); } return output + "\n"; } /** * Send a string to STDOUT. * * The content is sent through to the less program if it's too long to * show without scrolling, unless the --paged option's been disabled. * * @param {String} input */ function print(input){ // Determine if the output should be piped through to a pager if(pagedView && input.match(/\n/g).length > process.stdout.rows){ const less = ChildProcess.spawn("less", ["-Ri"], { stdio: ["pipe", process.stdout, process.stderr] }); less.stdin.write(input); less.stdin.end(); } else process.stdout.write(input); }
Parse input as JavaScript instead of JSON This allows us to format object data containing unquoted property names, such as parsing the output of `npm show`.
index.js
Parse input as JavaScript instead of JSON
<ide><path>ndex.js <ide> } <ide> <ide> <add>/** <add> * Parse JSON or JSON-like data. <add> * <add> * @param {String} <add> * @return {Object} <add> */ <add>function parseJSON(input = ""){ <add> if(!input) return undefined; <add> input = input.trim() <add> .replace(/;$|^\s*"use strict"\s*(?:;\s*)?$/g, "") <add> .replace(/^(module\s*\.\s*)?exports\s*=\s*/g, "") <add> .replace(/^export(\s+default)?\s*/, ""); <add> return require("vm").runInNewContext(`(${input})`); <add>} <add> <ide> <ide> /** <ide> * Spruce up JSON for console display. <ide> * @return {String} <ide> */ <ide> function prettifyJSON(input){ <del> let output = JSON.parse(input); <add> let output = parseJSON(input); <ide> <ide> // Order the properties of objects by alphabetical order, not enumeration order <ide> if(alphabetise)
Java
lgpl-2.1
4a5136d3f002c570330c935377066f3f472332ac
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.crowd.peer.server; import java.util.Map; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.threerings.util.Name; import com.threerings.presents.data.ClientObject; import com.threerings.presents.peer.data.ClientInfo; import com.threerings.presents.peer.data.NodeObject; import com.threerings.presents.peer.server.PeerManager; import com.threerings.presents.peer.server.PeerNode; import com.threerings.presents.server.InvocationException; import com.threerings.presents.server.InvocationManager; import com.threerings.presents.server.PresentsSession; import com.threerings.presents.server.ShutdownManager; import com.threerings.crowd.chat.client.ChatService; import com.threerings.crowd.chat.data.UserMessage; import com.threerings.crowd.chat.server.ChatProvider; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.peer.data.CrowdClientInfo; import com.threerings.crowd.peer.data.CrowdNodeObject; /** * Extends the standard peer manager and bridges certain Crowd services. */ public class CrowdPeerManager extends PeerManager implements CrowdPeerProvider, ChatProvider.ChatForwarder { /** * Creates an uninitialized peer manager. */ @Inject public CrowdPeerManager (ShutdownManager shutmgr) { super(shutmgr); } // from interface CrowdPeerProvider public void deliverTell (ClientObject caller, UserMessage message, Name target, ChatService.TellListener listener) throws InvocationException { // we just forward the message as if it originated on this server _chatprov.deliverTell(message, target, listener); } // from interface CrowdPeerProvider public void deliverBroadcast ( ClientObject caller, Name from, byte levelOrMode, String bundle, String msg) { // deliver the broadcast locally on this server _chatprov.broadcast(from, levelOrMode, bundle, msg, false); } // from interface ChatProvider.ChatForwarder public boolean forwardTell (UserMessage message, Name target, ChatService.TellListener listener) { // look up their auth username from their visible name Name username = _viztoauth.get(target); if (username == null) { return false; // sorry kid, don't know ya } // look through our peers to see if the target user is online on one of them for (PeerNode peer : _peers.values()) { CrowdNodeObject cnobj = (CrowdNodeObject)peer.nodeobj; if (cnobj == null) { continue; } // we have to use auth username to look up their ClientInfo CrowdClientInfo cinfo = (CrowdClientInfo)cnobj.clients.get(username); if (cinfo != null) { cnobj.crowdPeerService.deliverTell(peer.getClient(), message, target, listener); return true; } } return false; } // from interface ChatProvider.ChatForwarder public void forwardBroadcast (Name from, byte levelOrMode, String bundle, String msg) { for (PeerNode peer : _peers.values()) { if (peer.nodeobj != null) { ((CrowdNodeObject)peer.nodeobj).crowdPeerService.deliverBroadcast( peer.getClient(), from, levelOrMode, bundle, msg); } } } @Override // from PeerManager public void shutdown () { super.shutdown(); // unregister our invocation service if (_nodeobj != null) { _invmgr.clearDispatcher(((CrowdNodeObject)_nodeobj).crowdPeerService); } // clear our chat forwarder registration _chatprov.setChatForwarder(null); } @Override // from PeerManager protected NodeObject createNodeObject () { return new CrowdNodeObject(); } @Override // from PeerManager protected ClientInfo createClientInfo () { return new CrowdClientInfo(); } @Override // from PeerManager protected void initClientInfo (PresentsSession client, ClientInfo info) { super.initClientInfo(client, info); ((CrowdClientInfo)info).visibleName = ((BodyObject)client.getClientObject()).getVisibleName(); } @Override // from PeerManager protected void didInit () { super.didInit(); // register and initialize our invocation service CrowdNodeObject cnobj = (CrowdNodeObject)_nodeobj; cnobj.setCrowdPeerService(_invmgr.registerDispatcher(new CrowdPeerDispatcher(this))); // register ourselves as a chat forwarder _chatprov.setChatForwarder(this); } @Override // from PeerManager protected void clientLoggedOn (String nodeName, ClientInfo clinfo) { super.clientLoggedOn(nodeName, clinfo); // keep a mapping from visibleName to auth username if (clinfo instanceof CrowdClientInfo) { CrowdClientInfo ccinfo = (CrowdClientInfo)clinfo; _viztoauth.put(ccinfo.visibleName, ccinfo.username); } } @Override // from PeerManager protected void clientLoggedOff (String nodeName, ClientInfo clinfo) { super.clientLoggedOff(nodeName, clinfo); // update our mapping from visibleName to auth username if (clinfo instanceof CrowdClientInfo) { CrowdClientInfo ccinfo = (CrowdClientInfo)clinfo; _viztoauth.remove(ccinfo.visibleName); } } @Override // from PeerManager protected void connectedToPeer (PeerNode peer) { super.connectedToPeer(peer); for (ClientInfo clinfo : peer.nodeobj.clients) { if (clinfo instanceof CrowdClientInfo) { CrowdClientInfo ccinfo = (CrowdClientInfo)clinfo; _viztoauth.put(ccinfo.visibleName, ccinfo.username); } } } /** A mapping of visible name to username for all clients on all *remote* nodes. */ protected Map<Name, Name> _viztoauth = Maps.newHashMap(); @Inject protected InvocationManager _invmgr; @Inject protected ChatProvider _chatprov; }
src/java/com/threerings/crowd/peer/server/CrowdPeerManager.java
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.crowd.peer.server; import java.util.Map; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.threerings.util.Name; import com.threerings.presents.data.ClientObject; import com.threerings.presents.peer.data.ClientInfo; import com.threerings.presents.peer.data.NodeObject; import com.threerings.presents.peer.server.PeerManager; import com.threerings.presents.peer.server.PeerNode; import com.threerings.presents.server.InvocationException; import com.threerings.presents.server.InvocationManager; import com.threerings.presents.server.PresentsSession; import com.threerings.presents.server.ShutdownManager; import com.threerings.crowd.chat.client.ChatService; import com.threerings.crowd.chat.data.UserMessage; import com.threerings.crowd.chat.server.ChatProvider; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.peer.data.CrowdClientInfo; import com.threerings.crowd.peer.data.CrowdNodeObject; /** * Extends the standard peer manager and bridges certain Crowd services. */ public class CrowdPeerManager extends PeerManager implements CrowdPeerProvider, ChatProvider.ChatForwarder { /** * Creates an uninitialized peer manager. */ @Inject public CrowdPeerManager (ShutdownManager shutmgr) { super(shutmgr); } // from interface CrowdPeerProvider public void deliverTell (ClientObject caller, UserMessage message, Name target, ChatService.TellListener listener) throws InvocationException { // we just forward the message as if it originated on this server _chatprov.deliverTell(message, target, listener); } // from interface CrowdPeerProvider public void deliverBroadcast ( ClientObject caller, Name from, byte levelOrMode, String bundle, String msg) { // deliver the broadcast locally on this server _chatprov.broadcast(from, levelOrMode, bundle, msg, false); } // from interface ChatProvider.ChatForwarder public boolean forwardTell (UserMessage message, Name target, ChatService.TellListener listener) { // look up their auth username from their visible name Name username = _viztoauth.get(target); if (username == null) { return false; // sorry kid, don't know ya } // look through our peers to see if the target user is online on one of them for (PeerNode peer : _peers.values()) { CrowdNodeObject cnobj = (CrowdNodeObject)peer.nodeobj; if (cnobj == null) { continue; } // we have to use auth username to look up their ClientInfo CrowdClientInfo cinfo = (CrowdClientInfo)cnobj.clients.get(username); if (cinfo != null) { cnobj.crowdPeerService.deliverTell(peer.getClient(), message, target, listener); return true; } } return false; } // from interface ChatProvider.ChatForwarder public void forwardBroadcast (Name from, byte levelOrMode, String bundle, String msg) { for (PeerNode peer : _peers.values()) { if (peer.nodeobj != null) { ((CrowdNodeObject)peer.nodeobj).crowdPeerService.deliverBroadcast( peer.getClient(), from, levelOrMode, bundle, msg); } } } @Override // from PeerManager public void shutdown () { super.shutdown(); // unregister our invocation service if (_nodeobj != null) { _invmgr.clearDispatcher(((CrowdNodeObject)_nodeobj).crowdPeerService); } // clear our chat forwarder registration _chatprov.setChatForwarder(null); } @Override // from PeerManager protected NodeObject createNodeObject () { return new CrowdNodeObject(); } @Override // from PeerManager protected ClientInfo createClientInfo () { return new CrowdClientInfo(); } @Override // from PeerManager protected void initClientInfo (PresentsSession client, ClientInfo info) { super.initClientInfo(client, info); ((CrowdClientInfo)info).visibleName = ((BodyObject)client.getClientObject()).getVisibleName(); } @Override // from PeerManager protected void didInit () { super.didInit(); // register and initialize our invocation service CrowdNodeObject cnobj = (CrowdNodeObject)_nodeobj; cnobj.setCrowdPeerService(_invmgr.registerDispatcher(new CrowdPeerDispatcher(this))); // register ourselves as a chat forwarder _chatprov.setChatForwarder(this); } @Override // from PeerManager protected void clientLoggedOn (String nodeName, ClientInfo clinfo) { super.clientLoggedOn(nodeName, clinfo); // keep a mapping from visibleName to auth username if (clinfo instanceof CrowdClientInfo) { CrowdClientInfo ccinfo = (CrowdClientInfo)clinfo; _viztoauth.put(ccinfo.visibleName, ccinfo.username); } } @Override // from PeerManager protected void clientLoggedOff (String nodeName, ClientInfo clinfo) { super.clientLoggedOff(nodeName, clinfo); // update our mapping from visibleName to auth username if (clinfo instanceof CrowdClientInfo) { CrowdClientInfo ccinfo = (CrowdClientInfo)clinfo; _viztoauth.remove(ccinfo.visibleName); } } /** A mapping of visible name to username for all clients on all *remote* nodes. */ protected Map<Name, Name> _viztoauth = Maps.newHashMap(); @Inject protected InvocationManager _invmgr; @Inject protected ChatProvider _chatprov; }
Bugfix: chat bug. If node A started up and connected to node B, which already had players logged on, then nobody on A could send chat to anyone on B. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5695 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/crowd/peer/server/CrowdPeerManager.java
Bugfix: chat bug. If node A started up and connected to node B, which already had players logged on, then nobody on A could send chat to anyone on B.
<ide><path>rc/java/com/threerings/crowd/peer/server/CrowdPeerManager.java <ide> } <ide> } <ide> <add> @Override // from PeerManager <add> protected void connectedToPeer (PeerNode peer) <add> { <add> super.connectedToPeer(peer); <add> <add> for (ClientInfo clinfo : peer.nodeobj.clients) { <add> if (clinfo instanceof CrowdClientInfo) { <add> CrowdClientInfo ccinfo = (CrowdClientInfo)clinfo; <add> _viztoauth.put(ccinfo.visibleName, ccinfo.username); <add> } <add> } <add> } <add> <ide> /** A mapping of visible name to username for all clients on all *remote* nodes. */ <ide> protected Map<Name, Name> _viztoauth = Maps.newHashMap(); <ide>
JavaScript
mit
28ca73159d8615a5feb6085e9b11512aadc19925
0
SlateFoundation/opened.js,openedinc/opened.js,SlateFoundation/opened.js,SlateFoundation/opened.js,openedinc/opened.js,openedinc/opened.js,SlateFoundation/opened.js,openedinc/opened.js
;(function (root) { 'use strict'; root.OpenEd = root.OpenEd || {}; root.OpenEd.api = { tokenPrefix: '_openEd', apiHost: 'https://api.opened.io', openedHost: 'https://www.opened.com', _events: {}, on: function (eventName, callback) { if (eventName && typeof callback === 'function') { this._events[eventName] = this._events[eventName] || []; this._events[eventName].push(callback); } }, off: function (eventName, callback) { var eventsArr = this._events[eventName]; if (eventsArr && typeof callback === 'function') { var callbackIndex = eventsArr.indexOf(callback); if (callbackIndex !== -1) { eventsArr.slice(callbackIndex, 1); } } }, trigger: function (eventName) { var data = Array.prototype.slice.call(arguments).shift(), eventsArr = this._events[eventName] || []; eventsArr.forEach(function (callback) { callback.apply(null, data); }); }, init: function (options, callback) { if (!options || !options.client_id) { throw new Error('Bad init options.'); } this.options = options; var token = this.getToken(); if (token && options.status) { //check logged in status var self = this; this.checkLoginStatus(function () { self.trigger('auth.userLoggedIn'); (typeof callback !== 'function') || callback(); }); } else { (typeof callback !== 'function') || callback(); } }, runOnInit: function () { (typeof root.OpenEd.oninit !== 'function') || root.OpenEd.oninit() }, silentLogin: function(signedRequest, callback, errorCallback) { var self = this; self.xhr({ type: 'POST', url: self.apiHost + '/oauth/silent_login', raw_data: signedRequest, success: function(data){ self.saveToken(data); (typeof callback !== 'function') || callback(); }, error: errorCallback }); }, login: function (callback) { this._lastCallback = callback; var params = '?mode=implict'; var self = this; ['client_id', 'redirect_uri'].forEach(function (paramName) { var paramValue = self.options[paramName]; if (paramValue) { params += '&' + paramName + '=' + paramValue } }); var popup = window.open(this.openedHost + '/oauth/authorize' + params, '_blank', 'width=500, height=300'); popup.focus && popup.focus(); }, logout: function (callback) { var self = this; var token = self.getToken(); if (token) { this.xhr({ type: 'POST', url: self.apiHost + '/oauth/revoke', data: {token: token}, success: function () { self.resetToken(); callback && callback(); }, error: function () { self.resetToken(); callback && callback(); }, headers: { Authorization: 'Bearer ' + self.getToken() } }); } else { self.resetToken(); callback && callback(); } }, resetToken: function () { localStorage.removeItem(this.tokenPrefix + '.access_token'); this.trigger('auth.userSignedOut'); }, saveToken: function (tokenData) { for (var name in tokenData) { localStorage.setItem(this.tokenPrefix + '.' + name, tokenData[name]); } }, getToken: function () { return localStorage.getItem(this.tokenPrefix + '.access_token'); }, parseJSON: function (str) { try { return JSON.parse(str); } catch (e) { return null; } }, objToQueryString: function (obj) { return '?' + Object.keys(obj).map(function(key) { return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]); }).join('&'); }, xhr: function (options) { var xmlhttp = new XMLHttpRequest(), self = this, response; xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4) { response = self.parseJSON(xmlhttp.responseText); if (xmlhttp.status == 200 && response) { options.success(response); } else if (xmlhttp.status >= 400 && typeof options.error === 'function') { options.error(response || { error: 'HTTP ' + xmlhttp.status + ': ' + (xmlhttp.statusText || 'Unknown error') }); } } }; var type = options.type || 'GET'; var url = options.url; if (type === 'GET' && typeof options.data === 'object') { url += self.objToQueryString(options.data); } xmlhttp.open(type, url, true); if (type === 'POST') { if (options.raw_data){ xmlhttp.setRequestHeader('Content-Type', 'text/plain'); }else{ xmlhttp.setRequestHeader('Content-Type', 'application/json'); } } if (options.headers) { for (var name in options.headers) { xmlhttp.setRequestHeader(name, options.headers[name]); } } if (type !== 'GET') { if(options.raw_data){ xmlhttp.send(options.raw_data); }else{ xmlhttp.send(JSON.stringify(options.data)); } } else { xmlhttp.send(); } }, request: function (api, data, callback, errorCallback) { var self = this; data.access_token = self.getToken(); this.xhr({ url: this.apiHost + api, data: data, success: callback, error: errorCallback, headers: { Authorization: 'Bearer ' + self.getToken() } }); }, verifyToken: function (callback) { var self = this; if (this.checkTokenDate()) { this.request('/oauth/token/info', null, function (token) { if (token && token.application && token.application.uid && token.application.uid === self.options.client_id) { callback(); } else { self.resetToken(); callback(new Error('Wrong client id')); } }, function (error) { self.resetToken(); callback(error); }); } else { callback(new Error('token has expired')); } }, checkTokenDate: function () { var tokenDate = new Date(parseInt(localStorage.getItem(this.tokenPrefix + '.expires_in'), 10)); return new Date() < tokenDate; }, expireDate: function (expiresIn) { var date = new Date(); date.setTime(date.getTime() + (parseInt(expiresIn) * 1000, 10)); return date; }, checkLoginStatus: function (callback) { this.verifyToken(function (err) { if (err) { callback(err); } else { callback(); } }); }, _setToken: function (token) { this.saveToken(this.parseToken(token)); var self = this; this.verifyToken(function (err) { if (!err) { self.trigger('auth.userLoggedIn', token); } self._lastCallback && self._lastCallback(err); }) }, parseToken: function (token) { var params = token.substr(1); var result = {}; params.split('&').forEach(function (paramPairStr) { var paramPair = paramPairStr.split('='); result[paramPair[0]] = paramPair[1]; }); if (result.expires_in) { result.expires_in = this.expireDate(result.expires_in).getTime(); } return result; } }; root.OpenEd.api.runOnInit(); })(this);
opened-api.js
;(function (root) { 'use strict'; root.OpenEd = root.OpenEd || {}; root.OpenEd.api = { tokenPrefix: '_openEd', apiHost: 'https://api.opened.io', openedHost: 'https://www.opened.com', _events: {}, on: function (eventName, callback) { if (eventName && typeof callback === 'function') { this._events[eventName] = this._events[eventName] || []; this._events[eventName].push(callback); } }, off: function (eventName, callback) { var eventsArr = this._events[eventName]; if (eventsArr && typeof callback === 'function') { var callbackIndex = eventsArr.indexOf(callback); if (callbackIndex !== -1) { eventsArr.slice(callbackIndex, 1); } } }, trigger: function (eventName) { var data = Array.prototype.slice.call(arguments).shift(), eventsArr = this._events[eventName] || []; eventsArr.forEach(function (callback) { callback.apply(null, data); }); }, init: function (options, callback) { if (!options || !options.client_id) { throw new Error('Bad init options.'); } this.options = options; var token = this.getToken(); if (token && options.status) { //check logged in status var self = this; this.checkLoginStatus(function () { self.trigger('auth.userLoggedIn'); (typeof callback !== 'function') || callback(); }); } else { (typeof callback !== 'function') || callback(); } }, runOnInit: function () { (typeof root.OpenEd.oninit !== 'function') || root.OpenEd.oninit() }, silentLogin: function(signedRequest, callback, errorCallback) { var self = this; self.xhr({ type: 'POST', url: self.apiHost + '/oauth/silent_login', raw_data: signedRequest, success: function(data){ self.saveToken(data); (typeof callback !== 'function') || callback(); }, error: errorCallback }); }, login: function (callback) { this._lastCallback = callback; var params = '?mode=implict'; var self = this; ['client_id', 'redirect_uri'].forEach(function (paramName) { var paramValue = self.options[paramName]; if (paramValue) { params += '&' + paramName + '=' + paramValue } }); var popup = window.open(this.openedHost + '/oauth/authorize' + params, '_blank', 'width=500, height=300'); popup.focus && popup.focus(); }, logout: function (callback) { var self = this; var token = self.getToken(); if (token) { this.xhr({ type: 'POST', url: self.apiHost + '/oauth/revoke', data: {token: token}, success: function () { self.resetToken(); callback && callback(); }, error: function () { self.resetToken(); callback && callback(); }, headers: { Authorization: 'Bearer ' + self.getToken() } }); } else { self.resetToken(); callback && callback(); } }, resetToken: function () { localStorage.removeItem(this.tokenPrefix + '.access_token'); this.trigger('auth.userSignedOut'); }, saveToken: function (tokenData) { for (var name in tokenData) { localStorage.setItem(this.tokenPrefix + '.' + name, tokenData[name]); } }, getToken: function () { return localStorage.getItem(this.tokenPrefix + '.access_token'); }, parseJSON: function (str) { try { return JSON.parse(str); } catch (e) { return null; } }, objToQueryString: function (obj) { return '?' + Object.keys(obj).map(function(key) { return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]); }).join('&'); }, xhr: function (options) { var xmlhttp = new XMLHttpRequest(), self = this, response; xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4) { response = self.parseJSON(xmlhttp.responseText); if (xmlhttp.status == 200 && response) { options.success(response); } else if (xmlhttp.status >= 400 && typeof options.error === 'function') { options.error(response || { error: 'HTTP ' + xmlhttp.status + ': ' + (xmlhttp.statusText || 'Unknown error') }); } } }; var type = options.type || 'GET'; var url = options.url; if (type === 'GET' && typeof options.data === 'object') { url += self.objToQueryString(options.data); } xmlhttp.open(type, url, true); if (type === 'POST') { if (options.raw_data){ xmlhttp.setRequestHeader('Content-Type', 'text/plain'); }else{ xmlhttp.setRequestHeader('Content-Type', 'application/json'); } } if (options.headers) { for (var name in options.headers) { xmlhttp.setRequestHeader(name, options.headers[name]); } } if (type !== 'GET') { if(options.raw_data){ xmlhttp.send(options.raw_data); }else{ xmlhttp.send(JSON.stringify(options.data)); } } else { xmlhttp.send(); } }, request: function (api, data, callback, errorCallback) { var self = this; data.access_token = self.getToken(); this.xhr({ url: this.apiHost + api, data: data, success: callback, error: errorCallback, headers: { Authorization: 'Bearer ' + self.getToken() } }); }, verifyToken: function (callback) { var self = this; if (this.checkTokenDate()) { this.request('/oauth/token/info', null, function (token) { if (token && token.application && token.application.uid && token.application.uid === self.options.client_id) { callback(); } else { self.resetToken(); callback(new Error('Wrong client id')); } }, function (error) { self.resetToken(); callback(error); }); } else { callback(new Error('token has expired')); } }, checkTokenDate: function () { var tokenDate = new Date(parseInt(localStorage.getItem(this.tokenPrefix + '.expires_in'), 10)); var now = this.now(); return now.getTime() < tokenDate.getTime(); }, expireDate: function (expiresIn) { var date = this.now(); date.setTime(date.getTime() + (parseInt(expiresIn) * 1000, 10)); return date; }, now: function () { return new Date(); }, checkLoginStatus: function (callback) { this.verifyToken(function (err) { if (err) { callback(err); } else { callback(); } }); }, _setToken: function (token) { this.saveToken(this.parseToken(token)); var self = this; this.verifyToken(function (err) { if (!err) { self.trigger('auth.userLoggedIn', token); } self._lastCallback && self._lastCallback(err); }) }, parseToken: function (token) { var params = token.substr(1); var result = {}; params.split('&').forEach(function (paramPairStr) { var paramPair = paramPairStr.split('='); result[paramPair[0]] = paramPair[1]; }); if (result.expires_in) { result.expires_in = this.expireDate(result.expires_in).getTime(); } return result; } }; root.OpenEd.api.runOnInit(); })(this);
Simplify date handling
opened-api.js
Simplify date handling
<ide><path>pened-api.js <ide> <ide> checkTokenDate: function () { <ide> var tokenDate = new Date(parseInt(localStorage.getItem(this.tokenPrefix + '.expires_in'), 10)); <del> var now = this.now(); <del> return now.getTime() < tokenDate.getTime(); <add> return new Date() < tokenDate; <ide> }, <ide> <ide> expireDate: function (expiresIn) { <del> var date = this.now(); <add> var date = new Date(); <ide> date.setTime(date.getTime() + (parseInt(expiresIn) * 1000, 10)); <ide> return date; <del> }, <del> <del> now: function () { <del> return new Date(); <ide> }, <ide> <ide> checkLoginStatus: function (callback) {
Java
apache-2.0
cb14ac5c57661d53765a855209bfd91a02821730
0
tmurakami/dexopener,tmurakami/dexopener
/* * Copyright 2016 Tsuyoshi Murakami * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dexopener.simple; import android.app.Application; import android.content.Context; import android.support.test.runner.AndroidJUnitRunner; import com.github.tmurakami.dexopener.DexOpener; public class MyAndroidJUnitRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws ClassNotFoundException, IllegalAccessException, InstantiationException { DexOpener.install(this); // Call me first! return super.newApplication(cl, className, context); } }
dexopener-example/simple/src/androidTest/java/com/example/dexopener/simple/MyAndroidJUnitRunner.java
/* * Copyright 2016 Tsuyoshi Murakami * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dexopener.simple; import android.app.Application; import android.content.Context; import android.support.test.runner.AndroidJUnitRunner; import com.github.tmurakami.dexopener.DexOpener; public class MyAndroidJUnitRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws ClassNotFoundException, IllegalAccessException, InstantiationException { DexOpener.install(this); return super.newApplication(cl, className, context); } }
Tweak comments
dexopener-example/simple/src/androidTest/java/com/example/dexopener/simple/MyAndroidJUnitRunner.java
Tweak comments
<ide><path>exopener-example/simple/src/androidTest/java/com/example/dexopener/simple/MyAndroidJUnitRunner.java <ide> @Override <ide> public Application newApplication(ClassLoader cl, String className, Context context) <ide> throws ClassNotFoundException, IllegalAccessException, InstantiationException { <del> DexOpener.install(this); <add> DexOpener.install(this); // Call me first! <ide> return super.newApplication(cl, className, context); <ide> } <ide> }
Java
agpl-3.0
787e493990ad72ce4a6144de4d1849a8069131bb
0
PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver
package nl.mpi.kinnate.kintypestrings; import javax.xml.bind.annotation.XmlAttribute; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.DataTypes.RelationType; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityData.SymbolType; import nl.mpi.kinnate.kindata.EntityRelation; /** * Document : KinType * Created on : Jun 28, 2011, 11:31:35 AM * Author : Peter Withers */ public class KinType implements Comparable<KinType> { private KinType() { } public KinType(String codeStringLocal, DataTypes.RelationType[] relationTypes, EntityData.SymbolType[] symbolTypes, String displayStringLocal) { codeString = codeStringLocal; this.relationTypes = relationTypes; this.symbolTypes = symbolTypes; displayString = displayStringLocal; } @XmlAttribute(name = "code", namespace = "http://mpi.nl/tla/kin") protected String codeString = null; @XmlAttribute(name = "type", namespace = "http://mpi.nl/tla/kin") private DataTypes.RelationType[] relationTypes = null; @XmlAttribute(name = "symbol", namespace = "http://mpi.nl/tla/kin") private EntityData.SymbolType[] symbolTypes = null; @XmlAttribute(name = "name", namespace = "http://mpi.nl/tla/kin") protected String displayString = null; public String getCodeString() { return codeString; } public String getDisplayString() { return displayString; } public RelationType[] getRelationTypes() { return relationTypes; } public boolean hasNoRelationTypes() { // null means any relation type so this must not be null but a length of zero to indicate no relations return relationTypes != null && relationTypes.length == 0; } public SymbolType[] getSymbolTypes() { return symbolTypes; } public boolean isEgoType() { // todo: this could be better handled by adding a boolean: isego to each KinType return codeString.contains("E"); } public boolean matchesRelation(EntityRelation entityRelation, String kinTypeModifier) { // todo: make use of the kin type modifier if (entityRelation.getAlterNode().isEgo != this.isEgoType()) { return false; } boolean relationMatchFound = false; if (relationTypes == null) { relationMatchFound = true; // null will match all relation types } else { for (DataTypes.RelationType relationType : relationTypes) { if (relationType.equals(entityRelation.getRelationType())) { relationMatchFound = true; } } } boolean symbolMatchFound = false; if (symbolTypes == null) { symbolMatchFound = true; // null will match all symbol types } else { for (EntityData.SymbolType symbolType : symbolTypes) { // square was the wildcard symbol but now a null symbol array is used and since it is not null we compare all symbols in the array if (symbolType.name().equals(entityRelation.getAlterNode().getSymbolType())) { symbolMatchFound = true; } } } if (!relationMatchFound || !symbolMatchFound) { return false; } // compare the birth order if (kinTypeModifier != null && !kinTypeModifier.isEmpty()) { int relationOrder = entityRelation.getRelationOrder(); if (kinTypeModifier.equals("-")) { if (relationOrder >= 0) { return false; } } else if (kinTypeModifier.equals("+")) { if (relationOrder <= 0) { return false; } } else { // handle integer syntax ie EMD+3 for the third daughter int requiredOrder = Integer.parseInt(kinTypeModifier.replaceFirst("^\\+", "")); return (relationOrder == requiredOrder); } } return true; } public boolean matchesEgonessAndSymbol(EntityData entityData, String kinTypeModifier) { // todo: make use of the kin type modifier or remove it if it proves irelevant if (!entityData.isEgo || !this.isEgoType()) { return false; } if (symbolTypes == null) { return true; // null will match all symbols } // square used to be the wildcard symbol but now a null symbol array is used and since we know it is not null we compare all symbols in the array for (EntityData.SymbolType symbolType : symbolTypes) { if (symbolType.name().equals(entityData.getSymbolType())) { return true; } } return false; } public int compareTo(KinType o) { if (o == null) { return -1; } if (codeString.length() > o.codeString.length()) { return -1; } return codeString.compareToIgnoreCase(o.codeString); } public static KinType[] getReferenceKinTypes() { return referenceKinTypes; } private static KinType[] referenceKinTypes = new KinType[]{ // other types // todo: the gendered ego kin types Em and Ef are probably not correct and should be verified new KinType("Ef", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Ego Female"), new KinType("Em", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Ego Male"), // type 1 new KinType("Fa", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Father"), new KinType("Mo", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Mother"), new KinType("Br", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Brother"), new KinType("Si", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Sister"), new KinType("So", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Son"), new KinType("Da", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Daughter"), new KinType("Hu", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Husband"), new KinType("Wi", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Wife"), new KinType("Pa", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Parent"), new KinType("Sb", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Sibling"), //todo: are Sp and Sb correct? new KinType("Sp", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Spouse"), new KinType("Ch", new DataTypes.RelationType[]{DataTypes.RelationType.descendant,}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Child"), // type 2 new KinType("F", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Father"), new KinType("M", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Mother"), new KinType("B", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Brother"), new KinType("Z", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Sister"), new KinType("S", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Son"), new KinType("D", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Daughter"), new KinType("H", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Husband"), new KinType("W", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Wife"), new KinType("P", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Parent"), new KinType("G", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Sibling"), new KinType("E", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Ego"), new KinType("C", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Child"), // new KinType("X", DataTypes.RelationType.none, EntityData.SymbolType.none) // X is intended to indicate unknown or no type, for instance this is used after import to add all nodes to the graph // non ego types to be used to start a kin type string but cannot be used except at the beginning new KinType("m", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Male"), new KinType("f", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Female"), new KinType("x", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Undefined"), new KinType("*", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor, DataTypes.RelationType.descendant, DataTypes.RelationType.union, DataTypes.RelationType.sibling}, null, "Any Relation"),}; }
desktop/src/main/java/nl/mpi/kinnate/kintypestrings/KinType.java
package nl.mpi.kinnate.kintypestrings; import javax.xml.bind.annotation.XmlAttribute; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.DataTypes.RelationType; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityData.SymbolType; import nl.mpi.kinnate.kindata.EntityRelation; /** * Document : KinType * Created on : Jun 28, 2011, 11:31:35 AM * Author : Peter Withers */ public class KinType implements Comparable<KinType> { private KinType() { } public KinType(String codeStringLocal, DataTypes.RelationType[] relationTypes, EntityData.SymbolType[] symbolTypes, String displayStringLocal) { codeString = codeStringLocal; this.relationTypes = relationTypes; this.symbolTypes = symbolTypes; displayString = displayStringLocal; } @XmlAttribute(name = "code", namespace = "http://mpi.nl/tla/kin") protected String codeString = null; @XmlAttribute(name = "type", namespace = "http://mpi.nl/tla/kin") private DataTypes.RelationType[] relationTypes = null; @XmlAttribute(name = "symbol", namespace = "http://mpi.nl/tla/kin") private EntityData.SymbolType[] symbolTypes = null; @XmlAttribute(name = "name", namespace = "http://mpi.nl/tla/kin") protected String displayString = null; public String getCodeString() { return codeString; } public String getDisplayString() { return displayString; } public RelationType[] getRelationTypes() { return relationTypes; } public boolean hasNoRelationTypes() { // null means any relation type so this must not be null but a length of zero to indicate no relations return relationTypes != null && relationTypes.length == 0; } public SymbolType[] getSymbolTypes() { return symbolTypes; } public boolean isEgoType() { // todo: this could be better handled by adding a boolean: isego to each KinType return codeString.contains("E"); } public boolean matchesRelation(EntityRelation entityRelation, String kinTypeModifier) { // todo: make use of the kin type modifier if (entityRelation.getAlterNode().isEgo != this.isEgoType()) { return false; } boolean relationMatchFound = false; if (relationTypes == null) { relationMatchFound = true; // null will match all relation types } else { for (DataTypes.RelationType relationType : relationTypes) { if (relationType.equals(entityRelation.getRelationType())) { relationMatchFound = true; } } } boolean symbolMatchFound = false; if (symbolTypes == null) { symbolMatchFound = true; // null will match all symbol types } else { for (EntityData.SymbolType symbolType : symbolTypes) { // square was the wildcard symbol but now a null symbol array is used and since it is not null we compare all symbols in the array if (symbolType.name().equals(entityRelation.getAlterNode().getSymbolType())) { symbolMatchFound = true; } } } if (!relationMatchFound || !symbolMatchFound) { return false; } // compare the birth order if (kinTypeModifier != null && !kinTypeModifier.isEmpty()) { int relationOrder = entityRelation.getRelationOrder(); if (kinTypeModifier.equals("-")) { if (relationOrder >= 0) { return false; } } else if (kinTypeModifier.equals("+")) { if (relationOrder <= 0) { return false; } } else { // handle integer syntax ie EMD+3 for the third daughter int requiredOrder = Integer.parseInt(kinTypeModifier.replaceFirst("^\\+", "")); return (relationOrder == requiredOrder); } } return true; } public boolean matchesEgonessAndSymbol(EntityData entityData, String kinTypeModifier) { // todo: make use of the kin type modifier or remove it if it proves irelevant if (!entityData.isEgo || !this.isEgoType()) { return false; } if (symbolTypes == null) { return true; // null will match all symbols } // square used to be the wildcard symbol but now a null symbol array is used and since we know it is not null we compare all symbols in the array for (EntityData.SymbolType symbolType : symbolTypes) { if (symbolType.name().equals(entityData.getSymbolType())) { return true; } } return false; } public int compareTo(KinType o) { if (o == null) { return -1; } if (codeString.length() > o.codeString.length()) { return -1; } return codeString.compareToIgnoreCase(o.codeString); } public static KinType[] getReferenceKinTypes() { return referenceKinTypes; } private static KinType[] referenceKinTypes = new KinType[]{ // other types // todo: the gendered ego kin types Em and Ef are probably not correct and should be verified new KinType("Ef", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Ego Female"), new KinType("Em", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Ego Male"), // type 1 new KinType("Fa", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Father"), new KinType("Mo", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Mother"), new KinType("Br", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Brother"), new KinType("Si", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Sister"), new KinType("So", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Son"), new KinType("Da", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Daughter"), new KinType("Hu", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Husband"), new KinType("Wi", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Wife"), new KinType("Pa", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Parent"), new KinType("Sb", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Sibling"), //todo: are Sp and Sb correct? new KinType("Sp", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Spouse"), new KinType("Ch", new DataTypes.RelationType[]{DataTypes.RelationType.descendant,}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Child"), // type 2 new KinType("F", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Father"), new KinType("M", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Mother"), new KinType("B", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Brother"), new KinType("Z", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Sister"), new KinType("S", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Son"), new KinType("D", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Daughter"), new KinType("H", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Husband"), new KinType("W", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Wife"), new KinType("P", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Parent"), new KinType("G", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Sibling"), new KinType("E", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Ego"), new KinType("C", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Child"), // new KinType("X", DataTypes.RelationType.none, EntityData.SymbolType.none) // X is intended to indicate unknown or no type, for instance this is used after import to add all nodes to the graph // non ego types to be used to start a kin type string but cannot be used except at the beginning new KinType("m", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Male"), new KinType("f", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Female"), new KinType("x", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Undefined"), new KinType("*", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor, DataTypes.RelationType.descendant, DataTypes.RelationType.union, DataTypes.RelationType.sibling}, null, "Any Relation"),}; }
Updated the kin type matching to better handle wild cards (for either relation or symbol) and corrected an issue matching existing related entities. Updated the sample diagrams to match and test the multiple symbol and relation kin types.
desktop/src/main/java/nl/mpi/kinnate/kintypestrings/KinType.java
Updated the kin type matching to better handle wild cards (for either relation or symbol) and corrected an issue matching existing related entities. Updated the sample diagrams to match and test the multiple symbol and relation kin types.
<ide><path>esktop/src/main/java/nl/mpi/kinnate/kintypestrings/KinType.java <ide> new KinType("Hu", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Husband"), <ide> new KinType("Wi", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Wife"), <ide> new KinType("Pa", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Parent"), <del> new KinType("Sb", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Sibling"), //todo: are Sp and Sb correct? <del> new KinType("Sp", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Spouse"), <del> new KinType("Ch", new DataTypes.RelationType[]{DataTypes.RelationType.descendant,}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Child"), <add> new KinType("Sb", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Sibling"), //todo: are Sp and Sb correct? <add> new KinType("Sp", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Spouse"), <add> new KinType("Ch", new DataTypes.RelationType[]{DataTypes.RelationType.descendant,}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Child"), <ide> // type 2 <ide> new KinType("F", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Father"), <ide> new KinType("M", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Mother"), <ide> new KinType("H", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle}, "Husband"), <ide> new KinType("W", new DataTypes.RelationType[]{DataTypes.RelationType.union}, new EntityData.SymbolType[]{EntityData.SymbolType.circle}, "Wife"), <ide> new KinType("P", new DataTypes.RelationType[]{DataTypes.RelationType.ancestor}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Parent"), <del> new KinType("G", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Sibling"), <add> new KinType("G", new DataTypes.RelationType[]{DataTypes.RelationType.sibling}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Sibling"), <ide> new KinType("E", new DataTypes.RelationType[]{}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Ego"), <del> new KinType("C", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.square}, "Child"), <add> new KinType("C", new DataTypes.RelationType[]{DataTypes.RelationType.descendant}, new EntityData.SymbolType[]{EntityData.SymbolType.triangle, EntityData.SymbolType.circle}, "Child"), <ide> // new KinType("X", DataTypes.RelationType.none, EntityData.SymbolType.none) // X is intended to indicate unknown or no type, for instance this is used after import to add all nodes to the graph <ide> <ide> // non ego types to be used to start a kin type string but cannot be used except at the beginning
Java
apache-2.0
697ee5dc89cae7395ba7a6ebbb53973dea45ae4c
0
amzn/alexa-skills-kit-java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file * except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for * the specific language governing permissions and limitations under the License. */ package com.amazon.ask.dispatcher.request.handler.impl; import com.amazon.ask.dispatcher.request.handler.HandlerInput; import com.amazon.ask.dispatcher.request.handler.RequestHandler; import com.amazon.ask.model.interfaces.alexa.presentation.aplt.UserEvent; import com.amazon.ask.model.Response; import java.util.Optional; /** * Request handler for UserEvent requests. */ public interface UserEventHandler extends RequestHandler { /** * Returns true if the handler can dispatch the current request * * @param input input to the request handler * @param userEvent UserEvent request * @return true if the handler is capable of handling the current request and/or state */ boolean canHandle(HandlerInput input, UserEvent userEvent); /** * Handles the request. * * @param input input to the request handler * @param userEvent UserEvent request * @return output from the handler. */ Optional<Response> handle(HandlerInput input, UserEvent userEvent); @Override default boolean canHandle(HandlerInput handlerInput) { if (handlerInput.getRequest() instanceof UserEvent) { return canHandle(handlerInput, (UserEvent)handlerInput.getRequest()); } return false; } @Override default Optional<Response> handle(HandlerInput handlerInput) { return handle(handlerInput, (UserEvent)handlerInput.getRequest()); } }
ask-sdk-core/src/com/amazon/ask/dispatcher/request/handler/impl/UserEventHandler.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file * except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for * the specific language governing permissions and limitations under the License. */ package com.amazon.ask.dispatcher.request.handler.impl; import com.amazon.ask.dispatcher.request.handler.HandlerInput; import com.amazon.ask.dispatcher.request.handler.RequestHandler; import com.amazon.ask.model.interfaces.alexa.presentation.apl.UserEvent; import com.amazon.ask.model.Response; import java.util.Optional; /** * Request handler for UserEvent requests. */ public interface UserEventHandler extends RequestHandler { /** * Returns true if the handler can dispatch the current request * * @param input input to the request handler * @param userEvent UserEvent request * @return true if the handler is capable of handling the current request and/or state */ boolean canHandle(HandlerInput input, UserEvent userEvent); /** * Handles the request. * * @param input input to the request handler * @param userEvent UserEvent request * @return output from the handler. */ Optional<Response> handle(HandlerInput input, UserEvent userEvent); @Override default boolean canHandle(HandlerInput handlerInput) { if (handlerInput.getRequest() instanceof UserEvent) { return canHandle(handlerInput, (UserEvent)handlerInput.getRequest()); } return false; } @Override default Optional<Response> handle(HandlerInput handlerInput) { return handle(handlerInput, (UserEvent)handlerInput.getRequest()); } }
Updating typed request handler interfaces
ask-sdk-core/src/com/amazon/ask/dispatcher/request/handler/impl/UserEventHandler.java
Updating typed request handler interfaces
<ide><path>sk-sdk-core/src/com/amazon/ask/dispatcher/request/handler/impl/UserEventHandler.java <ide> <ide> import com.amazon.ask.dispatcher.request.handler.HandlerInput; <ide> import com.amazon.ask.dispatcher.request.handler.RequestHandler; <del>import com.amazon.ask.model.interfaces.alexa.presentation.apl.UserEvent; <add>import com.amazon.ask.model.interfaces.alexa.presentation.aplt.UserEvent; <ide> import com.amazon.ask.model.Response; <ide> <ide> import java.util.Optional;
Java
apache-2.0
dcd9ea6e9d370badeaece443a0653e80a0c6472a
0
nicolargo/intellij-community,apixandru/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,holmes/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,signed/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,semonte/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,ryano144/intellij-community,petteyg/intellij-community,asedunov/intellij-community,hurricup/intellij-community,izonder/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,kool79/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,allotria/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,slisson/intellij-community,ibinti/intellij-community,vladmm/intellij-community,fitermay/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,caot/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,petteyg/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,signed/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,fitermay/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,kool79/intellij-community,retomerz/intellij-community,robovm/robovm-studio,xfournet/intellij-community,FHannes/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,allotria/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,diorcety/intellij-community,holmes/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,kool79/intellij-community,slisson/intellij-community,izonder/intellij-community,robovm/robovm-studio,blademainer/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,holmes/intellij-community,fnouama/intellij-community,slisson/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,fnouama/intellij-community,ibinti/intellij-community,ibinti/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,caot/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,signed/intellij-community,apixandru/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,slisson/intellij-community,supersven/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,kdwink/intellij-community,adedayo/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,semonte/intellij-community,blademainer/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,ibinti/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,izonder/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ryano144/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,da1z/intellij-community,petteyg/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,izonder/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,semonte/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,caot/intellij-community,holmes/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,retomerz/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,signed/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,robovm/robovm-studio,holmes/intellij-community,FHannes/intellij-community,vladmm/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,robovm/robovm-studio,vladmm/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,da1z/intellij-community,da1z/intellij-community,clumsy/intellij-community,holmes/intellij-community,asedunov/intellij-community,petteyg/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,amith01994/intellij-community,adedayo/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,da1z/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,FHannes/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,kool79/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,signed/intellij-community,semonte/intellij-community,orekyuu/intellij-community,allotria/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,vladmm/intellij-community,signed/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,clumsy/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,nicolargo/intellij-community,slisson/intellij-community,caot/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,allotria/intellij-community,hurricup/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,kool79/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,robovm/robovm-studio,fitermay/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,xfournet/intellij-community,adedayo/intellij-community,supersven/intellij-community,amith01994/intellij-community,da1z/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,asedunov/intellij-community,samthor/intellij-community,youdonghai/intellij-community,izonder/intellij-community,kdwink/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,retomerz/intellij-community,hurricup/intellij-community,adedayo/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,ryano144/intellij-community,allotria/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,fnouama/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,blademainer/intellij-community,FHannes/intellij-community,samthor/intellij-community,vladmm/intellij-community,adedayo/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,izonder/intellij-community,diorcety/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,slisson/intellij-community,dslomov/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ryano144/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,retomerz/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,fnouama/intellij-community,semonte/intellij-community,apixandru/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ryano144/intellij-community,signed/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,caot/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ryano144/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,amith01994/intellij-community,caot/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,izonder/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,dslomov/intellij-community,caot/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,semonte/intellij-community,slisson/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,FHannes/intellij-community,apixandru/intellij-community,retomerz/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,retomerz/intellij-community,holmes/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,allotria/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,allotria/intellij-community,vvv1559/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,caot/intellij-community,blademainer/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,asedunov/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,xfournet/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,slisson/intellij-community,hurricup/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,asedunov/intellij-community,fnouama/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,samthor/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,caot/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,izonder/intellij-community,caot/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,supersven/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community
package com.jetbrains.python; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.jetbrains.python.fixtures.PyResolveTestCase; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher; import com.jetbrains.python.psi.types.PyClassType; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; import com.jetbrains.python.toolbox.Maybe; import junit.framework.TestSuite; /** * Tests property API. * User: dcheryasov * Date: Jun 30, 2010 8:09:12 AM */ public class PyPropertyTestSuite { public static TestSuite suite() { return new TestSuite(PyClassicPropertyTest.class); } abstract static class PyPropertyTest extends PyResolveTestCase { protected PyClass myClass; protected LanguageLevel myLanguageLevel = LanguageLevel.PYTHON26; @Override protected void setUp() throws Exception { super.setUp(); PsiReference ref = configureByFile("property/"+ "Classic.py"); final Project project = ref.getElement().getContainingFile().getProject(); project.putUserData(PyBuiltinCache.TEST_SDK, PythonMockSdk.findOrCreate()); PythonLanguageLevelPusher.setForcedLanguageLevel(project, myLanguageLevel); PsiElement elt = ref.resolve(); assertInstanceOf(elt, PyExpression.class); PyType type = ((PyExpression)elt).getType(TypeEvalContext.slow()); assertInstanceOf(type, PyClassType.class); myClass = ((PyClassType)type).getPyClass(); assertNotNull(myClass); } } public static class PyClassicPropertyTest extends PyPropertyTest { public PyClassicPropertyTest() { super(); } public void testV1() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("v1"); assertNotNull(p); assertNull(p.getDoc()); PyTargetExpression site = p.getDefinitionSite(); assertEquals("v1", site.getText()); accessor = p.getGetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("getter", accessor.value().getName()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("setter", accessor.value().getName()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); } public void testV2() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("v2"); assertNotNull(p); assertEquals("doc of v2", p.getDoc()); PyTargetExpression site = p.getDefinitionSite(); assertEquals("v2", site.getText()); accessor = p.getGetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("getter", accessor.value().getName()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("setter", accessor.value().getName()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("deleter", accessor.value().getName()); } public void testV3() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("v3"); assertNotNull(p); assertNull(p.getDoc()); PyTargetExpression site = p.getDefinitionSite(); assertEquals("v3", site.getText()); accessor = p.getGetter(); assertFalse(accessor.isDefined()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("deleter", accessor.value().getName()); } /* NOTE: we don't support this yet public void testV4() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("v4"); assertNotNull(p); assertEquals("otherworldly", p.getDoc()); PyTargetExpression site = p.getDefinitionSite(); assertEquals("otherworldly", site.getText()); accessor = p.getGetter(); assertFalse(accessor.isDefined()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); } */ } public static class PyDecoratedPropertyTest extends PyPropertyTest { public PyDecoratedPropertyTest() { super(); myLanguageLevel = LanguageLevel.PYTHON26; } public void testW1() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("W1"); assertNotNull(p); assertNull(p.getDoc()); assertNull(p.getDefinitionSite()); accessor = p.getGetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("getter", accessor.value().getName()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("setter", accessor.value().getName()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("deleter", accessor.value().getName()); } public void testW2() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("W2"); assertNotNull(p); assertNull(p.getDoc()); assertNull(p.getDefinitionSite()); accessor = p.getGetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("getter", accessor.value().getName()); assertEquals("doc of w2", accessor.value().getDocStringExpression().getStringValue()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); } } }
python/testSrc/com/jetbrains/python/PyPropertyTestSuite.java
package com.jetbrains.python; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.jetbrains.python.fixtures.PyResolveTestCase; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.types.PyClassType; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; import com.jetbrains.python.toolbox.Maybe; import junit.framework.TestSuite; /** * Tests property API. * User: dcheryasov * Date: Jun 30, 2010 8:09:12 AM */ public class PyPropertyTestSuite { public static TestSuite suite() { return new TestSuite(PyClassicPropertyTest.class); } abstract static class PyPropertyTest extends PyResolveTestCase { protected PyClass myClass; @Override protected void setUp() throws Exception { super.setUp(); PsiReference ref = configureByFile("property/"+ "Classic.py"); final Project project = ref.getElement().getContainingFile().getProject(); project.putUserData(PyBuiltinCache.TEST_SDK, PythonMockSdk.findOrCreate()); // if need be: PythonLanguageLevelPusher.setForcedLanguageLevel(project, LanguageLevel.PYTHON26); PsiElement elt = ref.resolve(); assertInstanceOf(elt, PyExpression.class); PyType type = ((PyExpression)elt).getType(TypeEvalContext.slow()); assertInstanceOf(type, PyClassType.class); myClass = ((PyClassType)type).getPyClass(); assertNotNull(myClass); } } public static class PyClassicPropertyTest extends PyPropertyTest { public PyClassicPropertyTest() { super(); } public void testV1() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("v1"); assertNotNull(p); assertNull(p.getDoc()); PyTargetExpression site = p.getDefinitionSite(); assertEquals("v1", site.getText()); accessor = p.getGetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("getter", accessor.value().getName()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("setter", accessor.value().getName()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); } public void testV2() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("v2"); assertNotNull(p); assertEquals("doc of v2", p.getDoc()); PyTargetExpression site = p.getDefinitionSite(); assertEquals("v2", site.getText()); accessor = p.getGetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("getter", accessor.value().getName()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("setter", accessor.value().getName()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("deleter", accessor.value().getName()); } public void testV3() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("v3"); assertNotNull(p); assertNull(p.getDoc()); PyTargetExpression site = p.getDefinitionSite(); assertEquals("v3", site.getText()); accessor = p.getGetter(); assertFalse(accessor.isDefined()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("deleter", accessor.value().getName()); } /* NOTE: we don't support this yet public void testV4() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("v4"); assertNotNull(p); assertEquals("otherworldly", p.getDoc()); PyTargetExpression site = p.getDefinitionSite(); assertEquals("otherworldly", site.getText()); accessor = p.getGetter(); assertFalse(accessor.isDefined()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); } */ } public static class PyDecoratedPropertyTest extends PyPropertyTest { public PyDecoratedPropertyTest() { super(); } public void testW1() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("W1"); assertNotNull(p); assertNull(p.getDoc()); assertNull(p.getDefinitionSite()); accessor = p.getGetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("getter", accessor.value().getName()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("setter", accessor.value().getName()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("deleter", accessor.value().getName()); } public void testW2() throws Exception { Property p; Maybe<PyFunction> accessor; p = myClass.findProperty("W2"); assertNotNull(p); assertNull(p.getDoc()); assertNull(p.getDefinitionSite()); accessor = p.getGetter(); assertTrue(accessor.isDefined()); assertNotNull(accessor.value()); assertEquals("getter", accessor.value().getName()); assertEquals("doc of w2", accessor.value().getDocStringExpression().getStringValue()); accessor = p.getSetter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); accessor = p.getDeleter(); assertTrue(accessor.isDefined()); assertNull(accessor.value()); } } }
Forced Python 2.6+ in property test where due.
python/testSrc/com/jetbrains/python/PyPropertyTestSuite.java
Forced Python 2.6+ in property test where due.
<ide><path>ython/testSrc/com/jetbrains/python/PyPropertyTestSuite.java <ide> import com.jetbrains.python.fixtures.PyResolveTestCase; <ide> import com.jetbrains.python.psi.*; <ide> import com.jetbrains.python.psi.impl.PyBuiltinCache; <add>import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher; <ide> import com.jetbrains.python.psi.types.PyClassType; <ide> import com.jetbrains.python.psi.types.PyType; <ide> import com.jetbrains.python.psi.types.TypeEvalContext; <ide> <ide> abstract static class PyPropertyTest extends PyResolveTestCase { <ide> protected PyClass myClass; <add> protected LanguageLevel myLanguageLevel = LanguageLevel.PYTHON26; <ide> <ide> @Override <ide> protected void setUp() throws Exception { <ide> PsiReference ref = configureByFile("property/"+ "Classic.py"); <ide> final Project project = ref.getElement().getContainingFile().getProject(); <ide> project.putUserData(PyBuiltinCache.TEST_SDK, PythonMockSdk.findOrCreate()); <del> // if need be: PythonLanguageLevelPusher.setForcedLanguageLevel(project, LanguageLevel.PYTHON26); <add> PythonLanguageLevelPusher.setForcedLanguageLevel(project, myLanguageLevel); <ide> PsiElement elt = ref.resolve(); <ide> assertInstanceOf(elt, PyExpression.class); <ide> PyType type = ((PyExpression)elt).getType(TypeEvalContext.slow()); <ide> public static class PyDecoratedPropertyTest extends PyPropertyTest { <ide> public PyDecoratedPropertyTest() { <ide> super(); <add> myLanguageLevel = LanguageLevel.PYTHON26; <ide> } <ide> <ide> public void testW1() throws Exception {
Java
apache-2.0
af40588f59e076b7a21529c501e039f0bc059c31
0
apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.web25.deployment.security; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.security.jacc.PolicyConfiguration; import javax.security.jacc.PolicyContextException; import javax.security.jacc.WebResourcePermission; import javax.security.jacc.WebRoleRefPermission; import javax.security.jacc.WebUserDataPermission; import org.apache.geronimo.security.jacc.ComponentPermissions; import org.apache.geronimo.xbeans.javaee6.RoleNameType; import org.apache.geronimo.xbeans.javaee6.SecurityConstraintType; import org.apache.geronimo.xbeans.javaee6.SecurityRoleRefType; import org.apache.geronimo.xbeans.javaee6.SecurityRoleType; import org.apache.geronimo.xbeans.javaee6.ServletType; import org.apache.geronimo.xbeans.javaee6.UrlPatternType; import org.apache.geronimo.xbeans.javaee6.WebAppType; import org.apache.geronimo.xbeans.javaee6.WebResourceCollectionType; /** * @version $Rev$ $Date$ */ public class SpecSecurityBuilder { private final Set<String> securityRoles = new HashSet<String>(); private final Map<String, URLPattern> uncheckedPatterns = new HashMap<String, URLPattern>(); private final Map<UncheckedItem, HTTPMethods> uncheckedResourcePatterns = new HashMap<UncheckedItem, HTTPMethods>(); private final Map<UncheckedItem, HTTPMethods> uncheckedUserPatterns = new HashMap<UncheckedItem, HTTPMethods>(); private final Map<String, URLPattern> excludedPatterns = new HashMap<String, URLPattern>(); private final Map<String, URLPattern> rolesPatterns = new HashMap<String, URLPattern>(); private final Set<URLPattern> allSet = new HashSet<URLPattern>(); private final Map<String, URLPattern> allMap = new HashMap<String, URLPattern>(); //uncheckedPatterns union excludedPatterns union rolesPatterns. //Currently, we always enable the useExcluded feature //private boolean useExcluded = true; private final RecordingPolicyConfiguration policyConfiguration = new RecordingPolicyConfiguration(true); public ComponentPermissions buildSpecSecurityConfig(WebAppType webApp) { collectRoleNames(webApp.getSecurityRoleArray()); try { for (ServletType servletType : webApp.getServletArray()) { processRoleRefPermissions(servletType); } //add the role-ref permissions for unmapped jsps addUnmappedJSPPermissions(); analyzeSecurityConstraints(webApp.getSecurityConstraintArray()); //Currently, we always enable the useExcluded feature removeExcludedDups(); return buildComponentPermissions(); } catch (PolicyContextException e) { throw new IllegalStateException("Should not happen", e); } } public void analyzeSecurityConstraints(SecurityConstraintType[] securityConstraintArray) { for (SecurityConstraintType securityConstraintType : securityConstraintArray) { Map<String, URLPattern> currentPatterns; if (securityConstraintType.isSetAuthConstraint()) { if (securityConstraintType.getAuthConstraint().getRoleNameArray().length == 0) { currentPatterns = excludedPatterns; } else { currentPatterns = rolesPatterns; } } else { currentPatterns = uncheckedPatterns; } String transport = ""; if (securityConstraintType.isSetUserDataConstraint()) { transport = securityConstraintType.getUserDataConstraint().getTransportGuarantee().getStringValue().trim().toUpperCase(); } WebResourceCollectionType[] webResourceCollectionTypeArray = securityConstraintType.getWebResourceCollectionArray(); for (WebResourceCollectionType webResourceCollectionType : webResourceCollectionTypeArray) { //Calculate HTTP methods list List<String> httpMethods = new ArrayList<String>(); if (webResourceCollectionType.getHttpMethodArray().length > 0) { for (String httpMethod : webResourceCollectionType.getHttpMethodArray()) { if (httpMethod != null) { httpMethods.add(httpMethod.trim()); } } } else { httpMethods.add(""); } for (UrlPatternType urlPatternType : webResourceCollectionType.getUrlPatternArray()) { String url = urlPatternType.getStringValue().trim(); URLPattern pattern = currentPatterns.get(url); if (pattern == null) { pattern = new URLPattern(url); currentPatterns.put(url, pattern); } URLPattern allPattern = allMap.get(url); if (allPattern == null) { allPattern = new URLPattern(url); allSet.add(allPattern); allMap.put(url, allPattern); } //Add HTTP methods to those url patterns for (String httpMethod : httpMethods) { pattern.addMethod(httpMethod); allPattern.addMethod(httpMethod); } if (currentPatterns == rolesPatterns) { RoleNameType[] roleNameTypeArray = securityConstraintType.getAuthConstraint().getRoleNameArray(); for (RoleNameType roleNameType : roleNameTypeArray) { String role = roleNameType.getStringValue().trim(); if (role.equals("*")) { pattern.addAllRoles(securityRoles); } else { pattern.addRole(role); } } } pattern.setTransport(transport); } } } } public void removeExcludedDups() { for (Map.Entry<String, URLPattern> excluded : excludedPatterns.entrySet()) { String url = excluded.getKey(); URLPattern pattern = excluded.getValue(); removeExcluded(url, pattern, uncheckedPatterns); removeExcluded(url, pattern, rolesPatterns); } } private void removeExcluded(String url, URLPattern pattern, Map<String, URLPattern> patterns) { URLPattern testPattern = patterns.get(url); if (testPattern != null) { if (!testPattern.removeMethods(pattern)) { patterns.remove(url); } } } public ComponentPermissions buildComponentPermissions() throws PolicyContextException { //Currently, we always enable excluded configuration for (URLPattern pattern : excludedPatterns.values()) { String name = pattern.getQualifiedPattern(allSet); String actions = pattern.getMethods(); policyConfiguration.addToExcludedPolicy(new WebResourcePermission(name, actions)); policyConfiguration.addToExcludedPolicy(new WebUserDataPermission(name, actions)); } for (URLPattern pattern : rolesPatterns.values()) { String name = pattern.getQualifiedPattern(allSet); String actions = pattern.getMethods(); WebResourcePermission permission = new WebResourcePermission(name, actions); for (String roleName : pattern.getRoles()) { policyConfiguration.addToRole(roleName, permission); } HTTPMethods methods = pattern.getHTTPMethods(); int transportType = pattern.getTransport(); addOrUpdatePattern(uncheckedUserPatterns, name, methods, transportType); } for (URLPattern pattern : uncheckedPatterns.values()) { String name = pattern.getQualifiedPattern(allSet); HTTPMethods methods = pattern.getHTTPMethods(); addOrUpdatePattern(uncheckedResourcePatterns, name, methods, URLPattern.NA); int transportType = pattern.getTransport(); addOrUpdatePattern(uncheckedUserPatterns, name, methods, transportType); } /** * A <code>WebResourcePermission</code> and a <code>WebUserDataPermission</code> must be instantiated for * each <tt>url-pattern</tt> in the deployment descriptor and the default pattern "/", that is not combined * by the <tt>web-resource-collection</tt> elements of the deployment descriptor with ever HTTP method * value. The permission objects must be contructed using the qualified pattern as their name and with * actions defined by the subset of the HTTP methods that do not occur in combination with the pattern. * The resulting permissions that must be added to the unchecked policy statements by calling the * <code>addToUncheckedPolcy</code> method on the <code>PolicyConfiguration</code> object. */ for (URLPattern pattern : allSet) { String name = pattern.getQualifiedPattern(allSet); HTTPMethods methods = pattern.getComplementedHTTPMethods(); if (methods.isNone()) { continue; } addOrUpdatePattern(uncheckedResourcePatterns, name, methods, URLPattern.NA); addOrUpdatePattern(uncheckedUserPatterns, name, methods, URLPattern.NA); } URLPattern pattern = new URLPattern("/"); if (!allSet.contains(pattern)) { String name = pattern.getQualifiedPattern(allSet); HTTPMethods methods = pattern.getComplementedHTTPMethods(); addOrUpdatePattern(uncheckedResourcePatterns, name, methods, URLPattern.NA); addOrUpdatePattern(uncheckedUserPatterns, name, methods, URLPattern.NA); } //Create the uncheckedPermissions for WebResourcePermissions for (UncheckedItem item : uncheckedResourcePatterns.keySet()) { HTTPMethods methods = uncheckedResourcePatterns.get(item); String actions = URLPattern.getMethodsWithTransport(methods, item.getTransportType()); policyConfiguration.addToUncheckedPolicy(new WebResourcePermission(item.getName(), actions)); } //Create the uncheckedPermissions for WebUserDataPermissions for (UncheckedItem item : uncheckedUserPatterns.keySet()) { HTTPMethods methods = uncheckedUserPatterns.get(item); String actions = URLPattern.getMethodsWithTransport(methods, item.getTransportType()); policyConfiguration.addToUncheckedPolicy(new WebUserDataPermission(item.getName(), actions)); } return policyConfiguration.getComponentPermissions(); } private void addOrUpdatePattern(Map<UncheckedItem, HTTPMethods> patternMap, String name, HTTPMethods actions, int transportType) { UncheckedItem item = new UncheckedItem(name, transportType); HTTPMethods existingActions = patternMap.get(item); if (existingActions != null) { patternMap.put(item, existingActions.add(actions)); return; } patternMap.put(item, new HTTPMethods(actions, false)); } protected void processRoleRefPermissions(ServletType servletType) throws PolicyContextException { String servletName = servletType.getServletName().getStringValue().trim(); //WebRoleRefPermissions SecurityRoleRefType[] securityRoleRefTypeArray = servletType.getSecurityRoleRefArray(); Set<String> unmappedRoles = new HashSet<String>(securityRoles); for (SecurityRoleRefType securityRoleRefType : securityRoleRefTypeArray) { String roleName = securityRoleRefType.getRoleName().getStringValue().trim(); String roleLink = securityRoleRefType.getRoleLink().getStringValue().trim(); //jacc 3.1.3.2 /* The name of the WebRoleRefPermission must be the servlet-name in whose * context the security-role-ref is defined. The actions of the WebRoleRefPermission * must be the value of the role-name (that is the reference), appearing in the security-role-ref. * The deployment tools must call the addToRole method on the PolicyConfiguration object to add the * WebRoleRefPermission object resulting from the translation to the role * identified in the role-link appearing in the security-role-ref. */ policyConfiguration.addToRole(roleLink, new WebRoleRefPermission(servletName, roleName)); unmappedRoles.remove(roleName); } for (String roleName : unmappedRoles) { policyConfiguration.addToRole(roleName, new WebRoleRefPermission(servletName, roleName)); } } protected void addUnmappedJSPPermissions() throws PolicyContextException { for (String roleName : securityRoles) { policyConfiguration.addToRole(roleName, new WebRoleRefPermission("", roleName)); } } protected void collectRoleNames(SecurityRoleType[] securityRoles) { for (SecurityRoleType securityRole : securityRoles) { this.securityRoles.add(securityRole.getRoleName().getStringValue().trim()); } } private static class RecordingPolicyConfiguration implements PolicyConfiguration { private final PermissionCollection excludedPermissions = new Permissions(); private final PermissionCollection uncheckedPermissions = new Permissions(); private final Map<String, PermissionCollection> rolePermissions = new HashMap<String, PermissionCollection>(); private final StringBuilder audit; private RecordingPolicyConfiguration(boolean audit) { if (audit) { this.audit = new StringBuilder(); } else { this.audit = null; } } public String getContextID() throws PolicyContextException { return null; } public void addToRole(String roleName, PermissionCollection permissions) { throw new IllegalStateException("not implemented"); } public void addToRole(String roleName, Permission permission) throws PolicyContextException { if (audit != null) { audit.append("Role: ").append(roleName).append(" -> ").append(permission).append('\n'); } PermissionCollection permissionsForRole = rolePermissions.get(roleName); if (permissionsForRole == null) { permissionsForRole = new Permissions(); rolePermissions.put(roleName, permissionsForRole); } permissionsForRole.add(permission); } public void addToUncheckedPolicy(PermissionCollection permissions) { throw new IllegalStateException("not implemented"); } public void addToUncheckedPolicy(Permission permission) throws PolicyContextException { if (audit != null) { audit.append("Unchecked -> ").append(permission).append('\n'); } uncheckedPermissions.add(permission); } public void addToExcludedPolicy(PermissionCollection permissions) { throw new IllegalStateException("not implemented"); } public void addToExcludedPolicy(Permission permission) throws PolicyContextException { if (audit != null) { audit.append("Excluded -> ").append(permission).append('\n'); } excludedPermissions.add(permission); } public void removeRole(String roleName) throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void removeUncheckedPolicy() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void removeExcludedPolicy() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void linkConfiguration(PolicyConfiguration link) throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void delete() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void commit() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public boolean inService() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public ComponentPermissions getComponentPermissions() { return new ComponentPermissions(excludedPermissions, uncheckedPermissions, rolePermissions); } public String getAudit() { if (audit == null) { return "no audit kept"; } return audit.toString(); } } }
plugins/j2ee/geronimo-web-2.5-builder/src/main/java/org/apache/geronimo/web25/deployment/security/SpecSecurityBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.web25.deployment.security; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.security.jacc.WebResourcePermission; import javax.security.jacc.WebUserDataPermission; import javax.security.jacc.WebRoleRefPermission; import javax.security.jacc.PolicyConfiguration; import javax.security.jacc.PolicyContextException; import org.apache.geronimo.security.jacc.ComponentPermissions; import org.apache.geronimo.xbeans.javaee6.RoleNameType; import org.apache.geronimo.xbeans.javaee6.SecurityConstraintType; import org.apache.geronimo.xbeans.javaee6.UrlPatternType; import org.apache.geronimo.xbeans.javaee6.WebAppType; import org.apache.geronimo.xbeans.javaee6.WebResourceCollectionType; import org.apache.geronimo.xbeans.javaee6.SecurityRoleType; import org.apache.geronimo.xbeans.javaee6.ServletType; import org.apache.geronimo.xbeans.javaee6.SecurityRoleRefType; /** * @version $Rev$ $Date$ */ public class SpecSecurityBuilder { private final Set<String> securityRoles = new HashSet<String>(); private final Map<String, URLPattern> uncheckedPatterns = new HashMap<String, URLPattern>(); private final Map<UncheckedItem, HTTPMethods> uncheckedResourcePatterns = new HashMap<UncheckedItem, HTTPMethods>(); private final Map<UncheckedItem, HTTPMethods> uncheckedUserPatterns = new HashMap<UncheckedItem, HTTPMethods>(); private final Map<String, URLPattern> excludedPatterns = new HashMap<String, URLPattern>(); private final Map<String, URLPattern> rolesPatterns = new HashMap<String, URLPattern>(); private final Set<URLPattern> allSet = new HashSet<URLPattern>(); // == allMap.values() private final Map<String, URLPattern> allMap = new HashMap<String, URLPattern>(); //uncheckedPatterns union excludedPatterns union rolesPatterns. // private boolean useExcluded = false; private boolean useExcluded = true; private final RecordingPolicyConfiguration policyConfiguration = new RecordingPolicyConfiguration(true); public ComponentPermissions buildSpecSecurityConfig(WebAppType webApp) { collectRoleNames(webApp.getSecurityRoleArray()); //role refs try { for (ServletType servletType: webApp.getServletArray()) { processRoleRefPermissions(servletType); } //add the role-ref permissions for unmapped jsps addUnmappedJSPPermissions(); analyzeSecurityConstraints(webApp.getSecurityConstraintArray()); // if (!useExcluded) { removeExcludedDups(); // } return buildComponentPermissions(); } catch (PolicyContextException e) { throw new IllegalStateException("Should not happen", e); } } public void analyzeSecurityConstraints(SecurityConstraintType[] securityConstraintArray) { for (SecurityConstraintType securityConstraintType : securityConstraintArray) { Map<String, URLPattern> currentPatterns; if (securityConstraintType.isSetAuthConstraint()) { if (securityConstraintType.getAuthConstraint().getRoleNameArray().length == 0) { currentPatterns = excludedPatterns; } else { currentPatterns = rolesPatterns; } } else { currentPatterns = uncheckedPatterns; } String transport = ""; if (securityConstraintType.isSetUserDataConstraint()) { transport = securityConstraintType.getUserDataConstraint().getTransportGuarantee().getStringValue().trim().toUpperCase(); } WebResourceCollectionType[] webResourceCollectionTypeArray = securityConstraintType.getWebResourceCollectionArray(); for (WebResourceCollectionType webResourceCollectionType : webResourceCollectionTypeArray) { UrlPatternType[] urlPatternTypeArray = webResourceCollectionType.getUrlPatternArray(); for (UrlPatternType urlPatternType : urlPatternTypeArray) { String url = urlPatternType.getStringValue().trim(); URLPattern pattern = currentPatterns.get(url); if (pattern == null) { pattern = new URLPattern(url); currentPatterns.put(url, pattern); } URLPattern allPattern = allMap.get(url); if (allPattern == null) { allPattern = new URLPattern(url); allSet.add(allPattern); allMap.put(url, allPattern); } String[] httpMethodTypeArray = webResourceCollectionType.getHttpMethodArray(); if (httpMethodTypeArray.length == 0) { pattern.addMethod(""); allPattern.addMethod(""); } else { for (String aHttpMethodTypeArray : httpMethodTypeArray) { String method = (aHttpMethodTypeArray == null ? null : aHttpMethodTypeArray.trim()); if (method != null) { pattern.addMethod(method); allPattern.addMethod(method); } } } if (currentPatterns == rolesPatterns) { RoleNameType[] roleNameTypeArray = securityConstraintType.getAuthConstraint().getRoleNameArray(); for (RoleNameType roleNameType : roleNameTypeArray) { String role = roleNameType.getStringValue().trim(); if (role.equals("*")) { pattern.addAllRoles(securityRoles); } else { pattern.addRole(role); } } } pattern.setTransport(transport); } } } } public void removeExcludedDups() { for (Map.Entry<String, URLPattern> excluded: excludedPatterns.entrySet()) { String url = excluded.getKey(); URLPattern pattern = excluded.getValue(); removeExcluded(url, pattern, uncheckedPatterns); removeExcluded(url, pattern, rolesPatterns); } } private void removeExcluded(String url, URLPattern pattern, Map<String, URLPattern> patterns) { URLPattern testPattern = patterns.get(url); if (testPattern != null) { if (!testPattern.removeMethods(pattern)) { patterns.remove(url); } } } public ComponentPermissions buildComponentPermissions() throws PolicyContextException { if (useExcluded) { for (URLPattern pattern : excludedPatterns.values()) { String name = pattern.getQualifiedPattern(allSet); String actions = pattern.getMethods(); policyConfiguration.addToExcludedPolicy(new WebResourcePermission(name, actions)); policyConfiguration.addToExcludedPolicy(new WebUserDataPermission(name, actions)); } } for (URLPattern pattern : rolesPatterns.values()) { String name = pattern.getQualifiedPattern(allSet); String actions = pattern.getMethods(); WebResourcePermission permission = new WebResourcePermission(name, actions); for (String roleName : pattern.getRoles()) { policyConfiguration.addToRole(roleName, permission); } HTTPMethods methods = pattern.getHTTPMethods(); int transportType = pattern.getTransport(); addOrUpdatePattern(uncheckedUserPatterns, name, methods, transportType); } for (URLPattern pattern : uncheckedPatterns.values()) { String name = pattern.getQualifiedPattern(allSet); HTTPMethods methods = pattern.getHTTPMethods(); addOrUpdatePattern(uncheckedResourcePatterns, name, methods, URLPattern.NA); int transportType = pattern.getTransport(); addOrUpdatePattern(uncheckedUserPatterns, name, methods, transportType); } /** * A <code>WebResourcePermission</code> and a <code>WebUserDataPermission</code> must be instantiated for * each <tt>url-pattern</tt> in the deployment descriptor and the default pattern "/", that is not combined * by the <tt>web-resource-collection</tt> elements of the deployment descriptor with ever HTTP method * value. The permission objects must be contructed using the qualified pattern as their name and with * actions defined by the subset of the HTTP methods that do not occur in combination with the pattern. * The resulting permissions that must be added to the unchecked policy statements by calling the * <code>addToUncheckedPolcy</code> method on the <code>PolicyConfiguration</code> object. */ for (URLPattern pattern : allSet) { String name = pattern.getQualifiedPattern(allSet); HTTPMethods methods = pattern.getComplementedHTTPMethods(); if (methods.isNone()) { continue; } addOrUpdatePattern(uncheckedResourcePatterns, name, methods, URLPattern.NA); addOrUpdatePattern(uncheckedUserPatterns, name, methods, URLPattern.NA); } URLPattern pattern = new URLPattern("/"); if (!allSet.contains(pattern)) { String name = pattern.getQualifiedPattern(allSet); HTTPMethods methods = pattern.getComplementedHTTPMethods(); addOrUpdatePattern(uncheckedResourcePatterns, name, methods, URLPattern.NA); addOrUpdatePattern(uncheckedUserPatterns, name, methods, URLPattern.NA); } //Create the uncheckedPermissions for WebResourcePermissions for (UncheckedItem item : uncheckedResourcePatterns.keySet()) { HTTPMethods methods = uncheckedResourcePatterns.get(item); String actions = URLPattern.getMethodsWithTransport(methods, item.getTransportType()); policyConfiguration.addToUncheckedPolicy(new WebResourcePermission(item.getName(), actions)); } //Create the uncheckedPermissions for WebUserDataPermissions for (UncheckedItem item : uncheckedUserPatterns.keySet()) { HTTPMethods methods = uncheckedUserPatterns.get(item); String actions = URLPattern.getMethodsWithTransport(methods, item.getTransportType()); policyConfiguration.addToUncheckedPolicy(new WebUserDataPermission(item.getName(), actions)); } // System.out.println(policyConfiguration.getAudit()); return policyConfiguration.getComponentPermissions(); } private void addOrUpdatePattern(Map<UncheckedItem, HTTPMethods> patternMap, String name, HTTPMethods actions, int transportType) { UncheckedItem item = new UncheckedItem(name, transportType); HTTPMethods existingActions = patternMap.get(item); if (existingActions != null) { patternMap.put(item, existingActions.add(actions)); return; } patternMap.put(item, new HTTPMethods(actions, false)); } protected void processRoleRefPermissions(ServletType servletType) throws PolicyContextException { String servletName = servletType.getServletName().getStringValue().trim(); //WebRoleRefPermissions SecurityRoleRefType[] securityRoleRefTypeArray = servletType.getSecurityRoleRefArray(); Set<String> unmappedRoles = new HashSet<String>(securityRoles); for (SecurityRoleRefType securityRoleRefType : securityRoleRefTypeArray) { String roleName = securityRoleRefType.getRoleName().getStringValue().trim(); String roleLink = securityRoleRefType.getRoleLink().getStringValue().trim(); //jacc 3.1.3.2 /* The name of the WebRoleRefPermission must be the servlet-name in whose * context the security-role-ref is defined. The actions of the WebRoleRefPermission * must be the value of the role-name (that is the reference), appearing in the security-role-ref. * The deployment tools must call the addToRole method on the PolicyConfiguration object to add the * WebRoleRefPermission object resulting from the translation to the role * identified in the role-link appearing in the security-role-ref. */ policyConfiguration.addToRole(roleLink, new WebRoleRefPermission(servletName, roleName)); unmappedRoles.remove(roleName); } for (String roleName : unmappedRoles) { policyConfiguration.addToRole(roleName, new WebRoleRefPermission(servletName, roleName)); } } protected void addUnmappedJSPPermissions() throws PolicyContextException { for (String roleName : securityRoles) { policyConfiguration.addToRole(roleName, new WebRoleRefPermission("", roleName)); } } protected void collectRoleNames(SecurityRoleType[] securityRoles) { for (SecurityRoleType securityRole : securityRoles) { this.securityRoles.add(securityRole.getRoleName().getStringValue().trim()); } } private static class RecordingPolicyConfiguration implements PolicyConfiguration { private final PermissionCollection excludedPermissions = new Permissions(); private final PermissionCollection uncheckedPermissions = new Permissions(); private final Map<String, PermissionCollection> rolePermissions = new HashMap<String, PermissionCollection>(); private final StringBuilder audit; private RecordingPolicyConfiguration(boolean audit) { if (audit) { this.audit = new StringBuilder(); } else { this.audit = null; } } public String getContextID() throws PolicyContextException { return null; } public void addToRole(String roleName, PermissionCollection permissions) { throw new IllegalStateException("not implemented"); } public void addToRole(String roleName, Permission permission) throws PolicyContextException { if (audit != null) { audit.append("Role: ").append(roleName).append(" -> ").append(permission).append('\n'); } PermissionCollection permissionsForRole = rolePermissions.get(roleName); if (permissionsForRole == null) { permissionsForRole = new Permissions(); rolePermissions.put(roleName, permissionsForRole); } permissionsForRole.add(permission); } public void addToUncheckedPolicy(PermissionCollection permissions) { throw new IllegalStateException("not implemented"); } public void addToUncheckedPolicy(Permission permission) throws PolicyContextException { if (audit != null) { audit.append("Unchecked -> ").append(permission).append('\n'); } uncheckedPermissions.add(permission); } public void addToExcludedPolicy(PermissionCollection permissions) { throw new IllegalStateException("not implemented"); } public void addToExcludedPolicy(Permission permission) throws PolicyContextException { if (audit != null) { audit.append("Excluded -> ").append(permission).append('\n'); } excludedPermissions.add(permission); } public void removeRole(String roleName) throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void removeUncheckedPolicy() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void removeExcludedPolicy() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void linkConfiguration(PolicyConfiguration link) throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void delete() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public void commit() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public boolean inService() throws PolicyContextException { throw new IllegalStateException("not implemented"); } public ComponentPermissions getComponentPermissions() { return new ComponentPermissions(excludedPermissions, uncheckedPermissions, rolePermissions); } public String getAudit() { if (audit == null) { return "no audit kept"; } return audit.toString(); } } }
No logic change, just format the codes ,remove some unused codes and prepare for next step change git-svn-id: 0d16bf2c240b8111500ec482b35765e5042f5526@935451 13f79535-47bb-0310-9956-ffa450edef68
plugins/j2ee/geronimo-web-2.5-builder/src/main/java/org/apache/geronimo/web25/deployment/security/SpecSecurityBuilder.java
No logic change, just format the codes ,remove some unused codes and prepare for next step change
<ide><path>lugins/j2ee/geronimo-web-2.5-builder/src/main/java/org/apache/geronimo/web25/deployment/security/SpecSecurityBuilder.java <ide> * under the License. <ide> */ <ide> <del> <ide> package org.apache.geronimo.web25.deployment.security; <ide> <ide> import java.security.Permission; <ide> import java.security.PermissionCollection; <ide> import java.security.Permissions; <add>import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.HashSet; <add>import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <ide> <del>import javax.security.jacc.WebResourcePermission; <del>import javax.security.jacc.WebUserDataPermission; <del>import javax.security.jacc.WebRoleRefPermission; <ide> import javax.security.jacc.PolicyConfiguration; <ide> import javax.security.jacc.PolicyContextException; <add>import javax.security.jacc.WebResourcePermission; <add>import javax.security.jacc.WebRoleRefPermission; <add>import javax.security.jacc.WebUserDataPermission; <ide> <ide> import org.apache.geronimo.security.jacc.ComponentPermissions; <ide> import org.apache.geronimo.xbeans.javaee6.RoleNameType; <ide> import org.apache.geronimo.xbeans.javaee6.SecurityConstraintType; <add>import org.apache.geronimo.xbeans.javaee6.SecurityRoleRefType; <add>import org.apache.geronimo.xbeans.javaee6.SecurityRoleType; <add>import org.apache.geronimo.xbeans.javaee6.ServletType; <ide> import org.apache.geronimo.xbeans.javaee6.UrlPatternType; <ide> import org.apache.geronimo.xbeans.javaee6.WebAppType; <ide> import org.apache.geronimo.xbeans.javaee6.WebResourceCollectionType; <del>import org.apache.geronimo.xbeans.javaee6.SecurityRoleType; <del>import org.apache.geronimo.xbeans.javaee6.ServletType; <del>import org.apache.geronimo.xbeans.javaee6.SecurityRoleRefType; <ide> <ide> /** <ide> * @version $Rev$ $Date$ <ide> */ <ide> public class SpecSecurityBuilder { <add> <ide> private final Set<String> securityRoles = new HashSet<String>(); <add> <ide> private final Map<String, URLPattern> uncheckedPatterns = new HashMap<String, URLPattern>(); <add> <ide> private final Map<UncheckedItem, HTTPMethods> uncheckedResourcePatterns = new HashMap<UncheckedItem, HTTPMethods>(); <add> <ide> private final Map<UncheckedItem, HTTPMethods> uncheckedUserPatterns = new HashMap<UncheckedItem, HTTPMethods>(); <add> <ide> private final Map<String, URLPattern> excludedPatterns = new HashMap<String, URLPattern>(); <add> <ide> private final Map<String, URLPattern> rolesPatterns = new HashMap<String, URLPattern>(); <del> private final Set<URLPattern> allSet = new HashSet<URLPattern>(); // == allMap.values() <del> private final Map<String, URLPattern> allMap = new HashMap<String, URLPattern>(); //uncheckedPatterns union excludedPatterns union rolesPatterns. <del>// private boolean useExcluded = false; <del> private boolean useExcluded = true; <del> <add> <add> private final Set<URLPattern> allSet = new HashSet<URLPattern>(); <add> <add> private final Map<String, URLPattern> allMap = new HashMap<String, URLPattern>(); //uncheckedPatterns union excludedPatterns union rolesPatterns. <add> <add> //Currently, we always enable the useExcluded feature <add> //private boolean useExcluded = true; <ide> private final RecordingPolicyConfiguration policyConfiguration = new RecordingPolicyConfiguration(true); <ide> <ide> public ComponentPermissions buildSpecSecurityConfig(WebAppType webApp) { <ide> collectRoleNames(webApp.getSecurityRoleArray()); <del> //role refs <ide> try { <del> for (ServletType servletType: webApp.getServletArray()) { <del> processRoleRefPermissions(servletType); <add> for (ServletType servletType : webApp.getServletArray()) { <add> processRoleRefPermissions(servletType); <ide> } <ide> //add the role-ref permissions for unmapped jsps <ide> addUnmappedJSPPermissions(); <del> <ide> analyzeSecurityConstraints(webApp.getSecurityConstraintArray()); <del>// if (!useExcluded) { <add> //Currently, we always enable the useExcluded feature <ide> removeExcludedDups(); <del>// } <ide> return buildComponentPermissions(); <ide> } catch (PolicyContextException e) { <ide> throw new IllegalStateException("Should not happen", e); <ide> } else { <ide> currentPatterns = uncheckedPatterns; <ide> } <del> <ide> String transport = ""; <ide> if (securityConstraintType.isSetUserDataConstraint()) { <ide> transport = securityConstraintType.getUserDataConstraint().getTransportGuarantee().getStringValue().trim().toUpperCase(); <ide> } <del> <ide> WebResourceCollectionType[] webResourceCollectionTypeArray = securityConstraintType.getWebResourceCollectionArray(); <ide> for (WebResourceCollectionType webResourceCollectionType : webResourceCollectionTypeArray) { <del> UrlPatternType[] urlPatternTypeArray = webResourceCollectionType.getUrlPatternArray(); <del> for (UrlPatternType urlPatternType : urlPatternTypeArray) { <add> //Calculate HTTP methods list <add> List<String> httpMethods = new ArrayList<String>(); <add> if (webResourceCollectionType.getHttpMethodArray().length > 0) { <add> for (String httpMethod : webResourceCollectionType.getHttpMethodArray()) { <add> if (httpMethod != null) { <add> httpMethods.add(httpMethod.trim()); <add> } <add> } <add> } else { <add> httpMethods.add(""); <add> } <add> for (UrlPatternType urlPatternType : webResourceCollectionType.getUrlPatternArray()) { <ide> String url = urlPatternType.getStringValue().trim(); <ide> URLPattern pattern = currentPatterns.get(url); <ide> if (pattern == null) { <ide> pattern = new URLPattern(url); <ide> currentPatterns.put(url, pattern); <ide> } <del> <ide> URLPattern allPattern = allMap.get(url); <ide> if (allPattern == null) { <ide> allPattern = new URLPattern(url); <ide> allSet.add(allPattern); <ide> allMap.put(url, allPattern); <ide> } <del> <del> String[] httpMethodTypeArray = webResourceCollectionType.getHttpMethodArray(); <del> if (httpMethodTypeArray.length == 0) { <del> pattern.addMethod(""); <del> allPattern.addMethod(""); <del> } else { <del> for (String aHttpMethodTypeArray : httpMethodTypeArray) { <del> String method = (aHttpMethodTypeArray == null ? null : aHttpMethodTypeArray.trim()); <del> if (method != null) { <del> pattern.addMethod(method); <del> allPattern.addMethod(method); <del> } <del> } <add> //Add HTTP methods to those url patterns <add> for (String httpMethod : httpMethods) { <add> pattern.addMethod(httpMethod); <add> allPattern.addMethod(httpMethod); <ide> } <ide> if (currentPatterns == rolesPatterns) { <ide> RoleNameType[] roleNameTypeArray = securityConstraintType.getAuthConstraint().getRoleNameArray(); <ide> } <ide> } <ide> } <del> <ide> pattern.setTransport(transport); <ide> } <ide> } <ide> } <ide> <ide> public void removeExcludedDups() { <del> for (Map.Entry<String, URLPattern> excluded: excludedPatterns.entrySet()) { <add> for (Map.Entry<String, URLPattern> excluded : excludedPatterns.entrySet()) { <ide> String url = excluded.getKey(); <ide> URLPattern pattern = excluded.getValue(); <ide> removeExcluded(url, pattern, uncheckedPatterns); <ide> } <ide> <ide> public ComponentPermissions buildComponentPermissions() throws PolicyContextException { <del> <del> if (useExcluded) { <del> for (URLPattern pattern : excludedPatterns.values()) { <del> String name = pattern.getQualifiedPattern(allSet); <del> String actions = pattern.getMethods(); <del> <del> policyConfiguration.addToExcludedPolicy(new WebResourcePermission(name, actions)); <del> policyConfiguration.addToExcludedPolicy(new WebUserDataPermission(name, actions)); <del> } <del> } <del> <add> //Currently, we always enable excluded configuration <add> for (URLPattern pattern : excludedPatterns.values()) { <add> String name = pattern.getQualifiedPattern(allSet); <add> String actions = pattern.getMethods(); <add> policyConfiguration.addToExcludedPolicy(new WebResourcePermission(name, actions)); <add> policyConfiguration.addToExcludedPolicy(new WebUserDataPermission(name, actions)); <add> } <ide> for (URLPattern pattern : rolesPatterns.values()) { <ide> String name = pattern.getQualifiedPattern(allSet); <ide> String actions = pattern.getMethods(); <ide> WebResourcePermission permission = new WebResourcePermission(name, actions); <del> <ide> for (String roleName : pattern.getRoles()) { <ide> policyConfiguration.addToRole(roleName, permission); <ide> } <ide> HTTPMethods methods = pattern.getHTTPMethods(); <ide> int transportType = pattern.getTransport(); <del> <ide> addOrUpdatePattern(uncheckedUserPatterns, name, methods, transportType); <ide> } <del> <ide> for (URLPattern pattern : uncheckedPatterns.values()) { <ide> String name = pattern.getQualifiedPattern(allSet); <ide> HTTPMethods methods = pattern.getHTTPMethods(); <del> <ide> addOrUpdatePattern(uncheckedResourcePatterns, name, methods, URLPattern.NA); <del> <ide> int transportType = pattern.getTransport(); <ide> addOrUpdatePattern(uncheckedUserPatterns, name, methods, transportType); <ide> } <del> <ide> /** <ide> * A <code>WebResourcePermission</code> and a <code>WebUserDataPermission</code> must be instantiated for <ide> * each <tt>url-pattern</tt> in the deployment descriptor and the default pattern "/", that is not combined <ide> for (URLPattern pattern : allSet) { <ide> String name = pattern.getQualifiedPattern(allSet); <ide> HTTPMethods methods = pattern.getComplementedHTTPMethods(); <del> <ide> if (methods.isNone()) { <ide> continue; <ide> } <del> <ide> addOrUpdatePattern(uncheckedResourcePatterns, name, methods, URLPattern.NA); <ide> addOrUpdatePattern(uncheckedUserPatterns, name, methods, URLPattern.NA); <ide> } <del> <ide> URLPattern pattern = new URLPattern("/"); <ide> if (!allSet.contains(pattern)) { <ide> String name = pattern.getQualifiedPattern(allSet); <ide> HTTPMethods methods = pattern.getComplementedHTTPMethods(); <del> <ide> addOrUpdatePattern(uncheckedResourcePatterns, name, methods, URLPattern.NA); <ide> addOrUpdatePattern(uncheckedUserPatterns, name, methods, URLPattern.NA); <ide> } <del> <ide> //Create the uncheckedPermissions for WebResourcePermissions <ide> for (UncheckedItem item : uncheckedResourcePatterns.keySet()) { <ide> HTTPMethods methods = uncheckedResourcePatterns.get(item); <ide> String actions = URLPattern.getMethodsWithTransport(methods, item.getTransportType()); <del> <ide> policyConfiguration.addToUncheckedPolicy(new WebResourcePermission(item.getName(), actions)); <ide> } <ide> //Create the uncheckedPermissions for WebUserDataPermissions <ide> for (UncheckedItem item : uncheckedUserPatterns.keySet()) { <ide> HTTPMethods methods = uncheckedUserPatterns.get(item); <ide> String actions = URLPattern.getMethodsWithTransport(methods, item.getTransportType()); <del> <ide> policyConfiguration.addToUncheckedPolicy(new WebUserDataPermission(item.getName(), actions)); <ide> } <del> <del>// System.out.println(policyConfiguration.getAudit()); <ide> return policyConfiguration.getComponentPermissions(); <ide> } <ide> <ide> patternMap.put(item, existingActions.add(actions)); <ide> return; <ide> } <del> <ide> patternMap.put(item, new HTTPMethods(actions, false)); <ide> } <ide> <ide> } <ide> } <ide> <del> <ide> private static class RecordingPolicyConfiguration implements PolicyConfiguration { <add> <ide> private final PermissionCollection excludedPermissions = new Permissions(); <add> <ide> private final PermissionCollection uncheckedPermissions = new Permissions(); <add> <ide> private final Map<String, PermissionCollection> rolePermissions = new HashMap<String, PermissionCollection>(); <ide> <ide> private final StringBuilder audit; <del> <ide> <ide> private RecordingPolicyConfiguration(boolean audit) { <ide> if (audit) { <ide> } <ide> return audit.toString(); <ide> } <del> <ide> } <ide> }
Java
mit
b43fc17b32fd1b6ee0d2404123911503f7df4546
0
heavyplayer/AudioPlayerRecorder
package com.audiomanager.app; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.Toast; import com.audiomanager.obj.Item; import com.audiomanager.service.AudioPlayerService; import com.audiomanager.widget.AudioPlayer; public class PlayerActivity extends RecorderActivity { private AudioPlayerService.LocalBinder mAudioPlayerBinder; private AudioPlayerServiceConnection mServiceConnection = new AudioPlayerServiceConnection(); private boolean mIsPortrait; @Override protected ListAdapter onCreateAdapter(Context context, Item[] objects) { return new AudioPlayerItemAdapter(context, objects); } @Override protected void onStart() { super.onStart(); mIsPortrait = isPortrait(); startService(new Intent(this, AudioPlayerService.class)); } protected boolean isPortrait() { DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); return displaymetrics.heightPixels > displaymetrics.widthPixels; } @Override protected void onResume() { super.onResume(); bindService(); } @Override protected void onPause() { super.onPause(); unbindService(); if(mIsPortrait == isPortrait()) stopService(new Intent(this, AudioPlayerService.class)); } protected void bindService() { bindService( new Intent(this, AudioPlayerService.class), mServiceConnection, Context.BIND_AUTO_CREATE); } protected void unbindService() { if(mAudioPlayerBinder != null) { mAudioPlayerBinder = null; // Detach our existing connection. unbindService(mServiceConnection); } } private class AudioPlayerServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. mAudioPlayerBinder = (AudioPlayerService.LocalBinder)service; mListView.invalidateViews(); // Tell the user about this for our demo. Toast.makeText(PlayerActivity.this, R.string.local_service_connected, Toast.LENGTH_SHORT).show(); } @Override public void onServiceDisconnected(ComponentName name) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mAudioPlayerBinder = null; Toast.makeText(PlayerActivity.this, R.string.local_service_disconnected, Toast.LENGTH_SHORT).show(); } } protected class AudioPlayerItemAdapter extends ItemAdapter { public AudioPlayerItemAdapter(Context context, Item[] objects) { super(context, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { final View view = super.getView(position, convertView, parent); if(mAudioPlayerBinder != null) { final AudioPlayer audioPlayer = (AudioPlayer)view.findViewById(R.id.item_audio_player); if(audioPlayer != null) { final Item item = getItem(position); mAudioPlayerBinder.registerAudioPlayer(audioPlayer, item.getId(), item.getFileName()); } } return view; } } }
app/src/main/java/com/audiomanager/app/PlayerActivity.java
package com.audiomanager.app; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.Toast; import com.audiomanager.obj.Item; import com.audiomanager.service.AudioPlayerService; import com.audiomanager.widget.AudioPlayer; public class PlayerActivity extends RecorderActivity { private AudioPlayerService.LocalBinder mAudioPlayerBinder; private AudioPlayerServiceConnection mServiceConnection = new AudioPlayerServiceConnection(); private boolean mIsPortrait; @Override protected ListAdapter onCreateAdapter(Context context, Item[] objects) { return new AudioPlayerItemAdapter(context, objects); } @Override protected void onStart() { super.onStart(); mIsPortrait = isPortrait(); startService(new Intent(this, AudioPlayerService.class)); } protected boolean isPortrait() { DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); return displaymetrics.heightPixels > displaymetrics.widthPixels; } @Override protected void onResume() { super.onResume(); bindService(); } @Override protected void onPause() { super.onPause(); unbindService(); } protected void bindService() { bindService( new Intent(this, AudioPlayerService.class), mServiceConnection, Context.BIND_AUTO_CREATE); } protected void unbindService() { if(mAudioPlayerBinder != null) { mAudioPlayerBinder = null; // Detach our existing connection. unbindService(mServiceConnection); } } @Override protected void onStop() { super.onStop(); if(mIsPortrait == isPortrait()) stopService(new Intent(this, AudioPlayerService.class)); } private class AudioPlayerServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. mAudioPlayerBinder = (AudioPlayerService.LocalBinder)service; mListView.invalidateViews(); // Tell the user about this for our demo. Toast.makeText(PlayerActivity.this, R.string.local_service_connected, Toast.LENGTH_SHORT).show(); } @Override public void onServiceDisconnected(ComponentName name) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mAudioPlayerBinder = null; Toast.makeText(PlayerActivity.this, R.string.local_service_disconnected, Toast.LENGTH_SHORT).show(); } } protected class AudioPlayerItemAdapter extends ItemAdapter { public AudioPlayerItemAdapter(Context context, Item[] objects) { super(context, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { final View view = super.getView(position, convertView, parent); if(mAudioPlayerBinder != null) { final AudioPlayer audioPlayer = (AudioPlayer)view.findViewById(R.id.item_audio_player); if(audioPlayer != null) { final Item item = getItem(position); mAudioPlayerBinder.registerAudioPlayer(audioPlayer, item.getId(), item.getFileName()); } } return view; } } }
Stop service in onPause method, to make sure it stops
app/src/main/java/com/audiomanager/app/PlayerActivity.java
Stop service in onPause method, to make sure it stops
<ide><path>pp/src/main/java/com/audiomanager/app/PlayerActivity.java <ide> super.onPause(); <ide> <ide> unbindService(); <add> <add> if(mIsPortrait == isPortrait()) <add> stopService(new Intent(this, AudioPlayerService.class)); <ide> } <ide> <ide> protected void bindService() { <ide> // Detach our existing connection. <ide> unbindService(mServiceConnection); <ide> } <del> } <del> <del> @Override <del> protected void onStop() { <del> super.onStop(); <del> <del> if(mIsPortrait == isPortrait()) <del> stopService(new Intent(this, AudioPlayerService.class)); <ide> } <ide> <ide> private class AudioPlayerServiceConnection implements ServiceConnection {
JavaScript
agpl-3.0
3b473d2bb8b7239c77a47897bbbf1256a7870000
0
marioestradarosa/axelor-development-kit,donsunsoft/axelor-development-kit,donsunsoft/axelor-development-kit,axelor/axelor-development-kit,marioestradarosa/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,marioestradarosa/axelor-development-kit,marioestradarosa/axelor-development-kit,donsunsoft/axelor-development-kit,donsunsoft/axelor-development-kit
(function() { var ui = angular.module('axelor.ui'); this.TreeViewCtrl = TreeViewCtrl; this.TreeViewCtrl.$inject = ['$scope', '$element', 'DataSource', 'ActionService']; function TreeViewCtrl($scope, $element, DataSource, ActionService) { var view = $scope._views['tree']; var viewPromise = $scope.loadView('tree', view.name); $scope.applyLater(function() { if (view.deferred) { view.deferred.resolve($scope); } }); viewPromise.success(function(fields, schema){ $scope.parse(schema); }); $scope.show = function() { $scope.updateRoute(); }; $scope.onShow = function(promise) { }; $scope.getRouteOptions = function() { return { mode: "tree" }; }; $scope.setRouteOptions = function(options) { $scope.updateRoute(); }; $scope.parse = function(schema) { var columns = _.map(schema.columns, function(col) { return new Column($scope, col); }); var last = null; var loaders = _.map(schema.nodes, function(node) { var loader = new Loader($scope, node, DataSource); if (last) { last.child = loader; } return last = loader; }); $scope.columns = columns; $scope.loaders = loaders; }; $scope.onClick = function(e, options) { var loader = options.loader, record = options.record; if (!loader.action) { return; } if (record.$handler === undefined) { record.$handler = ActionService.handler($scope.$new(), $(e.currentTarget), { action: loader.action }); } if (record.$handler) { var model = loader.model; var context = record.$record; record.$handler.scope.record = context; record.$handler.scope.getContext = function() { return _.extend({ _model: model, }, context); }; record.$handler.onClick().then(function(res){ console.log('aaaaa', res); }); } }; } /** * Column controller. * */ function Column(scope, col) { this.css = col.type || 'string'; this.name = col.name; this.title = col.title; if (this.title === null || this.title === undefined) { this.title = _.humanize(col.name); } this.cellCss = function(record) { return this.css; }; this.cellText = function(record) { var text = record[this.name]; if (text === undefined) { return '---'; } return text; }; } /** * Node loader. * */ function Loader(scope, node, DataSource) { var ds = DataSource.create(node.model); var domain = null; if (node.parent) { domain = "self." + node.parent + ".id = :parent"; } this.child = null; this.model = node.model; this.action = node.onClick; this.load = function(parent, fn) { var names = _.pluck(node.fields, 'name'); var context = {}; if (parent) { context.parent = parent.id; } var promise = ds.search({ fields: names, domain: domain, context: context, archived: true }); promise.success(function(records) { fn(accept(records, parent)); }); return promise; }; var that = this; function accept(records, parent) { var fields = node.fields; var child = that.child; return _.map(records, function(record) { var item = { '$id': record.id, '$record': record, '$parent': parent && parent.id, '$folder': child != null, '$expand': function(fn) { if (child) { return child.load(record, fn); } } }; if (node.onClick) { item.$click = function(e) { scope.onClick(e, { loader: that, record: item, parent: parent }); }; } _.each(fields, function(field) { item[field.as || field.name] = record[field.name]; }); return item; }); }; } ui.directive('uiViewTree', function(){ return { replace: true, link: function(scope, element, attrs) { element.treetable({ expandable: true, clickableNodeNames: true, nodeIdAttr: "id", parentIdAttr: "parent", branchAttr: "folder", onNodeCollapse: function onNodeCollapse() { var node = this, row = node.row; if (node._state === "collapsed") { return; } node._state = "collapsed"; element.treetable("collapseNode", row.data("id")); }, onNodeExpand: function onNodeExpand() { var node = this, row = this.row, record = row.data('$record'); if (node._loading || node._state === "expanded") { return; } node._state = "expanded"; if (node._loaded) { return element.treetable("expandNode", row.data("id")); } node._loading = true; if (record.$expand) { record.$expand(function(records) { acceptNodes(records, node); node._loading = false; node._loaded = true; }); } } }); function acceptNodes(records, after) { var rows = _.map(records, makeRow); element.treetable("loadBranch", after, rows); } function makeRow(record) { var tr = $('<tr>') .attr('data-id', record.$id) .attr('data-parent', record.$parent) .attr('data-folder', record.$folder); tr.data('$record', record); _.each(scope.columns, function(col) { $('<td>').html(col.cellText(record)).appendTo(tr); }); return tr[0]; } element.on('dblclick.treeview', 'tbody tr', function(e) { var record = $(e.currentTarget).data('$record'); if (record && record.$click) { record.$click(e); } }); element.on('mousedown.treeview', 'tbody tr', function(e) { element.find('tr.selected').removeClass('selected'); $(this).addClass("selected"); }); var watcher = scope.$watch('loaders', function(loaders) { if (loaders === undefined) { return; } watcher(); var root = _.first(loaders); if (root) { root.load(null, acceptNodes); } }); }, template: '<table>'+ '<thead>'+ '<tr>'+ '<th ng-repeat="column in columns" ng-class="column.css">{{column.title}}</th>'+ '</tr>'+ '</thead>'+ '<tbody>'+ '</tbody>'+ '</table>' }; }); }).call(this);
axelor-web/src/main/webapp/js/view/view.tree.js
(function() { var ui = angular.module('axelor.ui'); this.TreeViewCtrl = TreeViewCtrl; this.TreeViewCtrl.$inject = ['$scope', '$element', 'DataSource', 'ActionService']; function TreeViewCtrl($scope, $element, DataSource, ActionService) { var view = $scope._views['tree']; var viewPromise = $scope.loadView('tree', view.name); $scope.applyLater(function() { if (view.deferred) { view.deferred.resolve($scope); } }); viewPromise.success(function(fields, schema){ $scope.parse(schema); }); $scope.show = function() { $scope.updateRoute(); }; $scope.onShow = function(promise) { }; $scope.getRouteOptions = function() { return { mode: "tree" }; }; $scope.setRouteOptions = function(options) { $scope.updateRoute(); }; $scope.parse = function(schema) { var columns = _.map(schema.columns, function(col) { return new Column($scope, col); }); var last = null; var loaders = _.map(schema.nodes, function(node) { var loader = new Loader($scope, node, DataSource); if (last) { last.child = loader; } return last = loader; }); $scope.columns = columns; $scope.loaders = loaders; }; $scope.onClick = function(e, options) { var loader = options.loader, record = options.record; if (!loader.action) { return; } if (record.$handler === undefined) { record.$handler = ActionService.handler($scope.$new(), $(e.currentTarget), { action: loader.action }); } if (record.$handler) { var model = loader.model; var context = record.$record; record.$handler.scope.record = context; record.$handler.scope.getContext = function() { return _.extend({ _model: model, }, context); }; record.$handler.onClick().then(function(res){ console.log('aaaaa', res); }); } }; } /** * Column controller. * */ function Column(scope, col) { this.css = col.type || 'string'; this.name = col.name; this.title = col.title; if (this.title === null || this.title === undefined) { this.title = _.humanize(col.name); } this.cellCss = function(record) { return this.css; }; this.cellText = function(record) { var text = record[this.name]; if (text === undefined) { return '---'; } return text; }; } /** * Node loader. * */ function Loader(scope, node, DataSource) { var ds = DataSource.create(node.model); var domain = null; if (node.parent) { domain = "self." + node.parent + ".id = :parent"; } this.child = null; this.model = node.model; this.action = node.onClick; this.load = function(parent, fn) { var names = _.pluck(node.fields, 'name'); var context = {}; if (parent) { context.parent = parent.id; } var promise = ds.search({ fields: names, domain: domain, context: context, archived: true }); promise.success(function(records) { fn(accept(records, parent)); }); return promise; }; var that = this; function accept(records, parent) { var fields = node.fields; var child = that.child; return _.map(records, function(record) { var item = { '$id': record.id, '$record': record, '$parent': parent && parent.id, '$folder': child != null, '$expand': function(fn) { if (child) { return child.load(record, fn); } } }; if (node.onClick) { item.$click = function(e) { scope.onClick(e, { loader: that, record: item, parent: parent }); }; } _.each(fields, function(field) { item[field.as || field.name] = record[field.name]; }); return item; }); }; } ui.directive('uiViewTree', function(){ return { replace: true, link: function(scope, element, attrs) { element.treetable({ expandable: true, clickableNodeNames: true, nodeIdAttr: "id", parentIdAttr: "parent", branchAttr: "folder", onNodeCollapse: function onNodeCollapse() { var node = this, row = node.row; if (node._state === "collapsed") { return; } node._state = "collapsed"; element.treetable("collapseNode", row.data("id")); }, onNodeExpand: function onNodeExpand() { var node = this, row = this.row, record = row.data('$record'); if (node._loading || node._state === "expanded") { return; } node._state = "expanded"; if (node._loaded) { return element.treetable("expandNode", row.data("id")); } node._loading = true; if (record.$expand) { record.$expand(function(records) { acceptNodes(records, node); node._loading = false; node._loaded = true; }); } } }); function acceptNodes(records, after) { var rows = _.map(records, makeRow); element.treetable("loadBranch", after, rows); } function makeRow(record) { var tr = $('<tr>') .attr('data-id', record.$id) .attr('data-parent', record.$parent) .attr('data-folder', record.$folder); tr.data('$record', record); _.each(scope.columns, function(col) { $('<td>').html(col.cellText(record)).appendTo(tr); }); return tr[0]; } element.on('click.treeview', 'tr', function(e) { var record = $(e.currentTarget).data('$record'); if (record && record.$click) { record.$click(e); } }); var watcher = scope.$watch('loaders', function(loaders) { if (loaders === undefined) { return; } watcher(); var root = _.first(loaders); if (root) { root.load(null, acceptNodes); } }); }, template: '<table>'+ '<thead>'+ '<tr>'+ '<th ng-repeat="column in columns" ng-class="column.css">{{column.title}}</th>'+ '</tr>'+ '</thead>'+ '<tbody>'+ '</tbody>'+ '</table>' }; }); }).call(this);
Improved TreeView - execute action on double click - selected row highlight
axelor-web/src/main/webapp/js/view/view.tree.js
Improved TreeView
<ide><path>xelor-web/src/main/webapp/js/view/view.tree.js <ide> return tr[0]; <ide> } <ide> <del> element.on('click.treeview', 'tr', function(e) { <add> element.on('dblclick.treeview', 'tbody tr', function(e) { <ide> var record = $(e.currentTarget).data('$record'); <ide> if (record && record.$click) { <ide> record.$click(e); <ide> } <add> }); <add> <add> element.on('mousedown.treeview', 'tbody tr', function(e) { <add> element.find('tr.selected').removeClass('selected'); <add> $(this).addClass("selected"); <ide> }); <ide> <ide> var watcher = scope.$watch('loaders', function(loaders) {
Java
bsd-2-clause
bd139e23bc786474800f5b1fdc0f366ba7bcd6e4
0
bioinform/varsim,bioinform/varsim,bioinform/varsim,bioinform/varsim
package com.bina.varsim.types; import java.rmi.UnexpectedException; import java.util.*; import java.util.concurrent.Exchanger; /** * Created by guoy28 on 10/5/16. * CLass for VCF INFO field. * TODO: this class should be augmented to handle FORMAT field * TODO: constructors of this class should honor specifications outlined in VCF header */ public class VCFInfo { final private Map<String, VCFInfoElement> info2Value; /** * parse INFO field string * store each key value pair in a map * @param infoString */ public VCFInfo(final String infoString) throws UnexpectedException { this.info2Value = new HashMap<String, VCFInfoElement>(); String[] infos = infoString.split(";"); for (int i = 0; i < infos.length; i++) { String[] keyAndValue = infos[i].split("="); if (keyAndValue.length > 1) { this.info2Value.put(keyAndValue[0], new VCFInfoElement(keyAndValue[0], keyAndValue[1])); } else { //must be boolean or flag this.info2Value.put(keyAndValue[0], new VCFInfoElement()); } } } public Object getValue(final String id) { return this.info2Value.containsKey(id) ? this.info2Value.get(id).getValue() : null; } private class VCFInfoElement { private String[] stringFields; //TODO: Integer should be changed to Long if varsim is used for large genome. private int[] numberFields; private Boolean flagValue; private String type; /** * parse comma separated value and store it * in proper types * @param id * @param value */ public VCFInfoElement(final String id, String value) throws UnexpectedException { this.type = getType(id); String[] valueArray = value.split(","); switch(this.type) { case "Integer": numberFields = new int[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { numberFields[i] = Integer.parseInt(valueArray[i]); } break; case "String": stringFields = valueArray; break; default: throw new UnexpectedException("ERROR: only Integer and String supported for INFO field (" + id + ")."); } } /** * store id as a boolean field */ public VCFInfoElement() { this.type = "Boolean"; this.flagValue = true; } /** * return appropriate values based on types * @return return should be casted */ public Object getValue() { switch (this.type) { case "Integer": return this.numberFields; case "String": return this.stringFields; case "Boolean": return this.flagValue; default: return null; } } } /** * return hard-coded type for some INFO IDs (including some reserved IDs in VCF * spec) * TODO: replace hard-coded infoID-type mapping with VCF header defined mapping * "##INFO=<ID=SVLEN,Number=A,Type=Integer,Description=\"Length of variant\">\n" + "##INFO=<ID=POS2,Number=A,Type=Integer,Description=\"1-based Start position of source sequence\">\n" + "##INFO=<ID=END2,Number=A,Type=Integer,Description=\"1-based End position of source sequence\">\n" + "##INFO=<ID=SVTYPE,Number=1,Type=String,Description=\"Type of structural variant\">\n" + "##INFO=<ID=CHR2,Number=A,Type=String,Description=\"Chromosome of source sequence\">\n" + "##INFO=<ID=TRASUBTYPE,Number=A,Type=String,Description=\"Subtype of translocation event:" + " source sequence deleted (SELFISHNESS); source sequence accepted (CHIVALRY).\">\n" * @param infoID * @return */ public static String getType(final String infoID) { if (infoID.equals("SVLEN") || infoID.equals("POS2") || infoID.equals("END2") || infoID.equals("END") || infoID.equals("DP")) { return "Integer"; } else if (infoID.equals("SVTYPE") || infoID.equals("CHR2") || infoID.equals("TRASUBTYPE")) { return "String"; } else { //unrecognized INFO ID, retrun String for now return "String"; } } }
src/main/java/com/bina/varsim/types/VCFInfo.java
package com.bina.varsim.types; import java.rmi.UnexpectedException; import java.util.*; import java.util.concurrent.Exchanger; /** * Created by guoy28 on 10/5/16. * CLass for VCF INFO field. * TODO: this class should be augmented to handle FORMAT field * TODO: constructors of this class should honor specifications outlined in VCF header */ public class VCFInfo { final private Map<String, VCFInfoElement> info2Value; /** * parse INFO field string * store each key value pair in a map * @param infoString */ public VCFInfo(final String infoString) throws UnexpectedException { this.info2Value = new HashMap<String, VCFInfoElement>(); String[] infos = infoString.split(";"); for (int i = 0; i < infos.length; i++) { String[] keyAndValue = infos[i].split("="); if (keyAndValue.length > 1) { this.info2Value.put(keyAndValue[0], new VCFInfoElement(keyAndValue[0], keyAndValue[1])); } else { //must be boolean or flag this.info2Value.put(keyAndValue[0], new VCFInfoElement()); } } } public Object getValue(final String id) { return this.info2Value.containsKey(id) ? this.info2Value.get(id).getValue() : null; } private class VCFInfoElement { private String[] stringFields; //TODO: Integer should be changed to Long if varsim is used for large genome. private int[] numberFields; private Boolean flagValue; private String type; /** * parse comma separated value and store it * in proper types * @param id * @param value */ public VCFInfoElement(final String id, String value) throws UnexpectedException { this.type = getType(id); String[] valueArray = value.split(","); switch(this.type) { case "Integer": numberFields = new int[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { numberFields[i] = Integer.parseInt(valueArray[i]); } break; case "String": stringFields = valueArray; break; default: throw new UnexpectedException("ERROR: only Integer and String supported for INFO field (" + id + ")."); } } /** * store id as a boolean field */ public VCFInfoElement() { this.type = "Boolean"; this.flagValue = true; } /** * return appropriate values based on types * @return return should be casted */ public Object getValue() { switch (this.type) { case "Integer": return this.numberFields; case "String": return this.stringFields; case "Boolean": return this.flagValue; default: return null; } } } /** * return hard-coded type for some INFO IDs (including some reserved IDs in VCF * spec) * TODO: replace hard-coded infoID-type mapping with VCF header defined mapping * "##INFO=<ID=SVLEN,Number=A,Type=Integer,Description=\"Length of variant\">\n" + "##INFO=<ID=POS2,Number=A,Type=Integer,Description=\"1-based Start position of source sequence\">\n" + "##INFO=<ID=END2,Number=A,Type=Integer,Description=\"1-based End position of source sequence\">\n" + "##INFO=<ID=SVTYPE,Number=1,Type=String,Description=\"Type of structural variant\">\n" + "##INFO=<ID=CHR2,Number=A,Type=String,Description=\"Chromosome of source sequence\">\n" + "##INFO=<ID=TRASUBTYPE,Number=A,Type=String,Description=\"Subtype of translocation event:" + " source sequence deleted (SELFISHNESS); source sequence accepted (CHIVALRY).\">\n" * @param infoID * @return */ public static String getType(final String infoID) { if (infoID.equals("SVLEN") || infoID.equals("POS2") || infoID.equals("END2") || infoID.equals("END") || infoID.equals("DP")) { return "Integer"; } else if (infoID.equals("SVTYPE") || infoID.equals("CHR2") || infoID.equals("TRASUBTYPE")) { return "String"; } else { throw new IllegalArgumentException("ERROR: unrecognized INFO ID (" + infoID + ")."); } } }
return string for unhandled VCF INFO IDs.
src/main/java/com/bina/varsim/types/VCFInfo.java
return string for unhandled VCF INFO IDs.
<ide><path>rc/main/java/com/bina/varsim/types/VCFInfo.java <ide> } else if (infoID.equals("SVTYPE") || infoID.equals("CHR2") || infoID.equals("TRASUBTYPE")) { <ide> return "String"; <ide> } else { <del> throw new IllegalArgumentException("ERROR: unrecognized INFO ID (" + infoID + ")."); <add> //unrecognized INFO ID, retrun String for now <add> return "String"; <ide> } <ide> } <ide> }
Java
apache-2.0
5702d8ef7d02ba8adf1aad1e21d1f91e1aac27c9
0
Zrips/Jobs
package com.gamingmesh.jobs.container; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ShopItem { private String NodeName = null; private double price = 0D; private int slot = -1; private int page = -1; private int IconId = 1; private int IconData = 0; private int IconAmount = 1; private String IconName = null; private List<String> IconLore = new ArrayList<>(); private boolean HideWithoutPerm = false; private int RequiredTotalLevels = -1; private List<String> RequiredPerm = new ArrayList<>(); private HashMap<String, Integer> RequiredJobs = new HashMap<>(); private List<String> Commands = new ArrayList<>(); private List<JobItems> items = new ArrayList<>(); public ShopItem(String NodeName, double price, int IconId) { this.NodeName = NodeName; this.price = price; this.IconId = IconId; } public void setPage(Integer page) { this.page = page; } public int getPage() { return this.page; } public void setSlot(Integer slot) { this.slot = slot; } public int getSlot() { return this.slot; } public void setitems(List<JobItems> items) { this.items = items; } public List<JobItems> getitems() { return this.items; } public void setCommands(List<String> Commands) { this.Commands = Commands; } public List<String> getCommands() { return this.Commands; } public void setRequiredJobs(HashMap<String, Integer> RequiredJobs) { this.RequiredJobs = RequiredJobs; } public HashMap<String, Integer> getRequiredJobs() { return this.RequiredJobs; } public void setRequiredPerm(List<String> RequiredPerm) { this.RequiredPerm = RequiredPerm; } public List<String> getRequiredPerm() { return this.RequiredPerm; } public void setHideWithoutPerm(boolean HideWithoutPerm) { this.HideWithoutPerm = HideWithoutPerm; } public boolean isHideWithoutPerm() { return this.HideWithoutPerm; } public void setIconLore(List<String> IconLore) { this.IconLore = IconLore; } public List<String> getIconLore() { return this.IconLore; } public String getNodeName() { return this.NodeName; } public int getIconId() { return this.IconId; } public int getIconData() { return this.IconData; } public void setIconData(int IconData) { this.IconData = IconData; } public double getPrice() { return this.price; } public void setIconAmount(int IconAmount) { this.IconAmount = IconAmount; } public int getIconAmount() { return this.IconAmount; } public void setIconName(String IconName) { this.IconName = IconName; } public String getIconName() { return this.IconName; } public int getRequiredTotalLevels() { return RequiredTotalLevels; } public void setRequiredTotalLevels(int requiredTotalLevels) { RequiredTotalLevels = requiredTotalLevels; } }
src/main/java/com/gamingmesh/jobs/container/ShopItem.java
package com.gamingmesh.jobs.container; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ShopItem { private String NodeName = null; private double price = 0D; private int slot = -1; private int page = -1; private int IconId = 1; private int IconData = 0; private int IconAmount = 1; private String IconName = null; private List<String> IconLore = new ArrayList<String>(); private boolean HideWithoutPerm = false; private int RequiredTotalLevels = -1; private List<String> RequiredPerm = new ArrayList<String>(); private HashMap<String, Integer> RequiredJobs = new HashMap<String, Integer>(); private List<String> Commands = new ArrayList<String>(); private List<JobItems> items = new ArrayList<JobItems>(); public ShopItem(String NodeName, double price, int IconId) { this.NodeName = NodeName; this.price = price; this.IconId = IconId; } public void setPage(Integer page) { this.page = page; } public int getPage() { return this.page; } public void setSlot(Integer slot) { this.slot = slot; } public int getSlot() { return this.slot; } public void setitems(List<JobItems> items) { this.items = items; } public List<JobItems> getitems() { return this.items; } public void setCommands(List<String> Commands) { this.Commands = Commands; } public List<String> getCommands() { return this.Commands; } public void setRequiredJobs(HashMap<String, Integer> RequiredJobs) { this.RequiredJobs = RequiredJobs; } public HashMap<String, Integer> getRequiredJobs() { return this.RequiredJobs; } public void setRequiredPerm(List<String> RequiredPerm) { this.RequiredPerm = RequiredPerm; } public List<String> getRequiredPerm() { return this.RequiredPerm; } public void setHideWithoutPerm(boolean HideWithoutPerm) { this.HideWithoutPerm = HideWithoutPerm; } public boolean isHideWithoutPerm() { return this.HideWithoutPerm; } public void setIconLore(List<String> IconLore) { this.IconLore = IconLore; } public List<String> getIconLore() { return this.IconLore; } public String getNodeName() { return this.NodeName; } public int getIconId() { return this.IconId; } public int getIconData() { return this.IconData; } public void setIconData(int IconData) { this.IconData = IconData; } public double getPrice() { return this.price; } public void setIconAmount(int IconAmount) { this.IconAmount = IconAmount; } public int getIconAmount() { return this.IconAmount; } public void setIconName(String IconName) { this.IconName = IconName; } public String getIconName() { return this.IconName; } public int getRequiredTotalLevels() { return RequiredTotalLevels; } public void setRequiredTotalLevels(int requiredTotalLevels) { RequiredTotalLevels = requiredTotalLevels; } }
Update ShopItem.java
src/main/java/com/gamingmesh/jobs/container/ShopItem.java
Update ShopItem.java
<ide><path>rc/main/java/com/gamingmesh/jobs/container/ShopItem.java <ide> private int IconData = 0; <ide> private int IconAmount = 1; <ide> private String IconName = null; <del> private List<String> IconLore = new ArrayList<String>(); <add> private List<String> IconLore = new ArrayList<>(); <ide> <ide> private boolean HideWithoutPerm = false; <ide> private int RequiredTotalLevels = -1; <ide> <del> private List<String> RequiredPerm = new ArrayList<String>(); <del> private HashMap<String, Integer> RequiredJobs = new HashMap<String, Integer>(); <add> private List<String> RequiredPerm = new ArrayList<>(); <add> private HashMap<String, Integer> RequiredJobs = new HashMap<>(); <ide> <del> private List<String> Commands = new ArrayList<String>(); <add> private List<String> Commands = new ArrayList<>(); <ide> <del> private List<JobItems> items = new ArrayList<JobItems>(); <add> private List<JobItems> items = new ArrayList<>(); <ide> <ide> public ShopItem(String NodeName, double price, int IconId) { <ide> this.NodeName = NodeName;
Java
mit
237deeba5b6ec642d94c893017d614170048d15d
0
iParqDevelopers/cordova-plugin-flex-camera,iParqDevelopers/cordova-plugin-flex-camera,happieio/cordova-plugin-flex-camera,iParqDevelopers/cordova-plugin-flex-camera,happieio/cordova-plugin-flex-camera,happieio/cordova-plugin-flex-camera
package io.happie.cordovaCamera; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.Camera; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.OrientationEventListener; import android.view.Surface; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.hardware.SensorManager; import com.jobnimbus.JobNimbus2.R; //parent project package import org.apache.cordova.PluginResult; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * import com.jobnimbus.moderncamera.R; //Used For testing with the intenral ionic project */ public class HappieCameraActivity extends Activity { public static final int MEDIA_TYPE_IMAGE = 1; public static final int MEDIA_TYPE_VIDEO = 2; private static final String TAG = "HappieCameraActivity"; private ImageButton shutter; private ImageButton flash; private ImageView upperLeftThumbnail; private ImageView upperRightThumbnail; private ImageView lowerLeftThumbnail; private ImageView lowerRightThumbnail; private TextView badgeCount; private int badgeCounter; private int quadState; //0 = UL , 1 = UR, 2 = LL, 3 = LR private int flashState; private android.content.Context thisRef; File mediaStorageDir; File mediaThumbStorageDir; protected HappieCameraThumb thumbGen = new HappieCameraThumb(); protected HappieCameraJSON jsonGen = new HappieCameraJSON(); private Camera mCamera; /** * UI State Functions */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.happie_cam_layout); onCreateTasks(); } protected void onCreateTasks() { OrientationEventListener orientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) { @Override public void onOrientationChanged(int arg0) { //TODO update camera orientation with arg0 } }; if (orientationListener.canDetectOrientation()) orientationListener.enable(); ImageButton cancel = (ImageButton) findViewById(R.id.cancel); cancel.setOnClickListener(cancelSession); shutter = (ImageButton) findViewById(R.id.shutter); shutter.setOnClickListener(captureImage); ImageButton queue = (ImageButton) findViewById(R.id.confirm); queue.setOnClickListener(cameraFinishToQueue); flash = (ImageButton) findViewById(R.id.flashToggle); flash.setOnClickListener(switchFlash); upperLeftThumbnail = (ImageView) findViewById(R.id.UpperLeft); upperRightThumbnail = (ImageView) findViewById(R.id.UpperRight); lowerLeftThumbnail = (ImageView) findViewById(R.id.LowerLeft); lowerRightThumbnail = (ImageView) findViewById(R.id.LowerRight); badgeCount = (TextView) findViewById(R.id.badgeCount); quadState = 0; thisRef = this; mediaStorageDir = new File(HappieCamera.context.getExternalFilesDir(null) + "/media"); mediaThumbStorageDir = new File(HappieCamera.context.getExternalFilesDir(null) + "/media/thumb"); if (mediaStorageDir.mkdirs()) { Log.d(TAG, "media directory created"); } else { Log.d(TAG, "media directory already created"); } if (mediaThumbStorageDir.mkdirs()) { Log.d(TAG, "media thumbnail directory created"); } else { Log.d(TAG, "media thumbnail directory already created"); } String filePath = HappieCamera.context.getExternalFilesDir(null) + "/media/thumb"; File thumbDir = new File(filePath); String[] files = thumbDir.list(); for (String file : files) { File image = new File(filePath, file); BitmapFactory.Options bmOptions = new BitmapFactory.Options(); Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions); if (badgeCounter == 0) { upperLeftThumbnail.setImageBitmap(bitmap); quadState = 1; } else if (badgeCounter == 1) { upperRightThumbnail.setImageBitmap(bitmap); quadState = 2; } else if (badgeCounter == 2) { lowerLeftThumbnail.setImageBitmap(bitmap); quadState = 3; } else if (badgeCounter == 3) { lowerRightThumbnail.setImageBitmap(bitmap); quadState = 0; } badgeCounter++; badgeCount.setText(Integer.toString(badgeCounter)); } initCameraSession(); initCameraPreview(); setCamOrientation(); } protected void initCameraPreview() { HappieCameraPreview mPreview = new HappieCameraPreview(this, mCamera); FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mPreview); } protected void initCameraSession() { try { releaseCamera(); mCamera = Camera.open(); Camera.Parameters params = mCamera.getParameters(); params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); mCamera.setParameters(params); params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); flash.setImageResource(R.drawable.camera_flash_auto); flashState = 1; mCamera.setParameters(params); } catch (Exception e) { HappieCamera.callbackContext.error("Failed to initialize the camera"); PluginResult r = new PluginResult(PluginResult.Status.ERROR); HappieCamera.callbackContext.sendPluginResult(r); } } protected void setCamOrientation() { mCamera.stopPreview(); Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(0, info); int rotation = this.getWindowManager().getDefaultDisplay().getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; // compensate the mirror } else { // back-facing result = (info.orientation - degrees + 360) % 360; } mCamera.setDisplayOrientation(result); mCamera.startPreview(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); } @Override protected void onPause() { super.onPause(); releaseCamera(); // release the camera immediately on pause event } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setContentView(R.layout.happie_cam_layout); onCreateTasks(); } protected void onResume() { super.onResume(); if (mCamera == null) { initCameraSession(); // restart camera session when view returns } } protected void onDestroy() { super.onDestroy(); releaseCamera(); // release the camera immediately on pause event } private void releaseCamera() { if (mCamera != null) { mCamera.release(); // release the camera for other applications mCamera = null; } } /** * UI Buttons */ private View.OnClickListener cancelSession = new View.OnClickListener() { @Override public void onClick(View v) { String JSON = jsonGen.getFinalJSON("cancel", false); HappieCamera.sessionFinished(JSON); finish(); } }; private View.OnClickListener captureImage = new View.OnClickListener() { @Override public void onClick(View v) { shutter.setEnabled(false); mCamera.takePicture(null, null, capturePicture); //shutter, raw, jpeg } }; private View.OnClickListener cameraFinishToQueue = new View.OnClickListener() { @Override public void onClick(View v) { String JSON = jsonGen.getFinalJSON("queue", true); HappieCamera.sessionFinished(JSON); finish(); } }; private View.OnClickListener switchFlash = new View.OnClickListener() { @Override public void onClick(View v) { Camera.Parameters params = mCamera.getParameters(); if (flashState == 0) { params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); flash.setImageResource(R.drawable.camera_flash_off); flashState = 1; } else if (flashState == 1) { params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); flash.setImageResource(R.drawable.camera_flash_auto); flashState = 2; } else if (flashState == 2) { params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); flash.setImageResource(R.drawable.camera_flash_on); flashState = 0; } mCamera.setParameters(params); } }; /** * Camera and file implementations */ private Camera.PictureCallback capturePicture = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { mCamera.startPreview(); if (quadState == 0) { quadState = 1; } else if (quadState == 1) { quadState = 2; } else if (quadState == 2) { quadState = 3; } else if (quadState == 3) { quadState = 0; } badgeCounter += 1; badgeCount.setText(Integer.toString(badgeCounter)); new ProcessImage(badgeCounter, badgeCount, quadState, upperLeftThumbnail, upperRightThumbnail, lowerLeftThumbnail, lowerRightThumbnail, thisRef, mediaStorageDir, mediaThumbStorageDir).execute(data); shutter.setEnabled(true); } }; private class ProcessImage extends AsyncTask<byte[], Integer, android.graphics.Bitmap> { private android.content.Context thisRef; private ImageView upperLeftThumbnail; private ImageView upperRightThumbnail; private ImageView lowerLeftThumbnail; private ImageView lowerRightThumbnail; private TextView badgeCount; private int badgeCounter; private int quadState; //0 = UL , 1 = UR, 2 = LL, 3 = LR private File mediaStorageDir; private File mediaThumbStorageDir; ProcessImage(int badgeCounter, TextView badgeCount, int quadState, ImageView upperLeftThumb, ImageView upperRightThumb, ImageView lowerLeftThumb, ImageView lowerRightThumb, android.content.Context thisRef, File media, File thumb) { this.upperLeftThumbnail = upperLeftThumb; this.upperRightThumbnail = upperRightThumb; this.lowerLeftThumbnail = lowerLeftThumb; this.lowerRightThumbnail = lowerRightThumb; this.quadState = quadState; this.badgeCounter = badgeCounter; this.badgeCount = badgeCount; this.thisRef = thisRef; this.mediaStorageDir = media; this.mediaThumbStorageDir = thumb; } protected android.graphics.Bitmap doInBackground(byte[]... bytes) { if (Environment.getExternalStorageState().equals("MEDIA_MOUNTED") || Environment.getExternalStorageState().equals("mounted")) { final File[] pictureFiles = getOutputMediaFiles(MEDIA_TYPE_IMAGE); if (pictureFiles == null) { Log.d(TAG, "Error creating media file, check storage permissions: "); } try { //save image FileOutputStream fos = new FileOutputStream(pictureFiles[0]); fos.write(bytes[0]); fos.close(); //save thumbnail thumbGen.createThumbOfImage(pictureFiles[1], bytes[0]); String[] pathAndThumb = new String[2]; pathAndThumb[0] = Uri.fromFile(pictureFiles[0]).toString(); pathAndThumb[1] = Uri.fromFile(pictureFiles[1]).toString(); jsonGen.addToPathArray(pathAndThumb); Bitmap preview = BitmapFactory.decodeFile(pictureFiles[1].getAbsolutePath()); return preview; } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } } else { presentSDCardWarning(); Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types Bitmap bmp = Bitmap.createBitmap(100, 100, conf); return bmp; } Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types Bitmap bmp = Bitmap.createBitmap(100, 100, conf); return bmp; } protected void onPostExecute(android.graphics.Bitmap preview) { if (quadState == 0) { upperLeftThumbnail.setImageBitmap(preview); } else if (quadState == 1) { upperRightThumbnail.setImageBitmap((preview)); } else if (quadState == 2) { lowerLeftThumbnail.setImageBitmap((preview)); } else if (quadState == 3) { lowerRightThumbnail.setImageBitmap((preview)); } } private File[] getOutputMediaFiles(int type) { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File[] FileAndThumb = new File[2]; if (type == MEDIA_TYPE_IMAGE) { FileAndThumb[0] = new File(mediaStorageDir.getPath() + File.separator + timeStamp + "photo" + Integer.toString(badgeCounter) + ".jpg"); FileAndThumb[1] = new File(mediaThumbStorageDir.getPath() + File.separator + timeStamp + "photo" + Integer.toString(badgeCounter) + ".jpg"); } else if (type == MEDIA_TYPE_VIDEO) { FileAndThumb[0] = new File(mediaStorageDir.getPath() + File.separator + timeStamp + "vid" + Integer.toString(badgeCounter) + ".mp4"); FileAndThumb[1] = new File(mediaThumbStorageDir.getPath() + File.separator + timeStamp + "vid" + Integer.toString(badgeCounter) + ".mp4"); } else { return null; } return FileAndThumb; } private void presentSDCardWarning() { new AlertDialog.Builder(thisRef) .setTitle("SD Card Not Found") .setMessage("Cannot reach SD card, closing camera.") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); Log.d(TAG, "Error accessing file: SD Card Not Available"); } } }
src/android/HappieCameraActivity.java
package io.happie.cordovaCamera; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.Camera; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.OrientationEventListener; import android.view.Surface; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.hardware.SensorManager; import com.jobnimbus.JobNimbus2.R; //parent project package import org.apache.cordova.PluginResult; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * import com.jobnimbus.moderncamera.R; //Used For testing with the intenral ionic project */ public class HappieCameraActivity extends Activity { public static final int MEDIA_TYPE_IMAGE = 1; public static final int MEDIA_TYPE_VIDEO = 2; private static final String TAG = "HappieCameraActivity"; private ImageButton flash; private ImageView upperLeftThumbnail; private ImageView upperRightThumbnail; private ImageView lowerLeftThumbnail; private ImageView lowerRightThumbnail; private TextView badgeCount; private int badgeCounter; private int quadState; //0 = UL , 1 = UR, 2 = LL, 3 = LR private int flashState; private android.content.Context thisRef; File mediaStorageDir; File mediaThumbStorageDir; protected HappieCameraThumb thumbGen = new HappieCameraThumb(); protected HappieCameraJSON jsonGen = new HappieCameraJSON(); private Camera mCamera; /** * UI State Functions */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.happie_cam_layout); onCreateTasks(); } protected void onCreateTasks() { OrientationEventListener orientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) { @Override public void onOrientationChanged(int arg0) { //TODO update camera orientation with arg0 } }; if (orientationListener.canDetectOrientation()) orientationListener.enable(); ImageButton cancel = (ImageButton) findViewById(R.id.cancel); cancel.setOnClickListener(cancelSession); ImageButton shutter = (ImageButton) findViewById(R.id.shutter); shutter.setOnClickListener(captureImage); ImageButton queue = (ImageButton) findViewById(R.id.confirm); queue.setOnClickListener(cameraFinishToQueue); flash = (ImageButton) findViewById(R.id.flashToggle); flash.setOnClickListener(switchFlash); upperLeftThumbnail = (ImageView) findViewById(R.id.UpperLeft); upperRightThumbnail = (ImageView) findViewById(R.id.UpperRight); lowerLeftThumbnail = (ImageView) findViewById(R.id.LowerLeft); lowerRightThumbnail = (ImageView) findViewById(R.id.LowerRight); badgeCount = (TextView) findViewById(R.id.badgeCount); quadState = 0; thisRef = this; mediaStorageDir = new File(HappieCamera.context.getExternalFilesDir(null) + "/media"); mediaThumbStorageDir = new File(HappieCamera.context.getExternalFilesDir(null) + "/media/thumb"); if (mediaStorageDir.mkdirs()) { Log.d(TAG, "media directory created"); } else { Log.d(TAG, "media directory already created"); } if (mediaThumbStorageDir.mkdirs()) { Log.d(TAG, "media thumbnail directory created"); } else { Log.d(TAG, "media thumbnail directory already created"); } String filePath = HappieCamera.context.getExternalFilesDir(null) + "/media/thumb"; File thumbDir = new File(filePath); String[] files = thumbDir.list(); for (String file : files) { File image = new File(filePath, file); BitmapFactory.Options bmOptions = new BitmapFactory.Options(); Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions); if (badgeCounter == 0) { upperLeftThumbnail.setImageBitmap(bitmap); quadState = 1; } else if (badgeCounter == 1) { upperRightThumbnail.setImageBitmap(bitmap); quadState = 2; } else if (badgeCounter == 2) { lowerLeftThumbnail.setImageBitmap(bitmap); quadState = 3; } else if (badgeCounter == 3) { lowerRightThumbnail.setImageBitmap(bitmap); quadState = 0; } badgeCounter++; badgeCount.setText(Integer.toString(badgeCounter)); } initCameraSession(); initCameraPreview(); setCamOrientation(); } protected void initCameraPreview() { HappieCameraPreview mPreview = new HappieCameraPreview(this, mCamera); FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mPreview); } protected void initCameraSession() { try { releaseCamera(); mCamera = Camera.open(); Camera.Parameters params = mCamera.getParameters(); params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); mCamera.setParameters(params); params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); flash.setImageResource(R.drawable.camera_flash_auto); flashState = 1; mCamera.setParameters(params); } catch (Exception e) { HappieCamera.callbackContext.error("Failed to initialize the camera"); PluginResult r = new PluginResult(PluginResult.Status.ERROR); HappieCamera.callbackContext.sendPluginResult(r); } } protected void setCamOrientation() { mCamera.stopPreview(); Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(0, info); int rotation = this.getWindowManager().getDefaultDisplay().getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; // compensate the mirror } else { // back-facing result = (info.orientation - degrees + 360) % 360; } mCamera.setDisplayOrientation(result); mCamera.startPreview(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); } @Override protected void onPause() { super.onPause(); releaseCamera(); // release the camera immediately on pause event } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setContentView(R.layout.happie_cam_layout); onCreateTasks(); } protected void onResume() { super.onResume(); if (mCamera == null) { initCameraSession(); // restart camera session when view returns } } protected void onDestroy() { super.onDestroy(); releaseCamera(); // release the camera immediately on pause event } private void releaseCamera() { if (mCamera != null) { mCamera.release(); // release the camera for other applications mCamera = null; } } /** * UI Buttons */ private View.OnClickListener cancelSession = new View.OnClickListener() { @Override public void onClick(View v) { String JSON = jsonGen.getFinalJSON("cancel", false); HappieCamera.sessionFinished(JSON); finish(); } }; private View.OnClickListener captureImage = new View.OnClickListener() { @Override public void onClick(View v) { mCamera.takePicture(null, null, capturePicture); //shutter, raw, jpeg } }; private View.OnClickListener cameraFinishToQueue = new View.OnClickListener() { @Override public void onClick(View v) { String JSON = jsonGen.getFinalJSON("queue", true); HappieCamera.sessionFinished(JSON); finish(); } }; private View.OnClickListener switchFlash = new View.OnClickListener() { @Override public void onClick(View v) { Camera.Parameters params = mCamera.getParameters(); if (flashState == 0) { params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); flash.setImageResource(R.drawable.camera_flash_off); flashState = 1; } else if (flashState == 1) { params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); flash.setImageResource(R.drawable.camera_flash_auto); flashState = 2; } else if (flashState == 2) { params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); flash.setImageResource(R.drawable.camera_flash_on); flashState = 0; } mCamera.setParameters(params); } }; /** * Camera and file implementations */ private Camera.PictureCallback capturePicture = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { mCamera.startPreview(); if (quadState == 0) { quadState = 1; } else if (quadState == 1) { quadState = 2; } else if (quadState == 2) { quadState = 3; } else if (quadState == 3) { quadState = 0; } badgeCounter += 1; badgeCount.setText(Integer.toString(badgeCounter)); new ProcessImage(badgeCounter, badgeCount, quadState, upperLeftThumbnail, upperRightThumbnail, lowerLeftThumbnail, lowerRightThumbnail, thisRef, mediaStorageDir, mediaThumbStorageDir).execute(data); } }; private class ProcessImage extends AsyncTask<byte[], Integer, android.graphics.Bitmap> { private android.content.Context thisRef; private ImageView upperLeftThumbnail; private ImageView upperRightThumbnail; private ImageView lowerLeftThumbnail; private ImageView lowerRightThumbnail; private TextView badgeCount; private int badgeCounter; private int quadState; //0 = UL , 1 = UR, 2 = LL, 3 = LR private File mediaStorageDir; private File mediaThumbStorageDir; ProcessImage(int badgeCounter, TextView badgeCount, int quadState, ImageView upperLeftThumb, ImageView upperRightThumb, ImageView lowerLeftThumb, ImageView lowerRightThumb, android.content.Context thisRef, File media, File thumb) { this.upperLeftThumbnail = upperLeftThumb; this.upperRightThumbnail = upperRightThumb; this.lowerLeftThumbnail = lowerLeftThumb; this.lowerRightThumbnail = lowerRightThumb; this.quadState = quadState; this.badgeCounter = badgeCounter; this.badgeCount = badgeCount; this.thisRef = thisRef; this.mediaStorageDir = media; this.mediaThumbStorageDir = thumb; } protected android.graphics.Bitmap doInBackground(byte[]... bytes) { if (Environment.getExternalStorageState().equals("MEDIA_MOUNTED") || Environment.getExternalStorageState().equals("mounted")) { final File[] pictureFiles = getOutputMediaFiles(MEDIA_TYPE_IMAGE); if (pictureFiles == null) { Log.d(TAG, "Error creating media file, check storage permissions: "); } try { //save image FileOutputStream fos = new FileOutputStream(pictureFiles[0]); fos.write(bytes[0]); fos.close(); //save thumbnail thumbGen.createThumbOfImage(pictureFiles[1], bytes[0]); String[] pathAndThumb = new String[2]; pathAndThumb[0] = Uri.fromFile(pictureFiles[0]).toString(); pathAndThumb[1] = Uri.fromFile(pictureFiles[1]).toString(); jsonGen.addToPathArray(pathAndThumb); Bitmap preview = BitmapFactory.decodeFile(pictureFiles[1].getAbsolutePath()); return preview; } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } } else { presentSDCardWarning(); Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types Bitmap bmp = Bitmap.createBitmap(100, 100, conf); return bmp; } Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types Bitmap bmp = Bitmap.createBitmap(100, 100, conf); return bmp; } protected void onPostExecute(android.graphics.Bitmap preview) { if (quadState == 0) { upperLeftThumbnail.setImageBitmap(preview); } else if (quadState == 1) { upperRightThumbnail.setImageBitmap((preview)); } else if (quadState == 2) { lowerLeftThumbnail.setImageBitmap((preview)); } else if (quadState == 3) { lowerRightThumbnail.setImageBitmap((preview)); } } private File[] getOutputMediaFiles(int type) { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File[] FileAndThumb = new File[2]; if (type == MEDIA_TYPE_IMAGE) { FileAndThumb[0] = new File(mediaStorageDir.getPath() + File.separator + timeStamp + "photo" + Integer.toString(badgeCounter) + ".jpg"); FileAndThumb[1] = new File(mediaThumbStorageDir.getPath() + File.separator + timeStamp + "photo" + Integer.toString(badgeCounter) + ".jpg"); } else if (type == MEDIA_TYPE_VIDEO) { FileAndThumb[0] = new File(mediaStorageDir.getPath() + File.separator + timeStamp + "vid" + Integer.toString(badgeCounter) + ".mp4"); FileAndThumb[1] = new File(mediaThumbStorageDir.getPath() + File.separator + timeStamp + "vid" + Integer.toString(badgeCounter) + ".mp4"); } else { return null; } return FileAndThumb; } private void presentSDCardWarning() { new AlertDialog.Builder(thisRef) .setTitle("SD Card Not Found") .setMessage("Cannot reach SD card, closing camera.") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); Log.d(TAG, "Error accessing file: SD Card Not Available"); } } }
disable shut during crash sensitive processing time between taking pictures
src/android/HappieCameraActivity.java
disable shut during crash sensitive processing time between taking pictures
<ide><path>rc/android/HappieCameraActivity.java <ide> import android.view.View; <ide> import android.widget.FrameLayout; <ide> import android.widget.ImageButton; <del>import android.widget.Button; <ide> import android.widget.ImageView; <ide> import android.widget.TextView; <ide> import android.hardware.SensorManager; <ide> public static final int MEDIA_TYPE_VIDEO = 2; <ide> private static final String TAG = "HappieCameraActivity"; <ide> <add> private ImageButton shutter; <ide> private ImageButton flash; <ide> <ide> private ImageView upperLeftThumbnail; <ide> ImageButton cancel = (ImageButton) findViewById(R.id.cancel); <ide> cancel.setOnClickListener(cancelSession); <ide> <del> ImageButton shutter = (ImageButton) findViewById(R.id.shutter); <add> shutter = (ImageButton) findViewById(R.id.shutter); <ide> shutter.setOnClickListener(captureImage); <ide> <ide> ImageButton queue = (ImageButton) findViewById(R.id.confirm); <ide> private View.OnClickListener captureImage = new View.OnClickListener() { <ide> @Override <ide> public void onClick(View v) { <add> shutter.setEnabled(false); <ide> mCamera.takePicture(null, null, capturePicture); //shutter, raw, jpeg <ide> } <ide> }; <ide> new ProcessImage(badgeCounter, badgeCount, quadState, upperLeftThumbnail, <ide> upperRightThumbnail, lowerLeftThumbnail, lowerRightThumbnail, thisRef, <ide> mediaStorageDir, mediaThumbStorageDir).execute(data); <add> shutter.setEnabled(true); <ide> <ide> } <ide> };
JavaScript
mit
69fc12e892fee9eb78666cbd0ec51f780632c158
0
kmtabish/customerFeedbackPlugin,kmtabish/customerFeedbackPlugin
'use strict'; (function (angular) { angular .module('customerFeedbackPluginDesign') .controller('DesignHomeCtrl', ['$scope','Buildfire','DataStore', 'TAG_NAMES', function ($scope, Buildfire, DataStore, TAG_NAMES) { var DesignHome = this; function init() { var feedBackInfo = { design: { backgroundImage: '' }, content: { "carouselImages": [], "description": '<p>&nbsp;<br></p>' } }; Buildfire.datastore.get(TAG_NAMES.FEEDBACK_APP_INFO, function (err, data) { console.log('datastore.get customer feedback Info-----------', data); if (err) { console.log('------------Error in Design of customer feedback plugin------------', err); } else if (data && data.data) { DesignHome.feedBackInfo = angular.copy(data.data); if (!DesignHome.feedBackInfo.design) DesignHome.feedBackInfo.design = {}; if (DesignHome.feedBackInfo && DesignHome.feedBackInfo.design && DesignHome.feedBackInfo.design.backgroundImage) { DesignHome.background.loadbackground(DesignHome.feedBackInfo.design.backgroundImage); } if (!$scope.$$phase && !$scope.$root.$$phase) { $scope.$digest(); } } else { DesignHome.feedBackInfo = feedBackInfo; console.info('------------------unable to load data---------------'); } }); } DesignHome.background = new Buildfire.components.images.thumbnail("#background"); DesignHome.background.onChange = function (url) { DesignHome.feedBackInfo.design.backgroundImage = url; if (!$scope.$$phase && !$scope.$root.$$phase) { $scope.$apply(); } }; DesignHome.background.onDelete = function (url) { DesignHome.feedBackInfo.design.backgroundImage = ""; if (!$scope.$$phase && !$scope.$root.$$phase) { $scope.$apply(); } }; init(); /*watch the change event and update in database*/ $scope.$watch(function () { return DesignHome.feedBackInfo; }, function (oldObj,newObj) { if (oldObj != newObj && newObj) { console.log("Updated Object:", newObj, oldObj); Buildfire.datastore.save(DesignHome.feedBackInfo, TAG_NAMES.FEEDBACK_APP_INFO, function (err, data) { if (err) { //return DesignHome.data = angular.copy(DesignHomeMaster); } else if (data) { //return DesignHomeMaster = data.obj; console.log("Updated Object:", newObj); } $scope.$digest(); }); } }, true); }]); })(window.angular);
control/design/controllers/design.home.controller.js
'use strict'; (function (angular) { angular .module('customerFeedbackPluginDesign') .controller('DesignHomeCtrl', ['$scope','Buildfire','DataStore', 'TAG_NAMES', function ($scope, Buildfire, DataStore, TAG_NAMES) { var DesignHome = this; function init() { var feedBackInfo = { design: { backgroundImage: '' } }; Buildfire.datastore.get(TAG_NAMES.FEEDBACK_APP_INFO, function (err, data) { console.log('datastore.get customer feedback Info-----------', data); if (err) { console.log('------------Error in Design of customer feedback plugin------------', err); } else if (data && data.data) { DesignHome.feedBackInfo = angular.copy(data.data); if (!DesignHome.feedBackInfo.design) DesignHome.feedBackInfo.design = {}; if (DesignHome.feedBackInfo && DesignHome.feedBackInfo.design && DesignHome.feedBackInfo.design.backgroundImage) { DesignHome.background.loadbackground(DesignHome.feedBackInfo.design.backgroundImage); } if (!$scope.$$phase && !$scope.$root.$$phase) { $scope.$digest(); } } else { DesignHome.feedBackInfo = feedBackInfo; console.info('------------------unable to load data---------------'); } }); } DesignHome.background = new Buildfire.components.images.thumbnail("#background"); DesignHome.background.onChange = function (url) { DesignHome.feedBackInfo.design.backgroundImage = url; if (!$scope.$$phase && !$scope.$root.$$phase) { $scope.$apply(); } }; DesignHome.background.onDelete = function (url) { DesignHome.feedBackInfo.design.backgroundImage = ""; if (!$scope.$$phase && !$scope.$root.$$phase) { $scope.$apply(); } }; init(); /*watch the change event and update in database*/ $scope.$watch(function () { return DesignHome.feedBackInfo; }, function (oldObj,newObj) { if (oldObj != newObj && newObj) { console.log("Updated Object:", newObj, oldObj); Buildfire.datastore.save(DesignHome.feedBackInfo, TAG_NAMES.FEEDBACK_APP_INFO, function (err, data) { if (err) { //return DesignHome.data = angular.copy(DesignHomeMaster); } else if (data) { //return DesignHomeMaster = data.obj; console.log("Updated Object:", newObj); } $scope.$digest(); }); } }, true); }]); })(window.angular);
Added default content object values while saving object
control/design/controllers/design.home.controller.js
Added default content object values while saving object
<ide><path>ontrol/design/controllers/design.home.controller.js <ide> var feedBackInfo = { <ide> design: { <ide> backgroundImage: '' <del> } <add> }, <add> content: { <add> "carouselImages": [], <add> "description": '<p>&nbsp;<br></p>' <add> } <ide> }; <ide> <ide> Buildfire.datastore.get(TAG_NAMES.FEEDBACK_APP_INFO, function (err, data) {
JavaScript
mit
4473d2cdb6c8fc6b267532b96f5a47f802f44aba
0
trailsjs/trailpack-router
module.exports = { 'Footprint.UnknownModel': { message: 'The Model specified in this request is not defined in the API', statusCode: 404 }, 'Footprint.UnknownParentModel': { message: 'The Parent Model specified in this association request is not defined in the API', statusCode: 404 }, 'Footprint.UnknownChildModel': { message: 'The Child Model specified in this association request is not defined in the API', statusCode: 404 } }
config/errors.js
module.exports = { 'Footprint.UnknownModel': { message: 'The Model specified in this request is not defined in the API', statusCode: 404 }, 'Footprint.UnknownParentModel': { message: 'The Parent Model specified in this association request is not defined in the API',, statusCode: 404 }, 'Footprint.UnknownChildModel': { message: 'The Child Model specified in this association request is not defined in the API',, statusCode: 404 } }
[config] added errors config
config/errors.js
[config] added errors config
<ide><path>onfig/errors.js <ide> statusCode: 404 <ide> }, <ide> 'Footprint.UnknownParentModel': { <del> message: 'The Parent Model specified in this association request is not defined in the API',, <add> message: 'The Parent Model specified in this association request is not defined in the API', <ide> statusCode: 404 <ide> }, <ide> 'Footprint.UnknownChildModel': { <del> message: 'The Child Model specified in this association request is not defined in the API',, <add> message: 'The Child Model specified in this association request is not defined in the API', <ide> statusCode: 404 <ide> } <ide>
Java
mit
c1a6a90e3be21d4934239d0de9c08899d8051e9a
0
fr1kin/ForgeHax,fr1kin/ForgeHax
package com.matt.forgehax.util.draw; import com.matt.forgehax.util.Utils; import net.minecraft.client.renderer.GlStateManager; import uk.co.hexeption.thx.ttf.MinecraftFontRenderer; import java.util.Arrays; import static org.lwjgl.opengl.GL11.*; /** * Created on 9/2/2017 by fr1kin */ public class SurfaceBuilder { private static final float[] EMPTY_COLOR = new float[] {0.f, 0.f, 0.f, 0.f}; private static final SurfaceBuilder INSTANCE = new SurfaceBuilder(); public static SurfaceBuilder getBuilder() { return INSTANCE; } // -------------------- private final float[] color4f = Arrays.copyOf(EMPTY_COLOR, EMPTY_COLOR.length); public SurfaceBuilder begin(int mode) { glBegin(mode); return this; } public SurfaceBuilder beginLines() { return begin(GL_LINES); } public SurfaceBuilder beginLineLoop() { return begin(GL_LINE_LOOP); } public SurfaceBuilder beginQuads() { return begin(GL_QUADS); } public SurfaceBuilder beginPolygon() { return begin(GL_POLYGON); } public SurfaceBuilder end() { glEnd(); return this; } public SurfaceBuilder push() { GlStateManager.pushMatrix(); return this; } public SurfaceBuilder pop() { System.arraycopy(EMPTY_COLOR, 0, color4f, 0, color4f.length); GlStateManager.popMatrix(); return this; } public SurfaceBuilder color(float r, float g, float b, float a) { color4f[0] = r; color4f[1] = g; color4f[2] = b; color4f[3] = a; glColor4f(r, g, b, a); return this; } public SurfaceBuilder color(int buffer) { return color( (buffer >> 16 & 255) / 255.0F, (buffer >> 8 & 255) / 255.0F, (buffer & 255) / 255.0F, (buffer >> 24 & 255) / 255.0F ); } public SurfaceBuilder color(int r, int g, int b, int a) { return color(r / 255.f, g / 255.f, b / 255.f, a / 255.f); } public SurfaceBuilder scale(double x, double y, double z) { glScaled(Math.max(x, 0), Math.max(y, 0), Math.max(z, 0)); return this; } public SurfaceBuilder scale(double s) { return scale(s, s, s); } public SurfaceBuilder scale() { return scale(0.D); } public SurfaceBuilder translate(double x, double y, double z) { GlStateManager.translate(x, y, z); return this; } public SurfaceBuilder rotate(double angle, double x, double y, double z) { glRotated(angle, x, y, z); return this; } public SurfaceBuilder width(double width) { GlStateManager.glLineWidth((float) width); return this; } public SurfaceBuilder vertex(double x, double y, double z) { glVertex3d(x, y, z); return this; } public SurfaceBuilder vertex(double x, double y) { return vertex(x, y, 0.D); } public SurfaceBuilder line(double startX, double startY, double endX, double endY) { return vertex(startX, startY) .vertex(endX, endY); } public SurfaceBuilder rectangle(double x, double y, double w, double h) { return vertex(x, y) .vertex(x, y + h) .vertex(x + w, y + h) .vertex(x + w, y); } private SurfaceBuilder text(MinecraftFontRenderer renderer, String text, double x, double y, boolean shadow) { renderer.drawString(text, x, y, Utils.toRGBA(color4f), shadow); return this; } private SurfaceBuilder text(MinecraftFontRenderer renderer, String text, double x, double y) { return text(renderer, text, x, y, false); } private SurfaceBuilder textWithShadow(MinecraftFontRenderer renderer, String text, double x, double y) { return text(renderer, text, x, y, true); } public SurfaceBuilder task(Runnable task) { task.run(); return this; } // -------------------- public static void preRenderSetup() { GlStateManager.enableBlend(); GlStateManager.disableTexture2D(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); } public static void postRenderSetup() { GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); } }
src/main/java/com/matt/forgehax/util/draw/SurfaceBuilder.java
package com.matt.forgehax.util.draw; import com.matt.forgehax.util.Utils; import net.minecraft.client.renderer.GlStateManager; import uk.co.hexeption.thx.ttf.MinecraftFontRenderer; import static org.lwjgl.opengl.GL11.*; /** * Created on 9/2/2017 by fr1kin */ public class SurfaceBuilder { private static final float[] EMPTY_COLOR = new float[] {0.f, 0.f, 0.f, 0.f}; private static final SurfaceBuilder INSTANCE = new SurfaceBuilder(); public static SurfaceBuilder getBuilder() { return INSTANCE; } // -------------------- private final float[] color4f = EMPTY_COLOR; public SurfaceBuilder begin(int mode) { glBegin(mode); return this; } public SurfaceBuilder beginLines() { return begin(GL_LINES); } public SurfaceBuilder beginLineLoop() { return begin(GL_LINE_LOOP); } public SurfaceBuilder beginQuads() { return begin(GL_QUADS); } public SurfaceBuilder beginPolygon() { return begin(GL_POLYGON); } public SurfaceBuilder end() { glEnd(); return this; } public SurfaceBuilder push() { GlStateManager.pushMatrix(); return this; } public SurfaceBuilder pop() { GlStateManager.popMatrix(); return this; } public SurfaceBuilder color(float r, float g, float b, float a) { color4f[0] = r; color4f[1] = g; color4f[2] = b; color4f[3] = a; glColor4f(r, g, b, a); return this; } public SurfaceBuilder color(int buffer) { return color( (buffer >> 16 & 255) / 255.0F, (buffer >> 8 & 255) / 255.0F, (buffer & 255) / 255.0F, (buffer >> 24 & 255) / 255.0F ); } public SurfaceBuilder color(int r, int g, int b, int a) { return color(r / 255.f, g / 255.f, b / 255.f, a / 255.f); } public SurfaceBuilder scale(double x, double y, double z) { glScaled(Math.max(x, 0), Math.max(y, 0), Math.max(z, 0)); return this; } public SurfaceBuilder scale(double s) { return scale(s, s, s); } public SurfaceBuilder scale() { return scale(0.D); } public SurfaceBuilder translate(double x, double y, double z) { GlStateManager.translate(x, y, z); return this; } public SurfaceBuilder rotate(double angle, double x, double y, double z) { glRotated(angle, x, y, z); return this; } public SurfaceBuilder width(double width) { GlStateManager.glLineWidth((float) width); return this; } public SurfaceBuilder vertex(double x, double y, double z) { glVertex3d(x, y, z); return this; } public SurfaceBuilder vertex(double x, double y) { return vertex(x, y, 0.D); } public SurfaceBuilder line(double startX, double startY, double endX, double endY) { return vertex(startX, startY) .vertex(endX, endY); } public SurfaceBuilder rectangle(double x, double y, double w, double h) { return vertex(x, y) .vertex(x, y + h) .vertex(x + w, y + h) .vertex(x + w, y); } private SurfaceBuilder text(MinecraftFontRenderer renderer, String text, double x, double y, boolean shadow) { renderer.drawString(text, x, y, Utils.toRGBA(color4f), shadow); return this; } private SurfaceBuilder text(MinecraftFontRenderer renderer, String text, double x, double y) { return text(renderer, text, x, y, false); } private SurfaceBuilder textWithShadow(MinecraftFontRenderer renderer, String text, double x, double y) { return text(renderer, text, x, y, true); } public SurfaceBuilder task(Runnable task) { task.run(); return this; } // -------------------- public static void preRenderSetup() { GlStateManager.enableBlend(); GlStateManager.disableTexture2D(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); } public static void postRenderSetup() { GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); } }
clear color on pop()
src/main/java/com/matt/forgehax/util/draw/SurfaceBuilder.java
clear color on pop()
<ide><path>rc/main/java/com/matt/forgehax/util/draw/SurfaceBuilder.java <ide> import com.matt.forgehax.util.Utils; <ide> import net.minecraft.client.renderer.GlStateManager; <ide> import uk.co.hexeption.thx.ttf.MinecraftFontRenderer; <add> <add>import java.util.Arrays; <ide> <ide> import static org.lwjgl.opengl.GL11.*; <ide> <ide> <ide> // -------------------- <ide> <del> private final float[] color4f = EMPTY_COLOR; <add> private final float[] color4f = Arrays.copyOf(EMPTY_COLOR, EMPTY_COLOR.length); <ide> <ide> public SurfaceBuilder begin(int mode) { <ide> glBegin(mode); <ide> } <ide> <ide> public SurfaceBuilder pop() { <add> System.arraycopy(EMPTY_COLOR, 0, color4f, 0, color4f.length); <ide> GlStateManager.popMatrix(); <ide> return this; <ide> }
Java
apache-2.0
73026584771d0817f430e647ac88cd681fcb1667
0
caskdata/cdap,hsaputra/cdap,caskdata/cdap,mpouttuclarke/cdap,chtyim/cdap,hsaputra/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,anthcp/cdap,chtyim/cdap,caskdata/cdap,hsaputra/cdap,anthcp/cdap,chtyim/cdap,mpouttuclarke/cdap,anthcp/cdap,hsaputra/cdap,caskdata/cdap,hsaputra/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,caskdata/cdap,anthcp/cdap,caskdata/cdap,chtyim/cdap,anthcp/cdap
/** * Copyright (C) 2012 Continuuity, Inc. */ package com.continuuity.data.operation.executor.omid; import com.continuuity.api.data.*; import com.continuuity.common.metrics.CMetrics; import com.continuuity.common.metrics.MetricType; import com.continuuity.common.utils.ImmutablePair; import com.continuuity.data.metadata.SerializingMetaDataStore; import com.continuuity.data.operation.*; import com.continuuity.data.operation.StatusCode; import com.continuuity.data.operation.executor.TransactionalOperationExecutor; import com.continuuity.data.operation.executor.omid.QueueInvalidate.QueueFinalize; import com.continuuity.data.operation.executor.omid.QueueInvalidate.QueueUnack; import com.continuuity.data.operation.executor.omid.QueueInvalidate.QueueUnenqueue; import com.continuuity.data.operation.executor.omid.memory.MemoryRowSet; import com.continuuity.data.operation.ttqueue.*; import com.continuuity.data.operation.ttqueue.QueueAdmin.GetGroupID; import com.continuuity.data.operation.ttqueue.QueueAdmin.GetQueueMeta; import com.continuuity.data.operation.ttqueue.QueueAdmin.QueueMeta; import com.continuuity.data.table.OVCTableHandle; import com.continuuity.data.table.OrderedVersionedColumnarTable; import com.continuuity.data.table.ReadPointer; import com.continuuity.data.util.TupleMetaDataAnnotator.DequeuePayload; import com.continuuity.data.util.TupleMetaDataAnnotator.EnqueuePayload; import com.google.common.base.Objects; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.Singleton; import org.apache.hadoop.hbase.util.Bytes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; /** * Implementation of an {@link com.continuuity.data.operation.executor.OperationExecutor} * that executes all operations within Omid-style transactions. * * See https://github.com/yahoo/omid/ for more information on the Omid design. */ @Singleton public class OmidTransactionalOperationExecutor implements TransactionalOperationExecutor { private static final Logger Log = LoggerFactory.getLogger(OmidTransactionalOperationExecutor.class); public String getName() { return "omid(" + tableHandle.getName() + ")"; } /** * The Transaction Oracle used by this executor instance. */ @Inject TransactionOracle oracle; /** * The {@link OVCTableHandle} handle used to get references to tables. */ @Inject OVCTableHandle tableHandle; private OrderedVersionedColumnarTable metaTable; private OrderedVersionedColumnarTable randomTable; private MetaDataStore metaStore; private TTQueueTable queueTable; private TTQueueTable streamTable; public static boolean DISABLE_QUEUE_PAYLOADS = false; static int MAX_DEQUEUE_RETRIES = 200; static long DEQUEUE_RETRY_SLEEP = 5; // Metrics /* ------------------- data fabric system metrics ---------------- */ private CMetrics cmetric = new CMetrics(MetricType.System); private static final String METRIC_PREFIX = "omid-opex-"; private void requestMetric(String requestType) { // TODO rework metric emission to avoid always generating the metric names cmetric.meter(METRIC_PREFIX + requestType + "-numops", 1); } private long begin() { return System.currentTimeMillis(); } private void end(String requestType, long beginning) { cmetric.histogram(METRIC_PREFIX + requestType + "-latency", System.currentTimeMillis() - beginning); } /* ------------------- (interstitial) queue metrics ---------------- */ private ConcurrentMap<String, CMetrics> queueMetrics = new ConcurrentHashMap<String, CMetrics>(); private CMetrics getQueueMetric(String group) { CMetrics metric = queueMetrics.get(group); if (metric == null) { queueMetrics.putIfAbsent(group, new CMetrics(MetricType.FlowSystem, group)); metric = queueMetrics.get(group); Log.debug("Created new CMetrics for group '" + group + "'."); } return metric; } private ConcurrentMap<byte[], ImmutablePair<String, String>> queueMetricNames = new ConcurrentSkipListMap<byte[], ImmutablePair<String, String>>(Bytes.BYTES_COMPARATOR); private ImmutablePair<String, String> getQueueMetricNames(byte[] queue) { ImmutablePair<String, String> names = queueMetricNames.get(queue); if (names == null) { String name = new String(queue).replace(":", ""); queueMetricNames.putIfAbsent(queue, new ImmutablePair<String, String> ("q.enqueue." + name, "q.ack." + name)); names = queueMetricNames.get(queue); Log.debug("using metric name '" + names.getFirst() + "' and '" + names.getSecond() + "' for queue '" + new String(queue) + "'"); } return names; } private void enqueueMetric(byte[] queue, QueueProducer producer) { if (producer != null && producer.getProducerName() != null) { String metricName = getQueueMetricNames(queue).getFirst(); getQueueMetric(producer.getProducerName()).meter(metricName, 1); } } private void ackMetric(byte[] queue, QueueConsumer consumer) { if (consumer != null && consumer.getGroupName() != null) { String metricName = getQueueMetricNames(queue).getSecond(); getQueueMetric(consumer.getGroupName()).meter(metricName, 1); } } /* ------------------- (global) stream metrics ---------------- */ private CMetrics streamMetric = // we use a global flow group new CMetrics(MetricType.FlowSystem, "-.-.-.-.-.0"); private ConcurrentMap<byte[], ImmutablePair<String, String>> streamMetricNames = new ConcurrentSkipListMap<byte[], ImmutablePair<String, String>>(Bytes.BYTES_COMPARATOR); private ImmutablePair<String, String> getStreamMetricNames(byte[] stream) { ImmutablePair<String, String> names = streamMetricNames.get(stream); if (names == null) { String name = new String(stream).replace(":", ""); streamMetricNames.putIfAbsent(stream, new ImmutablePair<String, String>( "stream.enqueue." + name, "stream.storage." + name)); names = streamMetricNames.get(stream); Log.debug("using metric name '" + names.getFirst() + "' and '" + names.getSecond() + "' for stream '" + new String(stream) + "'"); } return names; } private boolean isStream(byte[] queueName) { return Bytes.startsWith(queueName, TTQueue.STREAM_NAME_PREFIX); } private int streamSizeEstimate(byte[] streamName, byte[] data) { // assume HBase uses space for the stream name, the data, and some metadata return streamName.length + data.length + 50; } private void streamMetric(byte[] streamName, byte[] data) { ImmutablePair<String, String> names = getStreamMetricNames(streamName); streamMetric.meter(names.getFirst(), 1); streamMetric.meter(names.getSecond(), streamSizeEstimate(streamName, data)); } /* ------------------- end metrics ---------------- */ // named table management // a map of logical table name to existing <real name, table>, caches // the meta data store and the ovc table handle // there are three possible states for a table: // 1. table does not exist or is not known -> no entry // 2. table is being created -> entry with real name, but null for the table // 3. table is known -> entry with name and table ConcurrentMap<ImmutablePair<String,String>, ImmutablePair<byte[], OrderedVersionedColumnarTable>> namedTables; // method to find - and if necessary create - a table OrderedVersionedColumnarTable findRandomTable( OperationContext context, String name) throws OperationException { // check whether it is one of the default tables these are always // pre-loaded at initializaton and we can just return them if (null == name) return this.randomTable; if ("meta".equals(name)) return this.metaTable; // look up table in in-memory map. if this returns: // an actual name and OVCTable, return that OVCTable ImmutablePair<String, String> tableKey = new ImmutablePair<String, String>(context.getAccount(), name); ImmutablePair<byte[], OrderedVersionedColumnarTable> nameAndTable = this.namedTables.get(tableKey); if (nameAndTable != null) { if (nameAndTable.getSecond() != null) return nameAndTable.getSecond(); // an actual name and null for the table, then sleep/repeat until the look // up returns non-null for the table. This is the case when some other // thread in the same process has generated an actual name and is in the // process of creating that table. return waitForTableToMaterialize(tableKey); } // null: then this table has not been opened by any thread in this // process. In this case: // Read the meta data for the logical name from MDS. MetaDataEntry meta = this.metaStore.get( context, context.getAccount(), null, "namedTable", name); if (null != meta) { return waitForTableToMaterializeInMeta(context, name, meta); // Null: Nobody has started to create this. } else { // Generate a new actual name, and write that name with status Pending // to MDS in a Compare-and-Swap operation byte[] actualName = generateActualName(context, name); MetaDataEntry newMeta = new MetaDataEntry(context.getAccount(), null, "namedTable", name); newMeta.addField("actual", actualName); newMeta.addField("status", "pending"); try { this.metaStore.add(context, newMeta); } catch (OperationException e) { if (e.getStatus() == StatusCode.WRITE_CONFLICT) { // If C-a-S failed with write conflict, then some other process (or // thread) has concurrently attempted the same and wins. return waitForTableToMaterializeInMeta(context, name, meta); } else throw e; } //C-a-S succeeded, add <actual name, null> to MEM to inform other threads //in this process to wait (no other thread could have updated in the // mean-time without updating MDS) this.namedTables.put(tableKey, new ImmutablePair<byte[], OrderedVersionedColumnarTable>( actualName, null)); //Create a new actual table for the actual name. This should never fail. OrderedVersionedColumnarTable table = getTableHandle().getTable(actualName); // Update MDS with the new status Ready. This can be an ordinary Write newMeta.addField("status", "ready"); this.metaStore.update(context, newMeta); // because all others are waiting. // Update MEM with the actual created OVCTable. this.namedTables.put(tableKey, new ImmutablePair<byte[], OrderedVersionedColumnarTable>( actualName, table)); //Return the created table. return table; } } private byte[] generateActualName(OperationContext context, String name) { // TODO make this generate a new id every time it is called return ("random_" + context.getAccount() + "_" + name).getBytes(); } private OrderedVersionedColumnarTable waitForTableToMaterialize( ImmutablePair<String, String> tableKey) { while (true) { ImmutablePair<byte[], OrderedVersionedColumnarTable> nameAndTable = this.namedTables.get(tableKey); if (nameAndTable == null) { throw new InternalError("In-memory entry went from non-null to null " + "for named table \"" + tableKey.getSecond() + "\""); } if (nameAndTable.getSecond() != null) { return nameAndTable.getSecond(); } // sleep a little try { Thread.sleep(50); } catch (InterruptedException e) { // what the heck should I do? } } // TODO should this time out after some time or number of attempts? } OrderedVersionedColumnarTable waitForTableToMaterializeInMeta( OperationContext context, String name, MetaDataEntry meta) throws OperationException { while(true) { // If this returns: An actual name and status Ready: The table is ready // to use, open the table, add it to MEM and return it if ("ready".equals(meta.getTextField("status"))) { byte[] actualName = meta.getBinaryField("actual"); if (actualName == null) throw new InternalError("Encountered meta data entry of type " + "\"namedTable\" without actual name for table name \"" + name +"\"."); OrderedVersionedColumnarTable table = getTableHandle().getTable(actualName); if (table == null) throw new InternalError("table handle \"" + getTableHandle() .getName() + "\": getTable returned null for actual table name " + "\"" + new String(actualName) + "\""); // update MEM. This can be ordinary put, because even if some other // thread updated it in the meantime, it would have put the same table. ImmutablePair<String, String> tableKey = new ImmutablePair<String, String>(context.getAccount(), name); this.namedTables.put(tableKey, new ImmutablePair<byte[], OrderedVersionedColumnarTable>( actualName, table)); return table; } // An actual name and status Pending: The table is being created. Loop // and repeat MDS read until status is Ready and see previous case else if (!"pending".equals(meta.getTextField("status"))) { throw new InternalError("Found meta data entry with unkown status " + Objects.toStringHelper(meta.getTextField("status"))); } // sleep a little try { Thread.sleep(50); } catch (InterruptedException e) { // what the heck should I do? } // reread the meta data, hopefully it has changed to ready meta = this.metaStore.get( context, context.getAccount(), null, "namedTable", name); if (meta == null) throw new InternalError("Meta data entry went from non-null to null " + "for table \"" + name + "\""); // TODO should this time out after some time or number of attempts? } } // Single reads @Override public OperationResult<byte[]> execute(OperationContext context, ReadKey read) throws OperationException { initialize(); requestMetric("ReadKey"); long begin = begin(); OperationResult<byte[]> result = read(context, read, this.oracle.getReadPointer()); end("ReadKey", begin); return result; } OperationResult<byte[]> read(OperationContext context, ReadKey read, ReadPointer pointer) throws OperationException { OrderedVersionedColumnarTable table = this.findRandomTable(context, read.getTable()); return table.get(read.getKey(), Operation.KV_COL, pointer); } @Override public OperationResult<List<byte[]>> execute(OperationContext context, ReadAllKeys readKeys) throws OperationException { initialize(); requestMetric("ReadAllKeys"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, readKeys.getTable()); List<byte[]> result = table.getKeys(readKeys.getLimit(), readKeys.getOffset(), this.oracle.getReadPointer()); end("ReadKey", begin); return new OperationResult<List<byte[]>>(result); } @Override public OperationResult<Map<byte[], byte[]>> execute(OperationContext context, Read read) throws OperationException { initialize(); requestMetric("Read"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, read.getTable()); OperationResult<Map<byte[], byte[]>> result = table.get( read.getKey(), read.getColumns(), this.oracle.getReadPointer()); end("Read", begin); return result; } @Override public OperationResult<Map<byte[], byte[]>> execute(OperationContext context, ReadColumnRange readColumnRange) throws OperationException { initialize(); requestMetric("ReadColumnRange"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, readColumnRange.getTable()); OperationResult<Map<byte[], byte[]>> result = table.get( readColumnRange.getKey(), readColumnRange.getStartColumn(), readColumnRange.getStopColumn(), readColumnRange.getLimit(), this.oracle.getReadPointer()); end("ReadColumnRange", begin); return result; } // Administrative calls @Override public void execute(OperationContext context, ClearFabric clearFabric) throws OperationException { initialize(); requestMetric("ClearFabric"); long begin = begin(); if (clearFabric.shouldClearData()) this.randomTable.clear(); if (clearFabric.shouldClearTables()) { List<MetaDataEntry> entries = this.metaStore.list( context, context.getAccount(), null, "namedTable", null); for (MetaDataEntry entry : entries) { String name = entry.getId(); OrderedVersionedColumnarTable table = findRandomTable(context, name); table.clear(); this.namedTables.remove(new ImmutablePair<String, String>(context.getAccount(),name)); this.metaStore.delete(context, entry.getAccount(), entry.getApplication(), entry.getType(), entry.getId()); } } if (clearFabric.shouldClearMeta()) this.metaTable.clear(); if (clearFabric.shouldClearQueues()) this.queueTable.clear(); if (clearFabric.shouldClearStreams()) this.streamTable.clear(); end("ClearFabric", begin); } @Override public void execute(OperationContext context, OpenTable openTable) throws OperationException { initialize(); findRandomTable(context, openTable.getTableName()); } // Write batches @Override public void execute(OperationContext context, List<WriteOperation> writes) throws OperationException { initialize(); requestMetric("WriteOperationBatch"); long begin = begin(); cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_NumReqs", writes.size()); execute(context, writes, startTransaction()); end("WriteOperationBatch", begin); } private void executeAsBatch(OperationContext context, WriteOperation write) throws OperationException { execute(context, Collections.singletonList(write)); } void execute(OperationContext context, List<WriteOperation> writes, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { if (writes.isEmpty()) return; // Re-order operations (create a copy for now) List<WriteOperation> orderedWrites = new ArrayList<WriteOperation>(writes); Collections.sort(orderedWrites, new WriteOperationComparator()); // Execute operations RowSet rows = new MemoryRowSet(); List<Delete> deletes = new ArrayList<Delete>(writes.size()); List<QueueInvalidate> invalidates = new ArrayList<QueueInvalidate>(); // Track a map from increment operation ids to post-increment values Map<Long,Long> incrementResults = new TreeMap<Long,Long>(); for (WriteOperation write : orderedWrites) { // See if write operation is an enqueue, and if so, update serialized data if (write instanceof QueueEnqueue) { processEnqueue((QueueEnqueue)write, incrementResults); } WriteTransactionResult writeTxReturn = dispatchWrite(context, write, pointer); if (!writeTxReturn.success) { // Write operation failed cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_FailedWrites", 1); abortTransaction(context, pointer, deletes, invalidates); throw new OmidTransactionException( writeTxReturn.statusCode, writeTxReturn.message); } else { // Write was successful. Store delete if we need to abort and continue deletes.addAll(writeTxReturn.deletes); if (writeTxReturn.invalidate != null) { // Queue operation invalidates.add(writeTxReturn.invalidate); } else { // Normal write operation rows.addRow(write.getKey()); } // See if write operation was an Increment, and if so, add result to map if (write instanceof Increment) { incrementResults.put(write.getId(), writeTxReturn.incrementValue); } } } // All operations completed successfully, commit transaction if (!commitTransaction(pointer, rows)) { // Commit failed, abort cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_FailedCommits", 1); abortTransaction(context, pointer, deletes, invalidates); throw new OmidTransactionException(StatusCode.WRITE_CONFLICT, "Commit of transaction failed, transaction aborted"); } // If last operation was an ack, finalize it if (orderedWrites.get(orderedWrites.size() - 1) instanceof QueueAck) { QueueAck ack = (QueueAck)orderedWrites.get(orderedWrites.size() - 1); QueueFinalize finalize = new QueueFinalize(ack.getKey(), ack.getEntryPointer(), ack.getConsumer(), ack.getNumGroups()); finalize.execute(getQueueTable(ack.getKey()), pointer); } // Transaction was successfully committed, emit metrics // - for the transaction cmetric.meter( METRIC_PREFIX + "WriteOperationBatch_SuccessfulTransactions", 1); // for each queue operation (enqueue or ack) for (QueueInvalidate invalidate : invalidates) if (invalidate instanceof QueueUnenqueue) { QueueUnenqueue unenqueue = (QueueUnenqueue)invalidate; QueueProducer producer = unenqueue.producer; enqueueMetric(unenqueue.queueName, producer); if (isStream(unenqueue.queueName)) streamMetric(unenqueue.queueName, unenqueue.data); } else if (invalidate instanceof QueueUnack) { QueueUnack unack = (QueueUnack)invalidate; QueueConsumer consumer = unack.consumer; ackMetric(unack.queueName, consumer); } } /** * Deserializes enqueue data into enqueue payload, checks if any fields are * marked to contain increment values, construct a dequeue payload, update any * fields necessary, and finally update the enqueue data to contain a dequeue * payload. */ private void processEnqueue(QueueEnqueue enqueue, Map<Long, Long> incrementResults) throws OperationException { if (DISABLE_QUEUE_PAYLOADS) return; // Deserialize enqueue payload byte [] enqueuePayloadBytes = enqueue.getData(); EnqueuePayload enqueuePayload; try { enqueuePayload = EnqueuePayload.read(enqueuePayloadBytes); } catch (IOException e) { // Unable to deserialize the enqueue payload, fatal error (if queues are // not using payloads, change DISABLE_QUEUE_PAYLOADS=true e.printStackTrace(); throw new RuntimeException(e); } Map<String,Long> fieldsToIds = enqueuePayload.getOperationIds(); Map<String,Long> fieldsToValues = new TreeMap<String,Long>(); // For every field-to-id mapping, find increment result for (Map.Entry<String,Long> fieldAndId : fieldsToIds.entrySet()) { String field = fieldAndId.getKey(); Long operationId = fieldAndId.getValue(); Long incrementValue = incrementResults.get(operationId); if (incrementValue == null) { throw new OperationException(StatusCode.INTERNAL_ERROR, "Field specified as containing an increment result but no " + "matching increment operation found"); } // Store field-to-value in map for dequeue payload fieldsToValues.put(field, incrementValue); } // Serialize dequeue payload and overwrite enqueue data try { enqueue.setData(DequeuePayload.write(fieldsToValues, enqueuePayload.getSerializedTuple())); } catch (IOException e) { // Fatal error serializing dequeue payload e.printStackTrace(); throw new RuntimeException(e); } } public OVCTableHandle getTableHandle() { return this.tableHandle; } static final List<Delete> noDeletes = Collections.emptyList(); private class WriteTransactionResult { final boolean success; final int statusCode; final String message; final List<Delete> deletes; final QueueInvalidate invalidate; Long incrementValue; WriteTransactionResult(boolean success, int status, String message, List<Delete> deletes, QueueInvalidate invalidate) { this.success = success; this.statusCode = status; this.message = message; this.deletes = deletes; this.invalidate = invalidate; } // successful, one delete to undo WriteTransactionResult(Delete delete) { this(true, StatusCode.OK, null, Collections.singletonList(delete), null); } // successful increment, one delete to undo WriteTransactionResult(Delete delete, Long incrementValue) { this(true, StatusCode.OK, null, Collections.singletonList(delete), null); this.incrementValue = incrementValue; } // successful, one queue operation to invalidate WriteTransactionResult(QueueInvalidate invalidate) { this(true, StatusCode.OK, null, noDeletes, invalidate); } // failure with status code and message, nothing to undo WriteTransactionResult(int status, String message) { this(false, status, message, noDeletes, null); } } /** * Actually perform the various write operations. */ private WriteTransactionResult dispatchWrite( OperationContext context, WriteOperation write, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { if (write instanceof Write) { return write(context, (Write)write, pointer); } else if (write instanceof Delete) { return write(context, (Delete)write, pointer); } else if (write instanceof Increment) { return write(context, (Increment)write, pointer); } else if (write instanceof CompareAndSwap) { return write(context, (CompareAndSwap)write, pointer); } else if (write instanceof QueueEnqueue) { return write((QueueEnqueue)write, pointer); } else if (write instanceof QueueAck) { return write((QueueAck)write, pointer); } return new WriteTransactionResult(StatusCode.INTERNAL_ERROR, "Unknown write operation " + write.getClass().getName()); } WriteTransactionResult write(OperationContext context, Write write, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { initialize(); requestMetric("Write"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, write.getTable()); table.put(write.getKey(), write.getColumns(), pointer.getSecond(), write.getValues()); end("Write", begin); return new WriteTransactionResult( new Delete(write.getTable(), write.getKey(), write.getColumns())); } WriteTransactionResult write(OperationContext context, Delete delete, ImmutablePair<ReadPointer, Long> pointer) throws OperationException { initialize(); requestMetric("Delete"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, delete.getTable()); table.deleteAll(delete.getKey(), delete.getColumns(), pointer.getSecond()); end("Delete", begin); return new WriteTransactionResult( new Undelete(delete.getTable(), delete.getKey(), delete.getColumns())); } WriteTransactionResult write(OperationContext context, Increment increment, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { initialize(); requestMetric("Increment"); long begin = begin(); Long incrementValue; try { @SuppressWarnings("unused") OrderedVersionedColumnarTable table = this.findRandomTable(context, increment.getTable()); Map<byte[],Long> map = table.increment(increment.getKey(), increment.getColumns(), increment.getAmounts(), pointer.getFirst(), pointer.getSecond()); incrementValue = map.values().iterator().next(); } catch (OperationException e) { return new WriteTransactionResult(e.getStatus(), e.getMessage()); } end("Increment", begin); return new WriteTransactionResult( new Delete(increment.getTable(), increment.getKey(), increment.getColumns()), incrementValue); } WriteTransactionResult write(OperationContext context, CompareAndSwap write, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { initialize(); requestMetric("CompareAndSwap"); long begin = begin(); try { OrderedVersionedColumnarTable table = this.findRandomTable(context, write.getTable()); table.compareAndSwap(write.getKey(), write.getColumn(), write.getExpectedValue(), write.getNewValue(), pointer.getFirst(), pointer.getSecond()); } catch (OperationException e) { return new WriteTransactionResult(e.getStatus(), e.getMessage()); } end("CompareAndSwap", begin); return new WriteTransactionResult( new Delete(write.getTable(), write.getKey(), write.getColumn())); } // TTQueues /** * EnqueuePayload operations always succeed but can be rolled back. * * They are rolled back with an invalidate. */ WriteTransactionResult write(QueueEnqueue enqueue, ImmutablePair<ReadPointer, Long> pointer) throws OperationException { initialize(); requestMetric("QueueEnqueue"); long begin = begin(); EnqueueResult result = getQueueTable(enqueue.getKey()).enqueue( enqueue.getKey(), enqueue.getData(), pointer.getSecond()); end("QueueEnqueue", begin); return new WriteTransactionResult( new QueueUnenqueue(enqueue.getKey(), enqueue.getData(), enqueue.getProducer(), result.getEntryPointer())); } WriteTransactionResult write(QueueAck ack, @SuppressWarnings("unused") ImmutablePair<ReadPointer, Long> pointer) throws OperationException { initialize(); requestMetric("QueueAck"); long begin = begin(); try { getQueueTable(ack.getKey()).ack(ack.getKey(), ack.getEntryPointer(), ack.getConsumer()); } catch (OperationException e) { // Ack failed, roll back transaction return new WriteTransactionResult(StatusCode.ILLEGAL_ACK, "Attempt to ack a dequeue of a different consumer"); } finally { end("QueueAck", begin); } return new WriteTransactionResult( new QueueUnack(ack.getKey(), ack.getEntryPointer(), ack.getConsumer())); } @Override public DequeueResult execute(OperationContext context, QueueDequeue dequeue) throws OperationException { initialize(); requestMetric("QueueDequeue"); long begin = begin(); int retries = 0; long start = System.currentTimeMillis(); TTQueueTable queueTable = getQueueTable(dequeue.getKey()); while (retries < MAX_DEQUEUE_RETRIES) { DequeueResult result = queueTable.dequeue(dequeue.getKey(), dequeue.getConsumer(), dequeue.getConfig(), this.oracle.getReadPointer()); if (result.shouldRetry()) { retries++; try { if (DEQUEUE_RETRY_SLEEP > 0) Thread.sleep(DEQUEUE_RETRY_SLEEP); } catch (InterruptedException e) { e.printStackTrace(); // continue in loop } continue; } end("QueueDequeue", begin); return result; } long end = System.currentTimeMillis(); end("QueueDequeue", begin); throw new OperationException(StatusCode.TOO_MANY_RETRIES, "Maximum retries (retried " + retries + " times over " + (end-start) + " millis"); } @Override public long execute(OperationContext context, GetGroupID getGroupId) throws OperationException { initialize(); requestMetric("GetGroupID"); long begin = begin(); TTQueueTable table = getQueueTable(getGroupId.getQueueName()); long groupid = table.getGroupID(getGroupId.getQueueName()); end("GetGroupID", begin); return groupid; } @Override public OperationResult<QueueMeta> execute(OperationContext context, GetQueueMeta getQueueMeta) throws OperationException { initialize(); requestMetric("GetQueueMeta"); long begin = begin(); TTQueueTable table = getQueueTable(getQueueMeta.getQueueName()); QueueMeta queueMeta = table.getQueueMeta(getQueueMeta.getQueueName()); end("GetQueueMeta", begin); return new OperationResult<QueueMeta>(queueMeta); } ImmutablePair<ReadPointer, Long> startTransaction() { requestMetric("StartTransaction"); return this.oracle.getNewPointer(); } boolean commitTransaction(ImmutablePair<ReadPointer, Long> pointer, RowSet rows) throws OmidTransactionException { requestMetric("CommitTransaction"); return this.oracle.commit(pointer.getSecond(), rows); } private void abortTransaction(OperationContext context, ImmutablePair<ReadPointer, Long> pointer, List<Delete> deletes, List<QueueInvalidate> invalidates) throws OperationException { // Perform queue invalidates cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_AbortedTransactions", 1); for (QueueInvalidate invalidate : invalidates) { invalidate.execute(getQueueTable(invalidate.queueName), pointer); } // Perform deletes for (Delete delete : deletes) { assert(delete != null); OrderedVersionedColumnarTable table = this.findRandomTable(context, delete.getTable()); if (delete instanceof Undelete) { table.undeleteAll(delete.getKey(), delete.getColumns(), pointer.getSecond()); } else { table.delete(delete.getKey(), delete.getColumns(), pointer.getSecond()); } } // Notify oracle this.oracle.aborted(pointer.getSecond()); } // Single Write Operations (Wrapped and called in a transaction batch) @SuppressWarnings("unused") private void unsupported(String msg) { throw new RuntimeException(msg); } @Override public void execute(OperationContext context, Write write) throws OperationException { executeAsBatch(context, write); } @Override public void execute(OperationContext context, Delete delete) throws OperationException { executeAsBatch(context, delete); } @Override public void execute(OperationContext context, Increment inc) throws OperationException { executeAsBatch(context, inc); } @Override public void execute(OperationContext context, CompareAndSwap cas) throws OperationException { executeAsBatch(context, cas); } @Override public void execute(OperationContext context, QueueAck ack) throws OperationException { executeAsBatch(context, ack); } @Override public void execute(OperationContext context, QueueEnqueue enqueue) throws OperationException { executeAsBatch(context, enqueue); } private TTQueueTable getQueueTable(byte[] queueName) { if (Bytes.startsWith(queueName, TTQueue.QUEUE_NAME_PREFIX)) return this.queueTable; if (Bytes.startsWith(queueName, TTQueue.STREAM_NAME_PREFIX)) return this.streamTable; // by default, use queue table return this.queueTable; } /** * A utility method that ensures this class is properly initialized before * it can be used. This currently entails creating real objects for all * our table handlers. */ private synchronized void initialize() throws OperationException { if (this.randomTable == null) { this.metaTable = this.tableHandle.getTable(Bytes.toBytes("meta")); this.randomTable = this.tableHandle.getTable(Bytes.toBytes("random")); this.queueTable = this.tableHandle.getQueueTable(Bytes.toBytes("queues")); this.streamTable = this.tableHandle.getStreamTable(Bytes.toBytes("streams")); this.namedTables = Maps.newConcurrentMap(); this.metaStore = new SerializingMetaDataStore(this); } } } // end of OmitTransactionalOperationExecutor
src/main/java/com/continuuity/data/operation/executor/omid/OmidTransactionalOperationExecutor.java
/** * Copyright (C) 2012 Continuuity, Inc. */ package com.continuuity.data.operation.executor.omid; import com.continuuity.api.data.*; import com.continuuity.common.metrics.CMetrics; import com.continuuity.common.metrics.MetricType; import com.continuuity.common.utils.ImmutablePair; import com.continuuity.data.metadata.SerializingMetaDataStore; import com.continuuity.data.operation.*; import com.continuuity.data.operation.StatusCode; import com.continuuity.data.operation.executor.TransactionalOperationExecutor; import com.continuuity.data.operation.executor.omid.QueueInvalidate.QueueFinalize; import com.continuuity.data.operation.executor.omid.QueueInvalidate.QueueUnack; import com.continuuity.data.operation.executor.omid.QueueInvalidate.QueueUnenqueue; import com.continuuity.data.operation.executor.omid.memory.MemoryRowSet; import com.continuuity.data.operation.ttqueue.*; import com.continuuity.data.operation.ttqueue.QueueAdmin.GetGroupID; import com.continuuity.data.operation.ttqueue.QueueAdmin.GetQueueMeta; import com.continuuity.data.operation.ttqueue.QueueAdmin.QueueMeta; import com.continuuity.data.table.OVCTableHandle; import com.continuuity.data.table.OrderedVersionedColumnarTable; import com.continuuity.data.table.ReadPointer; import com.continuuity.data.util.TupleMetaDataAnnotator.DequeuePayload; import com.continuuity.data.util.TupleMetaDataAnnotator.EnqueuePayload; import com.esotericsoftware.minlog.Log; import com.google.common.base.Objects; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.Singleton; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; /** * Implementation of an {@link com.continuuity.data.operation.executor.OperationExecutor} * that executes all operations within Omid-style transactions. * * See https://github.com/yahoo/omid/ for more information on the Omid design. */ @Singleton public class OmidTransactionalOperationExecutor implements TransactionalOperationExecutor { public String getName() { return "omid(" + tableHandle.getName() + ")"; } /** * The Transaction Oracle used by this executor instance. */ @Inject TransactionOracle oracle; /** * The {@link OVCTableHandle} handle used to get references to tables. */ @Inject OVCTableHandle tableHandle; private OrderedVersionedColumnarTable metaTable; private OrderedVersionedColumnarTable randomTable; private MetaDataStore metaStore; private TTQueueTable queueTable; private TTQueueTable streamTable; public static boolean DISABLE_QUEUE_PAYLOADS = false; static int MAX_DEQUEUE_RETRIES = 200; static long DEQUEUE_RETRY_SLEEP = 5; // Metrics /* ------------------- data fabric system metrics ---------------- */ private CMetrics cmetric = new CMetrics(MetricType.System); private static final String METRIC_PREFIX = "omid-opex-"; private void requestMetric(String requestType) { // TODO rework metric emission to avoid always generating the metric names cmetric.meter(METRIC_PREFIX + requestType + "-numops", 1); } private long begin() { return System.currentTimeMillis(); } private void end(String requestType, long beginning) { cmetric.histogram(METRIC_PREFIX + requestType + "-latency", System.currentTimeMillis() - beginning); } /* ------------------- (interstitial) queue metrics ---------------- */ private ConcurrentMap<String, CMetrics> queueMetrics = new ConcurrentHashMap<String, CMetrics>(); private CMetrics getQueueMetric(String group) { CMetrics metric = queueMetrics.get(group); if (metric == null) { queueMetrics.putIfAbsent(group, new CMetrics(MetricType.FlowSystem, group)); metric = queueMetrics.get(group); Log.debug("Created new CMetrics for group '" + group + "'."); } return metric; } private ConcurrentMap<byte[], ImmutablePair<String, String>> queueMetricNames = new ConcurrentSkipListMap<byte[], ImmutablePair<String, String>>(Bytes.BYTES_COMPARATOR); private ImmutablePair<String, String> getQueueMetricNames(byte[] queue) { ImmutablePair<String, String> names = queueMetricNames.get(queue); if (names == null) { String name = new String(queue).replace(":", ""); queueMetricNames.putIfAbsent(queue, new ImmutablePair<String, String> ("q.enqueue." + name, "q.ack." + name)); names = queueMetricNames.get(queue); Log.debug("using metric name '" + names.getFirst() + "' and '" + names.getSecond() + "' for queue '" + new String(queue) + "'"); } return names; } private void enqueueMetric(byte[] queue, QueueProducer producer) { if (producer != null && producer.getProducerName() != null) { String metricName = getQueueMetricNames(queue).getFirst(); getQueueMetric(producer.getProducerName()).meter(metricName, 1); } } private void ackMetric(byte[] queue, QueueConsumer consumer) { if (consumer != null && consumer.getGroupName() != null) { String metricName = getQueueMetricNames(queue).getSecond(); getQueueMetric(consumer.getGroupName()).meter(metricName, 1); } } /* ------------------- (global) stream metrics ---------------- */ private CMetrics streamMetric = // we use a global flow group new CMetrics(MetricType.FlowSystem, "-.-.-.-.-.0"); private ConcurrentMap<byte[], ImmutablePair<String, String>> streamMetricNames = new ConcurrentSkipListMap<byte[], ImmutablePair<String, String>>(Bytes.BYTES_COMPARATOR); private ImmutablePair<String, String> getStreamMetricNames(byte[] stream) { ImmutablePair<String, String> names = streamMetricNames.get(stream); if (names == null) { String name = new String(stream).replace(":", ""); streamMetricNames.putIfAbsent(stream, new ImmutablePair<String, String>( "stream.enqueue." + name, "stream.storage." + name)); names = streamMetricNames.get(stream); Log.debug("using metric name '" + names.getFirst() + "' and '" + names.getSecond() + "' for stream '" + new String(stream) + "'"); } return names; } private boolean isStream(byte[] queueName) { return Bytes.startsWith(queueName, TTQueue.STREAM_NAME_PREFIX); } private int streamSizeEstimate(byte[] streamName, byte[] data) { // assume HBase uses space for the stream name, the data, and some metadata return streamName.length + data.length + 50; } private void streamMetric(byte[] streamName, byte[] data) { ImmutablePair<String, String> names = getStreamMetricNames(streamName); streamMetric.meter(names.getFirst(), 1); streamMetric.meter(names.getSecond(), streamSizeEstimate(streamName, data)); } /* ------------------- end metrics ---------------- */ // named table management // a map of logical table name to existing <real name, table>, caches // the meta data store and the ovc table handle // there are three possible states for a table: // 1. table does not exist or is not known -> no entry // 2. table is being created -> entry with real name, but null for the table // 3. table is known -> entry with name and table ConcurrentMap<ImmutablePair<String,String>, ImmutablePair<byte[], OrderedVersionedColumnarTable>> namedTables; // method to find - and if necessary create - a table OrderedVersionedColumnarTable findRandomTable( OperationContext context, String name) throws OperationException { // check whether it is one of the default tables these are always // pre-loaded at initializaton and we can just return them if (null == name) return this.randomTable; if ("meta".equals(name)) return this.metaTable; // look up table in in-memory map. if this returns: // an actual name and OVCTable, return that OVCTable ImmutablePair<String, String> tableKey = new ImmutablePair<String, String>(context.getAccount(), name); ImmutablePair<byte[], OrderedVersionedColumnarTable> nameAndTable = this.namedTables.get(tableKey); if (nameAndTable != null) { if (nameAndTable.getSecond() != null) return nameAndTable.getSecond(); // an actual name and null for the table, then sleep/repeat until the look // up returns non-null for the table. This is the case when some other // thread in the same process has generated an actual name and is in the // process of creating that table. return waitForTableToMaterialize(tableKey); } // null: then this table has not been opened by any thread in this // process. In this case: // Read the meta data for the logical name from MDS. MetaDataEntry meta = this.metaStore.get( context, context.getAccount(), null, "namedTable", name); if (null != meta) { return waitForTableToMaterializeInMeta(context, name, meta); // Null: Nobody has started to create this. } else { // Generate a new actual name, and write that name with status Pending // to MDS in a Compare-and-Swap operation byte[] actualName = generateActualName(context, name); MetaDataEntry newMeta = new MetaDataEntry(context.getAccount(), null, "namedTable", name); newMeta.addField("actual", actualName); newMeta.addField("status", "pending"); try { this.metaStore.add(context, newMeta); } catch (OperationException e) { if (e.getStatus() == StatusCode.WRITE_CONFLICT) { // If C-a-S failed with write conflict, then some other process (or // thread) has concurrently attempted the same and wins. return waitForTableToMaterializeInMeta(context, name, meta); } else throw e; } //C-a-S succeeded, add <actual name, null> to MEM to inform other threads //in this process to wait (no other thread could have updated in the // mean-time without updating MDS) this.namedTables.put(tableKey, new ImmutablePair<byte[], OrderedVersionedColumnarTable>( actualName, null)); //Create a new actual table for the actual name. This should never fail. OrderedVersionedColumnarTable table = getTableHandle().getTable(actualName); // Update MDS with the new status Ready. This can be an ordinary Write newMeta.addField("status", "ready"); this.metaStore.update(context, newMeta); // because all others are waiting. // Update MEM with the actual created OVCTable. this.namedTables.put(tableKey, new ImmutablePair<byte[], OrderedVersionedColumnarTable>( actualName, table)); //Return the created table. return table; } } private byte[] generateActualName(OperationContext context, String name) { // TODO make this generate a new id every time it is called return ("random_" + context.getAccount() + "_" + name).getBytes(); } private OrderedVersionedColumnarTable waitForTableToMaterialize( ImmutablePair<String, String> tableKey) { while (true) { ImmutablePair<byte[], OrderedVersionedColumnarTable> nameAndTable = this.namedTables.get(tableKey); if (nameAndTable == null) { throw new InternalError("In-memory entry went from non-null to null " + "for named table \"" + tableKey.getSecond() + "\""); } if (nameAndTable.getSecond() != null) { return nameAndTable.getSecond(); } // sleep a little try { Thread.sleep(50); } catch (InterruptedException e) { // what the heck should I do? } } // TODO should this time out after some time or number of attempts? } OrderedVersionedColumnarTable waitForTableToMaterializeInMeta( OperationContext context, String name, MetaDataEntry meta) throws OperationException { while(true) { // If this returns: An actual name and status Ready: The table is ready // to use, open the table, add it to MEM and return it if ("ready".equals(meta.getTextField("status"))) { byte[] actualName = meta.getBinaryField("actual"); if (actualName == null) throw new InternalError("Encountered meta data entry of type " + "\"namedTable\" without actual name for table name \"" + name +"\"."); OrderedVersionedColumnarTable table = getTableHandle().getTable(actualName); if (table == null) throw new InternalError("table handle \"" + getTableHandle() .getName() + "\": getTable returned null for actual table name " + "\"" + new String(actualName) + "\""); // update MEM. This can be ordinary put, because even if some other // thread updated it in the meantime, it would have put the same table. ImmutablePair<String, String> tableKey = new ImmutablePair<String, String>(context.getAccount(), name); this.namedTables.put(tableKey, new ImmutablePair<byte[], OrderedVersionedColumnarTable>( actualName, table)); return table; } // An actual name and status Pending: The table is being created. Loop // and repeat MDS read until status is Ready and see previous case else if (!"pending".equals(meta.getTextField("status"))) { throw new InternalError("Found meta data entry with unkown status " + Objects.toStringHelper(meta.getTextField("status"))); } // sleep a little try { Thread.sleep(50); } catch (InterruptedException e) { // what the heck should I do? } // reread the meta data, hopefully it has changed to ready meta = this.metaStore.get( context, context.getAccount(), null, "namedTable", name); if (meta == null) throw new InternalError("Meta data entry went from non-null to null " + "for table \"" + name + "\""); // TODO should this time out after some time or number of attempts? } } // Single reads @Override public OperationResult<byte[]> execute(OperationContext context, ReadKey read) throws OperationException { initialize(); requestMetric("ReadKey"); long begin = begin(); OperationResult<byte[]> result = read(context, read, this.oracle.getReadPointer()); end("ReadKey", begin); return result; } OperationResult<byte[]> read(OperationContext context, ReadKey read, ReadPointer pointer) throws OperationException { OrderedVersionedColumnarTable table = this.findRandomTable(context, read.getTable()); return table.get(read.getKey(), Operation.KV_COL, pointer); } @Override public OperationResult<List<byte[]>> execute(OperationContext context, ReadAllKeys readKeys) throws OperationException { initialize(); requestMetric("ReadAllKeys"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, readKeys.getTable()); List<byte[]> result = table.getKeys(readKeys.getLimit(), readKeys.getOffset(), this.oracle.getReadPointer()); end("ReadKey", begin); return new OperationResult<List<byte[]>>(result); } @Override public OperationResult<Map<byte[], byte[]>> execute(OperationContext context, Read read) throws OperationException { initialize(); requestMetric("Read"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, read.getTable()); OperationResult<Map<byte[], byte[]>> result = table.get( read.getKey(), read.getColumns(), this.oracle.getReadPointer()); end("Read", begin); return result; } @Override public OperationResult<Map<byte[], byte[]>> execute(OperationContext context, ReadColumnRange readColumnRange) throws OperationException { initialize(); requestMetric("ReadColumnRange"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, readColumnRange.getTable()); OperationResult<Map<byte[], byte[]>> result = table.get( readColumnRange.getKey(), readColumnRange.getStartColumn(), readColumnRange.getStopColumn(), readColumnRange.getLimit(), this.oracle.getReadPointer()); end("ReadColumnRange", begin); return result; } // Administrative calls @Override public void execute(OperationContext context, ClearFabric clearFabric) throws OperationException { initialize(); requestMetric("ClearFabric"); long begin = begin(); if (clearFabric.shouldClearData()) this.randomTable.clear(); if (clearFabric.shouldClearTables()) { List<MetaDataEntry> entries = this.metaStore.list( context, context.getAccount(), null, "namedTable", null); for (MetaDataEntry entry : entries) { String name = entry.getId(); OrderedVersionedColumnarTable table = findRandomTable(context, name); table.clear(); this.namedTables.remove(new ImmutablePair<String, String>(context.getAccount(),name)); this.metaStore.delete(context, entry.getAccount(), entry.getApplication(), entry.getType(), entry.getId()); } } if (clearFabric.shouldClearMeta()) this.metaTable.clear(); if (clearFabric.shouldClearQueues()) this.queueTable.clear(); if (clearFabric.shouldClearStreams()) this.streamTable.clear(); end("ClearFabric", begin); } @Override public void execute(OperationContext context, OpenTable openTable) throws OperationException { initialize(); findRandomTable(context, openTable.getTableName()); } // Write batches @Override public void execute(OperationContext context, List<WriteOperation> writes) throws OperationException { initialize(); requestMetric("WriteOperationBatch"); long begin = begin(); cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_NumReqs", writes.size()); execute(context, writes, startTransaction()); end("WriteOperationBatch", begin); } private void executeAsBatch(OperationContext context, WriteOperation write) throws OperationException { execute(context, Collections.singletonList(write)); } void execute(OperationContext context, List<WriteOperation> writes, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { if (writes.isEmpty()) return; // Re-order operations (create a copy for now) List<WriteOperation> orderedWrites = new ArrayList<WriteOperation>(writes); Collections.sort(orderedWrites, new WriteOperationComparator()); // Execute operations RowSet rows = new MemoryRowSet(); List<Delete> deletes = new ArrayList<Delete>(writes.size()); List<QueueInvalidate> invalidates = new ArrayList<QueueInvalidate>(); // Track a map from increment operation ids to post-increment values Map<Long,Long> incrementResults = new TreeMap<Long,Long>(); for (WriteOperation write : orderedWrites) { // See if write operation is an enqueue, and if so, update serialized data if (write instanceof QueueEnqueue) { processEnqueue((QueueEnqueue)write, incrementResults); } WriteTransactionResult writeTxReturn = dispatchWrite(context, write, pointer); if (!writeTxReturn.success) { // Write operation failed cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_FailedWrites", 1); abortTransaction(context, pointer, deletes, invalidates); throw new OmidTransactionException( writeTxReturn.statusCode, writeTxReturn.message); } else { // Write was successful. Store delete if we need to abort and continue deletes.addAll(writeTxReturn.deletes); if (writeTxReturn.invalidate != null) { // Queue operation invalidates.add(writeTxReturn.invalidate); } else { // Normal write operation rows.addRow(write.getKey()); } // See if write operation was an Increment, and if so, add result to map if (write instanceof Increment) { incrementResults.put(write.getId(), writeTxReturn.incrementValue); } } } // All operations completed successfully, commit transaction if (!commitTransaction(pointer, rows)) { // Commit failed, abort cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_FailedCommits", 1); abortTransaction(context, pointer, deletes, invalidates); throw new OmidTransactionException(StatusCode.WRITE_CONFLICT, "Commit of transaction failed, transaction aborted"); } // If last operation was an ack, finalize it if (orderedWrites.get(orderedWrites.size() - 1) instanceof QueueAck) { QueueAck ack = (QueueAck)orderedWrites.get(orderedWrites.size() - 1); QueueFinalize finalize = new QueueFinalize(ack.getKey(), ack.getEntryPointer(), ack.getConsumer(), ack.getNumGroups()); finalize.execute(getQueueTable(ack.getKey()), pointer); } // Transaction was successfully committed, emit metrics // - for the transaction cmetric.meter( METRIC_PREFIX + "WriteOperationBatch_SuccessfulTransactions", 1); // for each queue operation (enqueue or ack) for (QueueInvalidate invalidate : invalidates) if (invalidate instanceof QueueUnenqueue) { QueueUnenqueue unenqueue = (QueueUnenqueue)invalidate; QueueProducer producer = unenqueue.producer; enqueueMetric(unenqueue.queueName, producer); if (isStream(unenqueue.queueName)) streamMetric(unenqueue.queueName, unenqueue.data); } else if (invalidate instanceof QueueUnack) { QueueUnack unack = (QueueUnack)invalidate; QueueConsumer consumer = unack.consumer; ackMetric(unack.queueName, consumer); } } /** * Deserializes enqueue data into enqueue payload, checks if any fields are * marked to contain increment values, construct a dequeue payload, update any * fields necessary, and finally update the enqueue data to contain a dequeue * payload. */ private void processEnqueue(QueueEnqueue enqueue, Map<Long, Long> incrementResults) throws OperationException { if (DISABLE_QUEUE_PAYLOADS) return; // Deserialize enqueue payload byte [] enqueuePayloadBytes = enqueue.getData(); EnqueuePayload enqueuePayload; try { enqueuePayload = EnqueuePayload.read(enqueuePayloadBytes); } catch (IOException e) { // Unable to deserialize the enqueue payload, fatal error (if queues are // not using payloads, change DISABLE_QUEUE_PAYLOADS=true e.printStackTrace(); throw new RuntimeException(e); } Map<String,Long> fieldsToIds = enqueuePayload.getOperationIds(); Map<String,Long> fieldsToValues = new TreeMap<String,Long>(); // For every field-to-id mapping, find increment result for (Map.Entry<String,Long> fieldAndId : fieldsToIds.entrySet()) { String field = fieldAndId.getKey(); Long operationId = fieldAndId.getValue(); Long incrementValue = incrementResults.get(operationId); if (incrementValue == null) { throw new OperationException(StatusCode.INTERNAL_ERROR, "Field specified as containing an increment result but no " + "matching increment operation found"); } // Store field-to-value in map for dequeue payload fieldsToValues.put(field, incrementValue); } // Serialize dequeue payload and overwrite enqueue data try { enqueue.setData(DequeuePayload.write(fieldsToValues, enqueuePayload.getSerializedTuple())); } catch (IOException e) { // Fatal error serializing dequeue payload e.printStackTrace(); throw new RuntimeException(e); } } public OVCTableHandle getTableHandle() { return this.tableHandle; } static final List<Delete> noDeletes = Collections.emptyList(); private class WriteTransactionResult { final boolean success; final int statusCode; final String message; final List<Delete> deletes; final QueueInvalidate invalidate; Long incrementValue; WriteTransactionResult(boolean success, int status, String message, List<Delete> deletes, QueueInvalidate invalidate) { this.success = success; this.statusCode = status; this.message = message; this.deletes = deletes; this.invalidate = invalidate; } // successful, one delete to undo WriteTransactionResult(Delete delete) { this(true, StatusCode.OK, null, Collections.singletonList(delete), null); } // successful increment, one delete to undo WriteTransactionResult(Delete delete, Long incrementValue) { this(true, StatusCode.OK, null, Collections.singletonList(delete), null); this.incrementValue = incrementValue; } // successful, one queue operation to invalidate WriteTransactionResult(QueueInvalidate invalidate) { this(true, StatusCode.OK, null, noDeletes, invalidate); } // failure with status code and message, nothing to undo WriteTransactionResult(int status, String message) { this(false, status, message, noDeletes, null); } } /** * Actually perform the various write operations. */ private WriteTransactionResult dispatchWrite( OperationContext context, WriteOperation write, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { if (write instanceof Write) { return write(context, (Write)write, pointer); } else if (write instanceof Delete) { return write(context, (Delete)write, pointer); } else if (write instanceof Increment) { return write(context, (Increment)write, pointer); } else if (write instanceof CompareAndSwap) { return write(context, (CompareAndSwap)write, pointer); } else if (write instanceof QueueEnqueue) { return write((QueueEnqueue)write, pointer); } else if (write instanceof QueueAck) { return write((QueueAck)write, pointer); } return new WriteTransactionResult(StatusCode.INTERNAL_ERROR, "Unknown write operation " + write.getClass().getName()); } WriteTransactionResult write(OperationContext context, Write write, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { initialize(); requestMetric("Write"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, write.getTable()); table.put(write.getKey(), write.getColumns(), pointer.getSecond(), write.getValues()); end("Write", begin); return new WriteTransactionResult( new Delete(write.getTable(), write.getKey(), write.getColumns())); } WriteTransactionResult write(OperationContext context, Delete delete, ImmutablePair<ReadPointer, Long> pointer) throws OperationException { initialize(); requestMetric("Delete"); long begin = begin(); OrderedVersionedColumnarTable table = this.findRandomTable(context, delete.getTable()); table.deleteAll(delete.getKey(), delete.getColumns(), pointer.getSecond()); end("Delete", begin); return new WriteTransactionResult( new Undelete(delete.getTable(), delete.getKey(), delete.getColumns())); } WriteTransactionResult write(OperationContext context, Increment increment, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { initialize(); requestMetric("Increment"); long begin = begin(); Long incrementValue; try { @SuppressWarnings("unused") OrderedVersionedColumnarTable table = this.findRandomTable(context, increment.getTable()); Map<byte[],Long> map = table.increment(increment.getKey(), increment.getColumns(), increment.getAmounts(), pointer.getFirst(), pointer.getSecond()); incrementValue = map.values().iterator().next(); } catch (OperationException e) { return new WriteTransactionResult(e.getStatus(), e.getMessage()); } end("Increment", begin); return new WriteTransactionResult( new Delete(increment.getTable(), increment.getKey(), increment.getColumns()), incrementValue); } WriteTransactionResult write(OperationContext context, CompareAndSwap write, ImmutablePair<ReadPointer,Long> pointer) throws OperationException { initialize(); requestMetric("CompareAndSwap"); long begin = begin(); try { OrderedVersionedColumnarTable table = this.findRandomTable(context, write.getTable()); table.compareAndSwap(write.getKey(), write.getColumn(), write.getExpectedValue(), write.getNewValue(), pointer.getFirst(), pointer.getSecond()); } catch (OperationException e) { return new WriteTransactionResult(e.getStatus(), e.getMessage()); } end("CompareAndSwap", begin); return new WriteTransactionResult( new Delete(write.getTable(), write.getKey(), write.getColumn())); } // TTQueues /** * EnqueuePayload operations always succeed but can be rolled back. * * They are rolled back with an invalidate. */ WriteTransactionResult write(QueueEnqueue enqueue, ImmutablePair<ReadPointer, Long> pointer) throws OperationException { initialize(); requestMetric("QueueEnqueue"); long begin = begin(); EnqueueResult result = getQueueTable(enqueue.getKey()).enqueue( enqueue.getKey(), enqueue.getData(), pointer.getSecond()); end("QueueEnqueue", begin); return new WriteTransactionResult( new QueueUnenqueue(enqueue.getKey(), enqueue.getData(), enqueue.getProducer(), result.getEntryPointer())); } WriteTransactionResult write(QueueAck ack, @SuppressWarnings("unused") ImmutablePair<ReadPointer, Long> pointer) throws OperationException { initialize(); requestMetric("QueueAck"); long begin = begin(); try { getQueueTable(ack.getKey()).ack(ack.getKey(), ack.getEntryPointer(), ack.getConsumer()); } catch (OperationException e) { // Ack failed, roll back transaction return new WriteTransactionResult(StatusCode.ILLEGAL_ACK, "Attempt to ack a dequeue of a different consumer"); } finally { end("QueueAck", begin); } return new WriteTransactionResult( new QueueUnack(ack.getKey(), ack.getEntryPointer(), ack.getConsumer())); } @Override public DequeueResult execute(OperationContext context, QueueDequeue dequeue) throws OperationException { initialize(); requestMetric("QueueDequeue"); long begin = begin(); int retries = 0; long start = System.currentTimeMillis(); TTQueueTable queueTable = getQueueTable(dequeue.getKey()); while (retries < MAX_DEQUEUE_RETRIES) { DequeueResult result = queueTable.dequeue(dequeue.getKey(), dequeue.getConsumer(), dequeue.getConfig(), this.oracle.getReadPointer()); if (result.shouldRetry()) { retries++; try { if (DEQUEUE_RETRY_SLEEP > 0) Thread.sleep(DEQUEUE_RETRY_SLEEP); } catch (InterruptedException e) { e.printStackTrace(); // continue in loop } continue; } end("QueueDequeue", begin); return result; } long end = System.currentTimeMillis(); end("QueueDequeue", begin); throw new OperationException(StatusCode.TOO_MANY_RETRIES, "Maximum retries (retried " + retries + " times over " + (end-start) + " millis"); } @Override public long execute(OperationContext context, GetGroupID getGroupId) throws OperationException { initialize(); requestMetric("GetGroupID"); long begin = begin(); TTQueueTable table = getQueueTable(getGroupId.getQueueName()); long groupid = table.getGroupID(getGroupId.getQueueName()); end("GetGroupID", begin); return groupid; } @Override public OperationResult<QueueMeta> execute(OperationContext context, GetQueueMeta getQueueMeta) throws OperationException { initialize(); requestMetric("GetQueueMeta"); long begin = begin(); TTQueueTable table = getQueueTable(getQueueMeta.getQueueName()); QueueMeta queueMeta = table.getQueueMeta(getQueueMeta.getQueueName()); end("GetQueueMeta", begin); return new OperationResult<QueueMeta>(queueMeta); } ImmutablePair<ReadPointer, Long> startTransaction() { requestMetric("StartTransaction"); return this.oracle.getNewPointer(); } boolean commitTransaction(ImmutablePair<ReadPointer, Long> pointer, RowSet rows) throws OmidTransactionException { requestMetric("CommitTransaction"); return this.oracle.commit(pointer.getSecond(), rows); } private void abortTransaction(OperationContext context, ImmutablePair<ReadPointer, Long> pointer, List<Delete> deletes, List<QueueInvalidate> invalidates) throws OperationException { // Perform queue invalidates cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_AbortedTransactions", 1); for (QueueInvalidate invalidate : invalidates) { invalidate.execute(getQueueTable(invalidate.queueName), pointer); } // Perform deletes for (Delete delete : deletes) { assert(delete != null); OrderedVersionedColumnarTable table = this.findRandomTable(context, delete.getTable()); if (delete instanceof Undelete) { table.undeleteAll(delete.getKey(), delete.getColumns(), pointer.getSecond()); } else { table.delete(delete.getKey(), delete.getColumns(), pointer.getSecond()); } } // Notify oracle this.oracle.aborted(pointer.getSecond()); } // Single Write Operations (Wrapped and called in a transaction batch) @SuppressWarnings("unused") private void unsupported(String msg) { throw new RuntimeException(msg); } @Override public void execute(OperationContext context, Write write) throws OperationException { executeAsBatch(context, write); } @Override public void execute(OperationContext context, Delete delete) throws OperationException { executeAsBatch(context, delete); } @Override public void execute(OperationContext context, Increment inc) throws OperationException { executeAsBatch(context, inc); } @Override public void execute(OperationContext context, CompareAndSwap cas) throws OperationException { executeAsBatch(context, cas); } @Override public void execute(OperationContext context, QueueAck ack) throws OperationException { executeAsBatch(context, ack); } @Override public void execute(OperationContext context, QueueEnqueue enqueue) throws OperationException { executeAsBatch(context, enqueue); } private TTQueueTable getQueueTable(byte[] queueName) { if (Bytes.startsWith(queueName, TTQueue.QUEUE_NAME_PREFIX)) return this.queueTable; if (Bytes.startsWith(queueName, TTQueue.STREAM_NAME_PREFIX)) return this.streamTable; // by default, use queue table return this.queueTable; } /** * A utility method that ensures this class is properly initialized before * it can be used. This currently entails creating real objects for all * our table handlers. */ private synchronized void initialize() throws OperationException { if (this.randomTable == null) { this.metaTable = this.tableHandle.getTable(Bytes.toBytes("meta")); this.randomTable = this.tableHandle.getTable(Bytes.toBytes("random")); this.queueTable = this.tableHandle.getQueueTable(Bytes.toBytes("queues")); this.streamTable = this.tableHandle.getStreamTable(Bytes.toBytes("streams")); this.namedTables = Maps.newConcurrentMap(); this.metaStore = new SerializingMetaDataStore(this); } } } // end of OmitTransactionalOperationExecutor
ENG-767 Implement stream metrics
src/main/java/com/continuuity/data/operation/executor/omid/OmidTransactionalOperationExecutor.java
ENG-767 Implement stream metrics
<ide><path>rc/main/java/com/continuuity/data/operation/executor/omid/OmidTransactionalOperationExecutor.java <ide> import com.continuuity.data.table.ReadPointer; <ide> import com.continuuity.data.util.TupleMetaDataAnnotator.DequeuePayload; <ide> import com.continuuity.data.util.TupleMetaDataAnnotator.EnqueuePayload; <del>import com.esotericsoftware.minlog.Log; <ide> import com.google.common.base.Objects; <ide> import com.google.common.collect.Maps; <ide> import com.google.inject.Inject; <ide> import com.google.inject.Singleton; <ide> import org.apache.hadoop.hbase.util.Bytes; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <ide> <ide> import java.io.IOException; <ide> import java.util.*; <ide> @Singleton <ide> public class OmidTransactionalOperationExecutor <ide> implements TransactionalOperationExecutor { <add> <add> private static final Logger Log <add> = LoggerFactory.getLogger(OmidTransactionalOperationExecutor.class); <ide> <ide> public String getName() { <ide> return "omid(" + tableHandle.getName() + ")";
JavaScript
bsd-3-clause
c03764b79def61cec11a28791b12647e3aac9552
0
lietk12/fermenter,lietk12/fermentor,lietk12/fermenter,lietk12/fermenter,lietk12/fermentor,lietk12/fermentor
// Math function absorbance(calib, transmittance) { return (calib - transmittance) / calib; } function duty_cycle_to_percent(duty_cycle) { return ~~(duty_cycle * 100) } // Strings function time_text(data) { if (data) { return "Updated " + data[0] + "."; } } function start_text(data) { if (data) { return "Fermenter started at: " + data; } else { return "Fermenter has not yet started."; } } function stop_text(data, since) { if (data) { return "Fermenter stopped at: " + data; } else { return "Fermenter has been running for " + since.toFixed(2) + " hours."; } } function now_text(data) { return "Last update: " + data; } function temp_text(data) { if (data) { return "Vessel temperature: " + data[1].toFixed(2) + " °C"; } else { return "Vessel temperature will be updated soon!"; } } function heater_text(data) { if (data) { return "Heater duty cycle: " + duty_cycle_to_percent(data[1]) + " %"; } else { return "Heater duty cycle will be updated soon!"; } } function impeller_text(data) { if (data) { return "Impeller duty cycle: " + duty_cycle_to_percent([1]) + " %"; } else { return "Impeller duty cycle will be updated soon!"; } } function ambient_text(data) { if (data) { return "Ambient light: " + ~~(data[1]); } else { return "Ambient light will be updated soon!"; } } function red_text(red_calib, data) { if (data) { return "OD: " + absorbance(red_calib, data[1]).toFixed(2); } else { return "OD will be updated soon!"; } } function green_text(green_calib, data) { if (data) { return "Green absorbance: " + absorbance(green_calib, data[1]).toFixed(2); } else { return "Green absorbance will be updated soon!"; } } $(document).ready(function () { namespace = "/socket"; var socket = io.connect("http://" + document.domain + ":" + location.port + namespace); socket.on("connect", function () { socket.emit("socket event", {data: "Successful connection!"}); }); socket.on("stats update", function (msg) { $("#start").text(start_text(msg.start)); $("#stop").text(stop_text(msg.stop, msg.since)); $("#now").text(now_text(msg.now)); $('#impeller').text(impeller_text(msg.impeller)); $('#temp_update_time').text(time_text(msg.temp)); $('#temp').text(temp_text(msg.temp)); $('#heater').text(heater_text(msg.heater)); $('#optics_update_time').text(time_text(msg.optics.ambient)); $('#ambient').text(ambient_text(msg.optics.ambient)); $('#red').text(red_text(msg.optics.calibration.red, msg.optics.red)); $('#green').text(green_text(msg.optics.calibration.green, msg.optics.green)); }); socket.on("optics plot update", function(msg) { $('#optics_plot_cache').attr("data", "/plots/optics?" + msg.time); }); socket.on("temp plot update", function(msg) { $('#temp_plot_cache').attr("data", "/plots/temp?" + msg.time); }); socket.on("duty cycles plot update", function(msg) { $('#duty_cycles_plot_cache').attr("data", "/plots/duty_cycles?" + msg.time); }); $('#optics_plot_cache').bind("load", function () { $('#optics_plot').attr("data", $('#optics_plot_cache').attr("data")); }); $('#temp_plot_cache').bind("load", function () { $('#temp_plot').attr("data", $('#temp_plot_cache').attr("data")); }); $('#duty_cycles_plot_cache').bind("load", function () { $('#duty_cycles_plot').attr("data", $('#duty_cycles_plot_cache').attr("data")); }); });
static/client.js
// Math function absorbance(calib, transmittance) { return (calib - transmittance) / calib; } function duty_cycle_to_percent(duty_cycle) { return ~~(duty_cycle * 100) } // Strings function time_text(data) { if (data) { return "Updated " + data[0] + "."; } } function start_text(data) { if (data) { return "Fermenter started at: " + data; } else { return "Fermenter has not yet started."; } } function stop_text(data, since) { if (data) { return "Fermenter stopped at: " + data; } else { return "Fermenter has been running for " + since.toFixed(2) + " hours."; } } function now_text(data) { return "Last update: " + data; } function temp_text(data) { if (data) { return "Vessel temperature: " + data[1].toFixed(2) + " °C"; } else { return "Vessel temperature will be updated soon!"; } } function heater_text(data) { if (data) { return "Heater duty cycle: " + duty_cycle_to_percent(data[1]) + " %"; } else { return "Heater duty cycle will be updated soon!"; } } function impeller_text(data) { if (data) { return "Impeller duty cycle: " + duty_cycle_to_percent([1]) + " %"; } else { return "Impeller duty cycle will be updated soon!"; } } function ambient_text(data) { if (data) { return "Ambient light: " + ~~(data[1]); } else { return "Ambient light will be updated soon!"; } } function red_text(red_calib, data) { if (data) { return "OD: " + absorbance(red_calib, data[1]).toFixed(2); } else { return "OD will be updated soon!"; } } function green_text(green_calib, data) { if (data) { return "Green absorbance: " + absorbance(green_calib, data[1]).toFixed(2); } else { return "Green absorbance will be updated soon!"; } } $(document).ready(function () { namespace = "/socket"; var socket = io.connect("http://" + document.domain + ":" + location.port + namespace); socket.on("connect", function () { socket.emit("socket event", {data: "Successful connection!"}); }); socket.on("stats update", function (msg) { $("#start").text(start_text(msg.start)); $("#stop").text(stop_text(msg.stop, msg.since)); $("#now").text(now_text(msg.now)); $('#impeller').text(impeller_text(msg.impeller)); $('#temp_update_time').text(time_text(msg.temp)); $('#temp').text(temp_text(msg.temp)); $('#heater').text(heater_text(msg.heater)); $('#optics_update_time').text(time_text(msg.optics.ambient)); $('#ambient').text(ambient_text(msg.optics.ambient)); $('#red').text(red_text(msg.optics.calibration.red, msg.optics.red)); $('#green').text(green_text(msg.optics.calibration.green, msg.optics.green)); }); socket.on("optics plot update", function(msg) { $('#optics_plot_cache').attr("data", "/plots/optics?" + msg.time); $('#optics_plot_cache').load(function () { $('#optics_plot').attr("data", "/plots/optics?" + msg.time); }); }); socket.on("temp plot update", function(msg) { $('#temp_plot_cache').attr("data", "/plots/temp?" + msg.time); $('#temp_plot_cache').load(function () { $('#temp_plot').attr("data", "/plots/temp?" + msg.time); }); }); socket.on("duty cycles plot update", function(msg) { $('#duty_cycles_plot_cache').attr("data", "/plots/duty_cycles?" + msg.time); $('#duty_cycles_plot_cache').load(function () { $('#duty_cycles_plot').attr("data", "/plots/duty_cycles?" + msg.time); }); }); });
Trying to make cache work.
static/client.js
Trying to make cache work.
<ide><path>tatic/client.js <ide> }); <ide> socket.on("optics plot update", function(msg) { <ide> $('#optics_plot_cache').attr("data", "/plots/optics?" + msg.time); <del> $('#optics_plot_cache').load(function () { <del> $('#optics_plot').attr("data", "/plots/optics?" + msg.time); <del> }); <ide> }); <ide> socket.on("temp plot update", function(msg) { <ide> $('#temp_plot_cache').attr("data", "/plots/temp?" + msg.time); <del> $('#temp_plot_cache').load(function () { <del> $('#temp_plot').attr("data", "/plots/temp?" + msg.time); <del> }); <ide> }); <ide> socket.on("duty cycles plot update", function(msg) { <ide> $('#duty_cycles_plot_cache').attr("data", "/plots/duty_cycles?" + msg.time); <del> $('#duty_cycles_plot_cache').load(function () { <del> $('#duty_cycles_plot').attr("data", "/plots/duty_cycles?" + msg.time); <del> }); <add> }); <add> $('#optics_plot_cache').bind("load", function () { <add> $('#optics_plot').attr("data", $('#optics_plot_cache').attr("data")); <add> }); <add> $('#temp_plot_cache').bind("load", function () { <add> $('#temp_plot').attr("data", $('#temp_plot_cache').attr("data")); <add> }); <add> $('#duty_cycles_plot_cache').bind("load", function () { <add> $('#duty_cycles_plot').attr("data", $('#duty_cycles_plot_cache').attr("data")); <ide> }); <ide> });
Java
mit
2c8c1793596e9334426bcc1901de11640a918569
0
BranchMetrics/Android-Deferred-Deep-Linking-SDK,BranchMetrics/Android-Deferred-Deep-Linking-SDK,BranchMetrics/android-branch-deep-linking,BranchMetrics/Android-Deferred-Deep-Linking-SDK,BranchMetrics/Android-Deferred-Deep-Linking-SDK,BranchMetrics/android-branch-deep-linking,BranchMetrics/android-branch-deep-linking,BranchMetrics/android-branch-deep-linking
package io.branch.referral; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; /** * The core object required when using Branch SDK. You should declare an object of this type at the * class-level of each Activity or Fragment that you wish to use Branch functionality within. * * */ public class Branch { public static final String FEATURE_TAG_SHARE = "share"; public static final String FEATURE_TAG_REFERRAL = "referral"; public static final String FEATURE_TAG_INVITE = "invite"; public static final String FEATURE_TAG_DEAL = "deal"; public static final String FEATURE_TAG_GIFT = "gift"; public static final String REDEEM_CODE = "$redeem_code"; public static final String REFERRAL_BUCKET_DEFAULT = "default"; public static final String REFERRAL_CODE_TYPE = "credit"; public static final int REFERRAL_CREATION_SOURCE_SDK = 2; public static final String REFERRAL_CODE = "referral_code"; public static final String REDIRECT_DESKTOP_URL = "$desktop_url"; public static final String REDIRECT_ANDROID_URL = "$android_url"; public static final String REDIRECT_IOS_URL = "$ios_url"; public static final String REDIRECT_IPAD_URL = "$ipad_url"; public static final String REDIRECT_FIRE_URL = "$fire_url"; public static final String REDIRECT_BLACKBERRY_URL = "$blackberry_url"; public static final String REDIRECT_WINDOWNS_PHONE_URL = "$windows_phone_url"; public static final String OG_TITLE = "$og_title"; public static final String OG_DESC = "$og_description"; public static final String OG_IMAGE_URL = "$og_image_url"; public static final String OG_VIDEO = "$og_video"; public static final String OG_URL = "$og_url"; public static final String OG_APP_ID = "$og_app_id"; public static final String DEEPLINK_PATH = "$deeplink_path"; public static final String ALWAYS_DEEPLINK = "$always_deeplink"; public static final int REFERRAL_CODE_LOCATION_REFERREE = 0; public static final int REFERRAL_CODE_LOCATION_REFERRING_USER = 2; public static final int REFERRAL_CODE_LOCATION_BOTH = 3; public static final int REFERRAL_CODE_AWARD_UNLIMITED = 1; public static final int REFERRAL_CODE_AWARD_UNIQUE = 0; public static final int LINK_TYPE_UNLIMITED_USE = 0; public static final int LINK_TYPE_ONE_TIME_USE = 1; private static final int SESSION_KEEPALIVE = 2000; private static final int PREVENT_CLOSE_TIMEOUT = 500; private static Branch branchReferral_; private boolean isInit_; private BranchReferralInitListener initSessionFinishedCallback_; private BranchReferralInitListener initIdentityFinishedCallback_; private BranchReferralStateChangedListener stateChangedCallback_; private BranchLinkCreateListener linkCreateCallback_; private BranchListResponseListener creditHistoryCallback_; private BranchReferralInitListener getReferralCodeCallback_; private BranchReferralInitListener validateReferralCodeCallback_; private BranchReferralInitListener applyReferralCodeCallback_; private BranchRemoteInterface kRemoteInterface_; private PrefHelper prefHelper_; private SystemObserver systemObserver_; private Context context_; final Object lock; private Timer closeTimer; private Timer rotateCloseTimer; private boolean keepAlive_; private Semaphore serverSema_; private ServerRequestQueue requestQueue_; private int networkCount_; private int retryCount_; private boolean initNotStarted_; private boolean initFinished_; private boolean initFailed_; private boolean hasNetwork_; private boolean lastRequestWasInit_; private Handler debugHandler_; private SparseArray<String> debugListenerInitHistory_; private OnTouchListener debugOnTouchListener_; private Map<BranchLinkData, String> linkCache_; private ScheduledFuture<?> appListingSchedule_; private Branch(Context context) { prefHelper_ = PrefHelper.getInstance(context); kRemoteInterface_ = new BranchRemoteInterface(context); systemObserver_ = new SystemObserver(context); kRemoteInterface_.setNetworkCallbackListener(new ReferralNetworkCallback()); requestQueue_ = ServerRequestQueue.getInstance(context); serverSema_ = new Semaphore(1); closeTimer = new Timer(); rotateCloseTimer = new Timer(); lock = new Object(); initFinished_ = false; initFailed_ = false; lastRequestWasInit_ = true; keepAlive_ = false; isInit_ = false; initNotStarted_ = true; networkCount_ = 0; hasNetwork_ = true; debugListenerInitHistory_ = new SparseArray<String>(); debugHandler_ = new Handler(); debugOnTouchListener_ = retrieveOnTouchListener(); linkCache_ = new HashMap<BranchLinkData, String>(); } @Deprecated public static Branch getInstance(Context context, String key) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context; branchReferral_.prefHelper_.setAppKey(key); return branchReferral_; } public static Branch getInstance(Context context) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); String appKey = branchReferral_.prefHelper_.getAppKey(); if (appKey == null || appKey.equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) { Log.i("BranchSDK", "Branch Warning: Please enter your Branch App Key in your project's res/values/strings.xml!"); } } branchReferral_.context_ = context; return branchReferral_; } private static Branch initInstance(Context context) { return new Branch(context.getApplicationContext()); } public void resetUserSession() { isInit_ = false; } public void setRetryCount(int retryCount) { if (prefHelper_ != null && retryCount > 0) { prefHelper_.setRetryCount(retryCount); } } public void setRetryInterval(int retryInterval) { if (prefHelper_ != null && retryInterval > 0) { prefHelper_.setRetryInterval(retryInterval); } } public void setNetworkTimeout(int timeout) { if (prefHelper_ != null && timeout > 0) { prefHelper_.setTimeout(timeout); } } // if you want to flag debug, call this before initUserSession public void setDebug() { prefHelper_.setExternDebug(); } public void disableAppList() { prefHelper_.disableExternAppListing(); } // Note: smart session - we keep session alive for two seconds // if there's further Branch API call happening within the two seconds, we then don't close the session; // otherwise, we close the session after two seconds // Call this method if you don't want this smart session feature public void disableSmartSession() { prefHelper_.disableSmartSession(); } public boolean initSession(BranchReferralInitListener callback) { initSession(callback, (Activity)null); return false; } public boolean initSession(BranchReferralInitListener callback, Activity activity) { if (systemObserver_.getUpdateState() == 0 && !hasUser()) { prefHelper_.setIsReferrable(); } else { prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback, activity); return false; } public boolean initSession(BranchReferralInitListener callback, Uri data) { return initSession(callback, data, null); } public boolean initSession(BranchReferralInitListener callback, Uri data, Activity activity) { boolean uriHandled = false; if (data != null && data.isHierarchical()) { if (data.getQueryParameter("link_click_id") != null) { uriHandled = true; prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(callback, activity); return uriHandled; } public boolean initSession() { return initSession((Activity)null); } public boolean initSession(Activity activity) { return initSession(null, activity); } public boolean initSessionWithData(Uri data) { return initSessionWithData(data, null); } public boolean initSessionWithData(Uri data, Activity activity) { boolean uriHandled = false; if (data != null && data.isHierarchical()) { if (data.getQueryParameter("link_click_id") != null) { uriHandled = true; prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(null, activity); return uriHandled; } public boolean initSession(boolean isReferrable) { return initSession(null, isReferrable, (Activity)null); } public boolean initSession(boolean isReferrable, Activity activity) { return initSession(null, isReferrable, activity); } public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data) { return initSession(callback, isReferrable, data, null); } public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data, Activity activity) { boolean uriHandled = false; if (data != null && data.isHierarchical()) { if (data.getQueryParameter("link_click_id") != null) { uriHandled = true; prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(callback, isReferrable, activity); return uriHandled; } public boolean initSession(BranchReferralInitListener callback, boolean isReferrable) { return initSession(callback, isReferrable, (Activity)null); } public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) { if (isReferrable) { this.prefHelper_.setIsReferrable(); } else { this.prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback, activity); return false; } private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity) { initSessionFinishedCallback_ = callback; lastRequestWasInit_ = true; initNotStarted_ = false; initFailed_ = false; if (!isInit_) { isInit_ = true; new Thread(new Runnable() { @Override public void run() { initializeSession(); } }).start(); } else { boolean installOrOpenInQueue = requestQueue_.containsInstallOrOpen(); if (hasUser() && hasSession() && !installOrOpenInQueue) { if (callback != null) callback.onInitFinished(new JSONObject(), null); clearCloseTimer(); keepAlive(); } else { if (!installOrOpenInQueue) { new Thread(new Runnable() { @Override public void run() { initializeSession(); } }).start(); } else { new Thread(new Runnable() { @Override public void run() { requestQueue_.moveInstallOrOpenToFront(null, networkCount_); processNextQueueItem(); } }).start(); } } } if (activity != null && debugListenerInitHistory_.get(System.identityHashCode(activity)) == null) { debugListenerInitHistory_.put(System.identityHashCode(activity), "init"); View view = activity.getWindow().getDecorView().findViewById(android.R.id.content); if (view != null) { view.setOnTouchListener(debugOnTouchListener_); } } } private OnTouchListener retrieveOnTouchListener() { if (debugOnTouchListener_ == null) { debugOnTouchListener_ = new OnTouchListener() { class KeepDebugConnectionTask extends TimerTask { public void run() { if (!prefHelper_.keepDebugConnection()) { debugHandler_.post(_longPressed); } } } Runnable _longPressed = new Runnable() { private boolean started = false; private Timer timer; public void run() { debugHandler_.removeCallbacks(_longPressed); if (!started) { Log.i("Branch Debug","======= Start Debug Session ======="); prefHelper_.setDebug(); timer = new Timer(); timer.scheduleAtFixedRate(new KeepDebugConnectionTask(), new Date(), 20000); } else { Log.i("Branch Debug","======= End Debug Session ======="); prefHelper_.clearDebug(); timer.cancel(); timer = null; } this.started = !this.started; } }; @Override public boolean onTouch(View v, MotionEvent ev) { int pointerCount = ev.getPointerCount(); final int actionPeformed = ev.getAction(); switch (actionPeformed & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: if (systemObserver_.isSimulator()) { debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_CANCEL: debugHandler_.removeCallbacks(_longPressed); break; case MotionEvent.ACTION_UP: v.performClick(); debugHandler_.removeCallbacks(_longPressed); break; case MotionEvent.ACTION_POINTER_DOWN: if (pointerCount == PrefHelper.DEBUG_TRIGGER_NUM_FINGERS) { debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; } return true; } }; } return debugOnTouchListener_; } public void closeSession() { if (prefHelper_.getSmartSession()) { if (keepAlive_) { return; } // else, real close synchronized(lock) { clearCloseTimer(); rotateCloseTimer.schedule(new TimerTask() { @Override public void run() { executeClose(); } }, PREVENT_CLOSE_TIMEOUT); } } else { executeClose(); } if (prefHelper_.getExternAppListing()) { if (appListingSchedule_ == null) { scheduleListOfApps(); } } } private void executeClose() { isInit_ = false; lastRequestWasInit_ = false; initNotStarted_ = true; if (!hasNetwork_) { // if there's no network connectivity, purge the old install/open ServerRequest req = requestQueue_.peek(); if (req != null && (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN))) { requestQueue_.dequeue(); } } else { new Thread(new Runnable() { @Override public void run() { if (!requestQueue_.containsClose()) { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE, null); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } } }).start(); } } public void setIdentity(String userId, BranchReferralInitListener callback) { initIdentityFinishedCallback_ = callback; setIdentity(userId); } public void setIdentity(final String userId) { if (userId == null || userId.length() == 0 || userId.equals(prefHelper_.getIdentity())) { return; } new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("identity", userId); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_IDENTIFY, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void logout() { new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_LOGOUT, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void loadActionCounts() { loadActionCounts(null); } public void loadActionCounts(BranchReferralStateChangedListener callback) { stateChangedCallback_ = callback; new Thread(new Runnable() { @Override public void run() { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS, null); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void loadRewards() { loadRewards(null); } public void loadRewards(BranchReferralStateChangedListener callback) { stateChangedCallback_ = callback; new Thread(new Runnable() { @Override public void run() { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARDS, null); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public int getCredits() { return prefHelper_.getCreditCount(); } public int getCreditsForBucket(String bucket) { return prefHelper_.getCreditCount(bucket); } public int getTotalCountsForAction(String action) { return prefHelper_.getActionTotalCount(action); } public int getUniqueCountsForAction(String action) { return prefHelper_.getActionUniqueCount(action); } public void redeemRewards(int count) { redeemRewards("default", count); } public void redeemRewards(final String bucket, final int count) { new Thread(new Runnable() { @Override public void run() { int creditsToRedeem; int credits = prefHelper_.getCreditCount(bucket); if (count > credits) { creditsToRedeem = credits; Log.i("BranchSDK", "Branch Warning: You're trying to redeem more credits than are available. Have you updated loaded rewards"); } else { creditsToRedeem = count; } if (creditsToRedeem > 0) { retryCount_ = 0; JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("bucket", bucket); post.put("amount", creditsToRedeem); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } } }).start(); } public void getCreditHistory(BranchListResponseListener callback) { getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } public void getCreditHistory(final String bucket, BranchListResponseListener callback) { getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } public void getCreditHistory(final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { getCreditHistory(null, afterId, length, order, callback); } public void getCreditHistory(final String bucket, final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { creditHistoryCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("length", length); post.put("direction", order.ordinal()); if (bucket != null) { post.put("bucket", bucket); } if (afterId != null) { post.put("begin_after_id", afterId); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void userCompletedAction(final String action, final JSONObject metadata) { new Thread(new Runnable() { @Override public void run() { retryCount_ = 0; JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("event", action); if (metadata != null) post.put("metadata", filterOutBadCharacters(metadata)); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void userCompletedAction(final String action) { userCompletedAction(action, null); } public JSONObject getFirstReferringParams() { String storedParam = prefHelper_.getInstallParams(); return convertParamsStringToDictionary(storedParam); } public JSONObject getLatestReferringParams() { String storedParam = prefHelper_.getSessionParams(); return convertParamsStringToDictionary(storedParam); } public String getShortUrlSync() { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(null), null, false); } public String getShortUrlSync(JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getReferralUrlSync(String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getReferralUrlSync(Collection<String> tags, String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getContentUrlSync(String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getContentUrlSync(Collection<String> tags, String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String alias, String channel, String feature, String stage, JSONObject params) { return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(int type, String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, type, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String channel, String feature, String stage, JSONObject params, int duration) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params) { return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, type, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public void getShortUrl(BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(null), callback, true); } public void getShortUrl(JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getReferralUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getReferralUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getContentUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getContentUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String alias, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(int type, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, type, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, type, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getReferralCode(BranchReferralInitListener callback) { getReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void getReferralCode(final int amount, BranchReferralInitListener callback) { this.getReferralCode(null, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final String prefix, final int amount, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final int amount, final Date expiration, BranchReferralInitListener callback) { this.getReferralCode(null, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final String prefix, final int amount, final Date expiration, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final String prefix, final int amount, final int calculationType, final int location, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, calculationType, location, callback); } public void getReferralCode(final String prefix, final int amount, final Date expiration, final String bucket, final int calculationType, final int location, BranchReferralInitListener callback) { getReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("calculation_type", calculationType); post.put("location", location); post.put("type", REFERRAL_CODE_TYPE); post.put("creation_source", REFERRAL_CREATION_SOURCE_SDK); post.put("amount", amount); post.put("bucket", bucket != null ? bucket : REFERRAL_BUCKET_DEFAULT); if (prefix != null && prefix.length() > 0) { post.put("prefix", prefix); } if (expiration != null) { post.put("expiration", convertDate(expiration)); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void validateReferralCode(final String code, BranchReferralInitListener callback) { validateReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("referral_code", code); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void applyReferralCode(final String code, final BranchReferralInitListener callback) { applyReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("referral_code", code); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } // PRIVATE FUNCTIONS private String convertDate(Date date) { return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString(); } private String stringifyParams(JSONObject params) { if (params == null) { params = new JSONObject(); } try { params.put("source", "android"); } catch (JSONException e) { e.printStackTrace(); } return params.toString(); } private String generateShortLink(final String alias, final int type, final int duration, final Collection<String> tags, final String channel, final String feature, final String stage, final String params, BranchLinkCreateListener callback, boolean async) { linkCreateCallback_ = callback; if (hasUser()) { final BranchLinkData linkPost = new BranchLinkData(); try { linkPost.put("app_id", prefHelper_.getAppKey()); linkPost.put("identity_id", prefHelper_.getIdentityID()); linkPost.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); linkPost.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { linkPost.put("link_click_id", prefHelper_.getLinkClickID()); } linkPost.putType(type); linkPost.putDuration(duration); linkPost.putTags(tags); linkPost.putAlias(alias); linkPost.putChannel(channel); linkPost.putFeature(feature); linkPost.putStage(stage); linkPost.putParams(params); } catch (JSONException ex) { ex.printStackTrace(); } if (linkCache_.containsKey(linkPost)) { String url = linkCache_.get(linkPost); if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate(url, null); } return url; } else { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL, linkPost); if (async) { generateShortLinkAsync(req); } else { return generateShortLinkSync(req); } } } return null; } private String generateShortLinkSync(ServerRequest req) { if (!initFailed_ && initFinished_ && hasNetwork_) { ServerResponse response = kRemoteInterface_.createCustomUrlSync(req.getPost()); String url = prefHelper_.getUserURL(); if (response.getStatusCode() == 200) { try { url = response.getObject().getString("url"); if (response.getLinkData() != null) { linkCache_.put(response.getLinkData(), url); } } catch (JSONException e) { e.printStackTrace(); } } return url; } else { Log.i("BranchSDK", "Branch Warning: User session has not been initialized"); } return null; } private void generateShortLinkAsync(final ServerRequest req) { new Thread(new Runnable() { @Override public void run() { if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } private JSONObject filterOutBadCharacters(JSONObject inputObj) { JSONObject filteredObj = new JSONObject(); if (inputObj != null) { Iterator<?> keys = inputObj.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { if (inputObj.has(key) && inputObj.get(key).getClass().equals(String.class)) { filteredObj.put(key, inputObj.getString(key).replace("\n", "\\n").replace("\r", "\\r").replace("\"", "\\\"")); } else if (inputObj.has(key)) { filteredObj.put(key, inputObj.get(key)); } } catch(JSONException ignore) { } } } return filteredObj; } private JSONObject convertParamsStringToDictionary(String paramString) { if (paramString.equals(PrefHelper.NO_STRING_VALUE)) { return new JSONObject(); } else { try { return new JSONObject(paramString); } catch (JSONException e) { byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP); try { return new JSONObject(new String(encodedArray)); } catch (JSONException ex) { ex.printStackTrace(); return new JSONObject(); } } } } private void scheduleListOfApps() { ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1); Runnable periodicTask = new Runnable(){ @Override public void run() { SystemObserver sysObserver = new SystemObserver(context_); JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); if (!sysObserver.getOS().equals(SystemObserver.BLANK)) post.put("os", sysObserver.getOS()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("apps_data", sysObserver.getListOfApps()); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_SEND_APP_LIST, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } } }; Date date = new Date(); Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(date); int days = Calendar.SATURDAY - calendar.get(Calendar.DAY_OF_WEEK); // days to Saturday int hours = 2 - calendar.get(Calendar.HOUR_OF_DAY); // hours to 2am, can be negative if (days == 0 && hours < 0) { days = 7; } int interval = 7 * 24 * 60 * 60; appListingSchedule_ = scheduler.scheduleAtFixedRate(periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS); } private void processNextQueueItem() { try { serverSema_.acquire(); if (networkCount_ == 0 && requestQueue_.getSize() > 0) { networkCount_ = 1; ServerRequest req = requestQueue_.peek(); serverSema_.release(); if (!req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) && !hasUser()) { Log.i("BranchSDK", "Branch Error: User session has not been initialized!"); networkCount_ = 0; handleFailure(requestQueue_.getSize()-1); return; } if (!req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE) && !req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { keepAlive(); clearCloseTimer(); } if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) { kRemoteInterface_.registerInstall(PrefHelper.NO_STRING_VALUE, prefHelper_.isDebug()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { kRemoteInterface_.registerOpen(prefHelper_.isDebug()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS) && hasSession()) { kRemoteInterface_.getReferralCounts(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_SEND_APP_LIST) && hasSession()) { kRemoteInterface_.registerListOfApps(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS) && hasSession()) { kRemoteInterface_.getRewards(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS) && hasSession()) { kRemoteInterface_.redeemRewards(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY) && hasSession()) { kRemoteInterface_.getCreditHistory(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION) && hasSession()) { kRemoteInterface_.userCompletedAction(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL) && hasSession()) { kRemoteInterface_.createCustomUrl(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY) && hasSession()) { kRemoteInterface_.identifyUser(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE) && hasSession()) { kRemoteInterface_.registerClose(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_LOGOUT) && hasSession()) { kRemoteInterface_.logoutUser(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE) && hasSession()) { kRemoteInterface_.getReferralCode(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE) && hasSession()) { kRemoteInterface_.validateReferralCode(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE) && hasSession()) { kRemoteInterface_.applyReferralCode(req.getPost()); } } else { serverSema_.release(); } } catch (Exception e) { e.printStackTrace(); } } private void handleFailure(int index) { ServerRequest req; if (index >= requestQueue_.getSize()) { req = requestQueue_.peekAt(requestQueue_.getSize()-1); } else { req = requestQueue_.peekAt(index); } handleFailure(req); } private void handleFailure(final ServerRequest req) { if (req == null) return; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { if (initSessionFinishedCallback_ != null) { JSONObject obj = new JSONObject(); try { obj.put("error_message", "Trouble reaching server. Please try again in a few minutes"); } catch (JSONException ex) { ex.printStackTrace(); } initSessionFinishedCallback_.onInitFinished(obj, new BranchInitError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS)) { if (stateChangedCallback_ != null) { if (initNotStarted_) stateChangedCallback_.onStateChanged(false, new BranchNotInitError()); else stateChangedCallback_.onStateChanged(false, new BranchGetReferralsError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) { if (stateChangedCallback_ != null) { if (initNotStarted_) stateChangedCallback_.onStateChanged(false, new BranchNotInitError()); else stateChangedCallback_.onStateChanged(false, new BranchGetCreditsError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) { if (creditHistoryCallback_ != null) { if (initNotStarted_) creditHistoryCallback_.onReceivingResponse(null, new BranchNotInitError()); else creditHistoryCallback_.onReceivingResponse(null, new BranchGetCreditHistoryError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { if (linkCreateCallback_ != null) { String failedUrl = null; if (!prefHelper_.getUserURL().equals(PrefHelper.NO_STRING_VALUE)) { failedUrl = prefHelper_.getUserURL(); } if (initNotStarted_) linkCreateCallback_.onLinkCreate(null, new BranchNotInitError()); else linkCreateCallback_.onLinkCreate(failedUrl, new BranchCreateUrlError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) { if (initIdentityFinishedCallback_ != null) { JSONObject obj = new JSONObject(); try { obj.put("error_message", "Trouble reaching server. Please try again in a few minutes"); } catch (JSONException ex) { ex.printStackTrace(); } if (initNotStarted_) initIdentityFinishedCallback_.onInitFinished(obj, new BranchNotInitError()); else initIdentityFinishedCallback_.onInitFinished(obj, new BranchSetIdentityError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE)) { if (getReferralCodeCallback_ != null) { if (initNotStarted_) getReferralCodeCallback_.onInitFinished(null, new BranchNotInitError()); else getReferralCodeCallback_.onInitFinished(null, new BranchGetReferralCodeError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE)) { if (validateReferralCodeCallback_ != null) { if (initNotStarted_) validateReferralCodeCallback_.onInitFinished(null, new BranchNotInitError()); else validateReferralCodeCallback_.onInitFinished(null, new BranchValidateReferralCodeError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE)) { if (applyReferralCodeCallback_ != null) { if (initNotStarted_) applyReferralCodeCallback_.onInitFinished(null, new BranchNotInitError()); else applyReferralCodeCallback_.onInitFinished(null, new BranchApplyReferralCodeError()); } } } }); } private void retryLastRequest() { retryCount_ = retryCount_ + 1; if (retryCount_ > prefHelper_.getRetryCount()) { handleFailure(0); requestQueue_.dequeue(); retryCount_ = 0; } else { try { Thread.sleep(prefHelper_.getRetryInterval()); } catch (InterruptedException e) { e.printStackTrace(); } } } private void updateAllRequestsInQueue() { try { for (int i = 0; i < requestQueue_.getSize(); i++) { ServerRequest req = requestQueue_.peekAt(i); if (req.getPost() != null) { Iterator<?> keys = req.getPost().keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("app_id")) { req.getPost().put(key, prefHelper_.getAppKey()); } else if (key.equals("session_id")) { req.getPost().put(key, prefHelper_.getSessionID()); } else if (key.equals("identity_id")) { req.getPost().put(key, prefHelper_.getIdentityID()); } } } } } catch (JSONException e) { e.printStackTrace(); } } private void clearCloseTimer() { if (rotateCloseTimer == null) return; rotateCloseTimer.cancel(); rotateCloseTimer.purge(); rotateCloseTimer = new Timer(); } private void clearTimer() { if (closeTimer == null) return; closeTimer.cancel(); closeTimer.purge(); closeTimer = new Timer(); } private void keepAlive() { keepAlive_ = true; synchronized(lock) { clearTimer(); closeTimer.schedule(new TimerTask() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { keepAlive_ = false; } }).start(); } }, SESSION_KEEPALIVE); } } private boolean hasSession() { return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasUser() { return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE); } private void insertRequestAtFront(ServerRequest req) { if (networkCount_ == 0) { requestQueue_.insert(req, 0); } else { requestQueue_.insert(req, 1); } } private void registerInstallOrOpen(String tag) { if (!requestQueue_.containsInstallOrOpen()) { insertRequestAtFront(new ServerRequest(tag)); } else { requestQueue_.moveInstallOrOpenToFront(tag, networkCount_); } processNextQueueItem(); } private void initializeSession() { if (hasUser()) { registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN); } else { registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL); } } private void processReferralCounts(ServerResponse resp) { boolean updateListener = false; Iterator<?> keys = resp.getObject().keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { JSONObject counts = resp.getObject().getJSONObject(key); int total = counts.getInt("total"); int unique = counts.getInt("unique"); if (total != prefHelper_.getActionTotalCount(key) || unique != prefHelper_.getActionUniqueCount(key)) { updateListener = true; } prefHelper_.setActionTotalCount(key, total); prefHelper_.setActionUniqueCount(key, unique); } catch (JSONException e) { e.printStackTrace(); } } final boolean finUpdateListener = updateListener; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (stateChangedCallback_ != null) { stateChangedCallback_.onStateChanged(finUpdateListener, null); } } }); } private void processRewardCounts(ServerResponse resp) { boolean updateListener = false; Iterator<?> keys = resp.getObject().keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { int credits = resp.getObject().getInt(key); if (credits != prefHelper_.getCreditCount(key)) { updateListener = true; } prefHelper_.setCreditCount(key, credits); } catch (JSONException e) { e.printStackTrace(); } } final boolean finUpdateListener = updateListener; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (stateChangedCallback_ != null) { stateChangedCallback_.onStateChanged(finUpdateListener, null); } } }); } private void processCreditHistory(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (creditHistoryCallback_ != null) { creditHistoryCallback_.onReceivingResponse(resp.getArray(), null); } } }); } private void processReferralCodeGet(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (getReferralCodeCallback_ != null) { try { JSONObject json; BranchDuplicateReferralCodeError error = null; // check if a valid referral code json is returned if (!resp.getObject().has(REFERRAL_CODE)) { json = new JSONObject(); json.put("error_message", "Failed to get referral code"); error = new BranchDuplicateReferralCodeError(); } else { json = resp.getObject(); } getReferralCodeCallback_.onInitFinished(json, error); } catch (JSONException e) { e.printStackTrace(); } } } }); } private void processReferralCodeValidation(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (validateReferralCodeCallback_ != null) { try { JSONObject json; BranchInvalidReferralCodeError error = null; // check if a valid referral code json is returned if (!resp.getObject().has(REFERRAL_CODE)) { json = new JSONObject(); json.put("error_message", "Invalid referral code"); error = new BranchInvalidReferralCodeError(); } else { json = resp.getObject(); } validateReferralCodeCallback_.onInitFinished(json, error); } catch (JSONException e) { e.printStackTrace(); } } } }); } private void processReferralCodeApply(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (applyReferralCodeCallback_ != null) { try { JSONObject json; BranchInvalidReferralCodeError error = null; // check if a valid referral code json is returned if (!resp.getObject().has(REFERRAL_CODE)) { json = new JSONObject(); json.put("error_message", "Invalid referral code"); error = new BranchInvalidReferralCodeError(); } else { json = resp.getObject(); } applyReferralCodeCallback_.onInitFinished(json, error); } catch (JSONException e) { e.printStackTrace(); } } } }); } public class ReferralNetworkCallback implements NetworkCallback { @Override public void finished(ServerResponse serverResponse) { if (serverResponse != null) { try { int status = serverResponse.getStatusCode(); String requestTag = serverResponse.getTag(); hasNetwork_ = true; if (status == 409) { if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate(null, new BranchDuplicateUrlError()); } } }); } else { Log.i("BranchSDK", "Branch API Error: Conflicting resource error code from API"); handleFailure(0); } requestQueue_.dequeue(); } else if (status >= 400 && status < 500) { if (serverResponse.getObject().has("error") && serverResponse.getObject().getJSONObject("error").has("message")) { Log.i("BranchSDK", "Branch API Error: " + serverResponse.getObject().getJSONObject("error").getString("message")); } if (lastRequestWasInit_ && !initFailed_) { initFailed_ = true; for (int i = 0; i < requestQueue_.getSize()-1; i++) { handleFailure(i); } } handleFailure(requestQueue_.getSize()-1); requestQueue_.dequeue(); } else if (status != 200) { if (status == RemoteInterface.NO_CONNECTIVITY_STATUS) { hasNetwork_ = false; handleFailure(lastRequestWasInit_ ? 0 : requestQueue_.getSize()-1); if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE)) { requestQueue_.dequeue(); } Log.i("BranchSDK", "Branch API Error: poor network connectivity. Please try again later."); } else if (status == RemoteInterface.NO_API_KEY_STATUS) { handleFailure(lastRequestWasInit_ ? 0 : requestQueue_.getSize()-1); Log.i("BranchSDK", "Branch API Error: Please enter your Branch App Key in your project's res/values/strings.xml first!"); } else { retryLastRequest(); } } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS)) { processReferralCounts(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) { processRewardCounts(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) { processCreditHistory(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) { prefHelper_.setDeviceFingerPrintID(serverResponse.getObject().getString("device_fingerprint_id")); prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE); if (prefHelper_.getIsReferrable() == 1) { if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setInstallParams(params); } else { prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE); } } if (serverResponse.getObject().has("link_click_id")) { prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id")); } else { prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE); } if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setSessionParams(params); } else { prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); } updateAllRequestsInQueue(); Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initSessionFinishedCallback_ != null) { initSessionFinishedCallback_.onInitFinished(getLatestReferringParams(), null); } } }); requestQueue_.dequeue(); initFinished_ = true; } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setDeviceFingerPrintID(serverResponse.getObject().getString("device_fingerprint_id")); prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE); if (serverResponse.getObject().has("identity_id")) { prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); } if (serverResponse.getObject().has("link_click_id")) { prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id")); } else { prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE); } if (prefHelper_.getIsReferrable() == 1) { if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setInstallParams(params); } } if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setSessionParams(params); } else { prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); } Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initSessionFinishedCallback_ != null) { initSessionFinishedCallback_.onInitFinished(getLatestReferringParams(), null); } } }); requestQueue_.dequeue(); initFinished_ = true; } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_SEND_APP_LIST)) { prefHelper_.clearSystemReadStatus(); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { final String url = serverResponse.getObject().getString("url"); // cache the link linkCache_.put(serverResponse.getLinkData(), url); Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate(url, null); } } }); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_LOGOUT)) { prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE); prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); prefHelper_.setIdentity(PrefHelper.NO_STRING_VALUE); prefHelper_.clearUserValues(); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) { prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); if (serverResponse.getObject().has("referring_data")) { String params = serverResponse.getObject().getString("referring_data"); prefHelper_.setInstallParams(params); } if (requestQueue_.getSize() > 0) { ServerRequest req = requestQueue_.peek(); if (req.getPost() != null && req.getPost().has("identity")) { prefHelper_.setIdentity(req.getPost().getString("identity")); } } Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initIdentityFinishedCallback_ != null) { initIdentityFinishedCallback_.onInitFinished(getFirstReferringParams(), null); } } }); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE)) { processReferralCodeGet(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE)) { processReferralCodeValidation(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE)) { processReferralCodeApply(serverResponse); requestQueue_.dequeue(); } else { requestQueue_.dequeue(); } networkCount_ = 0; if (hasNetwork_ && !initFailed_) { lastRequestWasInit_ = false; processNextQueueItem(); } } catch (JSONException ex) { ex.printStackTrace(); } } } } public interface BranchReferralInitListener { public void onInitFinished(JSONObject referringParams, BranchError error); } public interface BranchReferralStateChangedListener { public void onStateChanged(boolean changed, BranchError error); } public interface BranchLinkCreateListener { public void onLinkCreate(String url, BranchError error); } public interface BranchListResponseListener { public void onReceivingResponse(JSONArray list, BranchError error); } public enum CreditHistoryOrder { kMostRecentFirst, kLeastRecentFirst } public class BranchInitError extends BranchError { @Override public String getMessage() { return "Trouble initializing Branch. Check network connectivity or that your app key is valid"; } } public class BranchGetReferralsError extends BranchError { @Override public String getMessage() { return "Trouble retrieving referral counts. Check network connectivity and that you properly initialized"; } } public class BranchGetCreditsError extends BranchError { @Override public String getMessage() { return "Trouble retrieving user credits. Check network connectivity and that you properly initialized"; } } public class BranchGetCreditHistoryError extends BranchError { @Override public String getMessage() { return "Trouble retrieving user credit history. Check network connectivity and that you properly initialized"; } } public class BranchCreateUrlError extends BranchError { @Override public String getMessage() { return "Trouble creating a URL. Check network connectivity and that you properly initialized"; } } public class BranchDuplicateUrlError extends BranchError { @Override public String getMessage() { return "Trouble creating a URL with that alias. If you want to reuse the alias, make sure to submit the same properties for all arguments and that the user is the same owner"; } } public class BranchSetIdentityError extends BranchError { @Override public String getMessage() { return "Trouble setting the user alias. Check network connectivity and that you properly initialized"; } } public class BranchGetReferralCodeError extends BranchError { @Override public String getMessage() { return "Trouble retrieving the referral code. Check network connectivity and that you properly initialized"; } } public class BranchValidateReferralCodeError extends BranchError { @Override public String getMessage() { return "Trouble validating the referral code. Check network connectivity and that you properly initialized"; } } public class BranchInvalidReferralCodeError extends BranchError { @Override public String getMessage() { return "That Branch referral code was invalid"; } } public class BranchDuplicateReferralCodeError extends BranchError { @Override public String getMessage() { return "That Branch referral code is already in use"; } } public class BranchApplyReferralCodeError extends BranchError { @Override public String getMessage() { return "Trouble applying the referral code. Check network connectivity and that you properly initialized"; } } public class BranchNotInitError extends BranchError { @Override public String getMessage() { return "Did you forget to call init? Make sure you init the session before making Branch calls"; } } }
Branch-SDK/src/io/branch/referral/Branch.java
package io.branch.referral; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class Branch { public static final String FEATURE_TAG_SHARE = "share"; public static final String FEATURE_TAG_REFERRAL = "referral"; public static final String FEATURE_TAG_INVITE = "invite"; public static final String FEATURE_TAG_DEAL = "deal"; public static final String FEATURE_TAG_GIFT = "gift"; public static final String REDEEM_CODE = "$redeem_code"; public static final String REFERRAL_BUCKET_DEFAULT = "default"; public static final String REFERRAL_CODE_TYPE = "credit"; public static final int REFERRAL_CREATION_SOURCE_SDK = 2; public static final String REFERRAL_CODE = "referral_code"; public static final String REDIRECT_DESKTOP_URL = "$desktop_url"; public static final String REDIRECT_ANDROID_URL = "$android_url"; public static final String REDIRECT_IOS_URL = "$ios_url"; public static final String REDIRECT_IPAD_URL = "$ipad_url"; public static final String REDIRECT_FIRE_URL = "$fire_url"; public static final String REDIRECT_BLACKBERRY_URL = "$blackberry_url"; public static final String REDIRECT_WINDOWNS_PHONE_URL = "$windows_phone_url"; public static final String OG_TITLE = "$og_title"; public static final String OG_DESC = "$og_description"; public static final String OG_IMAGE_URL = "$og_image_url"; public static final String OG_VIDEO = "$og_video"; public static final String OG_URL = "$og_url"; public static final String OG_APP_ID = "$og_app_id"; public static final String DEEPLINK_PATH = "$deeplink_path"; public static final String ALWAYS_DEEPLINK = "$always_deeplink"; public static final int REFERRAL_CODE_LOCATION_REFERREE = 0; public static final int REFERRAL_CODE_LOCATION_REFERRING_USER = 2; public static final int REFERRAL_CODE_LOCATION_BOTH = 3; public static final int REFERRAL_CODE_AWARD_UNLIMITED = 1; public static final int REFERRAL_CODE_AWARD_UNIQUE = 0; public static final int LINK_TYPE_UNLIMITED_USE = 0; public static final int LINK_TYPE_ONE_TIME_USE = 1; private static final int SESSION_KEEPALIVE = 2000; private static final int PREVENT_CLOSE_TIMEOUT = 500; private static Branch branchReferral_; private boolean isInit_; private BranchReferralInitListener initSessionFinishedCallback_; private BranchReferralInitListener initIdentityFinishedCallback_; private BranchReferralStateChangedListener stateChangedCallback_; private BranchLinkCreateListener linkCreateCallback_; private BranchListResponseListener creditHistoryCallback_; private BranchReferralInitListener getReferralCodeCallback_; private BranchReferralInitListener validateReferralCodeCallback_; private BranchReferralInitListener applyReferralCodeCallback_; private BranchRemoteInterface kRemoteInterface_; private PrefHelper prefHelper_; private SystemObserver systemObserver_; private Context context_; final Object lock; private Timer closeTimer; private Timer rotateCloseTimer; private boolean keepAlive_; private Semaphore serverSema_; private ServerRequestQueue requestQueue_; private int networkCount_; private int retryCount_; private boolean initNotStarted_; private boolean initFinished_; private boolean initFailed_; private boolean hasNetwork_; private boolean lastRequestWasInit_; private Handler debugHandler_; private SparseArray<String> debugListenerInitHistory_; private OnTouchListener debugOnTouchListener_; private Map<BranchLinkData, String> linkCache_; private ScheduledFuture<?> appListingSchedule_; private Branch(Context context) { prefHelper_ = PrefHelper.getInstance(context); kRemoteInterface_ = new BranchRemoteInterface(context); systemObserver_ = new SystemObserver(context); kRemoteInterface_.setNetworkCallbackListener(new ReferralNetworkCallback()); requestQueue_ = ServerRequestQueue.getInstance(context); serverSema_ = new Semaphore(1); closeTimer = new Timer(); rotateCloseTimer = new Timer(); lock = new Object(); initFinished_ = false; initFailed_ = false; lastRequestWasInit_ = true; keepAlive_ = false; isInit_ = false; initNotStarted_ = true; networkCount_ = 0; hasNetwork_ = true; debugListenerInitHistory_ = new SparseArray<String>(); debugHandler_ = new Handler(); debugOnTouchListener_ = retrieveOnTouchListener(); linkCache_ = new HashMap<BranchLinkData, String>(); } @Deprecated public static Branch getInstance(Context context, String key) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context; branchReferral_.prefHelper_.setAppKey(key); return branchReferral_; } public static Branch getInstance(Context context) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); String appKey = branchReferral_.prefHelper_.getAppKey(); if (appKey == null || appKey.equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) { Log.i("BranchSDK", "Branch Warning: Please enter your Branch App Key in your project's res/values/strings.xml!"); } } branchReferral_.context_ = context; return branchReferral_; } private static Branch initInstance(Context context) { return new Branch(context.getApplicationContext()); } public void resetUserSession() { isInit_ = false; } public void setRetryCount(int retryCount) { if (prefHelper_ != null && retryCount > 0) { prefHelper_.setRetryCount(retryCount); } } public void setRetryInterval(int retryInterval) { if (prefHelper_ != null && retryInterval > 0) { prefHelper_.setRetryInterval(retryInterval); } } public void setNetworkTimeout(int timeout) { if (prefHelper_ != null && timeout > 0) { prefHelper_.setTimeout(timeout); } } // if you want to flag debug, call this before initUserSession public void setDebug() { prefHelper_.setExternDebug(); } public void disableAppList() { prefHelper_.disableExternAppListing(); } // Note: smart session - we keep session alive for two seconds // if there's further Branch API call happening within the two seconds, we then don't close the session; // otherwise, we close the session after two seconds // Call this method if you don't want this smart session feature public void disableSmartSession() { prefHelper_.disableSmartSession(); } public boolean initSession(BranchReferralInitListener callback) { initSession(callback, (Activity)null); return false; } public boolean initSession(BranchReferralInitListener callback, Activity activity) { if (systemObserver_.getUpdateState() == 0 && !hasUser()) { prefHelper_.setIsReferrable(); } else { prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback, activity); return false; } public boolean initSession(BranchReferralInitListener callback, Uri data) { return initSession(callback, data, null); } public boolean initSession(BranchReferralInitListener callback, Uri data, Activity activity) { boolean uriHandled = false; if (data != null && data.isHierarchical()) { if (data.getQueryParameter("link_click_id") != null) { uriHandled = true; prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(callback, activity); return uriHandled; } public boolean initSession() { return initSession((Activity)null); } public boolean initSession(Activity activity) { return initSession(null, activity); } public boolean initSessionWithData(Uri data) { return initSessionWithData(data, null); } public boolean initSessionWithData(Uri data, Activity activity) { boolean uriHandled = false; if (data != null && data.isHierarchical()) { if (data.getQueryParameter("link_click_id") != null) { uriHandled = true; prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(null, activity); return uriHandled; } public boolean initSession(boolean isReferrable) { return initSession(null, isReferrable, (Activity)null); } public boolean initSession(boolean isReferrable, Activity activity) { return initSession(null, isReferrable, activity); } public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data) { return initSession(callback, isReferrable, data, null); } public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data, Activity activity) { boolean uriHandled = false; if (data != null && data.isHierarchical()) { if (data.getQueryParameter("link_click_id") != null) { uriHandled = true; prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(callback, isReferrable, activity); return uriHandled; } public boolean initSession(BranchReferralInitListener callback, boolean isReferrable) { return initSession(callback, isReferrable, (Activity)null); } public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) { if (isReferrable) { this.prefHelper_.setIsReferrable(); } else { this.prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback, activity); return false; } private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity) { initSessionFinishedCallback_ = callback; lastRequestWasInit_ = true; initNotStarted_ = false; initFailed_ = false; if (!isInit_) { isInit_ = true; new Thread(new Runnable() { @Override public void run() { initializeSession(); } }).start(); } else { boolean installOrOpenInQueue = requestQueue_.containsInstallOrOpen(); if (hasUser() && hasSession() && !installOrOpenInQueue) { if (callback != null) callback.onInitFinished(new JSONObject(), null); clearCloseTimer(); keepAlive(); } else { if (!installOrOpenInQueue) { new Thread(new Runnable() { @Override public void run() { initializeSession(); } }).start(); } else { new Thread(new Runnable() { @Override public void run() { requestQueue_.moveInstallOrOpenToFront(null, networkCount_); processNextQueueItem(); } }).start(); } } } if (activity != null && debugListenerInitHistory_.get(System.identityHashCode(activity)) == null) { debugListenerInitHistory_.put(System.identityHashCode(activity), "init"); View view = activity.getWindow().getDecorView().findViewById(android.R.id.content); if (view != null) { view.setOnTouchListener(debugOnTouchListener_); } } } private OnTouchListener retrieveOnTouchListener() { if (debugOnTouchListener_ == null) { debugOnTouchListener_ = new OnTouchListener() { class KeepDebugConnectionTask extends TimerTask { public void run() { if (!prefHelper_.keepDebugConnection()) { debugHandler_.post(_longPressed); } } } Runnable _longPressed = new Runnable() { private boolean started = false; private Timer timer; public void run() { debugHandler_.removeCallbacks(_longPressed); if (!started) { Log.i("Branch Debug","======= Start Debug Session ======="); prefHelper_.setDebug(); timer = new Timer(); timer.scheduleAtFixedRate(new KeepDebugConnectionTask(), new Date(), 20000); } else { Log.i("Branch Debug","======= End Debug Session ======="); prefHelper_.clearDebug(); timer.cancel(); timer = null; } this.started = !this.started; } }; @Override public boolean onTouch(View v, MotionEvent ev) { int pointerCount = ev.getPointerCount(); final int actionPeformed = ev.getAction(); switch (actionPeformed & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: if (systemObserver_.isSimulator()) { debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_CANCEL: debugHandler_.removeCallbacks(_longPressed); break; case MotionEvent.ACTION_UP: v.performClick(); debugHandler_.removeCallbacks(_longPressed); break; case MotionEvent.ACTION_POINTER_DOWN: if (pointerCount == PrefHelper.DEBUG_TRIGGER_NUM_FINGERS) { debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; } return true; } }; } return debugOnTouchListener_; } public void closeSession() { if (prefHelper_.getSmartSession()) { if (keepAlive_) { return; } // else, real close synchronized(lock) { clearCloseTimer(); rotateCloseTimer.schedule(new TimerTask() { @Override public void run() { executeClose(); } }, PREVENT_CLOSE_TIMEOUT); } } else { executeClose(); } if (prefHelper_.getExternAppListing()) { if (appListingSchedule_ == null) { scheduleListOfApps(); } } } private void executeClose() { isInit_ = false; lastRequestWasInit_ = false; initNotStarted_ = true; if (!hasNetwork_) { // if there's no network connectivity, purge the old install/open ServerRequest req = requestQueue_.peek(); if (req != null && (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN))) { requestQueue_.dequeue(); } } else { new Thread(new Runnable() { @Override public void run() { if (!requestQueue_.containsClose()) { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE, null); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } } }).start(); } } public void setIdentity(String userId, BranchReferralInitListener callback) { initIdentityFinishedCallback_ = callback; setIdentity(userId); } public void setIdentity(final String userId) { if (userId == null || userId.length() == 0 || userId.equals(prefHelper_.getIdentity())) { return; } new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("identity", userId); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_IDENTIFY, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void logout() { new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_LOGOUT, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void loadActionCounts() { loadActionCounts(null); } public void loadActionCounts(BranchReferralStateChangedListener callback) { stateChangedCallback_ = callback; new Thread(new Runnable() { @Override public void run() { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS, null); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void loadRewards() { loadRewards(null); } public void loadRewards(BranchReferralStateChangedListener callback) { stateChangedCallback_ = callback; new Thread(new Runnable() { @Override public void run() { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARDS, null); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public int getCredits() { return prefHelper_.getCreditCount(); } public int getCreditsForBucket(String bucket) { return prefHelper_.getCreditCount(bucket); } public int getTotalCountsForAction(String action) { return prefHelper_.getActionTotalCount(action); } public int getUniqueCountsForAction(String action) { return prefHelper_.getActionUniqueCount(action); } public void redeemRewards(int count) { redeemRewards("default", count); } public void redeemRewards(final String bucket, final int count) { new Thread(new Runnable() { @Override public void run() { int creditsToRedeem; int credits = prefHelper_.getCreditCount(bucket); if (count > credits) { creditsToRedeem = credits; Log.i("BranchSDK", "Branch Warning: You're trying to redeem more credits than are available. Have you updated loaded rewards"); } else { creditsToRedeem = count; } if (creditsToRedeem > 0) { retryCount_ = 0; JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("bucket", bucket); post.put("amount", creditsToRedeem); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } } }).start(); } public void getCreditHistory(BranchListResponseListener callback) { getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } public void getCreditHistory(final String bucket, BranchListResponseListener callback) { getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } public void getCreditHistory(final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { getCreditHistory(null, afterId, length, order, callback); } public void getCreditHistory(final String bucket, final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { creditHistoryCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("length", length); post.put("direction", order.ordinal()); if (bucket != null) { post.put("bucket", bucket); } if (afterId != null) { post.put("begin_after_id", afterId); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void userCompletedAction(final String action, final JSONObject metadata) { new Thread(new Runnable() { @Override public void run() { retryCount_ = 0; JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("event", action); if (metadata != null) post.put("metadata", filterOutBadCharacters(metadata)); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void userCompletedAction(final String action) { userCompletedAction(action, null); } public JSONObject getFirstReferringParams() { String storedParam = prefHelper_.getInstallParams(); return convertParamsStringToDictionary(storedParam); } public JSONObject getLatestReferringParams() { String storedParam = prefHelper_.getSessionParams(); return convertParamsStringToDictionary(storedParam); } public String getShortUrlSync() { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(null), null, false); } public String getShortUrlSync(JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getReferralUrlSync(String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getReferralUrlSync(Collection<String> tags, String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getContentUrlSync(String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getContentUrlSync(Collection<String> tags, String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String alias, String channel, String feature, String stage, JSONObject params) { return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(int type, String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, type, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String channel, String feature, String stage, JSONObject params, int duration) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params) { return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, type, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public void getShortUrl(BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(null), callback, true); } public void getShortUrl(JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getReferralUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getReferralUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getContentUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getContentUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String alias, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(int type, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, type, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, type, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getReferralCode(BranchReferralInitListener callback) { getReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void getReferralCode(final int amount, BranchReferralInitListener callback) { this.getReferralCode(null, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final String prefix, final int amount, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final int amount, final Date expiration, BranchReferralInitListener callback) { this.getReferralCode(null, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final String prefix, final int amount, final Date expiration, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final String prefix, final int amount, final int calculationType, final int location, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, calculationType, location, callback); } public void getReferralCode(final String prefix, final int amount, final Date expiration, final String bucket, final int calculationType, final int location, BranchReferralInitListener callback) { getReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("calculation_type", calculationType); post.put("location", location); post.put("type", REFERRAL_CODE_TYPE); post.put("creation_source", REFERRAL_CREATION_SOURCE_SDK); post.put("amount", amount); post.put("bucket", bucket != null ? bucket : REFERRAL_BUCKET_DEFAULT); if (prefix != null && prefix.length() > 0) { post.put("prefix", prefix); } if (expiration != null) { post.put("expiration", convertDate(expiration)); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void validateReferralCode(final String code, BranchReferralInitListener callback) { validateReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("referral_code", code); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void applyReferralCode(final String code, final BranchReferralInitListener callback) { applyReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put("link_click_id", prefHelper_.getLinkClickID()); } post.put("referral_code", code); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } // PRIVATE FUNCTIONS private String convertDate(Date date) { return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString(); } private String stringifyParams(JSONObject params) { if (params == null) { params = new JSONObject(); } try { params.put("source", "android"); } catch (JSONException e) { e.printStackTrace(); } return params.toString(); } private String generateShortLink(final String alias, final int type, final int duration, final Collection<String> tags, final String channel, final String feature, final String stage, final String params, BranchLinkCreateListener callback, boolean async) { linkCreateCallback_ = callback; if (hasUser()) { final BranchLinkData linkPost = new BranchLinkData(); try { linkPost.put("app_id", prefHelper_.getAppKey()); linkPost.put("identity_id", prefHelper_.getIdentityID()); linkPost.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); linkPost.put("session_id", prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { linkPost.put("link_click_id", prefHelper_.getLinkClickID()); } linkPost.putType(type); linkPost.putDuration(duration); linkPost.putTags(tags); linkPost.putAlias(alias); linkPost.putChannel(channel); linkPost.putFeature(feature); linkPost.putStage(stage); linkPost.putParams(params); } catch (JSONException ex) { ex.printStackTrace(); } if (linkCache_.containsKey(linkPost)) { String url = linkCache_.get(linkPost); if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate(url, null); } return url; } else { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL, linkPost); if (async) { generateShortLinkAsync(req); } else { return generateShortLinkSync(req); } } } return null; } private String generateShortLinkSync(ServerRequest req) { if (!initFailed_ && initFinished_ && hasNetwork_) { ServerResponse response = kRemoteInterface_.createCustomUrlSync(req.getPost()); String url = prefHelper_.getUserURL(); if (response.getStatusCode() == 200) { try { url = response.getObject().getString("url"); if (response.getLinkData() != null) { linkCache_.put(response.getLinkData(), url); } } catch (JSONException e) { e.printStackTrace(); } } return url; } else { Log.i("BranchSDK", "Branch Warning: User session has not been initialized"); } return null; } private void generateShortLinkAsync(final ServerRequest req) { new Thread(new Runnable() { @Override public void run() { if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } private JSONObject filterOutBadCharacters(JSONObject inputObj) { JSONObject filteredObj = new JSONObject(); if (inputObj != null) { Iterator<?> keys = inputObj.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { if (inputObj.has(key) && inputObj.get(key).getClass().equals(String.class)) { filteredObj.put(key, inputObj.getString(key).replace("\n", "\\n").replace("\r", "\\r").replace("\"", "\\\"")); } else if (inputObj.has(key)) { filteredObj.put(key, inputObj.get(key)); } } catch(JSONException ignore) { } } } return filteredObj; } private JSONObject convertParamsStringToDictionary(String paramString) { if (paramString.equals(PrefHelper.NO_STRING_VALUE)) { return new JSONObject(); } else { try { return new JSONObject(paramString); } catch (JSONException e) { byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP); try { return new JSONObject(new String(encodedArray)); } catch (JSONException ex) { ex.printStackTrace(); return new JSONObject(); } } } } private void scheduleListOfApps() { ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1); Runnable periodicTask = new Runnable(){ @Override public void run() { SystemObserver sysObserver = new SystemObserver(context_); JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); if (!sysObserver.getOS().equals(SystemObserver.BLANK)) post.put("os", sysObserver.getOS()); post.put("device_fingerprint_id", prefHelper_.getDeviceFingerPrintID()); post.put("apps_data", sysObserver.getListOfApps()); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_SEND_APP_LIST, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } } }; Date date = new Date(); Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(date); int days = Calendar.SATURDAY - calendar.get(Calendar.DAY_OF_WEEK); // days to Saturday int hours = 2 - calendar.get(Calendar.HOUR_OF_DAY); // hours to 2am, can be negative if (days == 0 && hours < 0) { days = 7; } int interval = 7 * 24 * 60 * 60; appListingSchedule_ = scheduler.scheduleAtFixedRate(periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS); } private void processNextQueueItem() { try { serverSema_.acquire(); if (networkCount_ == 0 && requestQueue_.getSize() > 0) { networkCount_ = 1; ServerRequest req = requestQueue_.peek(); serverSema_.release(); if (!req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) && !hasUser()) { Log.i("BranchSDK", "Branch Error: User session has not been initialized!"); networkCount_ = 0; handleFailure(requestQueue_.getSize()-1); return; } if (!req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE) && !req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { keepAlive(); clearCloseTimer(); } if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) { kRemoteInterface_.registerInstall(PrefHelper.NO_STRING_VALUE, prefHelper_.isDebug()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { kRemoteInterface_.registerOpen(prefHelper_.isDebug()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS) && hasSession()) { kRemoteInterface_.getReferralCounts(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_SEND_APP_LIST) && hasSession()) { kRemoteInterface_.registerListOfApps(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS) && hasSession()) { kRemoteInterface_.getRewards(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS) && hasSession()) { kRemoteInterface_.redeemRewards(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY) && hasSession()) { kRemoteInterface_.getCreditHistory(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION) && hasSession()) { kRemoteInterface_.userCompletedAction(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL) && hasSession()) { kRemoteInterface_.createCustomUrl(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY) && hasSession()) { kRemoteInterface_.identifyUser(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE) && hasSession()) { kRemoteInterface_.registerClose(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_LOGOUT) && hasSession()) { kRemoteInterface_.logoutUser(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE) && hasSession()) { kRemoteInterface_.getReferralCode(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE) && hasSession()) { kRemoteInterface_.validateReferralCode(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE) && hasSession()) { kRemoteInterface_.applyReferralCode(req.getPost()); } } else { serverSema_.release(); } } catch (Exception e) { e.printStackTrace(); } } private void handleFailure(int index) { ServerRequest req; if (index >= requestQueue_.getSize()) { req = requestQueue_.peekAt(requestQueue_.getSize()-1); } else { req = requestQueue_.peekAt(index); } handleFailure(req); } private void handleFailure(final ServerRequest req) { if (req == null) return; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { if (initSessionFinishedCallback_ != null) { JSONObject obj = new JSONObject(); try { obj.put("error_message", "Trouble reaching server. Please try again in a few minutes"); } catch (JSONException ex) { ex.printStackTrace(); } initSessionFinishedCallback_.onInitFinished(obj, new BranchInitError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS)) { if (stateChangedCallback_ != null) { if (initNotStarted_) stateChangedCallback_.onStateChanged(false, new BranchNotInitError()); else stateChangedCallback_.onStateChanged(false, new BranchGetReferralsError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) { if (stateChangedCallback_ != null) { if (initNotStarted_) stateChangedCallback_.onStateChanged(false, new BranchNotInitError()); else stateChangedCallback_.onStateChanged(false, new BranchGetCreditsError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) { if (creditHistoryCallback_ != null) { if (initNotStarted_) creditHistoryCallback_.onReceivingResponse(null, new BranchNotInitError()); else creditHistoryCallback_.onReceivingResponse(null, new BranchGetCreditHistoryError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { if (linkCreateCallback_ != null) { String failedUrl = null; if (!prefHelper_.getUserURL().equals(PrefHelper.NO_STRING_VALUE)) { failedUrl = prefHelper_.getUserURL(); } if (initNotStarted_) linkCreateCallback_.onLinkCreate(null, new BranchNotInitError()); else linkCreateCallback_.onLinkCreate(failedUrl, new BranchCreateUrlError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) { if (initIdentityFinishedCallback_ != null) { JSONObject obj = new JSONObject(); try { obj.put("error_message", "Trouble reaching server. Please try again in a few minutes"); } catch (JSONException ex) { ex.printStackTrace(); } if (initNotStarted_) initIdentityFinishedCallback_.onInitFinished(obj, new BranchNotInitError()); else initIdentityFinishedCallback_.onInitFinished(obj, new BranchSetIdentityError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE)) { if (getReferralCodeCallback_ != null) { if (initNotStarted_) getReferralCodeCallback_.onInitFinished(null, new BranchNotInitError()); else getReferralCodeCallback_.onInitFinished(null, new BranchGetReferralCodeError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE)) { if (validateReferralCodeCallback_ != null) { if (initNotStarted_) validateReferralCodeCallback_.onInitFinished(null, new BranchNotInitError()); else validateReferralCodeCallback_.onInitFinished(null, new BranchValidateReferralCodeError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE)) { if (applyReferralCodeCallback_ != null) { if (initNotStarted_) applyReferralCodeCallback_.onInitFinished(null, new BranchNotInitError()); else applyReferralCodeCallback_.onInitFinished(null, new BranchApplyReferralCodeError()); } } } }); } private void retryLastRequest() { retryCount_ = retryCount_ + 1; if (retryCount_ > prefHelper_.getRetryCount()) { handleFailure(0); requestQueue_.dequeue(); retryCount_ = 0; } else { try { Thread.sleep(prefHelper_.getRetryInterval()); } catch (InterruptedException e) { e.printStackTrace(); } } } private void updateAllRequestsInQueue() { try { for (int i = 0; i < requestQueue_.getSize(); i++) { ServerRequest req = requestQueue_.peekAt(i); if (req.getPost() != null) { Iterator<?> keys = req.getPost().keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("app_id")) { req.getPost().put(key, prefHelper_.getAppKey()); } else if (key.equals("session_id")) { req.getPost().put(key, prefHelper_.getSessionID()); } else if (key.equals("identity_id")) { req.getPost().put(key, prefHelper_.getIdentityID()); } } } } } catch (JSONException e) { e.printStackTrace(); } } private void clearCloseTimer() { if (rotateCloseTimer == null) return; rotateCloseTimer.cancel(); rotateCloseTimer.purge(); rotateCloseTimer = new Timer(); } private void clearTimer() { if (closeTimer == null) return; closeTimer.cancel(); closeTimer.purge(); closeTimer = new Timer(); } private void keepAlive() { keepAlive_ = true; synchronized(lock) { clearTimer(); closeTimer.schedule(new TimerTask() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { keepAlive_ = false; } }).start(); } }, SESSION_KEEPALIVE); } } private boolean hasSession() { return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasUser() { return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE); } private void insertRequestAtFront(ServerRequest req) { if (networkCount_ == 0) { requestQueue_.insert(req, 0); } else { requestQueue_.insert(req, 1); } } private void registerInstallOrOpen(String tag) { if (!requestQueue_.containsInstallOrOpen()) { insertRequestAtFront(new ServerRequest(tag)); } else { requestQueue_.moveInstallOrOpenToFront(tag, networkCount_); } processNextQueueItem(); } private void initializeSession() { if (hasUser()) { registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN); } else { registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL); } } private void processReferralCounts(ServerResponse resp) { boolean updateListener = false; Iterator<?> keys = resp.getObject().keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { JSONObject counts = resp.getObject().getJSONObject(key); int total = counts.getInt("total"); int unique = counts.getInt("unique"); if (total != prefHelper_.getActionTotalCount(key) || unique != prefHelper_.getActionUniqueCount(key)) { updateListener = true; } prefHelper_.setActionTotalCount(key, total); prefHelper_.setActionUniqueCount(key, unique); } catch (JSONException e) { e.printStackTrace(); } } final boolean finUpdateListener = updateListener; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (stateChangedCallback_ != null) { stateChangedCallback_.onStateChanged(finUpdateListener, null); } } }); } private void processRewardCounts(ServerResponse resp) { boolean updateListener = false; Iterator<?> keys = resp.getObject().keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { int credits = resp.getObject().getInt(key); if (credits != prefHelper_.getCreditCount(key)) { updateListener = true; } prefHelper_.setCreditCount(key, credits); } catch (JSONException e) { e.printStackTrace(); } } final boolean finUpdateListener = updateListener; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (stateChangedCallback_ != null) { stateChangedCallback_.onStateChanged(finUpdateListener, null); } } }); } private void processCreditHistory(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (creditHistoryCallback_ != null) { creditHistoryCallback_.onReceivingResponse(resp.getArray(), null); } } }); } private void processReferralCodeGet(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (getReferralCodeCallback_ != null) { try { JSONObject json; BranchDuplicateReferralCodeError error = null; // check if a valid referral code json is returned if (!resp.getObject().has(REFERRAL_CODE)) { json = new JSONObject(); json.put("error_message", "Failed to get referral code"); error = new BranchDuplicateReferralCodeError(); } else { json = resp.getObject(); } getReferralCodeCallback_.onInitFinished(json, error); } catch (JSONException e) { e.printStackTrace(); } } } }); } private void processReferralCodeValidation(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (validateReferralCodeCallback_ != null) { try { JSONObject json; BranchInvalidReferralCodeError error = null; // check if a valid referral code json is returned if (!resp.getObject().has(REFERRAL_CODE)) { json = new JSONObject(); json.put("error_message", "Invalid referral code"); error = new BranchInvalidReferralCodeError(); } else { json = resp.getObject(); } validateReferralCodeCallback_.onInitFinished(json, error); } catch (JSONException e) { e.printStackTrace(); } } } }); } private void processReferralCodeApply(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (applyReferralCodeCallback_ != null) { try { JSONObject json; BranchInvalidReferralCodeError error = null; // check if a valid referral code json is returned if (!resp.getObject().has(REFERRAL_CODE)) { json = new JSONObject(); json.put("error_message", "Invalid referral code"); error = new BranchInvalidReferralCodeError(); } else { json = resp.getObject(); } applyReferralCodeCallback_.onInitFinished(json, error); } catch (JSONException e) { e.printStackTrace(); } } } }); } public class ReferralNetworkCallback implements NetworkCallback { @Override public void finished(ServerResponse serverResponse) { if (serverResponse != null) { try { int status = serverResponse.getStatusCode(); String requestTag = serverResponse.getTag(); hasNetwork_ = true; if (status == 409) { if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate(null, new BranchDuplicateUrlError()); } } }); } else { Log.i("BranchSDK", "Branch API Error: Conflicting resource error code from API"); handleFailure(0); } requestQueue_.dequeue(); } else if (status >= 400 && status < 500) { if (serverResponse.getObject().has("error") && serverResponse.getObject().getJSONObject("error").has("message")) { Log.i("BranchSDK", "Branch API Error: " + serverResponse.getObject().getJSONObject("error").getString("message")); } if (lastRequestWasInit_ && !initFailed_) { initFailed_ = true; for (int i = 0; i < requestQueue_.getSize()-1; i++) { handleFailure(i); } } handleFailure(requestQueue_.getSize()-1); requestQueue_.dequeue(); } else if (status != 200) { if (status == RemoteInterface.NO_CONNECTIVITY_STATUS) { hasNetwork_ = false; handleFailure(lastRequestWasInit_ ? 0 : requestQueue_.getSize()-1); if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE)) { requestQueue_.dequeue(); } Log.i("BranchSDK", "Branch API Error: poor network connectivity. Please try again later."); } else if (status == RemoteInterface.NO_API_KEY_STATUS) { handleFailure(lastRequestWasInit_ ? 0 : requestQueue_.getSize()-1); Log.i("BranchSDK", "Branch API Error: Please enter your Branch App Key in your project's res/values/strings.xml first!"); } else { retryLastRequest(); } } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS)) { processReferralCounts(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) { processRewardCounts(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) { processCreditHistory(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) { prefHelper_.setDeviceFingerPrintID(serverResponse.getObject().getString("device_fingerprint_id")); prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE); if (prefHelper_.getIsReferrable() == 1) { if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setInstallParams(params); } else { prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE); } } if (serverResponse.getObject().has("link_click_id")) { prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id")); } else { prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE); } if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setSessionParams(params); } else { prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); } updateAllRequestsInQueue(); Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initSessionFinishedCallback_ != null) { initSessionFinishedCallback_.onInitFinished(getLatestReferringParams(), null); } } }); requestQueue_.dequeue(); initFinished_ = true; } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setDeviceFingerPrintID(serverResponse.getObject().getString("device_fingerprint_id")); prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE); if (serverResponse.getObject().has("identity_id")) { prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); } if (serverResponse.getObject().has("link_click_id")) { prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id")); } else { prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE); } if (prefHelper_.getIsReferrable() == 1) { if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setInstallParams(params); } } if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setSessionParams(params); } else { prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); } Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initSessionFinishedCallback_ != null) { initSessionFinishedCallback_.onInitFinished(getLatestReferringParams(), null); } } }); requestQueue_.dequeue(); initFinished_ = true; } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_SEND_APP_LIST)) { prefHelper_.clearSystemReadStatus(); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { final String url = serverResponse.getObject().getString("url"); // cache the link linkCache_.put(serverResponse.getLinkData(), url); Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate(url, null); } } }); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_LOGOUT)) { prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE); prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); prefHelper_.setIdentity(PrefHelper.NO_STRING_VALUE); prefHelper_.clearUserValues(); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) { prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); if (serverResponse.getObject().has("referring_data")) { String params = serverResponse.getObject().getString("referring_data"); prefHelper_.setInstallParams(params); } if (requestQueue_.getSize() > 0) { ServerRequest req = requestQueue_.peek(); if (req.getPost() != null && req.getPost().has("identity")) { prefHelper_.setIdentity(req.getPost().getString("identity")); } } Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initIdentityFinishedCallback_ != null) { initIdentityFinishedCallback_.onInitFinished(getFirstReferringParams(), null); } } }); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE)) { processReferralCodeGet(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE)) { processReferralCodeValidation(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE)) { processReferralCodeApply(serverResponse); requestQueue_.dequeue(); } else { requestQueue_.dequeue(); } networkCount_ = 0; if (hasNetwork_ && !initFailed_) { lastRequestWasInit_ = false; processNextQueueItem(); } } catch (JSONException ex) { ex.printStackTrace(); } } } } public interface BranchReferralInitListener { public void onInitFinished(JSONObject referringParams, BranchError error); } public interface BranchReferralStateChangedListener { public void onStateChanged(boolean changed, BranchError error); } public interface BranchLinkCreateListener { public void onLinkCreate(String url, BranchError error); } public interface BranchListResponseListener { public void onReceivingResponse(JSONArray list, BranchError error); } public enum CreditHistoryOrder { kMostRecentFirst, kLeastRecentFirst } public class BranchInitError extends BranchError { @Override public String getMessage() { return "Trouble initializing Branch. Check network connectivity or that your app key is valid"; } } public class BranchGetReferralsError extends BranchError { @Override public String getMessage() { return "Trouble retrieving referral counts. Check network connectivity and that you properly initialized"; } } public class BranchGetCreditsError extends BranchError { @Override public String getMessage() { return "Trouble retrieving user credits. Check network connectivity and that you properly initialized"; } } public class BranchGetCreditHistoryError extends BranchError { @Override public String getMessage() { return "Trouble retrieving user credit history. Check network connectivity and that you properly initialized"; } } public class BranchCreateUrlError extends BranchError { @Override public String getMessage() { return "Trouble creating a URL. Check network connectivity and that you properly initialized"; } } public class BranchDuplicateUrlError extends BranchError { @Override public String getMessage() { return "Trouble creating a URL with that alias. If you want to reuse the alias, make sure to submit the same properties for all arguments and that the user is the same owner"; } } public class BranchSetIdentityError extends BranchError { @Override public String getMessage() { return "Trouble setting the user alias. Check network connectivity and that you properly initialized"; } } public class BranchGetReferralCodeError extends BranchError { @Override public String getMessage() { return "Trouble retrieving the referral code. Check network connectivity and that you properly initialized"; } } public class BranchValidateReferralCodeError extends BranchError { @Override public String getMessage() { return "Trouble validating the referral code. Check network connectivity and that you properly initialized"; } } public class BranchInvalidReferralCodeError extends BranchError { @Override public String getMessage() { return "That Branch referral code was invalid"; } } public class BranchDuplicateReferralCodeError extends BranchError { @Override public String getMessage() { return "That Branch referral code is already in use"; } } public class BranchApplyReferralCodeError extends BranchError { @Override public String getMessage() { return "Trouble applying the referral code. Check network connectivity and that you properly initialized"; } } public class BranchNotInitError extends BranchError { @Override public String getMessage() { return "Did you forget to call init? Make sure you init the session before making Branch calls"; } } }
Pushing latest JavaDocs work.
Branch-SDK/src/io/branch/referral/Branch.java
Pushing latest JavaDocs work.
<ide><path>ranch-SDK/src/io/branch/referral/Branch.java <ide> import android.view.View; <ide> import android.view.View.OnTouchListener; <ide> <add>/** <add> * The core object required when using Branch SDK. You should declare an object of this type at the <add> * class-level of each Activity or Fragment that you wish to use Branch functionality within. <add> * <add> * <add> */ <ide> public class Branch { <ide> public static final String FEATURE_TAG_SHARE = "share"; <ide> public static final String FEATURE_TAG_REFERRAL = "referral";
Java
apache-2.0
eb2d2bb4a4b8e436da1bbe7c3b783c9d64541b3c
0
dasein-cloud/dasein-cloud-azure,greese/dasein-cloud-azure,daniellemayne/dasein-cloud-azure,vladmunthiu/dasein-cloud-azure,daniellemayne/dasein-cloud-azure_old,JanewzhWang/dasein-cloud-azure,drewlyall/dasein-cloud-azure,jeffrey-yan/dasein-cloud-azure
/** * Copyright (C) 2012 enStratus Networks Inc * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.azure.compute.vm; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.Requirement; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.Tag; import org.dasein.cloud.azure.Azure; import org.dasein.cloud.azure.AzureConfigException; import org.dasein.cloud.azure.AzureMethod; import org.dasein.cloud.azure.AzureService; import org.dasein.cloud.azure.compute.image.AzureMachineImage; import org.dasein.cloud.compute.AbstractVMSupport; import org.dasein.cloud.compute.Architecture; import org.dasein.cloud.compute.ImageClass; import org.dasein.cloud.compute.MachineImage; import org.dasein.cloud.compute.Platform; import org.dasein.cloud.compute.VMFilterOptions; import org.dasein.cloud.compute.VMLaunchOptions; import org.dasein.cloud.compute.VMScalingCapabilities; import org.dasein.cloud.compute.VMScalingOptions; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.VirtualMachineProduct; import org.dasein.cloud.compute.VmState; import org.dasein.cloud.compute.VmStatistics; import org.dasein.cloud.dc.DataCenter; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.network.Subnet; import org.dasein.cloud.network.VLAN; import org.dasein.cloud.util.APITrace; import org.dasein.util.CalendarWrapper; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Storage; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * Implements virtual machine support for Microsoft Azure. * @author George Reese ([email protected]) * @author Qunying Huang * @since 2012.04.1 initial version * @version 2012.04.1 * @version 2012.09 updated for model changes */ public class AzureVM extends AbstractVMSupport { static private final Logger logger = Azure.getLogger(AzureVM.class); static public final String HOSTED_SERVICES = "/services/hostedservices"; private Azure provider; public AzureVM(Azure provider) { super(provider); this.provider = provider; } @Override public void start(@Nonnull String vmId) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".Boot()"); } VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } String serviceName, deploymentName, roleName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); roleName = vm.getTag("roleName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roleInstances/" + roleName + "/Operations"; logger.debug("_______________________________________________________"); logger.debug("Start operation - "+resourceDir); try{ AzureMethod method = new AzureMethod(provider); StringBuilder xml = new StringBuilder(); xml.append("<StartRoleOperation xmlns=\"http://schemas.microsoft.com/windowsazure\""); xml.append(" "); xml.append("xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("\n"); xml.append("<OperationType>StartRoleOperation</OperationType>"); xml.append("\n"); xml.append("</StartRoleOperation>"); xml.append("\n"); logger.debug(xml); logger.debug("___________________________________________________"); method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); }finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".launch()"); } } } @Override public VirtualMachine alterVirtualMachine(@Nonnull String vmId, @Nonnull VMScalingOptions options) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".alterVM()"); } if (vmId == null || options.getProviderProductId() == null) { throw new AzureConfigException("No vmid and/or product id set for this operation"); } String[] parts = options.getProviderProductId().split(":"); String productId = null; String disks = ""; if (parts.length == 1) { productId=parts[0]; } else if (parts.length == 2) { productId = parts[0]; disks = parts[1].replace("[","").replace("]",""); } else { throw new InternalException("Invalid product id string. Product id format is PRODUCT_NAME or PRODUCT_NAME:[disk_0_size,disk_1_size,disk_n_size]"); } //check the product id is legitimate boolean found = false; Iterable<VirtualMachineProduct> products = listProducts(Architecture.I64); for (VirtualMachineProduct p : products) { if (p.getProviderProductId().equals(productId)) { found = true; break; } } if (!found) { throw new InternalException("Product id invalid: should be one of ExtraSmall, Small, Medium, Large, ExtraLarge"); } String[] diskSizes = disks.split(","); VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } String serviceName, deploymentName, roleName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); roleName = vm.getTag("roleName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/" + roleName; try{ AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir); StringBuilder xml = new StringBuilder(); NodeList roles = doc.getElementsByTagName("PersistentVMRole"); Node role = roles.item(0); NodeList entries = role.getChildNodes(); boolean changeProduct = false; for (int i = 0; i<entries.getLength(); i++) { Node vn = entries.item(i); String vnName = vn.getNodeName(); if( vnName.equalsIgnoreCase("RoleSize") && vn.hasChildNodes() ) { if (!productId.equals(vn.getFirstChild().getNodeValue())) { vn.getFirstChild().setNodeValue(productId); changeProduct=true; } else { logger.info("No product change required"); } break; } } String requestId=null; if (changeProduct) { String output=""; try{ TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); output = writer.getBuffer().toString().replaceAll("\n|\r", ""); } catch (Exception e){ System.err.println(e); } xml.append(output); logger.debug(xml); logger.debug("___________________________________________________"); resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/" + roleName; requestId = method.invoke("PUT", ctx.getAccountNumber(), resourceDir, xml.toString()); } else { requestId="noChange"; } if (requestId != null) { int httpCode = -1; if (!requestId.equals("noChange")) { httpCode = method.getOperationStatus(requestId); while (httpCode == -1) { try { Thread.sleep(15000L); } catch (InterruptedException ignored){} httpCode = method.getOperationStatus(requestId); } } if (httpCode == HttpServletResponse.SC_OK || requestId.equals("noChange")) { //attach any disks as appropriate for (int i = 0; i < diskSizes.length; i++) { if (!diskSizes[i].equals("")) { xml = new StringBuilder(); xml.append("<DataVirtualHardDisk xmlns=\"http://schemas.microsoft.com/windowsazure\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("<HostCaching>ReadWrite</HostCaching>"); xml.append("<LogicalDiskSizeInGB>").append(diskSizes[i]).append("</LogicalDiskSizeInGB>"); xml.append("<MediaLink>").append(provider.getStorageEndpoint()).append("vhds/").append(roleName).append(System.currentTimeMillis()%10000).append(".vhd</MediaLink>"); xml.append("</DataVirtualHardDisk>"); logger.debug(xml); resourceDir = HOSTED_SERVICES + "/" +serviceName+ "/deployments" + "/" + deploymentName + "/roles"+"/" + roleName+ "/DataDisks"; requestId = method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); if (requestId != null) { httpCode = method.getOperationStatus(requestId); while (httpCode == -1) { try { Thread.sleep(15000L); } catch (InterruptedException ignored){} httpCode = method.getOperationStatus(requestId); } } } } } } return getVirtualMachine(vmId); }finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".alterVM()"); } } } @Override public @Nonnull VirtualMachine clone(@Nonnull String vmId, @Nonnull String intoDcId, @Nonnull String name, @Nonnull String description, boolean powerOn, @Nullable String... firewallIds) throws InternalException, CloudException { throw new OperationNotSupportedException("Not supported in Microsoft Azure"); } @Override public VMScalingCapabilities describeVerticalScalingCapabilities() throws CloudException, InternalException { return VMScalingCapabilities.getInstance(false,true,Requirement.REQUIRED,Requirement.NONE); } @Override public void disableAnalytics(String vmId) throws InternalException, CloudException { // NO-OP } @Override public void enableAnalytics(String vmId) throws InternalException, CloudException { // NO-OP } @Override public @Nonnull String getConsoleOutput(@Nonnull String vmId) throws InternalException, CloudException { return ""; } @Override public int getCostFactor(@Nonnull VmState state) throws InternalException, CloudException { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getMaximumVirtualMachineCount() throws CloudException, InternalException { return -2; } @Override public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException { for( VirtualMachineProduct product : listProducts(Architecture.I64) ) { if( product.getProviderProductId().equals(productId) ) { return product; } } return null; } @Override public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) { return "virtual machine"; } @Override public @Nullable VirtualMachine getVirtualMachine(@Nonnull String vmId) throws InternalException, CloudException { String[] parts = vmId.split(":"); String sName, deploymentName, roleName; if (parts.length == 3) { sName = parts[0]; deploymentName = parts[1]; roleName= parts[2]; } else if( parts.length == 2 ) { sName = parts[0]; deploymentName = parts[1]; roleName = sName; } else { sName = vmId; deploymentName = vmId; roleName = vmId; } DataCenter dc = null; ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES+ "/"+sName); if (doc == null) { return null; } NodeList entries = doc.getElementsByTagName("HostedService"); ArrayList<VirtualMachine> vms = new ArrayList<VirtualMachine>(); for (int h = 0; h < entries.getLength(); h++) { Node entry = entries.item(h); NodeList attributes = entry.getChildNodes(); boolean mediaLocationFound = false; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if(attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("hostedserviceproperties") && attribute.hasChildNodes() ) { NodeList properties = attribute.getChildNodes(); for( int j=0; j<properties.getLength(); j++ ) { Node property = properties.item(j); if(property.getNodeType() == Node.TEXT_NODE) { continue; } if( property.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes() ) { //get the region for this affinity group String affinityGroup = property.getFirstChild().getNodeValue().trim(); if (affinityGroup != null && !affinityGroup.equals("")) { dc = provider.getDataCenterServices().getDataCenter(affinityGroup); if (dc != null && dc.getRegionId().equals(ctx.getRegionId())) { mediaLocationFound = true; } else { // not correct region/datacenter return null; } } } else if( property.getNodeName().equalsIgnoreCase("location") && property.hasChildNodes() ) { if( !mediaLocationFound && !ctx.getRegionId().equals(property.getFirstChild().getNodeValue().trim()) ) { return null; } } } } } } doc = method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES+ "/"+sName+"/deployments/"+deploymentName); if( doc == null ) { return null; } entries = doc.getElementsByTagName("Deployment"); ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>(); for (int i = 0; i < entries.getLength(); i++) { parseDeployment(ctx, ctx.getRegionId(), sName+":"+deploymentName, entries.item(i), list); } if (list != null && list.size() > 0) { VirtualMachine vm = list.get(0); if (dc != null) { vm.setProviderDataCenterId(dc.getProviderDataCenterId()); } else { Collection<DataCenter> dcs = provider.getDataCenterServices().listDataCenters(ctx.getRegionId()); vm.setProviderDataCenterId(dcs.iterator().next().getProviderDataCenterId()); } return vm; } return null; } @Override public @Nullable VmStatistics getVMStatistics(String vmId, long from, long to) throws InternalException, CloudException { return new VmStatistics(); } @Override public @Nonnull Iterable<VmStatistics> getVMStatisticsForPeriod(@Nonnull String vmId, @Nonnegative long from, @Nonnegative long to) throws InternalException, CloudException { return Collections.emptyList(); } @Nonnull @Override public Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException { return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.NONE); } @Override public @Nonnull Requirement identifyPasswordRequirement() throws CloudException, InternalException { return Requirement.OPTIONAL; } @Nonnull @Override public Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException { return Requirement.OPTIONAL; } @Override public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyShellKeyRequirement() throws CloudException, InternalException { return Requirement.OPTIONAL; } @Nonnull @Override public Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException { return Requirement.OPTIONAL; } @Nonnull @Override public Requirement identifyStaticIPRequirement() throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException { return Requirement.OPTIONAL; } @Override public boolean isAPITerminationPreventable() throws CloudException, InternalException { return false; } @Override public boolean isBasicAnalyticsSupported() throws CloudException, InternalException { return false; } @Override public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException { return false; } @Override public boolean isSubscribed() throws CloudException, InternalException { return provider.getDataCenterServices().isSubscribed(AzureService.PERSISTENT_VM_ROLE); } @Override public boolean isUserDataSupported() throws CloudException, InternalException { return false; } @Override public @Nonnull VirtualMachine launch(VMLaunchOptions options) throws CloudException, InternalException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".launch(" + options + ")"); } try { String storageEndpoint = provider.getStorageEndpoint(); logger.debug("----------------------------------------------------------"); logger.debug("launching vm "+options.getHostName()+" with machine image id: "+options.getMachineImageId()); AzureMachineImage image = (AzureMachineImage)provider.getComputeServices().getImageSupport().getMachineImage(options.getMachineImageId()); if( image == null ) { throw new CloudException("No such image: " + options.getMachineImageId()); } logger.debug("----------------------------------------------------------"); ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } String label; try { label = new String(Base64.encodeBase64(options.getFriendlyName().getBytes("utf-8"))); } catch( UnsupportedEncodingException e ) { throw new InternalException(e); } AzureMethod method = new AzureMethod(provider); StringBuilder xml = new StringBuilder(); String hostName = toUniqueId(options.getHostName(), method, ctx); String deploymentSlot = (String)options.getMetaData().get("environment"); String dataCenterId = options.getDataCenterId(); if (dataCenterId == null) { Collection<DataCenter> dcs = provider.getDataCenterServices().listDataCenters(ctx.getRegionId()); dataCenterId = dcs.iterator().next().getProviderDataCenterId(); } if( deploymentSlot == null ) { deploymentSlot = "Production"; } else if( !deploymentSlot.equalsIgnoreCase("Production") && !deploymentSlot.equalsIgnoreCase("Staging") ) { deploymentSlot = "Production"; } xml.append("<CreateHostedService xmlns=\"http://schemas.microsoft.com/windowsazure\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("<ServiceName>").append(hostName).append("</ServiceName>"); xml.append("<Label>").append(label).append("</Label>"); xml.append("<Description>").append(options.getDescription()).append("</Description>"); xml.append("<AffinityGroup>").append(dataCenterId).append("</AffinityGroup>"); xml.append("</CreateHostedService>"); method.post(ctx.getAccountNumber(), HOSTED_SERVICES, xml.toString()); String requestId = null; String password = null; try { xml = new StringBuilder(); xml.append("<Deployment xmlns=\"http://schemas.microsoft.com/windowsazure\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("<Name>").append(hostName).append("</Name>"); xml.append("<DeploymentSlot>").append(deploymentSlot).append("</DeploymentSlot>"); xml.append("<Label>").append(label).append("</Label>"); xml.append("<RoleList>"); xml.append("<Role>"); xml.append("<RoleName>").append(hostName).append("</RoleName>"); xml.append("<RoleType>PersistentVMRole</RoleType>"); xml.append("<ConfigurationSets>"); password = (options.getBootstrapPassword() == null ? provider.generateToken(8, 15) : options.getBootstrapPassword()); if( image.getPlatform().isWindows() ) { xml.append("<ConfigurationSet>"); xml.append("<ConfigurationSetType>WindowsProvisioningConfiguration</ConfigurationSetType>"); xml.append("<ComputerName>").append(hostName).append("</ComputerName>"); xml.append("<AdminPassword>").append(password).append("</AdminPassword>"); xml.append("<EnableAutomaticUpdate>true</EnableAutomaticUpdate>"); xml.append("<TimeZone>UTC</TimeZone>"); xml.append("</ConfigurationSet>"); } else { xml.append("<ConfigurationSet>"); xml.append("<ConfigurationSetType>LinuxProvisioningConfiguration</ConfigurationSetType>"); xml.append("<HostName>").append(hostName).append("</HostName>"); //dmayne using root causes vm to fail provisioning xml.append("<UserName>dasein</UserName>"); xml.append("<UserPassword>").append(password).append("</UserPassword>"); xml.append("<DisableSshPasswordAuthentication>false</DisableSshPasswordAuthentication>"); xml.append("</ConfigurationSet>"); } xml.append("<ConfigurationSet>"); xml.append("<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>") ; xml.append("<InputEndpoints><InputEndpoint>"); if( image.getPlatform().isWindows() ) { xml.append("<LocalPort>3389</LocalPort>"); xml.append("<Name>RemoteDesktop</Name>"); xml.append("<Port>58622</Port>"); } else { xml.append("<LocalPort>22</LocalPort>"); xml.append("<Name>SSH</Name>"); xml.append("<Port>22</Port>"); } xml.append("<Protocol>TCP</Protocol>"); xml.append("</InputEndpoint></InputEndpoints>"); //dmayne assuming this is a subnet Subnet subnet = null; String vlanName = null; if (options.getVlanId() != null) { subnet = provider.getNetworkServices().getVlanSupport().getSubnet(options.getVlanId()); if (subnet!= null) { xml.append("<SubnetNames>"); xml.append("<SubnetName>").append(subnet.getName()).append("</SubnetName>"); xml.append("</SubnetNames>"); //dmayne needed for virtual network name later vlanName = subnet.getTags().get("vlanName"); } else { VLAN vlan = provider.getNetworkServices().getVlanSupport().getVlan(options.getVlanId()); if (vlan != null) { vlanName = vlan.getName(); } } } xml.append("</ConfigurationSet>"); xml.append("</ConfigurationSets>"); xml.append("<DataVirtualHardDisks/>"); xml.append("<OSVirtualHardDisk>"); xml.append("<HostCaching>ReadWrite</HostCaching>"); xml.append("<DiskLabel>OS</DiskLabel>"); xml.append("<MediaLink>").append(storageEndpoint).append("vhds/").append(hostName).append(".vhd</MediaLink>"); xml.append("<SourceImageName>").append(options.getMachineImageId()).append("</SourceImageName>"); xml.append("</OSVirtualHardDisk>"); xml.append("<RoleSize>").append(options.getStandardProductId()).append("</RoleSize>"); xml.append("</Role>"); xml.append("</RoleList>"); if (options.getVlanId() != null) { xml.append("<VirtualNetworkName>").append(vlanName).append("</VirtualNetworkName>"); } xml.append("</Deployment>"); requestId = method.post(ctx.getAccountNumber(), HOSTED_SERVICES + "/" + hostName + "/deployments", xml.toString()); } catch (CloudException e) { logger.error("Launch server failed - now cleaning up service"); String resourceDir = HOSTED_SERVICES + "/" + hostName; long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L); while( timeout > System.currentTimeMillis() ) { try{ if( logger.isInfoEnabled() ) { logger.info("Deleting hosted service " + hostName); } method.invoke("DELETE", ctx.getAccountNumber(), resourceDir, ""); break; } catch( CloudException err ) { logger.error("Unable to delete hosted service for " + hostName + ": " + err.getMessage()); logger.error("Retrying..."); try { Thread.sleep(30000L); } catch( InterruptedException ignore ) { } continue; } } throw e; } long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L); VirtualMachine vm = null ; if (requestId != null) { int httpCode = method.getOperationStatus(requestId); while (httpCode == -1) { try { Thread.sleep(15000L); } catch (InterruptedException ignored){} httpCode = method.getOperationStatus(requestId); } if (httpCode == HttpServletResponse.SC_OK) { try { vm = getVirtualMachine(hostName + ":" + hostName+":"+hostName); } catch( Throwable ignore ) { } if( vm != null ) { vm.setRootUser("dasein"); vm.setRootPassword(password); } } } else { while( timeout > System.currentTimeMillis() ) { try { vm = getVirtualMachine(hostName + ":" + hostName+":"+hostName); } catch( Throwable ignore ) { } if( vm != null ) { vm.setRootUser("dasein"); vm.setRootPassword(password); break; } try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } } } if( vm == null ) { throw new CloudException("System timed out waiting for virtual machine to appear"); } if( VmState.STOPPED.equals(vm.getCurrentState()) ) { start(vm.getProviderVirtualMachineId()); } return vm; } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".launch()"); } } } @Override public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException { return Collections.emptyList(); } @Override public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException { if( architecture.equals(Architecture.I32) ) { return Collections.emptyList(); } ArrayList<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>(); VirtualMachineProduct product = new VirtualMachineProduct(); product.setCpuCount(1); product.setDescription("Extra Small"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Extra Small"); product.setProviderProductId("ExtraSmall"); product.setRamSize(new Storage<Gigabyte>(1, Storage.GIGABYTE)); list.add(product); product = new VirtualMachineProduct(); product.setCpuCount(1); product.setDescription("Small"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Small"); product.setProviderProductId("Small"); product.setRamSize(new Storage<Gigabyte>(2, Storage.GIGABYTE)); list.add(product); product = new VirtualMachineProduct(); product.setCpuCount(2); product.setDescription("Medium"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Medium"); product.setProviderProductId("Medium"); product.setRamSize(new Storage<Gigabyte>(4, Storage.GIGABYTE)); //3.5G list.add(product); product = new VirtualMachineProduct(); product.setCpuCount(4); product.setDescription("Large"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Large"); product.setProviderProductId("Large"); product.setRamSize(new Storage<Gigabyte>(7, Storage.GIGABYTE)); //3.5G list.add(product); product = new VirtualMachineProduct(); product.setCpuCount(8); product.setDescription("Extra Large"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Extra Large"); product.setProviderProductId("ExtraLarge"); product.setRamSize(new Storage<Gigabyte>(14, Storage.GIGABYTE)); //3.5G list.add(product); return Collections.unmodifiableList(list); } @Override public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException { return Collections.singletonList(Architecture.I64); } @Nonnull @Override public Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES); if( doc == null ) { return Collections.emptyList(); } NodeList entries = doc.getElementsByTagName("HostedService"); ArrayList<ResourceStatus> status = new ArrayList<ResourceStatus>(); for( int i=0; i<entries.getLength(); i++ ) { parseHostedServiceForStatus(ctx, entries.item(i), null, status); } return status; } @Override public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES); if( doc == null ) { return Collections.emptyList(); } NodeList entries = doc.getElementsByTagName("HostedService"); ArrayList<VirtualMachine> vms = new ArrayList<VirtualMachine>(); for( int i=0; i<entries.getLength(); i++ ) { parseHostedService(ctx, entries.item(i), null, vms); } return vms; } @Nonnull @Override public Iterable<VirtualMachine> listVirtualMachines(@Nullable VMFilterOptions vmFilterOptions) throws InternalException, CloudException { Iterable<VirtualMachine> vms = listVirtualMachines(); ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>(); for (VirtualMachine vm : vms) { if (vm.getName().matches(vmFilterOptions.getRegex())) { list.add(vm); } } return list; } private void parseDeployment(@Nonnull ProviderContext ctx, @Nonnull String regionId, @Nonnull String serviceName, @Nonnull Node node, @Nonnull List<VirtualMachine> virtualMachines) { ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>(); NodeList attributes = node.getChildNodes(); String deploymentSlot = null; String deploymentId = null; String dnsName = null; String vmRoleName = null; String imageId = null; String mediaLink = null; String vlan = null; String subnetName = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if( attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("deploymentslot") && attribute.hasChildNodes() ) { deploymentSlot = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("privateid") && attribute.hasChildNodes() ) { deploymentId = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes() ) { try { URI u = new URI(attribute.getFirstChild().getNodeValue().trim()); dnsName = u.getHost(); } catch( URISyntaxException e ) { // ignore } } else if( attribute.getNodeName().equalsIgnoreCase("roleinstancelist") && attribute.hasChildNodes() ) { NodeList roleInstances = attribute.getChildNodes(); for( int j=0; j<roleInstances.getLength(); j++ ) { Node roleInstance = roleInstances.item(j); if(roleInstance.getNodeType() == Node.TEXT_NODE) { continue; } if( roleInstance.getNodeName().equalsIgnoreCase("roleinstance") && roleInstance.hasChildNodes() ) { VirtualMachine role = new VirtualMachine(); role.setArchitecture(Architecture.I64); role.setClonable(false); role.setCurrentState(VmState.TERMINATED); role.setImagable(false); role.setPersistent(true); role.setPlatform(Platform.UNKNOWN); role.setProviderOwnerId(ctx.getAccountNumber()); role.setProviderRegionId(regionId); role.setProviderDataCenterId(regionId); NodeList roleAttributes = roleInstance.getChildNodes(); for( int l=0; l<roleAttributes.getLength(); l++ ) { Node roleAttribute = roleAttributes.item(l); if( roleAttribute.getNodeType() == Node.TEXT_NODE ) { continue; } if( roleAttribute.getNodeName().equalsIgnoreCase("RoleName") && roleAttribute.hasChildNodes() ) { String vmId = roleAttribute.getFirstChild().getNodeValue().trim(); role.setProviderVirtualMachineId(serviceName + ":" + vmId); role.setName(vmId); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instancesize") && roleAttribute.hasChildNodes() ) { role.setProductId(roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instanceupgradedomain") && roleAttribute.hasChildNodes() ) { role.setTag("UpgradeDomain", roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instanceerrorcode") && roleAttribute.hasChildNodes() ) { role.setTag("ErrorCode", roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instancefaultdomain") && roleAttribute.hasChildNodes() ) { role.setTag("FaultDomain", roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("fqdn") && roleAttribute.hasChildNodes() ) { role.setPrivateDnsAddress(roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("ipaddress") && roleAttribute.hasChildNodes() ) { role.setPrivateIpAddresses(new String[] { roleAttribute.getFirstChild().getNodeValue().trim() }); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instanceendpoints") && roleAttribute.hasChildNodes() ) { NodeList endpoints = roleAttribute.getChildNodes(); for( int m=0; m<endpoints.getLength(); m++ ) { Node endpoint = endpoints.item(m); if( endpoint.hasChildNodes() ) { NodeList ea = endpoint.getChildNodes(); for( int n=0; n<ea.getLength(); n++ ) { Node a = ea.item(n); if( a.getNodeName().equalsIgnoreCase("vip") && a.hasChildNodes() ) { String addr = a.getFirstChild().getNodeValue().trim(); String[] ips = role.getPublicIpAddresses(); if( ips == null || ips.length < 1 ) { role.setPublicIpAddresses(new String[] { addr }); } else { boolean found = false; for( String ip : ips ) { if( ip.equals(addr) ) { found = true; break; } } if( !found ) { String[] tmp = new String[ips.length + 1]; System.arraycopy(ips, 0, tmp, 0, ips.length); tmp[tmp.length-1] = addr; role.setPublicIpAddresses(tmp); } } } } } } } else if( roleAttribute.getNodeName().equalsIgnoreCase("PowerState") && roleAttribute.hasChildNodes() ) { String powerStatus = roleAttribute.getFirstChild().getNodeValue().trim(); if( "Started".equalsIgnoreCase(powerStatus)){ role.setCurrentState(VmState.RUNNING); } else if( "Stopped".equalsIgnoreCase(powerStatus)){ role.setCurrentState(VmState.STOPPED); role.setImagable(true); } else if( "Stopping".equalsIgnoreCase(powerStatus)){ role.setCurrentState(VmState.STOPPING); } else if( "Starting".equalsIgnoreCase(powerStatus)){ role.setCurrentState(VmState.PENDING); } else { logger.warn("DEBUG: Unknown Azure status: " + powerStatus); } } } if( role.getProviderVirtualMachineId() == null ) { continue; } if( role.getName() == null ) { role.setName(role.getProviderVirtualMachineId()); } if( role.getDescription() == null ) { role.setDescription(role.getName()); } if( role.getPlatform().equals(Platform.UNKNOWN) ) { String descriptor = (role.getProviderVirtualMachineId() + " " + role.getName() + " " + role.getDescription() + " " + role.getProviderMachineImageId()).replaceAll("_", " "); role.setPlatform(Platform.guess(descriptor)); } else if( role.getPlatform().equals(Platform.UNIX) ) { String descriptor = (role.getProviderVirtualMachineId() + " " + role.getName() + " " + role.getDescription() + " " + role.getProviderMachineImageId()).replaceAll("_", " "); Platform p = Platform.guess(descriptor); if( p.isUnix() ) { role.setPlatform(p); } } list.add(role); } } } //Contain the information about disk and firewall; else if( attribute.getNodeName().equalsIgnoreCase("rolelist") && attribute.hasChildNodes() ) { NodeList roles = attribute.getChildNodes(); for( int k=0; k<roles.getLength(); k++ ) { Node role = roles.item(k); if( role.getNodeName().equalsIgnoreCase("role") && role.hasChildNodes() ) { if( role.hasAttributes() ) { Node n = role.getAttributes().getNamedItem("i:type"); if( n != null ) { String val = n.getNodeValue(); if( !"PersistentVMRole".equalsIgnoreCase(val) ) { continue; } } } NodeList roleAttributes = role.getChildNodes(); for( int l=0; l<roleAttributes.getLength(); l++ ) { Node roleAttribute = roleAttributes.item(l); if( roleAttribute.getNodeType() == Node.TEXT_NODE ) { continue; } if( roleAttribute.getNodeName().equalsIgnoreCase("osvirtualharddisk") && roleAttribute.hasChildNodes() ) { NodeList diskAttributes = roleAttribute.getChildNodes(); for( int m=0; m<diskAttributes.getLength(); m++ ) { Node diskAttribute = diskAttributes.item(m); if( diskAttribute.getNodeName().equalsIgnoreCase("SourceImageName") && diskAttribute.hasChildNodes() ) { imageId = diskAttribute.getFirstChild().getNodeValue().trim(); } else if( diskAttribute.getNodeName().equalsIgnoreCase("medialink") && diskAttribute.hasChildNodes() ) { mediaLink = diskAttribute.getFirstChild().getNodeValue().trim(); } } } else if( roleAttribute.getNodeName().equalsIgnoreCase("RoleName") && roleAttribute.hasChildNodes() ) { vmRoleName = roleAttribute.getFirstChild().getNodeValue().trim(); } else if( roleAttribute.getNodeName().equalsIgnoreCase("ConfigurationSets") && roleAttribute.hasChildNodes() ) { NodeList configs = ((Element) roleAttribute).getElementsByTagName("ConfigurationSet"); for (int n = 0; n<configs.getLength();n++) { boolean foundNetConfig = false; Node config = configs.item(n); if( config.hasAttributes() ) { Node c = config.getAttributes().getNamedItem("i:type"); if( c != null ) { String val = c.getNodeValue(); if( !"NetworkConfigurationSet".equalsIgnoreCase(val) ) { continue; } } } if (config.hasChildNodes()) { NodeList configAttribs = config.getChildNodes(); for (int o = 0; o<configAttribs.getLength();o++) { Node attrib = configAttribs.item(o); if (attrib.getNodeName().equalsIgnoreCase("SubnetNames")&& attrib.hasChildNodes()) { NodeList subnets = attrib.getChildNodes(); for (int p=0;p<subnets.getLength();p++) { Node subnet = subnets.item(p); if (subnet.getNodeName().equalsIgnoreCase("SubnetName") && subnet.hasChildNodes()) { subnetName = subnet.getFirstChild().getNodeValue().trim(); } } } } } } } } } } } else if (attribute.getNodeName().equalsIgnoreCase("virtualnetworkname") && attribute.hasChildNodes() ) { vlan = attribute.getFirstChild().getNodeValue().trim(); } } if( vmRoleName != null ) { for( VirtualMachine vm : list ) { if( deploymentSlot != null ) { vm.setTag("environment", deploymentSlot); } if( deploymentId != null ) { vm.setTag("deploymentId", deploymentId); } if( dnsName != null ) { vm.setPublicDnsAddress(dnsName); } if( imageId != null ) { Platform fallback = vm.getPlatform(); vm.setProviderMachineImageId(imageId); vm.setPlatform(Platform.guess(vm.getProviderMachineImageId())); if( vm.getPlatform().equals(Platform.UNKNOWN) ) { try { MachineImage img = provider.getComputeServices().getImageSupport().getMachineImage(vm.getProviderMachineImageId()); if( img != null ) { vm.setPlatform(img.getPlatform()); } } catch( Throwable t ) { logger.warn("Error loading machine image: " + t.getMessage()); } if( vm.getPlatform().equals(Platform.UNKNOWN) ) { vm.setPlatform(fallback); } } } if (vlan != null) { try { vm.setProviderVlanId(provider.getNetworkServices().getVlanSupport().getVlan(vlan).getProviderVlanId()); } catch (CloudException e) { logger.error("Error getting vlan id for vlan "+vlan); continue; } catch (InternalException ie){ logger.error("Error getting vlan id for vlan "+vlan); continue; } } if (subnetName != null) { vm.setProviderSubnetId(subnetName); } String[] parts = vm.getProviderVirtualMachineId().split(":"); String sName, deploymentName, roleName; if (parts.length == 3) { sName = parts[0]; deploymentName = parts[1]; roleName= parts[2]; } else if( parts.length == 2 ) { sName = parts[0]; deploymentName = parts[1]; roleName = deploymentName; } else { sName = serviceName; deploymentName = serviceName; roleName = serviceName; } vm.setTag("serviceName", sName); vm.setTag("deploymentName", deploymentName); vm.setTag("roleName", roleName); if( mediaLink != null ) { vm.setTag("mediaLink", mediaLink); } virtualMachines.add(vm); } } } private void parseStatus(@Nonnull ProviderContext ctx, @Nonnull String regionId, @Nonnull String serviceName, @Nonnull Node node, @Nonnull List<ResourceStatus> status) { ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); NodeList attributes = node.getChildNodes(); String id = ""; ResourceStatus s = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if( attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("roleinstancelist") && attribute.hasChildNodes() ) { NodeList roleInstances = attribute.getChildNodes(); for( int j=0; j<roleInstances.getLength(); j++ ) { Node roleInstance = roleInstances.item(j); if(roleInstance.getNodeType() == Node.TEXT_NODE) { continue; } if( roleInstance.getNodeName().equalsIgnoreCase("roleinstance") && roleInstance.hasChildNodes() ) { NodeList roleAttributes = roleInstance.getChildNodes(); for( int l=0; l<roleAttributes.getLength(); l++ ) { Node roleAttribute = roleAttributes.item(l); if( roleAttribute.getNodeType() == Node.TEXT_NODE ) { continue; } if( roleAttribute.getNodeName().equalsIgnoreCase("RoleName") && roleAttribute.hasChildNodes() ) { String vmId = roleAttribute.getFirstChild().getNodeValue().trim(); id = serviceName + ":" + vmId; } else if( roleAttribute.getNodeName().equalsIgnoreCase("PowerState") && roleAttribute.hasChildNodes() ) { String powerStatus = roleAttribute.getFirstChild().getNodeValue().trim(); if( "Started".equalsIgnoreCase(powerStatus)){ s = new ResourceStatus(id, VmState.RUNNING); } else if( "Stopped".equalsIgnoreCase(powerStatus)){ s = new ResourceStatus(id, VmState.STOPPED); } else if( "Stopping".equalsIgnoreCase(powerStatus)){ s = new ResourceStatus(id, VmState.STOPPING); } else if( "Starting".equalsIgnoreCase(powerStatus)){ s = new ResourceStatus(id, VmState.PENDING); } else { logger.warn("DEBUG: Unknown Azure status: " + powerStatus); } } } if( id == null ) { continue; } if (s != null) { list.add(s); s = null; } } } } } for (ResourceStatus rs : list) { status.add(rs); } } private void parseHostedService(@Nonnull ProviderContext ctx, @Nonnull Node entry, @Nullable String serviceName, @Nonnull List<VirtualMachine> virtualMachines) throws CloudException, InternalException { String regionId = ctx.getRegionId(); if( regionId == null ) { throw new AzureConfigException("No region ID was specified for this request"); } NodeList attributes = entry.getChildNodes(); String uri = null; long created = 0L; String service = null; boolean mediaLocationFound = false; DataCenter dc = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if(attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes() ) { uri = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("servicename") && attribute.hasChildNodes() ) { service = attribute.getFirstChild().getNodeValue().trim(); if( serviceName != null && !service.equals(serviceName) ) { return; } } else if( attribute.getNodeName().equalsIgnoreCase("hostedserviceproperties") && attribute.hasChildNodes() ) { NodeList properties = attribute.getChildNodes(); for( int j=0; j<properties.getLength(); j++ ) { Node property = properties.item(j); if(property.getNodeType() == Node.TEXT_NODE) { continue; } if( property.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes() ) { //get the region for this affinity group String affinityGroup = property.getFirstChild().getNodeValue().trim(); if (affinityGroup != null && !affinityGroup.equals("")) { dc = provider.getDataCenterServices().getDataCenter(affinityGroup); if (dc != null && dc.getRegionId().equals(regionId)) { mediaLocationFound = true; } else { // not correct region/datacenter return; } } } else if( property.getNodeName().equalsIgnoreCase("location") && property.hasChildNodes() ) { if( !mediaLocationFound && !regionId.equals(property.getFirstChild().getNodeValue().trim()) ) { return; } } else if( property.getNodeName().equalsIgnoreCase("datecreated") && property.hasChildNodes() ) { created = provider.parseTimestamp(property.getFirstChild().getNodeValue().trim()); } } } } if( uri == null || service == null ) { return; } AzureMethod method = new AzureMethod(provider); //dmayne 20130416: get the deployment names for each hosted service so we can then extract the detail String deployURL = HOSTED_SERVICES + "/"+ service+"?embed-detail=true"; Document deployDoc = method.getAsXML(ctx.getAccountNumber(), deployURL); if (deployDoc == null) { return; } NodeList deployments = deployDoc.getElementsByTagName("Deployments"); for (int i = 0; i < deployments.getLength(); i++) { Node deployNode = deployments.item(i); NodeList deployAttributes = deployNode.getChildNodes(); String deploymentName = ""; for (int j = 0; j<deployAttributes.getLength(); j++) { Node deployment = deployAttributes.item(j); if(deployment.getNodeType() == Node.TEXT_NODE) { continue; } if( deployment.getNodeName().equalsIgnoreCase("Deployment") && deployment.hasChildNodes() ) { NodeList dAttribs = deployment.getChildNodes(); for (int k = 0; k<dAttribs.getLength(); k++) { Node mynode = dAttribs.item(k); if ( mynode.getNodeName().equalsIgnoreCase("name") && mynode.hasChildNodes() ) { deploymentName = mynode.getFirstChild().getNodeValue().trim(); String resourceDir = HOSTED_SERVICES + "/" + service + "/deployments/" + deploymentName; Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir); if (doc == null) { return; } NodeList entries = doc.getElementsByTagName("Deployment"); for (int l = 0; l < entries.getLength(); l++) { parseDeployment(ctx, regionId, service+":"+deploymentName, entries.item(l), virtualMachines); } for (VirtualMachine vm : virtualMachines) { if (vm.getCreationTimestamp() < 1L) { vm.setCreationTimestamp(created); } if (dc != null) { vm.setProviderDataCenterId(dc.getProviderDataCenterId()); } else { Collection<DataCenter> dcs = provider.getDataCenterServices().listDataCenters(regionId); vm.setProviderDataCenterId(dcs.iterator().next().getProviderDataCenterId()); } } } } } } } } private void parseHostedServiceForStatus(@Nonnull ProviderContext ctx, @Nonnull Node entry, @Nullable String serviceName, @Nonnull List<ResourceStatus> status) throws CloudException, InternalException { String regionId = ctx.getRegionId(); if( regionId == null ) { throw new AzureConfigException("No region ID was specified for this request"); } NodeList attributes = entry.getChildNodes(); String uri = null; String service = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if(attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes() ) { uri = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("servicename") && attribute.hasChildNodes() ) { service = attribute.getFirstChild().getNodeValue().trim(); if( serviceName != null && !service.equals(serviceName) ) { return; } } else if( attribute.getNodeName().equalsIgnoreCase("hostedserviceproperties") && attribute.hasChildNodes() ) { NodeList properties = attribute.getChildNodes(); boolean mediaLocationFound = false; for( int j=0; j<properties.getLength(); j++ ) { Node property = properties.item(j); if(property.getNodeType() == Node.TEXT_NODE) { continue; } if( property.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes() ) { //get the region for this affinity group String affinityGroup = property.getFirstChild().getNodeValue().trim(); if (affinityGroup != null && !affinityGroup.equals("")) { DataCenter dc = provider.getDataCenterServices().getDataCenter(affinityGroup); if (dc.getRegionId().equals(regionId)) { mediaLocationFound = true; } else { // not correct region/datacenter return; } } } else if( property.getNodeName().equalsIgnoreCase("location") && property.hasChildNodes() ) { if( !mediaLocationFound && !regionId.equals(property.getFirstChild().getNodeValue().trim()) ) { return; } } } } } if( uri == null || service == null ) { return; } AzureMethod method = new AzureMethod(provider); //dmayne 20130416: get the deployment names for each hosted service so we can then extract the detail String deployURL = HOSTED_SERVICES + "/"+ service+"?embed-detail=true"; Document deployDoc = method.getAsXML(ctx.getAccountNumber(), deployURL); if (deployDoc == null) { return; } NodeList deployments = deployDoc.getElementsByTagName("Deployments"); for (int i = 0; i < deployments.getLength(); i++) { Node deployNode = deployments.item(i); NodeList deployAttributes = deployNode.getChildNodes(); String deploymentName = ""; for (int j = 0; j<deployAttributes.getLength(); j++) { Node deployment = deployAttributes.item(j); if(deployment.getNodeType() == Node.TEXT_NODE) { continue; } if( deployment.getNodeName().equalsIgnoreCase("Deployment") && deployment.hasChildNodes() ) { NodeList dAttribs = deployment.getChildNodes(); for (int k = 0; k<dAttribs.getLength(); k++) { Node mynode = dAttribs.item(k); if ( mynode.getNodeName().equalsIgnoreCase("name") && mynode.hasChildNodes() ) { deploymentName = mynode.getFirstChild().getNodeValue().trim(); String resourceDir = HOSTED_SERVICES + "/" + service + "/deployments/" + deploymentName; Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir); if (doc == null) { return; } NodeList entries = doc.getElementsByTagName("Deployment"); for (int l = 0; l < entries.getLength(); l++) { parseStatus(ctx, regionId, service + ":" + deploymentName, entries.item(l), status); } } } } } } } @Override public void reboot(@Nonnull String vmId) throws CloudException, InternalException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".reboot()"); } try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } String serviceName, deploymentName, roleName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); roleName = vm.getTag("roleName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roleInstances/" + roleName + "/Operations"; AzureMethod method = new AzureMethod(provider); StringBuilder xml = new StringBuilder(); xml.append("<RestartRoleOperation xmlns=\"http://schemas.microsoft.com/windowsazure\""); xml.append(" "); xml.append("xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("\n"); xml.append("<OperationType>RestartRoleOperation</OperationType>"); xml.append("\n"); xml.append("</RestartRoleOperation>"); xml.append("\n"); if( logger.isInfoEnabled() ) { logger.info("Rebooting " + vmId); } method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".reboot()"); } } } @Override public void resume(@Nonnull String vmId) throws CloudException, InternalException { throw new OperationNotSupportedException("Suspend/resume is not supported in Microsoft Azure"); } @Override public void pause(@Nonnull String vmId) throws InternalException, CloudException { throw new OperationNotSupportedException("Pause/unpause is not supported in Microsoft Azure"); } @Override public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".Boot()"); } try { // TODO: force vs not force ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } String serviceName, deploymentName, roleName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); roleName = vm.getTag("roleName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roleInstances/" + roleName + "/Operations"; logger.debug("__________________________________________________________"); logger.debug("Stop vm "+resourceDir); AzureMethod method = new AzureMethod(provider); StringBuilder xml = new StringBuilder(); xml.append("<ShutdownRoleOperation xmlns=\"http://schemas.microsoft.com/windowsazure\""); xml.append(" "); xml.append("xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("\n"); xml.append("<OperationType>ShutdownRoleOperation </OperationType>"); xml.append("\n"); xml.append("</ShutdownRoleOperation>"); xml.append("\n"); if( logger.isInfoEnabled() ) { logger.info("Stopping the " + provider.getCloudName() + " virtual machine: " + vmId); } logger.debug(xml); logger.debug("__________________________________________________________"); method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".launch()"); } } } @Override public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) { return false; } @Override public boolean supportsStartStop(@Nonnull VirtualMachine vm) { return true; } @Override public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) { return false; } @Override public void suspend(@Nonnull String vmId) throws CloudException, InternalException { throw new OperationNotSupportedException("Suspend/resume is not supported in Microsoft Azure"); } @Override public void terminate(@Nonnull String vmId, @Nullable String explanation) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".terminate()"); } try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } ArrayList<String> disks = getAttachedDisks(vm); long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L); while( timeout > System.currentTimeMillis() ) { if( vm == null || VmState.TERMINATED.equals(vm.getCurrentState()) ) { return; } if( !VmState.PENDING.equals(vm.getCurrentState()) && !VmState.STOPPING.equals(vm.getCurrentState()) ) { break; } try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } try { vm = getVirtualMachine(vmId); } catch( Throwable ignore ) { } } ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } String serviceName, deploymentName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName; AzureMethod method = new AzureMethod(provider); timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*10L); while( timeout > System.currentTimeMillis() ) { if( logger.isInfoEnabled() ) { logger.info("Deleting deployments for " + serviceName); } try { method.invoke("DELETE", ctx.getAccountNumber(), resourceDir, ""); break; } catch( CloudException e ) { if( e.getProviderCode() != null && e.getProviderCode().equals("ConflictError") ) { logger.warn("Conflict error, maybe retrying in 30 seconds"); try { Thread.sleep(30000L); } catch( InterruptedException ignore ) { } continue; } throw e; } } timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*10L); while( timeout > System.currentTimeMillis() ) { if( vm == null || VmState.TERMINATED.equals(vm.getCurrentState()) ) { break; } try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } try { vm = getVirtualMachine(vmId); } catch( Throwable ignore ) { } } terminateService(serviceName, explanation); //now delete the orphaned disks for (String disk : disks) { provider.getComputeServices().getVolumeSupport().remove(disk); } } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".terminate()"); } } } public void terminateService(String serviceName, String explanation) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.terminateService"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } AzureMethod method = new AzureMethod(provider); String resourceDir = HOSTED_SERVICES + "/" + serviceName; long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L); while( timeout > System.currentTimeMillis() ) { try{ if( logger.isInfoEnabled() ) { logger.info("Deleting hosted service " + serviceName+": "+explanation); } method.invoke("DELETE", ctx.getAccountNumber(), resourceDir, ""); break; } catch( CloudException e ) { logger.error("Unable to delete hosted service for " + serviceName + ": " + e.getMessage()); logger.error("Retrying..."); try { Thread.sleep(30000L); } catch( InterruptedException ignore ) { } continue; } catch( Throwable t ) { logger.warn("Unable to delete hosted service for " + serviceName + ": " + t.getMessage()); return; } } } finally { APITrace.end(); } } private ArrayList<String> getAttachedDisks(VirtualMachine vm) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } ArrayList<String> list = new ArrayList<String>(); boolean diskFound = false; String serviceName, deploymentName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName; AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(),resourceDir); NodeList entries = doc.getElementsByTagName("Deployment"); for (int i = 0; i < entries.getLength(); i++) { Node entry = entries.item(i); NodeList attributes = entry.getChildNodes(); for (int j = 0; j < attributes.getLength(); j++){ Node attribute = attributes.item(j); if (attribute.getNodeName().equalsIgnoreCase("RoleList") && attribute.hasChildNodes()) { NodeList instances = attribute.getChildNodes(); for (int k = 0; k <instances.getLength(); k++){ Node instance = instances.item(k); if (instance.getNodeName().equalsIgnoreCase("Role") && instance.hasChildNodes()){ NodeList roles = instance.getChildNodes(); for (int l = 0; l<roles.getLength(); l++) { Node role = roles.item(l); if (role.getNodeName().equalsIgnoreCase("OSVirtualHardDisk") && role.hasChildNodes()) { NodeList disks = role.getChildNodes(); for (int m = 0; m<disks.getLength(); m++) { Node disk = disks.item(m); if (disk.getNodeName().equalsIgnoreCase("DiskName") && disk.hasChildNodes()) { String name = disk.getFirstChild().getNodeValue(); list.add(name); diskFound = true; break; } } } if (diskFound) { diskFound = false; break; } } } } } } } return list; } @Override public void unpause(@Nonnull String vmId) throws CloudException, InternalException { throw new OperationNotSupportedException("Pause/unpause is not supported in Microsoft Azure"); } @Override public void updateTags(@Nonnull String vmId, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void updateTags(@Nonnull String[] strings, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void removeTags(@Nonnull String s, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void removeTags(@Nonnull String[] strings, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) { return new String[0]; } private @Nonnull String toUniqueId(@Nonnull String name, @Nonnull AzureMethod method, ProviderContext ctx) throws CloudException, InternalException { name = name.toLowerCase().replaceAll(" ", ""); String id = name; int i = 0; while (method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES+ "/"+id) != null) { i++; id = name + "-" + i; } return id; } }
src/main/java/org/dasein/cloud/azure/compute/vm/AzureVM.java
/** * Copyright (C) 2012 enStratus Networks Inc * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.azure.compute.vm; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.Requirement; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.Tag; import org.dasein.cloud.azure.Azure; import org.dasein.cloud.azure.AzureConfigException; import org.dasein.cloud.azure.AzureMethod; import org.dasein.cloud.azure.AzureService; import org.dasein.cloud.azure.compute.image.AzureMachineImage; import org.dasein.cloud.compute.AbstractVMSupport; import org.dasein.cloud.compute.Architecture; import org.dasein.cloud.compute.ImageClass; import org.dasein.cloud.compute.MachineImage; import org.dasein.cloud.compute.Platform; import org.dasein.cloud.compute.VMFilterOptions; import org.dasein.cloud.compute.VMLaunchOptions; import org.dasein.cloud.compute.VMScalingCapabilities; import org.dasein.cloud.compute.VMScalingOptions; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.VirtualMachineProduct; import org.dasein.cloud.compute.VmState; import org.dasein.cloud.compute.VmStatistics; import org.dasein.cloud.dc.DataCenter; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.network.Subnet; import org.dasein.cloud.network.VLAN; import org.dasein.cloud.util.APITrace; import org.dasein.util.CalendarWrapper; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Storage; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * Implements virtual machine support for Microsoft Azure. * @author George Reese ([email protected]) * @author Qunying Huang * @since 2012.04.1 initial version * @version 2012.04.1 * @version 2012.09 updated for model changes */ public class AzureVM extends AbstractVMSupport { static private final Logger logger = Azure.getLogger(AzureVM.class); static public final String HOSTED_SERVICES = "/services/hostedservices"; private Azure provider; public AzureVM(Azure provider) { super(provider); this.provider = provider; } @Override public void start(@Nonnull String vmId) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".Boot()"); } VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } String serviceName, deploymentName, roleName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); roleName = vm.getTag("roleName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roleInstances/" + roleName + "/Operations"; logger.debug("_______________________________________________________"); logger.debug("Start operation - "+resourceDir); try{ AzureMethod method = new AzureMethod(provider); StringBuilder xml = new StringBuilder(); xml.append("<StartRoleOperation xmlns=\"http://schemas.microsoft.com/windowsazure\""); xml.append(" "); xml.append("xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("\n"); xml.append("<OperationType>StartRoleOperation</OperationType>"); xml.append("\n"); xml.append("</StartRoleOperation>"); xml.append("\n"); logger.debug(xml); logger.debug("___________________________________________________"); method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); }finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".launch()"); } } } @Override public VirtualMachine alterVirtualMachine(@Nonnull String vmId, @Nonnull VMScalingOptions options) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".alterVM()"); } if (vmId == null || options.getProviderProductId() == null) { throw new AzureConfigException("No vmid and/or product id set for this operation"); } String[] parts = options.getProviderProductId().split(":"); String productId = null; String disks = null; if (parts.length == 2) { productId = parts[0]; disks = parts[1].replace("[","").replace("]",""); } else { throw new InternalException("Invalid product id string. Product id format is product name:[disk_0_size,disk_1_size,disk_n_size]"); } String[] diskSizes = disks.split(","); VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } String serviceName, deploymentName, roleName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); roleName = vm.getTag("roleName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/" + roleName; try{ AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir); StringBuilder xml = new StringBuilder(); NodeList roles = doc.getElementsByTagName("PersistentVMRole"); Node role = roles.item(0); NodeList entries = role.getChildNodes(); for (int i = 0; i<entries.getLength(); i++) { Node vn = entries.item(i); String vnName = vn.getNodeName(); if( vnName.equalsIgnoreCase("RoleSize") && vn.hasChildNodes() ) { vn.setNodeValue(productId); } } String output=""; try{ TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); output = writer.getBuffer().toString().replaceAll("\n|\r", ""); } catch (Exception e){ System.err.println(e); } xml.append(output); logger.debug(xml); logger.debug("___________________________________________________"); resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/" + roleName; String requestId = method.invoke("PUT", ctx.getAccountNumber(), resourceDir, xml.toString()); if (requestId != null) { int httpCode = method.getOperationStatus(requestId); while (httpCode == -1) { try { Thread.sleep(15000L); } catch (InterruptedException ignored){} httpCode = method.getOperationStatus(requestId); } if (httpCode == HttpServletResponse.SC_OK) { //attach any disks as appropriate for (int i = 0; i < diskSizes.length; i++) { xml = new StringBuilder(); xml.append("<DataVirtualHardDisk xmlns=\"http://schemas.microsoft.com/windowsazure\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("<HostCaching>ReadWrite</HostCaching>"); xml.append("<LogicalDiskSizeInGB>").append(diskSizes[i]).append("</LogicalDiskSizeInGB>"); xml.append("<MediaLink>").append(provider.getStorageEndpoint()).append("vhds/").append(roleName).append(System.currentTimeMillis()%10000).append(".vhd</MediaLink>"); xml.append("</DataVirtualHardDisk>"); logger.debug(xml); resourceDir = HOSTED_SERVICES + "/" +serviceName+ "/deployments" + "/" + deploymentName + "/roles"+"/" + roleName+ "/DataDisks"; requestId = method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); if (requestId != null) { httpCode = method.getOperationStatus(requestId); while (httpCode == -1) { try { Thread.sleep(15000L); } catch (InterruptedException ignored){} httpCode = method.getOperationStatus(requestId); } } } } } return getVirtualMachine(vmId); }finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".alterVM()"); } } } @Override public @Nonnull VirtualMachine clone(@Nonnull String vmId, @Nonnull String intoDcId, @Nonnull String name, @Nonnull String description, boolean powerOn, @Nullable String... firewallIds) throws InternalException, CloudException { throw new OperationNotSupportedException("Not supported in Microsoft Azure"); } @Override public VMScalingCapabilities describeVerticalScalingCapabilities() throws CloudException, InternalException { return VMScalingCapabilities.getInstance(false,true,Requirement.REQUIRED,Requirement.NONE); } @Override public void disableAnalytics(String vmId) throws InternalException, CloudException { // NO-OP } @Override public void enableAnalytics(String vmId) throws InternalException, CloudException { // NO-OP } @Override public @Nonnull String getConsoleOutput(@Nonnull String vmId) throws InternalException, CloudException { return ""; } @Override public int getCostFactor(@Nonnull VmState state) throws InternalException, CloudException { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getMaximumVirtualMachineCount() throws CloudException, InternalException { return -2; } @Override public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException { for( VirtualMachineProduct product : listProducts(Architecture.I64) ) { if( product.getProviderProductId().equals(productId) ) { return product; } } return null; } @Override public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) { return "virtual machine"; } @Override public @Nullable VirtualMachine getVirtualMachine(@Nonnull String vmId) throws InternalException, CloudException { String[] parts = vmId.split(":"); String sName, deploymentName, roleName; if (parts.length == 3) { sName = parts[0]; deploymentName = parts[1]; roleName= parts[2]; } else if( parts.length == 2 ) { sName = parts[0]; deploymentName = parts[1]; roleName = sName; } else { sName = vmId; deploymentName = vmId; roleName = vmId; } DataCenter dc = null; ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES+ "/"+sName); if (doc == null) { return null; } NodeList entries = doc.getElementsByTagName("HostedService"); ArrayList<VirtualMachine> vms = new ArrayList<VirtualMachine>(); for (int h = 0; h < entries.getLength(); h++) { Node entry = entries.item(h); NodeList attributes = entry.getChildNodes(); boolean mediaLocationFound = false; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if(attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("hostedserviceproperties") && attribute.hasChildNodes() ) { NodeList properties = attribute.getChildNodes(); for( int j=0; j<properties.getLength(); j++ ) { Node property = properties.item(j); if(property.getNodeType() == Node.TEXT_NODE) { continue; } if( property.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes() ) { //get the region for this affinity group String affinityGroup = property.getFirstChild().getNodeValue().trim(); if (affinityGroup != null && !affinityGroup.equals("")) { dc = provider.getDataCenterServices().getDataCenter(affinityGroup); if (dc != null && dc.getRegionId().equals(ctx.getRegionId())) { mediaLocationFound = true; } else { // not correct region/datacenter return null; } } } else if( property.getNodeName().equalsIgnoreCase("location") && property.hasChildNodes() ) { if( !mediaLocationFound && !ctx.getRegionId().equals(property.getFirstChild().getNodeValue().trim()) ) { return null; } } } } } } doc = method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES+ "/"+sName+"/deployments/"+deploymentName); if( doc == null ) { return null; } entries = doc.getElementsByTagName("Deployment"); ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>(); for (int i = 0; i < entries.getLength(); i++) { parseDeployment(ctx, ctx.getRegionId(), sName+":"+deploymentName, entries.item(i), list); } if (list != null && list.size() > 0) { VirtualMachine vm = list.get(0); if (dc != null) { vm.setProviderDataCenterId(dc.getProviderDataCenterId()); } else { Collection<DataCenter> dcs = provider.getDataCenterServices().listDataCenters(ctx.getRegionId()); vm.setProviderDataCenterId(dcs.iterator().next().getProviderDataCenterId()); } return vm; } return null; } @Override public @Nullable VmStatistics getVMStatistics(String vmId, long from, long to) throws InternalException, CloudException { return new VmStatistics(); } @Override public @Nonnull Iterable<VmStatistics> getVMStatisticsForPeriod(@Nonnull String vmId, @Nonnegative long from, @Nonnegative long to) throws InternalException, CloudException { return Collections.emptyList(); } @Nonnull @Override public Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException { return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.NONE); } @Override public @Nonnull Requirement identifyPasswordRequirement() throws CloudException, InternalException { return Requirement.OPTIONAL; } @Nonnull @Override public Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException { return Requirement.OPTIONAL; } @Override public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyShellKeyRequirement() throws CloudException, InternalException { return Requirement.OPTIONAL; } @Nonnull @Override public Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException { return Requirement.OPTIONAL; } @Nonnull @Override public Requirement identifyStaticIPRequirement() throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException { return Requirement.OPTIONAL; } @Override public boolean isAPITerminationPreventable() throws CloudException, InternalException { return false; } @Override public boolean isBasicAnalyticsSupported() throws CloudException, InternalException { return false; } @Override public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException { return false; } @Override public boolean isSubscribed() throws CloudException, InternalException { return provider.getDataCenterServices().isSubscribed(AzureService.PERSISTENT_VM_ROLE); } @Override public boolean isUserDataSupported() throws CloudException, InternalException { return false; } @Override public @Nonnull VirtualMachine launch(VMLaunchOptions options) throws CloudException, InternalException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".launch(" + options + ")"); } try { String storageEndpoint = provider.getStorageEndpoint(); logger.debug("----------------------------------------------------------"); logger.debug("launching vm "+options.getHostName()+" with machine image id: "+options.getMachineImageId()); AzureMachineImage image = (AzureMachineImage)provider.getComputeServices().getImageSupport().getMachineImage(options.getMachineImageId()); if( image == null ) { throw new CloudException("No such image: " + options.getMachineImageId()); } logger.debug("----------------------------------------------------------"); ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } String label; try { label = new String(Base64.encodeBase64(options.getFriendlyName().getBytes("utf-8"))); } catch( UnsupportedEncodingException e ) { throw new InternalException(e); } AzureMethod method = new AzureMethod(provider); StringBuilder xml = new StringBuilder(); String hostName = toUniqueId(options.getHostName(), method, ctx); String deploymentSlot = (String)options.getMetaData().get("environment"); String dataCenterId = options.getDataCenterId(); if (dataCenterId == null) { Collection<DataCenter> dcs = provider.getDataCenterServices().listDataCenters(ctx.getRegionId()); dataCenterId = dcs.iterator().next().getProviderDataCenterId(); } if( deploymentSlot == null ) { deploymentSlot = "Production"; } else if( !deploymentSlot.equalsIgnoreCase("Production") && !deploymentSlot.equalsIgnoreCase("Staging") ) { deploymentSlot = "Production"; } xml.append("<CreateHostedService xmlns=\"http://schemas.microsoft.com/windowsazure\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("<ServiceName>").append(hostName).append("</ServiceName>"); xml.append("<Label>").append(label).append("</Label>"); xml.append("<Description>").append(options.getDescription()).append("</Description>"); xml.append("<AffinityGroup>").append(dataCenterId).append("</AffinityGroup>"); xml.append("</CreateHostedService>"); method.post(ctx.getAccountNumber(), HOSTED_SERVICES, xml.toString()); String requestId = null; String password = null; try { xml = new StringBuilder(); xml.append("<Deployment xmlns=\"http://schemas.microsoft.com/windowsazure\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("<Name>").append(hostName).append("</Name>"); xml.append("<DeploymentSlot>").append(deploymentSlot).append("</DeploymentSlot>"); xml.append("<Label>").append(label).append("</Label>"); xml.append("<RoleList>"); xml.append("<Role>"); xml.append("<RoleName>").append(hostName).append("</RoleName>"); xml.append("<RoleType>PersistentVMRole</RoleType>"); xml.append("<ConfigurationSets>"); password = (options.getBootstrapPassword() == null ? provider.generateToken(8, 15) : options.getBootstrapPassword()); if( image.getPlatform().isWindows() ) { xml.append("<ConfigurationSet>"); xml.append("<ConfigurationSetType>WindowsProvisioningConfiguration</ConfigurationSetType>"); xml.append("<ComputerName>").append(hostName).append("</ComputerName>"); xml.append("<AdminPassword>").append(password).append("</AdminPassword>"); xml.append("<EnableAutomaticUpdate>true</EnableAutomaticUpdate>"); xml.append("<TimeZone>UTC</TimeZone>"); xml.append("</ConfigurationSet>"); } else { xml.append("<ConfigurationSet>"); xml.append("<ConfigurationSetType>LinuxProvisioningConfiguration</ConfigurationSetType>"); xml.append("<HostName>").append(hostName).append("</HostName>"); //dmayne using root causes vm to fail provisioning xml.append("<UserName>dasein</UserName>"); xml.append("<UserPassword>").append(password).append("</UserPassword>"); xml.append("<DisableSshPasswordAuthentication>false</DisableSshPasswordAuthentication>"); xml.append("</ConfigurationSet>"); } xml.append("<ConfigurationSet>"); xml.append("<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>") ; xml.append("<InputEndpoints><InputEndpoint>"); if( image.getPlatform().isWindows() ) { xml.append("<LocalPort>3389</LocalPort>"); xml.append("<Name>RemoteDesktop</Name>"); xml.append("<Port>58622</Port>"); } else { xml.append("<LocalPort>22</LocalPort>"); xml.append("<Name>SSH</Name>"); xml.append("<Port>22</Port>"); } xml.append("<Protocol>TCP</Protocol>"); xml.append("</InputEndpoint></InputEndpoints>"); //dmayne assuming this is a subnet Subnet subnet = null; String vlanName = null; if (options.getVlanId() != null) { subnet = provider.getNetworkServices().getVlanSupport().getSubnet(options.getVlanId()); if (subnet!= null) { xml.append("<SubnetNames>"); xml.append("<SubnetName>").append(subnet.getName()).append("</SubnetName>"); xml.append("</SubnetNames>"); //dmayne needed for virtual network name later vlanName = subnet.getTags().get("vlanName"); } else { VLAN vlan = provider.getNetworkServices().getVlanSupport().getVlan(options.getVlanId()); if (vlan != null) { vlanName = vlan.getName(); } } } xml.append("</ConfigurationSet>"); xml.append("</ConfigurationSets>"); xml.append("<DataVirtualHardDisks/>"); xml.append("<OSVirtualHardDisk>"); xml.append("<HostCaching>ReadWrite</HostCaching>"); xml.append("<DiskLabel>OS</DiskLabel>"); xml.append("<MediaLink>").append(storageEndpoint).append("vhds/").append(hostName).append(".vhd</MediaLink>"); xml.append("<SourceImageName>").append(options.getMachineImageId()).append("</SourceImageName>"); xml.append("</OSVirtualHardDisk>"); xml.append("<RoleSize>").append(options.getStandardProductId()).append("</RoleSize>"); xml.append("</Role>"); xml.append("</RoleList>"); if (options.getVlanId() != null) { xml.append("<VirtualNetworkName>").append(vlanName).append("</VirtualNetworkName>"); } xml.append("</Deployment>"); requestId = method.post(ctx.getAccountNumber(), HOSTED_SERVICES + "/" + hostName + "/deployments", xml.toString()); } catch (CloudException e) { logger.error("Launch server failed - now cleaning up service"); String resourceDir = HOSTED_SERVICES + "/" + hostName; long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L); while( timeout > System.currentTimeMillis() ) { try{ if( logger.isInfoEnabled() ) { logger.info("Deleting hosted service " + hostName); } method.invoke("DELETE", ctx.getAccountNumber(), resourceDir, ""); break; } catch( CloudException err ) { logger.error("Unable to delete hosted service for " + hostName + ": " + err.getMessage()); logger.error("Retrying..."); try { Thread.sleep(30000L); } catch( InterruptedException ignore ) { } continue; } } throw e; } long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L); VirtualMachine vm = null ; if (requestId != null) { int httpCode = method.getOperationStatus(requestId); while (httpCode == -1) { try { Thread.sleep(15000L); } catch (InterruptedException ignored){} httpCode = method.getOperationStatus(requestId); } if (httpCode == HttpServletResponse.SC_OK) { try { vm = getVirtualMachine(hostName + ":" + hostName+":"+hostName); } catch( Throwable ignore ) { } if( vm != null ) { vm.setRootUser("dasein"); vm.setRootPassword(password); } } } else { while( timeout > System.currentTimeMillis() ) { try { vm = getVirtualMachine(hostName + ":" + hostName+":"+hostName); } catch( Throwable ignore ) { } if( vm != null ) { vm.setRootUser("dasein"); vm.setRootPassword(password); break; } try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } } } if( vm == null ) { throw new CloudException("System timed out waiting for virtual machine to appear"); } if( VmState.STOPPED.equals(vm.getCurrentState()) ) { start(vm.getProviderVirtualMachineId()); } return vm; } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".launch()"); } } } @Override public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException { return Collections.emptyList(); } @Override public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException { if( architecture.equals(Architecture.I32) ) { return Collections.emptyList(); } ArrayList<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>(); VirtualMachineProduct product = new VirtualMachineProduct(); product.setCpuCount(1); product.setDescription("Extra Small"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Extra Small"); product.setProviderProductId("ExtraSmall"); product.setRamSize(new Storage<Gigabyte>(1, Storage.GIGABYTE)); list.add(product); product = new VirtualMachineProduct(); product.setCpuCount(1); product.setDescription("Small"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Small"); product.setProviderProductId("Small"); product.setRamSize(new Storage<Gigabyte>(2, Storage.GIGABYTE)); list.add(product); product = new VirtualMachineProduct(); product.setCpuCount(2); product.setDescription("Medium"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Medium"); product.setProviderProductId("Medium"); product.setRamSize(new Storage<Gigabyte>(4, Storage.GIGABYTE)); //3.5G list.add(product); product = new VirtualMachineProduct(); product.setCpuCount(4); product.setDescription("Large"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Large"); product.setProviderProductId("Large"); product.setRamSize(new Storage<Gigabyte>(7, Storage.GIGABYTE)); //3.5G list.add(product); product = new VirtualMachineProduct(); product.setCpuCount(8); product.setDescription("Extra Large"); product.setRootVolumeSize(new Storage<Gigabyte>(15, Storage.GIGABYTE)); product.setName("Extra Large"); product.setProviderProductId("ExtraLarge"); product.setRamSize(new Storage<Gigabyte>(14, Storage.GIGABYTE)); //3.5G list.add(product); return Collections.unmodifiableList(list); } @Override public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException { return Collections.singletonList(Architecture.I64); } @Nonnull @Override public Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES); if( doc == null ) { return Collections.emptyList(); } NodeList entries = doc.getElementsByTagName("HostedService"); ArrayList<ResourceStatus> status = new ArrayList<ResourceStatus>(); for( int i=0; i<entries.getLength(); i++ ) { parseHostedServiceForStatus(ctx, entries.item(i), null, status); } return status; } @Override public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES); if( doc == null ) { return Collections.emptyList(); } NodeList entries = doc.getElementsByTagName("HostedService"); ArrayList<VirtualMachine> vms = new ArrayList<VirtualMachine>(); for( int i=0; i<entries.getLength(); i++ ) { parseHostedService(ctx, entries.item(i), null, vms); } return vms; } @Nonnull @Override public Iterable<VirtualMachine> listVirtualMachines(@Nullable VMFilterOptions vmFilterOptions) throws InternalException, CloudException { Iterable<VirtualMachine> vms = listVirtualMachines(); ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>(); for (VirtualMachine vm : vms) { if (vm.getName().matches(vmFilterOptions.getRegex())) { list.add(vm); } } return list; } private void parseDeployment(@Nonnull ProviderContext ctx, @Nonnull String regionId, @Nonnull String serviceName, @Nonnull Node node, @Nonnull List<VirtualMachine> virtualMachines) { ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>(); NodeList attributes = node.getChildNodes(); String deploymentSlot = null; String deploymentId = null; String dnsName = null; String vmRoleName = null; String imageId = null; String mediaLink = null; String vlan = null; String subnetName = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if( attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("deploymentslot") && attribute.hasChildNodes() ) { deploymentSlot = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("privateid") && attribute.hasChildNodes() ) { deploymentId = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes() ) { try { URI u = new URI(attribute.getFirstChild().getNodeValue().trim()); dnsName = u.getHost(); } catch( URISyntaxException e ) { // ignore } } else if( attribute.getNodeName().equalsIgnoreCase("roleinstancelist") && attribute.hasChildNodes() ) { NodeList roleInstances = attribute.getChildNodes(); for( int j=0; j<roleInstances.getLength(); j++ ) { Node roleInstance = roleInstances.item(j); if(roleInstance.getNodeType() == Node.TEXT_NODE) { continue; } if( roleInstance.getNodeName().equalsIgnoreCase("roleinstance") && roleInstance.hasChildNodes() ) { VirtualMachine role = new VirtualMachine(); role.setArchitecture(Architecture.I64); role.setClonable(false); role.setCurrentState(VmState.TERMINATED); role.setImagable(false); role.setPersistent(true); role.setPlatform(Platform.UNKNOWN); role.setProviderOwnerId(ctx.getAccountNumber()); role.setProviderRegionId(regionId); role.setProviderDataCenterId(regionId); NodeList roleAttributes = roleInstance.getChildNodes(); for( int l=0; l<roleAttributes.getLength(); l++ ) { Node roleAttribute = roleAttributes.item(l); if( roleAttribute.getNodeType() == Node.TEXT_NODE ) { continue; } if( roleAttribute.getNodeName().equalsIgnoreCase("RoleName") && roleAttribute.hasChildNodes() ) { String vmId = roleAttribute.getFirstChild().getNodeValue().trim(); role.setProviderVirtualMachineId(serviceName + ":" + vmId); role.setName(vmId); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instancesize") && roleAttribute.hasChildNodes() ) { role.setProductId(roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instanceupgradedomain") && roleAttribute.hasChildNodes() ) { role.setTag("UpgradeDomain", roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instanceerrorcode") && roleAttribute.hasChildNodes() ) { role.setTag("ErrorCode", roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instancefaultdomain") && roleAttribute.hasChildNodes() ) { role.setTag("FaultDomain", roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("fqdn") && roleAttribute.hasChildNodes() ) { role.setPrivateDnsAddress(roleAttribute.getFirstChild().getNodeValue().trim()); } else if( roleAttribute.getNodeName().equalsIgnoreCase("ipaddress") && roleAttribute.hasChildNodes() ) { role.setPrivateIpAddresses(new String[] { roleAttribute.getFirstChild().getNodeValue().trim() }); } else if( roleAttribute.getNodeName().equalsIgnoreCase("instanceendpoints") && roleAttribute.hasChildNodes() ) { NodeList endpoints = roleAttribute.getChildNodes(); for( int m=0; m<endpoints.getLength(); m++ ) { Node endpoint = endpoints.item(m); if( endpoint.hasChildNodes() ) { NodeList ea = endpoint.getChildNodes(); for( int n=0; n<ea.getLength(); n++ ) { Node a = ea.item(n); if( a.getNodeName().equalsIgnoreCase("vip") && a.hasChildNodes() ) { String addr = a.getFirstChild().getNodeValue().trim(); String[] ips = role.getPublicIpAddresses(); if( ips == null || ips.length < 1 ) { role.setPublicIpAddresses(new String[] { addr }); } else { boolean found = false; for( String ip : ips ) { if( ip.equals(addr) ) { found = true; break; } } if( !found ) { String[] tmp = new String[ips.length + 1]; System.arraycopy(ips, 0, tmp, 0, ips.length); tmp[tmp.length-1] = addr; role.setPublicIpAddresses(tmp); } } } } } } } else if( roleAttribute.getNodeName().equalsIgnoreCase("PowerState") && roleAttribute.hasChildNodes() ) { String powerStatus = roleAttribute.getFirstChild().getNodeValue().trim(); if( "Started".equalsIgnoreCase(powerStatus)){ role.setCurrentState(VmState.RUNNING); } else if( "Stopped".equalsIgnoreCase(powerStatus)){ role.setCurrentState(VmState.STOPPED); role.setImagable(true); } else if( "Stopping".equalsIgnoreCase(powerStatus)){ role.setCurrentState(VmState.STOPPING); } else if( "Starting".equalsIgnoreCase(powerStatus)){ role.setCurrentState(VmState.PENDING); } else { logger.warn("DEBUG: Unknown Azure status: " + powerStatus); } } } if( role.getProviderVirtualMachineId() == null ) { continue; } if( role.getName() == null ) { role.setName(role.getProviderVirtualMachineId()); } if( role.getDescription() == null ) { role.setDescription(role.getName()); } if( role.getPlatform().equals(Platform.UNKNOWN) ) { String descriptor = (role.getProviderVirtualMachineId() + " " + role.getName() + " " + role.getDescription() + " " + role.getProviderMachineImageId()).replaceAll("_", " "); role.setPlatform(Platform.guess(descriptor)); } else if( role.getPlatform().equals(Platform.UNIX) ) { String descriptor = (role.getProviderVirtualMachineId() + " " + role.getName() + " " + role.getDescription() + " " + role.getProviderMachineImageId()).replaceAll("_", " "); Platform p = Platform.guess(descriptor); if( p.isUnix() ) { role.setPlatform(p); } } list.add(role); } } } //Contain the information about disk and firewall; else if( attribute.getNodeName().equalsIgnoreCase("rolelist") && attribute.hasChildNodes() ) { NodeList roles = attribute.getChildNodes(); for( int k=0; k<roles.getLength(); k++ ) { Node role = roles.item(k); if( role.getNodeName().equalsIgnoreCase("role") && role.hasChildNodes() ) { if( role.hasAttributes() ) { Node n = role.getAttributes().getNamedItem("i:type"); if( n != null ) { String val = n.getNodeValue(); if( !"PersistentVMRole".equalsIgnoreCase(val) ) { continue; } } } NodeList roleAttributes = role.getChildNodes(); for( int l=0; l<roleAttributes.getLength(); l++ ) { Node roleAttribute = roleAttributes.item(l); if( roleAttribute.getNodeType() == Node.TEXT_NODE ) { continue; } if( roleAttribute.getNodeName().equalsIgnoreCase("osvirtualharddisk") && roleAttribute.hasChildNodes() ) { NodeList diskAttributes = roleAttribute.getChildNodes(); for( int m=0; m<diskAttributes.getLength(); m++ ) { Node diskAttribute = diskAttributes.item(m); if( diskAttribute.getNodeName().equalsIgnoreCase("SourceImageName") && diskAttribute.hasChildNodes() ) { imageId = diskAttribute.getFirstChild().getNodeValue().trim(); } else if( diskAttribute.getNodeName().equalsIgnoreCase("medialink") && diskAttribute.hasChildNodes() ) { mediaLink = diskAttribute.getFirstChild().getNodeValue().trim(); } } } else if( roleAttribute.getNodeName().equalsIgnoreCase("RoleName") && roleAttribute.hasChildNodes() ) { vmRoleName = roleAttribute.getFirstChild().getNodeValue().trim(); } else if( roleAttribute.getNodeName().equalsIgnoreCase("ConfigurationSets") && roleAttribute.hasChildNodes() ) { NodeList configs = ((Element) roleAttribute).getElementsByTagName("ConfigurationSet"); for (int n = 0; n<configs.getLength();n++) { boolean foundNetConfig = false; Node config = configs.item(n); if( config.hasAttributes() ) { Node c = config.getAttributes().getNamedItem("i:type"); if( c != null ) { String val = c.getNodeValue(); if( !"NetworkConfigurationSet".equalsIgnoreCase(val) ) { continue; } } } if (config.hasChildNodes()) { NodeList configAttribs = config.getChildNodes(); for (int o = 0; o<configAttribs.getLength();o++) { Node attrib = configAttribs.item(o); if (attrib.getNodeName().equalsIgnoreCase("SubnetNames")&& attrib.hasChildNodes()) { NodeList subnets = attrib.getChildNodes(); for (int p=0;p<subnets.getLength();p++) { Node subnet = subnets.item(p); if (subnet.getNodeName().equalsIgnoreCase("SubnetName") && subnet.hasChildNodes()) { subnetName = subnet.getFirstChild().getNodeValue().trim(); } } } } } } } } } } } else if (attribute.getNodeName().equalsIgnoreCase("virtualnetworkname") && attribute.hasChildNodes() ) { vlan = attribute.getFirstChild().getNodeValue().trim(); } } if( vmRoleName != null ) { for( VirtualMachine vm : list ) { if( deploymentSlot != null ) { vm.setTag("environment", deploymentSlot); } if( deploymentId != null ) { vm.setTag("deploymentId", deploymentId); } if( dnsName != null ) { vm.setPublicDnsAddress(dnsName); } if( imageId != null ) { Platform fallback = vm.getPlatform(); vm.setProviderMachineImageId(imageId); vm.setPlatform(Platform.guess(vm.getProviderMachineImageId())); if( vm.getPlatform().equals(Platform.UNKNOWN) ) { try { MachineImage img = provider.getComputeServices().getImageSupport().getMachineImage(vm.getProviderMachineImageId()); if( img != null ) { vm.setPlatform(img.getPlatform()); } } catch( Throwable t ) { logger.warn("Error loading machine image: " + t.getMessage()); } if( vm.getPlatform().equals(Platform.UNKNOWN) ) { vm.setPlatform(fallback); } } } if (vlan != null) { try { vm.setProviderVlanId(provider.getNetworkServices().getVlanSupport().getVlan(vlan).getProviderVlanId()); } catch (CloudException e) { logger.error("Error getting vlan id for vlan "+vlan); continue; } catch (InternalException ie){ logger.error("Error getting vlan id for vlan "+vlan); continue; } } if (subnetName != null) { vm.setProviderSubnetId(subnetName); } String[] parts = vm.getProviderVirtualMachineId().split(":"); String sName, deploymentName, roleName; if (parts.length == 3) { sName = parts[0]; deploymentName = parts[1]; roleName= parts[2]; } else if( parts.length == 2 ) { sName = parts[0]; deploymentName = parts[1]; roleName = deploymentName; } else { sName = serviceName; deploymentName = serviceName; roleName = serviceName; } vm.setTag("serviceName", sName); vm.setTag("deploymentName", deploymentName); vm.setTag("roleName", roleName); if( mediaLink != null ) { vm.setTag("mediaLink", mediaLink); } virtualMachines.add(vm); } } } private void parseStatus(@Nonnull ProviderContext ctx, @Nonnull String regionId, @Nonnull String serviceName, @Nonnull Node node, @Nonnull List<ResourceStatus> status) { ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); NodeList attributes = node.getChildNodes(); String id = ""; ResourceStatus s = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if( attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("roleinstancelist") && attribute.hasChildNodes() ) { NodeList roleInstances = attribute.getChildNodes(); for( int j=0; j<roleInstances.getLength(); j++ ) { Node roleInstance = roleInstances.item(j); if(roleInstance.getNodeType() == Node.TEXT_NODE) { continue; } if( roleInstance.getNodeName().equalsIgnoreCase("roleinstance") && roleInstance.hasChildNodes() ) { NodeList roleAttributes = roleInstance.getChildNodes(); for( int l=0; l<roleAttributes.getLength(); l++ ) { Node roleAttribute = roleAttributes.item(l); if( roleAttribute.getNodeType() == Node.TEXT_NODE ) { continue; } if( roleAttribute.getNodeName().equalsIgnoreCase("RoleName") && roleAttribute.hasChildNodes() ) { String vmId = roleAttribute.getFirstChild().getNodeValue().trim(); id = serviceName + ":" + vmId; } else if( roleAttribute.getNodeName().equalsIgnoreCase("PowerState") && roleAttribute.hasChildNodes() ) { String powerStatus = roleAttribute.getFirstChild().getNodeValue().trim(); if( "Started".equalsIgnoreCase(powerStatus)){ s = new ResourceStatus(id, VmState.RUNNING); } else if( "Stopped".equalsIgnoreCase(powerStatus)){ s = new ResourceStatus(id, VmState.STOPPED); } else if( "Stopping".equalsIgnoreCase(powerStatus)){ s = new ResourceStatus(id, VmState.STOPPING); } else if( "Starting".equalsIgnoreCase(powerStatus)){ s = new ResourceStatus(id, VmState.PENDING); } else { logger.warn("DEBUG: Unknown Azure status: " + powerStatus); } } } if( id == null ) { continue; } if (s != null) { list.add(s); s = null; } } } } } for (ResourceStatus rs : list) { status.add(rs); } } private void parseHostedService(@Nonnull ProviderContext ctx, @Nonnull Node entry, @Nullable String serviceName, @Nonnull List<VirtualMachine> virtualMachines) throws CloudException, InternalException { String regionId = ctx.getRegionId(); if( regionId == null ) { throw new AzureConfigException("No region ID was specified for this request"); } NodeList attributes = entry.getChildNodes(); String uri = null; long created = 0L; String service = null; boolean mediaLocationFound = false; DataCenter dc = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if(attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes() ) { uri = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("servicename") && attribute.hasChildNodes() ) { service = attribute.getFirstChild().getNodeValue().trim(); if( serviceName != null && !service.equals(serviceName) ) { return; } } else if( attribute.getNodeName().equalsIgnoreCase("hostedserviceproperties") && attribute.hasChildNodes() ) { NodeList properties = attribute.getChildNodes(); for( int j=0; j<properties.getLength(); j++ ) { Node property = properties.item(j); if(property.getNodeType() == Node.TEXT_NODE) { continue; } if( property.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes() ) { //get the region for this affinity group String affinityGroup = property.getFirstChild().getNodeValue().trim(); if (affinityGroup != null && !affinityGroup.equals("")) { dc = provider.getDataCenterServices().getDataCenter(affinityGroup); if (dc != null && dc.getRegionId().equals(regionId)) { mediaLocationFound = true; } else { // not correct region/datacenter return; } } } else if( property.getNodeName().equalsIgnoreCase("location") && property.hasChildNodes() ) { if( !mediaLocationFound && !regionId.equals(property.getFirstChild().getNodeValue().trim()) ) { return; } } else if( property.getNodeName().equalsIgnoreCase("datecreated") && property.hasChildNodes() ) { created = provider.parseTimestamp(property.getFirstChild().getNodeValue().trim()); } } } } if( uri == null || service == null ) { return; } AzureMethod method = new AzureMethod(provider); //dmayne 20130416: get the deployment names for each hosted service so we can then extract the detail String deployURL = HOSTED_SERVICES + "/"+ service+"?embed-detail=true"; Document deployDoc = method.getAsXML(ctx.getAccountNumber(), deployURL); if (deployDoc == null) { return; } NodeList deployments = deployDoc.getElementsByTagName("Deployments"); for (int i = 0; i < deployments.getLength(); i++) { Node deployNode = deployments.item(i); NodeList deployAttributes = deployNode.getChildNodes(); String deploymentName = ""; for (int j = 0; j<deployAttributes.getLength(); j++) { Node deployment = deployAttributes.item(j); if(deployment.getNodeType() == Node.TEXT_NODE) { continue; } if( deployment.getNodeName().equalsIgnoreCase("Deployment") && deployment.hasChildNodes() ) { NodeList dAttribs = deployment.getChildNodes(); for (int k = 0; k<dAttribs.getLength(); k++) { Node mynode = dAttribs.item(k); if ( mynode.getNodeName().equalsIgnoreCase("name") && mynode.hasChildNodes() ) { deploymentName = mynode.getFirstChild().getNodeValue().trim(); String resourceDir = HOSTED_SERVICES + "/" + service + "/deployments/" + deploymentName; Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir); if (doc == null) { return; } NodeList entries = doc.getElementsByTagName("Deployment"); for (int l = 0; l < entries.getLength(); l++) { parseDeployment(ctx, regionId, service+":"+deploymentName, entries.item(l), virtualMachines); } for (VirtualMachine vm : virtualMachines) { if (vm.getCreationTimestamp() < 1L) { vm.setCreationTimestamp(created); } if (dc != null) { vm.setProviderDataCenterId(dc.getProviderDataCenterId()); } else { Collection<DataCenter> dcs = provider.getDataCenterServices().listDataCenters(regionId); vm.setProviderDataCenterId(dcs.iterator().next().getProviderDataCenterId()); } } } } } } } } private void parseHostedServiceForStatus(@Nonnull ProviderContext ctx, @Nonnull Node entry, @Nullable String serviceName, @Nonnull List<ResourceStatus> status) throws CloudException, InternalException { String regionId = ctx.getRegionId(); if( regionId == null ) { throw new AzureConfigException("No region ID was specified for this request"); } NodeList attributes = entry.getChildNodes(); String uri = null; String service = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if(attribute.getNodeType() == Node.TEXT_NODE) { continue; } if( attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes() ) { uri = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("servicename") && attribute.hasChildNodes() ) { service = attribute.getFirstChild().getNodeValue().trim(); if( serviceName != null && !service.equals(serviceName) ) { return; } } else if( attribute.getNodeName().equalsIgnoreCase("hostedserviceproperties") && attribute.hasChildNodes() ) { NodeList properties = attribute.getChildNodes(); boolean mediaLocationFound = false; for( int j=0; j<properties.getLength(); j++ ) { Node property = properties.item(j); if(property.getNodeType() == Node.TEXT_NODE) { continue; } if( property.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes() ) { //get the region for this affinity group String affinityGroup = property.getFirstChild().getNodeValue().trim(); if (affinityGroup != null && !affinityGroup.equals("")) { DataCenter dc = provider.getDataCenterServices().getDataCenter(affinityGroup); if (dc.getRegionId().equals(regionId)) { mediaLocationFound = true; } else { // not correct region/datacenter return; } } } else if( property.getNodeName().equalsIgnoreCase("location") && property.hasChildNodes() ) { if( !mediaLocationFound && !regionId.equals(property.getFirstChild().getNodeValue().trim()) ) { return; } } } } } if( uri == null || service == null ) { return; } AzureMethod method = new AzureMethod(provider); //dmayne 20130416: get the deployment names for each hosted service so we can then extract the detail String deployURL = HOSTED_SERVICES + "/"+ service+"?embed-detail=true"; Document deployDoc = method.getAsXML(ctx.getAccountNumber(), deployURL); if (deployDoc == null) { return; } NodeList deployments = deployDoc.getElementsByTagName("Deployments"); for (int i = 0; i < deployments.getLength(); i++) { Node deployNode = deployments.item(i); NodeList deployAttributes = deployNode.getChildNodes(); String deploymentName = ""; for (int j = 0; j<deployAttributes.getLength(); j++) { Node deployment = deployAttributes.item(j); if(deployment.getNodeType() == Node.TEXT_NODE) { continue; } if( deployment.getNodeName().equalsIgnoreCase("Deployment") && deployment.hasChildNodes() ) { NodeList dAttribs = deployment.getChildNodes(); for (int k = 0; k<dAttribs.getLength(); k++) { Node mynode = dAttribs.item(k); if ( mynode.getNodeName().equalsIgnoreCase("name") && mynode.hasChildNodes() ) { deploymentName = mynode.getFirstChild().getNodeValue().trim(); String resourceDir = HOSTED_SERVICES + "/" + service + "/deployments/" + deploymentName; Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir); if (doc == null) { return; } NodeList entries = doc.getElementsByTagName("Deployment"); for (int l = 0; l < entries.getLength(); l++) { parseStatus(ctx, regionId, service + ":" + deploymentName, entries.item(l), status); } } } } } } } @Override public void reboot(@Nonnull String vmId) throws CloudException, InternalException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".reboot()"); } try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } String serviceName, deploymentName, roleName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); roleName = vm.getTag("roleName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roleInstances/" + roleName + "/Operations"; AzureMethod method = new AzureMethod(provider); StringBuilder xml = new StringBuilder(); xml.append("<RestartRoleOperation xmlns=\"http://schemas.microsoft.com/windowsazure\""); xml.append(" "); xml.append("xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("\n"); xml.append("<OperationType>RestartRoleOperation</OperationType>"); xml.append("\n"); xml.append("</RestartRoleOperation>"); xml.append("\n"); if( logger.isInfoEnabled() ) { logger.info("Rebooting " + vmId); } method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".reboot()"); } } } @Override public void resume(@Nonnull String vmId) throws CloudException, InternalException { throw new OperationNotSupportedException("Suspend/resume is not supported in Microsoft Azure"); } @Override public void pause(@Nonnull String vmId) throws InternalException, CloudException { throw new OperationNotSupportedException("Pause/unpause is not supported in Microsoft Azure"); } @Override public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".Boot()"); } try { // TODO: force vs not force ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } String serviceName, deploymentName, roleName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); roleName = vm.getTag("roleName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roleInstances/" + roleName + "/Operations"; logger.debug("__________________________________________________________"); logger.debug("Stop vm "+resourceDir); AzureMethod method = new AzureMethod(provider); StringBuilder xml = new StringBuilder(); xml.append("<ShutdownRoleOperation xmlns=\"http://schemas.microsoft.com/windowsazure\""); xml.append(" "); xml.append("xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); xml.append("\n"); xml.append("<OperationType>ShutdownRoleOperation </OperationType>"); xml.append("\n"); xml.append("</ShutdownRoleOperation>"); xml.append("\n"); if( logger.isInfoEnabled() ) { logger.info("Stopping the " + provider.getCloudName() + " virtual machine: " + vmId); } logger.debug(xml); logger.debug("__________________________________________________________"); method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".launch()"); } } } @Override public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) { return false; } @Override public boolean supportsStartStop(@Nonnull VirtualMachine vm) { return true; } @Override public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) { return false; } @Override public void suspend(@Nonnull String vmId) throws CloudException, InternalException { throw new OperationNotSupportedException("Suspend/resume is not supported in Microsoft Azure"); } @Override public void terminate(@Nonnull String vmId, @Nullable String explanation) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureVM.class.getName() + ".terminate()"); } try { VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { throw new CloudException("No such virtual machine: " + vmId); } ArrayList<String> disks = getAttachedDisks(vm); long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L); while( timeout > System.currentTimeMillis() ) { if( vm == null || VmState.TERMINATED.equals(vm.getCurrentState()) ) { return; } if( !VmState.PENDING.equals(vm.getCurrentState()) && !VmState.STOPPING.equals(vm.getCurrentState()) ) { break; } try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } try { vm = getVirtualMachine(vmId); } catch( Throwable ignore ) { } } ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } String serviceName, deploymentName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName; AzureMethod method = new AzureMethod(provider); timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*10L); while( timeout > System.currentTimeMillis() ) { if( logger.isInfoEnabled() ) { logger.info("Deleting deployments for " + serviceName); } try { method.invoke("DELETE", ctx.getAccountNumber(), resourceDir, ""); break; } catch( CloudException e ) { if( e.getProviderCode() != null && e.getProviderCode().equals("ConflictError") ) { logger.warn("Conflict error, maybe retrying in 30 seconds"); try { Thread.sleep(30000L); } catch( InterruptedException ignore ) { } continue; } throw e; } } timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*10L); while( timeout > System.currentTimeMillis() ) { if( vm == null || VmState.TERMINATED.equals(vm.getCurrentState()) ) { break; } try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } try { vm = getVirtualMachine(vmId); } catch( Throwable ignore ) { } } terminateService(serviceName, explanation); //now delete the orphaned disks for (String disk : disks) { provider.getComputeServices().getVolumeSupport().remove(disk); } } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureVM.class.getName() + ".terminate()"); } } } public void terminateService(String serviceName, String explanation) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.terminateService"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } AzureMethod method = new AzureMethod(provider); String resourceDir = HOSTED_SERVICES + "/" + serviceName; long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L); while( timeout > System.currentTimeMillis() ) { try{ if( logger.isInfoEnabled() ) { logger.info("Deleting hosted service " + serviceName+": "+explanation); } method.invoke("DELETE", ctx.getAccountNumber(), resourceDir, ""); break; } catch( CloudException e ) { logger.error("Unable to delete hosted service for " + serviceName + ": " + e.getMessage()); logger.error("Retrying..."); try { Thread.sleep(30000L); } catch( InterruptedException ignore ) { } continue; } catch( Throwable t ) { logger.warn("Unable to delete hosted service for " + serviceName + ": " + t.getMessage()); return; } } } finally { APITrace.end(); } } private ArrayList<String> getAttachedDisks(VirtualMachine vm) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was set for this request"); } ArrayList<String> list = new ArrayList<String>(); boolean diskFound = false; String serviceName, deploymentName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName; AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(),resourceDir); NodeList entries = doc.getElementsByTagName("Deployment"); for (int i = 0; i < entries.getLength(); i++) { Node entry = entries.item(i); NodeList attributes = entry.getChildNodes(); for (int j = 0; j < attributes.getLength(); j++){ Node attribute = attributes.item(j); if (attribute.getNodeName().equalsIgnoreCase("RoleList") && attribute.hasChildNodes()) { NodeList instances = attribute.getChildNodes(); for (int k = 0; k <instances.getLength(); k++){ Node instance = instances.item(k); if (instance.getNodeName().equalsIgnoreCase("Role") && instance.hasChildNodes()){ NodeList roles = instance.getChildNodes(); for (int l = 0; l<roles.getLength(); l++) { Node role = roles.item(l); if (role.getNodeName().equalsIgnoreCase("OSVirtualHardDisk") && role.hasChildNodes()) { NodeList disks = role.getChildNodes(); for (int m = 0; m<disks.getLength(); m++) { Node disk = disks.item(m); if (disk.getNodeName().equalsIgnoreCase("DiskName") && disk.hasChildNodes()) { String name = disk.getFirstChild().getNodeValue(); list.add(name); diskFound = true; break; } } } if (diskFound) { diskFound = false; break; } } } } } } } return list; } @Override public void unpause(@Nonnull String vmId) throws CloudException, InternalException { throw new OperationNotSupportedException("Pause/unpause is not supported in Microsoft Azure"); } @Override public void updateTags(@Nonnull String vmId, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void updateTags(@Nonnull String[] strings, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void removeTags(@Nonnull String s, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void removeTags(@Nonnull String[] strings, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) { return new String[0]; } private @Nonnull String toUniqueId(@Nonnull String name, @Nonnull AzureMethod method, ProviderContext ctx) throws CloudException, InternalException { name = name.toLowerCase().replaceAll(" ", ""); String id = name; int i = 0; while (method.getAsXML(ctx.getAccountNumber(), HOSTED_SERVICES+ "/"+id) != null) { i++; id = name + "-" + i; } return id; } }
bugzid 3585: fixed alter vm size
src/main/java/org/dasein/cloud/azure/compute/vm/AzureVM.java
bugzid 3585: fixed alter vm size
<ide><path>rc/main/java/org/dasein/cloud/azure/compute/vm/AzureVM.java <ide> <ide> String[] parts = options.getProviderProductId().split(":"); <ide> String productId = null; <del> String disks = null; <del> if (parts.length == 2) { <add> String disks = ""; <add> if (parts.length == 1) { <add> productId=parts[0]; <add> } <add> else if (parts.length == 2) { <ide> productId = parts[0]; <ide> disks = parts[1].replace("[","").replace("]",""); <ide> } <ide> else { <del> throw new InternalException("Invalid product id string. Product id format is product name:[disk_0_size,disk_1_size,disk_n_size]"); <del> } <add> throw new InternalException("Invalid product id string. Product id format is PRODUCT_NAME or PRODUCT_NAME:[disk_0_size,disk_1_size,disk_n_size]"); <add> } <add> //check the product id is legitimate <add> boolean found = false; <add> Iterable<VirtualMachineProduct> products = listProducts(Architecture.I64); <add> for (VirtualMachineProduct p : products) { <add> if (p.getProviderProductId().equals(productId)) { <add> found = true; <add> break; <add> } <add> } <add> <add> if (!found) { <add> throw new InternalException("Product id invalid: should be one of ExtraSmall, Small, Medium, Large, ExtraLarge"); <add> } <add> <ide> String[] diskSizes = disks.split(","); <ide> <ide> VirtualMachine vm = getVirtualMachine(vmId); <ide> Node role = roles.item(0); <ide> <ide> NodeList entries = role.getChildNodes(); <add> boolean changeProduct = false; <ide> <ide> for (int i = 0; i<entries.getLength(); i++) { <ide> Node vn = entries.item(i); <ide> String vnName = vn.getNodeName(); <ide> <ide> if( vnName.equalsIgnoreCase("RoleSize") && vn.hasChildNodes() ) { <del> vn.setNodeValue(productId); <del> } <del> } <del> <del> String output=""; <del> try{ <del> TransformerFactory tf = TransformerFactory.newInstance(); <del> Transformer transformer = tf.newTransformer(); <del> transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); <del> StringWriter writer = new StringWriter(); <del> transformer.transform(new DOMSource(doc), new StreamResult(writer)); <del> output = writer.getBuffer().toString().replaceAll("\n|\r", ""); <del> } <del> catch (Exception e){ <del> System.err.println(e); <del> } <del> xml.append(output); <del> <del> logger.debug(xml); <del> logger.debug("___________________________________________________"); <del> <del> resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/" + roleName; <del> String requestId = method.invoke("PUT", ctx.getAccountNumber(), resourceDir, xml.toString()); <del> <add> if (!productId.equals(vn.getFirstChild().getNodeValue())) { <add> vn.getFirstChild().setNodeValue(productId); <add> changeProduct=true; <add> } <add> else { <add> logger.info("No product change required"); <add> } <add> break; <add> } <add> } <add> <add> String requestId=null; <add> <add> if (changeProduct) { <add> String output=""; <add> try{ <add> TransformerFactory tf = TransformerFactory.newInstance(); <add> Transformer transformer = tf.newTransformer(); <add> transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); <add> StringWriter writer = new StringWriter(); <add> transformer.transform(new DOMSource(doc), new StreamResult(writer)); <add> output = writer.getBuffer().toString().replaceAll("\n|\r", ""); <add> } <add> catch (Exception e){ <add> System.err.println(e); <add> } <add> xml.append(output); <add> <add> logger.debug(xml); <add> logger.debug("___________________________________________________"); <add> <add> resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/" + roleName; <add> requestId = method.invoke("PUT", ctx.getAccountNumber(), resourceDir, xml.toString()); <add> } <add> else { <add> requestId="noChange"; <add> } <ide> if (requestId != null) { <del> int httpCode = method.getOperationStatus(requestId); <del> while (httpCode == -1) { <del> try { <del> Thread.sleep(15000L); <del> } <del> catch (InterruptedException ignored){} <add> int httpCode = -1; <add> if (!requestId.equals("noChange")) { <ide> httpCode = method.getOperationStatus(requestId); <del> } <del> if (httpCode == HttpServletResponse.SC_OK) { <add> while (httpCode == -1) { <add> try { <add> Thread.sleep(15000L); <add> } <add> catch (InterruptedException ignored){} <add> httpCode = method.getOperationStatus(requestId); <add> } <add> } <add> if (httpCode == HttpServletResponse.SC_OK || requestId.equals("noChange")) { <ide> //attach any disks as appropriate <ide> for (int i = 0; i < diskSizes.length; i++) { <del> xml = new StringBuilder(); <del> xml.append("<DataVirtualHardDisk xmlns=\"http://schemas.microsoft.com/windowsazure\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); <del> xml.append("<HostCaching>ReadWrite</HostCaching>"); <del> xml.append("<LogicalDiskSizeInGB>").append(diskSizes[i]).append("</LogicalDiskSizeInGB>"); <del> xml.append("<MediaLink>").append(provider.getStorageEndpoint()).append("vhds/").append(roleName).append(System.currentTimeMillis()%10000).append(".vhd</MediaLink>"); <del> xml.append("</DataVirtualHardDisk>"); <del> logger.debug(xml); <del> resourceDir = HOSTED_SERVICES + "/" +serviceName+ "/deployments" + "/" + deploymentName + "/roles"+"/" + roleName+ "/DataDisks"; <del> requestId = method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); <del> if (requestId != null) { <del> httpCode = method.getOperationStatus(requestId); <del> while (httpCode == -1) { <del> try { <del> Thread.sleep(15000L); <del> } <del> catch (InterruptedException ignored){} <add> if (!diskSizes[i].equals("")) { <add> xml = new StringBuilder(); <add> xml.append("<DataVirtualHardDisk xmlns=\"http://schemas.microsoft.com/windowsazure\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"); <add> xml.append("<HostCaching>ReadWrite</HostCaching>"); <add> xml.append("<LogicalDiskSizeInGB>").append(diskSizes[i]).append("</LogicalDiskSizeInGB>"); <add> xml.append("<MediaLink>").append(provider.getStorageEndpoint()).append("vhds/").append(roleName).append(System.currentTimeMillis()%10000).append(".vhd</MediaLink>"); <add> xml.append("</DataVirtualHardDisk>"); <add> logger.debug(xml); <add> resourceDir = HOSTED_SERVICES + "/" +serviceName+ "/deployments" + "/" + deploymentName + "/roles"+"/" + roleName+ "/DataDisks"; <add> requestId = method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); <add> if (requestId != null) { <ide> httpCode = method.getOperationStatus(requestId); <add> while (httpCode == -1) { <add> try { <add> Thread.sleep(15000L); <add> } <add> catch (InterruptedException ignored){} <add> httpCode = method.getOperationStatus(requestId); <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
9be3323e3027945fff483397aa38924bc6056425
0
yongaro/Pokemon
package pokemon.modele; import java.util.Arrays; import java.util.Random; import java.util.Scanner; import java.util.Stack; import java.util.Vector; import pokemon.annotations.Tps; import pokemon.launcher.MyGdxGame; @Tps(nbhours=17) public class Combat extends Thread { protected Terrain terrain; protected Climat climat; protected PokemonCombat[] equipe1; protected PokemonCombat[] equipe2; protected PokemonCombat[] pkmListe; protected boolean endOfTurn; protected String buffer; protected boolean bufferReady; protected PokemonCombat pCourant; protected PokemonCombat cibleCourante; protected Capacite capCur; protected int actflag; protected int act; protected int ind; protected boolean freeze; //0 niveau 1 XP 2 PV 3 ATT 4 DEF 5 ATTSP 6 DEFSP 7 VIT 8 Precision (100) 9 Esquive (5% de base) public Combat(){ terrain=Terrain.Plaine; climat=Climat.Normal; buffer=""; bufferReady=false; actflag=-1; act=-1; ind=-1; freeze=false; endOfTurn=false; } public Combat(Joueur j1,Joueur j2){ this(); this.initSolo(j1,j2); } public Combat(Joueur j,Dresseur d){ this(); this.initSolo(j,d); } public int gagnant(){ int nbko1=0; int nbko2=0; for(int i=0;i<equipe1.length;i++){ if(equipe1[i].pkm.stats[2][0]<=0){ nbko1++; } } for(int i=0;i<equipe2.length;i++){ if(equipe2[i].pkm.stats[2][0]<=0){ nbko2++; } } if(nbko2==equipe2.length){ return 1; } if(nbko1==equipe1.length){ return 2; } return 0; } public PokemonCombat[] getPkmListe() { return pkmListe; } public void run(){ this.combatsolo(); } public void initSolo(Joueur j1,Joueur j2){ equipe1=new PokemonCombat[j1.teamsize]; equipe2=new PokemonCombat[j2.teamsize]; pkmListe=new PokemonCombat[2]; for(int i=0;i<j1.teamsize;i++){ equipe1[i]=new PokemonCombat(j1.team[i],false,j1); equipe1[i].equipe=equipe1; } for(int i=0;i<j2.teamsize;i++){ equipe2[i]=new PokemonCombat(j2.team[i],true,j2); equipe2[i].equipe=equipe2; } pkmListe[0]=equipe1[0]; pkmListe[1]=equipe2[0]; pkmListe[0].adv[0]=pkmListe[1]; pkmListe[0].XpStack.add(pkmListe[0].adv[0].pkm); pkmListe[1].adv[0]=pkmListe[0]; pkmListe[1].XpStack.add(pkmListe[1].adv[0].pkm); pkmListe[0].listeIndice=0; pkmListe[1].listeIndice=1; } public void initSolo(Joueur j,Dresseur d){ equipe1=new PokemonCombat[j.teamsize]; equipe2=new PokemonCombat[d.getTeam().size()]; pkmListe=new PokemonCombat[2]; for(int i=0;i<j.teamsize;i++){ equipe1[i]=new PokemonCombat(j.team[i],false,j); equipe1[i].equipe=equipe1; } for(int i=0;i<d.getTeam().size();i++){ equipe2[i]=new PokemonCombat(d.getTeam().elementAt(i),true,d); equipe2[i].equipe=equipe2; } pkmListe[0]=equipe1[0]; pkmListe[1]=equipe2[0]; pkmListe[0].adv[0]=pkmListe[1]; pkmListe[0].XpStack.add(pkmListe[0].adv[0].pkm); pkmListe[1].adv[0]=pkmListe[0]; pkmListe[1].XpStack.add(pkmListe[1].adv[0].pkm); pkmListe[0].listeIndice=0; pkmListe[1].listeIndice=1; } public int combatsolo(){ System.out.println("FREEZE DE DEBUT DE COMBAT"); this.setfreeze(true); while(this.gagnant()==0){ Arrays.sort(pkmListe); for(int i=0;i<pkmListe.length;i++){ this.resetAct(); this.setBufferState(false); pCourant=pkmListe[i]; this.capCur=null; this.cibleCourante=null; pkmListe[i].action(pkmListe[i].adv[0],this); //System.out.println("FIN DE TOUR \n"+pCourant.pkm.nom+" "+cibleCourante.pkm.nom+" "+capCur.nom); } //Application des d�gats sur la dur�e endOfTurn=true; for(PokemonCombat p:pkmListe){ if(p.pkm.statut==Statut.Empoisonne || p.pkm.statut==Statut.Brule ){ this.pCourant=p; this.capCur=p.pkm.statut.dummy; this.cibleCourante=p; p.pkm.statut.StatEffect(p.pkm,1,this); this.setfreeze(true); for(Statut s: p.pkm.supTemp){ this.pCourant=p; this.capCur=s.dummy; this.cibleCourante=p; s.StatEffect(p.pkm,1,this); this.setfreeze(true); } if(p.pkm.stats[2][0]<=0){ p.XPreward(this); pokeswap(p,true); } } } endOfTurn=false; } return this.gagnant(); } public void action(PokemonCombat user,PokemonCombat cible){ int isdone=0; int i=0; int ch1=0; int ch2=1; while(isdone==0){ System.out.println("Debut du tour du joueur"); this.getAct(); switch(actflag){ case 0: System.out.println("Execution d'une Capacite"); //while((act=sc.nextInt())<user.cap.max){System.out.println(act); } //act=sc.nextInt(); //Application des statuts pouvant empecher l'action ch1=user.pkm.statut.StatEffect(user.pkm,0,this); for(Statut s: user.pkm.supTemp){ if(s.StatEffect(user.pkm,0,this)==0){ ch2=0; } } if(ch1==1 && ch2==1){ this.capCur=user.pkm.cap.elementAt(act).cible; this.cibleCourante=cible; user.pkm.cap.utiliser(act,user.pkm,cible.pkm,this); } //Consequences de l'action this.chercherKO(); if(user.pkm.stats[2][0]<=(int)(user.pkm.stats[2][1]/2) && cible.pkm.statut!=Statut.KO){ if(user.pkm.objTenu instanceof Medicament && cible.pkm.objTenu!=null){ Medicament m=(Medicament)user.pkm.objTenu; this.ajoutBuffer(user.pkm.nom+" utilise sa baie"); if(m.baie){ m.script(user.pkm,this); user.pkm.objTenu=null; } } } if(cible.pkm.stats[2][0]<=(int)(cible.pkm.stats[2][1]/2) && cible.pkm.statut!=Statut.KO){ if(cible.pkm.objTenu instanceof Medicament && cible.pkm.objTenu!=null){ Medicament m=(Medicament)cible.pkm.objTenu; this.ajoutBuffer(cible.pkm.nom+" utilise sa baie"); if(m.baie){ m.script(cible.pkm,this); cible.pkm.objTenu=null; } } } isdone=1; this.setBufferState(true); break; case 1: //Inventaire break; case 2: pokeswap(user,false); //traitement capacite passive ici isdone=1; this.setBufferState(true); break; case 3: System.out.println("FUITE"); break; default : System.out.println("mauvaise input dans "+user.pkm.nom+" action"); break; } } System.out.println("FIN D'ACTION DU JOUEUR"); } public void ajoutXpStack(PokemonCombat pkmc){ for(PokemonCombat p:pkmListe){ if(p.equipe!=pkmc.equipe && !p.XpStack.contains(pkmc.pkm)){ p.XpStack.push(pkmc.pkm); } } } public void chercherKO(){ for(PokemonCombat p: pkmListe){ if(p.pkm.stats[2][0]<=0){ p.XPreward(this); pokeswap(p,true); } } } public void pokeswap(PokemonCombat user,boolean ko){ /*int i=0; int act=0;*/ int done=0; int select=0;// Pkm pkmRef; Stack<Pkm> stackRef; if(!user.isIA){ while(done==0){ if(ko){ user.waitPlswap(); select=user.swap;} else{ select=this.act; } if(user.equipe[select].pkm.statut!=Statut.KO){ System.out.println(user.equipe[select].pkm.nom+" remplace "+user.pkm.nom); //pkmRef=user.pkm; stackRef=user.XpStack; user.pkm=user.equipe[select].pkm; user.XpStack=user.equipe[select].XpStack; //user.equipe[act].pkm=pkmRef; user.equipe[act].XpStack=stackRef; ajoutXpStack(user); done=1; } else{ System.out.println("Vous ne pouvez pas envoyer un Pokemon K.O au combat !"); } } } else{ for(int i=0;i<user.equipe.length;i++){ if(user.equipe[i].pkm.statut!=Statut.KO){ System.out.println(user.prop+" envoie "+user.equipe[i].pkm.nom+" au combat"); user.setSwap(i); user.waitIAswap(); //pkmRef=user.pkm; stackRef=user.XpStack; user.pkm=user.equipe[i].pkm; user.XpStack=user.equipe[i].XpStack; //p.pkm=pkmRef; p.XpStack=stackRef; ajoutXpStack(user); break; } } } } public Terrain getTerrain(){ return terrain; } public Climat getClimat(){ return climat; } public PokemonCombat[] getEquipe1(){ return equipe1;} public PokemonCombat[] getEquipe2(){ return equipe2;} public Capacite getCapCur() { return capCur; } // Fonctions de manipulation des objets synchronis�s entre modele et vue public synchronized void ajoutBuffer(String s){ this.buffer+=s+"\n"; notify(); } public synchronized boolean bufferIsEmpty(){ return this.buffer.compareTo("")==0; } public synchronized boolean bufferIsReady(){ return bufferReady; } public synchronized String readBuffer(){ while(this.buffer.compareTo("")==0){ try { wait(); } catch(InterruptedException ie) { ie.printStackTrace(); } } return this.buffer; } public synchronized void resetBuffer(){ this.buffer=""; setBufferState(false);} public synchronized void setBufferState(boolean st){ bufferReady=st; if(bufferReady){ notify(); } } public synchronized void getAct(){ while(actflag==-1 && act==-1){ try { wait(); } catch(InterruptedException ie) { ie.printStackTrace(); } } } public synchronized void setAct(int aflag,int act){ actflag=aflag; this.act=act; notify(); } public synchronized void resetAct(){ this.actflag=-1; this.act=-1; notify(); } public synchronized void setfreeze(boolean f){ freeze=f; if(!freeze){ System.out.println("SETFREEZE "+f); notify();} else{ while(freeze){ try { System.out.println("SETFREEZE "+f); this.wait(); } catch(InterruptedException ie) { ie.printStackTrace(); } } } } public synchronized PokemonCombat getPCourant(){ return pCourant;} public synchronized PokemonCombat getCibleCourante() { return cibleCourante; } public synchronized void setCible(PokemonCombat cible){ this.cibleCourante=cible; } public synchronized boolean getendOfTurn(){ return endOfTurn;} }
Pokemon-core/src/pokemon/modele/Combat.java
package pokemon.modele; import java.util.Arrays; import java.util.Random; import java.util.Scanner; import java.util.Stack; import java.util.Vector; import pokemon.annotations.Tps; import pokemon.launcher.MyGdxGame; @Tps(nbhours=17) public class Combat extends Thread { protected Terrain terrain; protected Climat climat; protected PokemonCombat[] equipe1; protected PokemonCombat[] equipe2; protected PokemonCombat[] pkmListe; protected boolean endOfTurn; protected String buffer; protected boolean bufferReady; protected PokemonCombat pCourant; protected PokemonCombat cibleCourante; protected Capacite capCur; protected int actflag; protected int act; protected int ind; protected boolean freeze; //0 niveau 1 XP 2 PV 3 ATT 4 DEF 5 ATTSP 6 DEFSP 7 VIT 8 Precision (100) 9 Esquive (5% de base) public Combat(){ terrain=Terrain.Plaine; climat=Climat.Normal; buffer=""; bufferReady=false; actflag=-1; act=-1; ind=-1; freeze=false; endOfTurn=false; } public Combat(Joueur j1,Joueur j2){ this(); this.initSolo(j1,j2); } public Combat(Joueur j,Dresseur d){ this(); this.initSolo(j,d); } public int gagnant(){ int nbko1=0; int nbko2=0; for(int i=0;i<equipe1.length;i++){ if(equipe1[i].pkm.stats[2][0]<=0){ nbko1++; } } for(int i=0;i<equipe2.length;i++){ if(equipe2[i].pkm.stats[2][0]<=0){ nbko2++; } } if(nbko2==equipe2.length){ return 1; } if(nbko1==equipe1.length){ return 2; } return 0; } public PokemonCombat[] getPkmListe() { return pkmListe; } public void run(){ this.combatsolo(); } public void initSolo(Joueur j1,Joueur j2){ equipe1=new PokemonCombat[j1.teamsize]; equipe2=new PokemonCombat[j2.teamsize]; pkmListe=new PokemonCombat[2]; for(int i=0;i<j1.teamsize;i++){ equipe1[i]=new PokemonCombat(j1.team[i],false,j1); equipe1[i].equipe=equipe1; } for(int i=0;i<j2.teamsize;i++){ equipe2[i]=new PokemonCombat(j2.team[i],true,j2); equipe2[i].equipe=equipe2; } pkmListe[0]=equipe1[0]; pkmListe[1]=equipe2[0]; pkmListe[0].adv[0]=pkmListe[1]; pkmListe[0].XpStack.add(pkmListe[0].adv[0].pkm); pkmListe[1].adv[0]=pkmListe[0]; pkmListe[1].XpStack.add(pkmListe[1].adv[0].pkm); pkmListe[0].listeIndice=0; pkmListe[1].listeIndice=1; } public void initSolo(Joueur j,Dresseur d){ equipe1=new PokemonCombat[j.teamsize]; equipe2=new PokemonCombat[d.getTeam().size()]; pkmListe=new PokemonCombat[2]; for(int i=0;i<j.teamsize;i++){ equipe1[i]=new PokemonCombat(j.team[i],false,j); equipe1[i].equipe=equipe1; } for(int i=0;i<d.getTeam().size();i++){ equipe2[i]=new PokemonCombat(d.getTeam().elementAt(i),true,d); equipe2[i].equipe=equipe2; } pkmListe[0]=equipe1[0]; pkmListe[1]=equipe2[0]; pkmListe[0].adv[0]=pkmListe[1]; pkmListe[0].XpStack.add(pkmListe[0].adv[0].pkm); pkmListe[1].adv[0]=pkmListe[0]; pkmListe[1].XpStack.add(pkmListe[1].adv[0].pkm); pkmListe[0].listeIndice=0; pkmListe[1].listeIndice=1; } public int combatsolo(){ System.out.println("FREEZE DE DEBUT DE COMBAT"); this.setfreeze(true); while(this.gagnant()==0){ Arrays.sort(pkmListe); for(int i=0;i<pkmListe.length;i++){ this.resetAct(); this.setBufferState(false); pCourant=pkmListe[i]; this.capCur=null; this.cibleCourante=null; pkmListe[i].action(pkmListe[i].adv[0],this); //System.out.println("FIN DE TOUR \n"+pCourant.pkm.nom+" "+cibleCourante.pkm.nom+" "+capCur.nom); } //Application des d�gats sur la dur�e endOfTurn=true; for(PokemonCombat p:pkmListe){ if(p.pkm.statut==Statut.Empoisonne || p.pkm.statut==Statut.Brule ){ this.pCourant=p; this.capCur=p.pkm.statut.dummy; this.cibleCourante=p; p.pkm.statut.StatEffect(p.pkm,1,this); this.setfreeze(true); for(Statut s: p.pkm.supTemp){ this.pCourant=p; this.capCur=s.dummy; this.cibleCourante=p; s.StatEffect(p.pkm,1,this); this.setfreeze(true); } if(p.pkm.stats[2][0]<=0){ p.XPreward(this); pokeswap(p,true); } } } endOfTurn=false; } return this.gagnant(); } public void action(PokemonCombat user,PokemonCombat cible){ int isdone=0; int i=0; int ch1=0; int ch2=1; while(isdone==0){ System.out.println("Debut du tour du joueur"); this.getAct(); switch(actflag){ case 0: System.out.println("Execution d'une Capacite"); //while((act=sc.nextInt())<user.cap.max){System.out.println(act); } //act=sc.nextInt(); //Application des statuts pouvant empecher l'action ch1=user.pkm.statut.StatEffect(user.pkm,0,this); for(Statut s: user.pkm.supTemp){ if(s.StatEffect(user.pkm,0,this)==0){ ch2=0; } } if(ch1==1 && ch2==1){ this.capCur=user.pkm.cap.elementAt(act).cible; this.cibleCourante=cible; user.pkm.cap.utiliser(act,user.pkm,cible.pkm,this); } //Consequences de l'action this.chercherKO(); if(user.pkm.stats[2][0]<=(int)(user.pkm.stats[2][1]/2) && cible.pkm.statut!=Statut.KO){ if(user.pkm.objTenu instanceof Medicament && cible.pkm.objTenu!=null){ Medicament m=(Medicament)user.pkm.objTenu; this.ajoutBuffer(user.pkm.nom+" utilise sa baie"); if(m.baie){ m.script(user.pkm,this); user.pkm.objTenu=null; } } } if(cible.pkm.stats[2][0]<=(int)(cible.pkm.stats[2][1]/2) && cible.pkm.statut!=Statut.KO){ if(cible.pkm.objTenu instanceof Medicament && cible.pkm.objTenu!=null){ Medicament m=(Medicament)cible.pkm.objTenu; this.ajoutBuffer(cible.pkm.nom+" utilise sa baie"); if(m.baie){ m.script(cible.pkm,this); cible.pkm.objTenu=null; } } } isdone=1; this.setBufferState(true); break; case 1: //Inventaire break; case 2: pokeswap(user,false); //traitement capacite passive ici isdone=1; this.setBufferState(true); break; case 3: System.out.println("FUITE"); break; default : System.out.println("mauvaise input dans "+user.pkm.nom+" action"); break; } } System.out.println("FIN D'ACTION DU JOUEUR"); } public void ajoutXpStack(PokemonCombat pkmc){ for(PokemonCombat p:pkmListe){ if(p.equipe!=pkmc.equipe && !p.XpStack.contains(pkmc.pkm)){ p.XpStack.push(pkmc.pkm); } } } public void chercherKO(){ for(PokemonCombat p: pkmListe){ if(p.pkm.stats[2][0]<=0){ p.XPreward(this); pokeswap(p,true); } } } public void pokeswap(PokemonCombat user,boolean ko){ /*int i=0; int act=0;*/ int done=0; int select=0;// Pkm pkmRef; Stack<Pkm> stackRef; if(!user.isIA){ while(done==0){ if(ko){ user.waitPlswap(); select=user.swap;} else{ select=this.act; } if(user.equipe[select].pkm.statut!=Statut.KO){ System.out.println(user.equipe[select].pkm.nom+" remplace "+user.pkm.nom); //pkmRef=user.pkm; stackRef=user.XpStack; user.pkm=user.equipe[select].pkm; user.XpStack=user.equipe[select].XpStack; //user.equipe[act].pkm=pkmRef; user.equipe[act].XpStack=stackRef; ajoutXpStack(user); done=1; } else{ System.out.println("Vous ne pouvez pas envoyer un Pokemon K.O au combat !"); } } } else{ for(int i=0;i<user.equipe.length;i++){ if(user.equipe[i].pkm.statut!=Statut.KO){ System.out.println(user.prop+" envoie "+user.equipe[i].pkm.nom+" au combat"); user.setSwap(i); user.waitIAswap(); //pkmRef=user.pkm; stackRef=user.XpStack; user.pkm=user.equipe[i].pkm; user.XpStack=user.equipe[i].XpStack; //p.pkm=pkmRef; p.XpStack=stackRef; ajoutXpStack(user); break; } } } } public Terrain getTerrain(){ return terrain; } public Climat getClimat(){ return climat; } public PokemonCombat[] getEquipe1(){ return equipe1;} public PokemonCombat[] getEquipe2(){ return equipe2;} public Capacite getCapCur() { return capCur; } // Fonctions de manipulation des objets synchronis�s entre modele et vue public synchronized void ajoutBuffer(String s){ this.buffer+=s+"\n"; notify(); } public synchronized boolean bufferIsEmpty(){ return this.buffer.compareTo("")==0; } public synchronized boolean bufferIsReady(){ return bufferReady; } public synchronized String readBuffer(){ while(this.buffer.compareTo("")==0){ try { wait(); } catch(InterruptedException ie) { ie.printStackTrace(); } } return this.buffer; } public synchronized void resetBuffer(){ this.buffer=""; setBufferState(false);} public synchronized void setBufferState(boolean st){ bufferReady=st; if(bufferReady){ notify(); } } public synchronized void getAct(){ while(actflag==-1 && act==-1){ try { wait(); } catch(InterruptedException ie) { ie.printStackTrace(); } } } public synchronized void setAct(int aflag,int act){ actflag=aflag; this.act=act; notify(); } public synchronized void resetAct(){ this.actflag=-1; this.act=-1; notify(); } public synchronized void setfreeze(boolean f){ freeze=f; if(!freeze){ System.out.println("SETFREEZE "+f); notify();} else{ while(freeze){ try { System.out.println("SETFREEZE "+f); this.wait(); } catch(InterruptedException ie) { ie.printStackTrace(); } } } } public synchronized PokemonCombat getPCourant(){ return pCourant;} public synchronized PokemonCombat getCibleCourante() { return cibleCourante; } public synchronized void setCible(PokemonCombat cible){ this.cibleCourante=cible; } }
endofturn accesseur
Pokemon-core/src/pokemon/modele/Combat.java
endofturn accesseur
<ide><path>okemon-core/src/pokemon/modele/Combat.java <ide> return cibleCourante; <ide> } <ide> public synchronized void setCible(PokemonCombat cible){ this.cibleCourante=cible; } <add> public synchronized boolean getendOfTurn(){ return endOfTurn;} <ide> <ide> <ide> }
JavaScript
agpl-3.0
86be5a270ecfd2f03568b99ed4a74db983348518
0
nextcloud/passman,nextcloud/passman,nextcloud/passman,nextcloud/passman
/** * Nextcloud - passman * * @copyright Copyright (c) 2016, Sander Brand ([email protected]) * @copyright Copyright (c) 2016, Marcos Zuriaga Miguel ([email protected]) * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ (function () { 'use strict'; /** * @ngdoc directive * @name passmanApp.directive:passwordGen * @description * # passwordGen */ angular.module('passmanApp') .directive('credentialCounter', [function () { return { template: '<div ng-show="counter" translate="number.filtered" translate-values="{number_filtered: counter, credential_number: total}"></div>', replace: false, restrict: 'A', scope: { filteredCredentials: '=credentialCounter', deleteTime: '=', vault: '=', filters: '=' }, link: function (scope) { function countCredentials() { var countedCredentials = 0; var total = 0; if(!scope.vault.hasOwnProperty('credentials')){ return; } angular.forEach(scope.vault.credentials, function (credential) { var pos = scope.filteredCredentials.map(function(c) { return c.guid; }).indexOf(credential.guid); if (scope.deleteTime === 0 && credential.hidden === 0 && credential.delete_time === 0) { total = total + 1; countedCredentials = (pos !== -1) ? countedCredentials + 1 : countedCredentials; } if (scope.deleteTime > 0 && credential.hidden === 0 && credential.delete_time > 0) { total = total + 1; countedCredentials = (pos !== -1) ? countedCredentials + 1 : countedCredentials; } }); scope.counter = countedCredentials; scope.total = total; } scope.$watch('[filteredCredentials, deleteTime, filters]', function () { countCredentials(); }, true); } }; }]); }());
js/app/directives/credentialcounter.js
/** * Nextcloud - passman * * @copyright Copyright (c) 2016, Sander Brand ([email protected]) * @copyright Copyright (c) 2016, Marcos Zuriaga Miguel ([email protected]) * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ (function () { 'use strict'; /** * @ngdoc directive * @name passmanApp.directive:passwordGen * @description * # passwordGen */ angular.module('passmanApp') .directive('credentialCounter', [function () { return { template: '<div ng-show="counter" translate="number.filtered" translate-values="{number_filtered: counter, credential_number: total}"></div>', replace: false, restrict: 'A', scope: { filteredCredentials: '=credentialCounter', deleteTime: '=', vault: '=', filters: '=' }, link: function (scope) { function countCredentials() { var countedCredentials = 0; var total = 0; angular.forEach(scope.vault.credentials, function (credential) { var pos = scope.filteredCredentials.map(function(c) { return c.guid; }).indexOf(credential.guid); if (scope.deleteTime === 0 && credential.hidden === 0 && credential.delete_time === 0) { total = total + 1; countedCredentials = (pos !== -1) ? countedCredentials + 1 : countedCredentials; } if (scope.deleteTime > 0 && credential.hidden === 0 && credential.delete_time > 0) { total = total + 1; countedCredentials = (pos !== -1) ? countedCredentials + 1 : countedCredentials; } }); scope.counter = countedCredentials; scope.total = total; } scope.$watch('[filteredCredentials, deleteTime, filters]', function () { countCredentials(); }, true); } }; }]); }());
Fix Cannot read property in credentialcounter
js/app/directives/credentialcounter.js
Fix Cannot read property in credentialcounter
<ide><path>s/app/directives/credentialcounter.js <ide> function countCredentials() { <ide> var countedCredentials = 0; <ide> var total = 0; <add> if(!scope.vault.hasOwnProperty('credentials')){ <add> return; <add> } <add> <ide> angular.forEach(scope.vault.credentials, function (credential) { <ide> var pos = scope.filteredCredentials.map(function(c) { return c.guid; }).indexOf(credential.guid); <ide>
Java
mpl-2.0
0d88ca697811b3b5981e17cad30c71b280490ad5
0
GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app
package org.openlca.app.rcp; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.PlatformUI; import com.google.common.io.Files; public enum ImageType { ACCEPT("graphical/accept.png"), ACTOR("model/actor.png"), ACTOR_CATEGORY("category/actor.png"), ACTOR_WIZARD("wizard/actor.png"), ADD("add.png"), ADD_DISABLED("add_disabled.png"), BACKGROUND_DATA_GROUP("model/background_data_group.png"), BUILD_SUPPLY_CHAIN("graphical/build_supply_chain.gif"), CALCULATE("calculation/calculate.png"), CALCULATE_COSTS("calculation/calculate_costs.png"), CALCULATION_WIZARD("wizard/calculation.gif"), CHANGE("change.gif"), CHART("chart.png"), CHECK_FALSE("check_false.gif"), CHECK_TRUE("check_true.gif"), COLLAPSE("collapse.png"), COMMIT("cloud/commit.png"), CONNECT("connect.png"), COPY_ALL_CHANGES("cloud/copy_all.png"), COPY_SELECTED_CHANGE("cloud/copy_selected.png"), CURRENCY("model/currency.png"), CURRENCY_CATEGORY("category/currency.png"), CURRENCY_WIZARD("wizard/currency.png"), DATABASE("model/database.png"), DATABASE_DISABLED("model/database_disabled.png"), DATABASE_IO("database_io.gif"), DATABASE_WIZARD("wizard/database.png"), DELETE("delete.gif"), DELETE_DISABLED("delete_disabled.gif"), DISCONNECT("disconnect.png"), DOWN("down.png"), EDIT("edit.png"), ERROR("error.png"), EXCHANGE_BG_LEFT("graphical/exchange_bg_left.jpg"), EXCHANGE_BG_MIDDLE("graphical/exchange_bg_middle.jpg"), EXCHANGE_BG_RIGHT("graphical/exchange_bg_right.jpg"), EXPAND("expand.png"), EXPORT("io/export.png"), EXPRESSION("expression.gif"), EXTENSION("extension.gif"), FILE("file.gif"), FILE_CSV("file/csv.gif"), FILE_EXCEL("file/excel.png"), FILE_IMAGE("file/image.png"), FILE_MARKUP("file/markup.png"), FILE_PDF("file/pdf.png"), FILE_POWERPOINT("file/powerpoint.png"), FILE_WORD("file/word.png"), FILE_XML("file/xml.gif"), FILE_ZIP("file/zip.gif"), FIREFOX("firefox.png"), FLOW("model/flow.png"), FLOW_CATEGORY("category/flow.png"), FLOW_ELEMENTARY("model/flow_elementary.png"), FLOW_PRODUCT("model/flow_product.png"), FLOW_PROPERTY("model/flow_property.png"), FLOW_PROPERTY_CATEGORY("category/flow_property.png"), FLOW_PROPERTY_WIZARD("wizard/flow_property.png"), FLOW_WASTE("model/flow_waste.png"), FLOW_WIZARD("wizard/flow.png"), FOLDER("folder.gif"), FOLDER_BLUE("folder_blue.png"), FOLDER_OPEN("folder_open.gif"), FORMULA("formula.png"), HELP("help.gif"), HOME("home.png"), IMPACT_METHOD("model/impact_method.png"), IMPACT_METHOD_CATEGORY("category/impact_method.png"), IMPACT_METHOD_WIZARD("wizard/impact_method.png"), IMPORT("import.png"), IMPORT_ZIP_WIZARD("wizard/zip.png"), INFO("info.gif"), INPUT("model/input.png"), INVENTORY_GROUP("model/inventory_group.png"), JAVASCRIPT("javascript.gif"), LAYOUT("graphical/layout.gif"), LINK("link.png"), LOCATION("model/location.png"), LOCATION_CATEGORY("category/location.png"), LOCATION_WIZARD("wizard/location.png"), LOGO("plugin/logo_32_32bit.png"), MAXIMIZE("graphical/maxmize.gif"), MINIATURE_VIEW("graphical/miniature_view.gif"), MINIMIZE("graphical/minimize.gif"), MINUS("graphical/minus.gif"), MODELS_GROUP("model/models_group.png"), NEXT_CHANGE("cloud/next_change.png"), NEW_WIZARD("wizard/new.png"), NUMBER("number.png"), OK("ok.png"), OUTLINE("graphical/outline.gif"), OUTPUT("model/output.png"), OVERLAY_ADDED("overlay/cloud/added.png"), OVERLAY_ADD_TO_LOCAL("overlay/cloud/add_local.png"), OVERLAY_ADD_TO_REMOTE("overlay/cloud/add_remote.png"), OVERLAY_CONFLICT("overlay/cloud/conflict.png"), OVERLAY_DELETED("overlay/cloud/deleted.png"), OVERLAY_DELETE_FROM_LOCAL("overlay/cloud/delete_local.png"), OVERLAY_DELETE_FROM_REMOTE("overlay/cloud/delete_remote.png"), OVERLAY_MERGED("overlay/cloud/merged.png"), OVERLAY_MODIFY_IN_LOCAL("overlay/cloud/modify_local.png"), OVERLAY_MODIFY_IN_REMOTE("overlay/cloud/modify_remote.png"), OVERLAY_NEW("overlay/new.png"), PARAMETER("model/parameter.png"), PARAMETER_CATEGORY("category/parameter.png"), PARAMETER_WIZARD("wizard/parameter.png"), PLUS("graphical/plus.gif"), PREVIOUS_CHANGE("cloud/previous_change.png"), PROCESS("model/process.png"), PROCESS_BG("graphical/process_bg.jpg"), PROCESS_BG_LCI("graphical/process_bg_lci.jpg"), PROCESS_BG_MARKED("graphical/process_bg_marked.jpg"), PROCESS_CATEGORY("category/process.png"), PROCESS_SYSTEM("model/process_system.png"), PROCESS_WIZARD("wizard/process.png"), PRODUCT_SYSTEM("model/product_system.png"), PRODUCT_SYSTEM_CATEGORY("category/product_system.png"), PRODUCT_SYSTEM_WIZARD("wizard/product_system.png"), PROJECT("model/project.png"), PROJECT_CATEGORY("category/project.png"), PROJECT_WIZARD("wizard/project.png"), PYTHON("python.gif"), REFRESH("refresh.png"), RESET_ALL_CHANGES("cloud/reset_all.png"), RESET_SELECTED_CHANGE("cloud/reset_selected.png"), RUN("run.gif"), SANKEY_OPTIONS("graphical/sankey_options.gif"), SAVE_AS_IMAGE("save_as_image.png"), SEARCH("search.png"), SIMULATE("calculation/simulate.png"), SOCIAL_INDICATOR("model/social_indicator.png"), SOCIAL_INDICATOR_CATEGORY("category/social_indicator.png"), SOCIAL_INDICATOR_WIZARD("wizard/social_indicator.png"), SOURCE("model/source.png"), SOURCE_CATEGORY("category/source.png"), SOURCE_WIZARD("wizard/source.png"), SQL("sql.gif"), UNIT_GROUP("model/unit_group.png"), UNIT_GROUP_CATEGORY("category/unit_group.png"), UNIT_GROUP_WIZARD("wizard/unit_group.png"), UP("up.png"), UP_DISABLED("up_disabled.png"), UP_DOUBLE("up_double.png"), UP_DOUBLE_DISABLED("up_double_disabled.png"), WARNING("warning.png"); private final String fileName; private ImageType(String fileName) { this.fileName = fileName; } Image createImage() { return RcpActivator.getImageDescriptor(getPath()).createImage(); } public Image get() { return ImageManager.getImage(this); } public ImageDescriptor getDescriptor() { return ImageManager.getImageDescriptor(this); } public String getPath() { return "icons/" + this.fileName; } public static ImageType forFile(String fileName) { if (fileName == null) return FILE; String extension = Files.getFileExtension(fileName); if (extension == null) return FILE; switch (extension) { case "pdf": return FILE_PDF; case "doc": case "docx": case "odt": return FILE_WORD; case "xls": case "xlsx": case "ods": case "csv": return FILE_EXCEL; case "png": case "jpg": case "gif": return FILE_IMAGE; case "ppt": case "pptx": case "odp": return FILE_POWERPOINT; case "xml": case "html": case "spold": case "htm": case "xhtml": return FILE_MARKUP; default: return FILE; } } /** * Returns the shared image descriptor with the given name from the Eclipse * platform. See ISharedImages for the image names. */ public static ImageDescriptor getPlatformDescriptor(String name) { return PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(name); } /** * Returns the shared image with the given name from the Eclipse platform. * See ISharedImages for the image names. */ public static Image getPlatformImage(String name) { return PlatformUI.getWorkbench().getSharedImages().getImage(name); } public static Image getNewImage(ImageType type) { return ImageManager.getImageWithOverlay(type, OVERLAY_NEW); } public static ImageDescriptor getNewDescriptor(ImageType type) { // TODO fix this, it does not work return ImageManager.getImageDescriptorWithOverlay(type, OVERLAY_NEW); } }
olca-app/src/org/openlca/app/rcp/ImageType.java
package org.openlca.app.rcp; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.PlatformUI; import com.google.common.io.Files; public enum ImageType { ACCEPT("graphical/accept.png"), ACTOR("model/actor.png"), ACTOR_CATEGORY("category/actor.png"), ACTOR_WIZARD("wizard/actor.png"), ADD("add.png"), ADD_DISABLED("add_disabled.png"), BACKGROUND_DATA_GROUP("model/background_data_group.png"), BUILD_SUPPLY_CHAIN("graphical/build_supply_chain.gif"), CALCULATE("calculation/calculate.png"), CALCULATE_COSTS("calculation/calculate_costs.png"), CALCULATION_WIZARD("wizard/calculation.gif"), CHANGE("change.gif"), CHART("chart.png"), CHECK_FALSE("check_false.gif"), CHECK_TRUE("check_true.gif"), COLLAPSE("collapse.png"), COMMIT("cloud/commit.png"), CONNECT("connect.png"), COPY_ALL_CHANGES("cloud/copy_all.png"), COPY_SELECTED_CHANGE("cloud/copy_selected.png"), CURRENCY("model/currency.png"), CURRENCY_CATEGORY("category/currency.png"), CURRENCY_WIZARD("wizard/currency.png"), DATABASE("model/database.png"), DATABASE_DISABLED("model/database_disabled.png"), DATABASE_IO("database_io.gif"), DATABASE_WIZARD("wizard/database.png"), DELETE("delete.gif"), DELETE_DISABLED("delete_disabled.gif"), DISCONNECT("disconnect.png"), DOWN("down.png"), EDIT("edit.png"), ERROR("error.png"), EXCHANGE_BG_LEFT("graphical/exchange_bg_left.jpg"), EXCHANGE_BG_MIDDLE("graphical/exchange_bg_middle.jpg"), EXCHANGE_BG_RIGHT("graphical/exchange_bg_right.jpg"), EXPAND("expand.png"), EXPORT("io/export.png"), EXPRESSION("expression.gif"), EXTENSION("extension.gif"), FILE("file.gif"), FILE_CSV("file/csv.gif"), FILE_EXCEL("file/excel.png"), FILE_IMAGE("file/image.png"), FILE_MARKUP("file/markup.png"), FILE_PDF("file/pdf.png"), FILE_POWERPOINT("file/powerpoint.png"), FILE_WORD("file/word.png"), FILE_XML("file/xml.png"), FILE_ZIP("file/zip.gif"), FIREFOX("firefox.png"), FLOW("model/flow.png"), FLOW_CATEGORY("category/flow.png"), FLOW_ELEMENTARY("model/flow_elementary.png"), FLOW_PRODUCT("model/flow_product.png"), FLOW_PROPERTY("model/flow_property.png"), FLOW_PROPERTY_CATEGORY("category/flow_property.png"), FLOW_PROPERTY_WIZARD("wizard/flow_property.png"), FLOW_WASTE("model/flow_waste.png"), FLOW_WIZARD("wizard/flow.png"), FOLDER("folder.gif"), FOLDER_BLUE("folder_blue.png"), FOLDER_OPEN("folder_open.gif"), FORMULA("formula.png"), HELP("help.gif"), HOME("home.png"), IMPACT_METHOD("model/impact_method.png"), IMPACT_METHOD_CATEGORY("category/impact_method.png"), IMPACT_METHOD_WIZARD("wizard/impact_method.png"), IMPORT("import.png"), IMPORT_ZIP_WIZARD("wizard/zip.png"), INFO("info.gif"), INPUT("model/input.png"), INVENTORY_GROUP("model/inventory_group.png"), JAVASCRIPT("javascript.gif"), LAYOUT("graphical/layout.gif"), LINK("link.png"), LOCATION("model/location.png"), LOCATION_CATEGORY("category/location.png"), LOCATION_WIZARD("wizard/location.png"), LOGO("plugin/logo_32_32bit.png"), MAXIMIZE("graphical/maxmize.gif"), MINIATURE_VIEW("graphical/miniature_view.gif"), MINIMIZE("graphical/minimize.gif"), MINUS("graphical/minus.gif"), MODELS_GROUP("model/models_group.png"), NEXT_CHANGE("cloud/next_change.png"), NEW_WIZARD("wizard/new.png"), NUMBER("number.png"), OK("ok.png"), OUTLINE("graphical/outline.gif"), OUTPUT("model/output.png"), OVERLAY_ADDED("overlay/cloud/added.png"), OVERLAY_ADD_TO_LOCAL("overlay/cloud/add_local.png"), OVERLAY_ADD_TO_REMOTE("overlay/cloud/add_remote.png"), OVERLAY_CONFLICT("overlay/cloud/conflict.png"), OVERLAY_DELETED("overlay/cloud/deleted.png"), OVERLAY_DELETE_FROM_LOCAL("overlay/cloud/delete_local.png"), OVERLAY_DELETE_FROM_REMOTE("overlay/cloud/delete_remote.png"), OVERLAY_MERGED("overlay/cloud/merged.png"), OVERLAY_MODIFY_IN_LOCAL("overlay/cloud/modify_local.png"), OVERLAY_MODIFY_IN_REMOTE("overlay/cloud/modify_remote.png"), OVERLAY_NEW("overlay/new.png"), PARAMETER("model/parameter.png"), PARAMETER_CATEGORY("category/parameter.png"), PARAMETER_WIZARD("wizard/parameter.png"), PLUS("graphical/plus.gif"), PREVIOUS_CHANGE("cloud/previous_change.png"), PROCESS("model/process.png"), PROCESS_BG("graphical/process_bg.jpg"), PROCESS_BG_LCI("graphical/process_bg_lci.jpg"), PROCESS_BG_MARKED("graphical/process_bg_marked.jpg"), PROCESS_CATEGORY("category/process.png"), PROCESS_SYSTEM("model/process_system.png"), PROCESS_WIZARD("wizard/process.png"), PRODUCT_SYSTEM("model/product_system.png"), PRODUCT_SYSTEM_CATEGORY("category/product_system.png"), PRODUCT_SYSTEM_WIZARD("wizard/product_system.png"), PROJECT("model/project.png"), PROJECT_CATEGORY("category/project.png"), PROJECT_WIZARD("wizard/project.png"), PYTHON("python.gif"), REFRESH("refresh.png"), RESET_ALL_CHANGES("cloud/reset_all.png"), RESET_SELECTED_CHANGE("cloud/reset_selected.png"), RUN("run.gif"), SANKEY_OPTIONS("graphical/sankey_options.gif"), SAVE_AS_IMAGE("save_as_image.png"), SEARCH("search.png"), SIMULATE("calculation/simulate.png"), SOCIAL_INDICATOR("model/social_indicator.png"), SOCIAL_INDICATOR_CATEGORY("category/social_indicator.png"), SOCIAL_INDICATOR_WIZARD("wizard/social_indicator.png"), SOURCE("model/source.png"), SOURCE_CATEGORY("category/source.png"), SOURCE_WIZARD("wizard/source.png"), SQL("sql.gif"), UNIT_GROUP("model/unit_group.png"), UNIT_GROUP_CATEGORY("category/unit_group.png"), UNIT_GROUP_WIZARD("wizard/unit_group.png"), UP("up.png"), UP_DISABLED("up_disabled.png"), UP_DOUBLE("up_double.png"), UP_DOUBLE_DISABLED("up_double_disabled.png"), WARNING("warning.png"); private final String fileName; private ImageType(String fileName) { this.fileName = fileName; } Image createImage() { return RcpActivator.getImageDescriptor(getPath()).createImage(); } public Image get() { return ImageManager.getImage(this); } public ImageDescriptor getDescriptor() { return ImageManager.getImageDescriptor(this); } public String getPath() { return "icons/" + this.fileName; } public static ImageType forFile(String fileName) { if (fileName == null) return FILE; String extension = Files.getFileExtension(fileName); if (extension == null) return FILE; switch (extension) { case "pdf": return FILE_PDF; case "doc": case "docx": case "odt": return FILE_WORD; case "xls": case "xlsx": case "ods": case "csv": return FILE_EXCEL; case "png": case "jpg": case "gif": return FILE_IMAGE; case "ppt": case "pptx": case "odp": return FILE_POWERPOINT; case "xml": case "html": case "spold": case "htm": case "xhtml": return FILE_MARKUP; default: return FILE; } } /** * Returns the shared image descriptor with the given name from the Eclipse * platform. See ISharedImages for the image names. */ public static ImageDescriptor getPlatformDescriptor(String name) { return PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(name); } /** * Returns the shared image with the given name from the Eclipse platform. * See ISharedImages for the image names. */ public static Image getPlatformImage(String name) { return PlatformUI.getWorkbench().getSharedImages().getImage(name); } public static Image getNewImage(ImageType type) { return ImageManager.getImageWithOverlay(type, OVERLAY_NEW); } public static ImageDescriptor getNewDescriptor(ImageType type) { // TODO fix this, it does not work return ImageManager.getImageDescriptorWithOverlay(type, OVERLAY_NEW); } }
:bug: wrong path for XML image
olca-app/src/org/openlca/app/rcp/ImageType.java
:bug: wrong path for XML image
<ide><path>lca-app/src/org/openlca/app/rcp/ImageType.java <ide> <ide> FILE_WORD("file/word.png"), <ide> <del> FILE_XML("file/xml.png"), <add> FILE_XML("file/xml.gif"), <ide> <ide> FILE_ZIP("file/zip.gif"), <ide>
Java
apache-2.0
686aed66f937918f48014d2aaeeb53349e63253d
0
sonamuthu/rice-1,jwillia/kc-rice1,kuali/kc-rice,geothomasp/kualico-rice-kc,smith750/rice,bhutchinson/rice,ewestfal/rice-svn2git-test,cniesen/rice,ewestfal/rice,shahess/rice,jwillia/kc-rice1,UniversityOfHawaiiORS/rice,ewestfal/rice-svn2git-test,kuali/kc-rice,ewestfal/rice,gathreya/rice-kc,UniversityOfHawaiiORS/rice,smith750/rice,geothomasp/kualico-rice-kc,jwillia/kc-rice1,smith750/rice,cniesen/rice,kuali/kc-rice,sonamuthu/rice-1,UniversityOfHawaiiORS/rice,rojlarge/rice-kc,bsmith83/rice-1,rojlarge/rice-kc,ewestfal/rice-svn2git-test,shahess/rice,bsmith83/rice-1,geothomasp/kualico-rice-kc,gathreya/rice-kc,bhutchinson/rice,geothomasp/kualico-rice-kc,gathreya/rice-kc,rojlarge/rice-kc,kuali/kc-rice,cniesen/rice,sonamuthu/rice-1,bsmith83/rice-1,gathreya/rice-kc,gathreya/rice-kc,bhutchinson/rice,cniesen/rice,ewestfal/rice,smith750/rice,shahess/rice,UniversityOfHawaiiORS/rice,sonamuthu/rice-1,bhutchinson/rice,shahess/rice,ewestfal/rice-svn2git-test,ewestfal/rice,shahess/rice,kuali/kc-rice,jwillia/kc-rice1,rojlarge/rice-kc,jwillia/kc-rice1,bsmith83/rice-1,geothomasp/kualico-rice-kc,rojlarge/rice-kc,cniesen/rice,bhutchinson/rice,UniversityOfHawaiiORS/rice,smith750/rice,ewestfal/rice
/** * Copyright 2005-2012 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kim.impl.permission; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.log4j.Logger; import org.kuali.rice.core.api.cache.CacheKeyUtils; import org.kuali.rice.core.api.criteria.CriteriaLookupService; import org.kuali.rice.core.api.criteria.GenericQueryResults; import org.kuali.rice.core.api.criteria.LookupCustomizer; import org.kuali.rice.core.api.criteria.QueryByCriteria; import org.kuali.rice.core.api.exception.RiceIllegalArgumentException; import org.kuali.rice.core.api.exception.RiceIllegalStateException; import org.kuali.rice.core.api.membership.MemberType; import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader; import org.kuali.rice.kim.api.KimConstants; import org.kuali.rice.kim.api.common.assignee.Assignee; import org.kuali.rice.kim.api.common.delegate.DelegateType; import org.kuali.rice.kim.api.common.template.Template; import org.kuali.rice.kim.api.common.template.TemplateQueryResults; import org.kuali.rice.kim.api.identity.principal.Principal; import org.kuali.rice.kim.api.permission.Permission; import org.kuali.rice.kim.api.permission.PermissionQueryResults; import org.kuali.rice.kim.api.permission.PermissionService; import org.kuali.rice.kim.api.role.RoleMembership; import org.kuali.rice.kim.api.role.RoleService; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.kim.api.type.KimType; import org.kuali.rice.kim.api.type.KimTypeInfoService; import org.kuali.rice.kim.framework.permission.PermissionTypeService; import org.kuali.rice.kim.impl.common.attribute.AttributeTransform; import org.kuali.rice.kim.impl.common.attribute.KimAttributeDataBo; import org.kuali.rice.kim.impl.role.RolePermissionBo; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.KRADPropertyConstants; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.support.NoOpCacheManager; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import static org.kuali.rice.core.api.criteria.PredicateFactory.equal; import static org.kuali.rice.core.api.criteria.PredicateFactory.in; public class PermissionServiceImpl implements PermissionService { private static final Logger LOG = Logger.getLogger( PermissionServiceImpl.class ); private RoleService roleService; private PermissionTypeService defaultPermissionTypeService; private KimTypeInfoService kimTypeInfoService; private BusinessObjectService businessObjectService; private CriteriaLookupService criteriaLookupService; private CacheManager cacheManager; private final CopyOnWriteArrayList<Template> allTemplates = new CopyOnWriteArrayList<Template>(); // -------------------- // Authorization Checks // -------------------- public PermissionServiceImpl() { this.cacheManager = new NoOpCacheManager(); } protected PermissionTypeService getPermissionTypeService(Template permissionTemplate) { if ( permissionTemplate == null ) { throw new IllegalArgumentException( "permissionTemplate may not be null" ); } KimType kimType = kimTypeInfoService.getKimType( permissionTemplate.getKimTypeId() ); String serviceName = kimType.getServiceName(); // if no service specified, return a default implementation if ( StringUtils.isBlank( serviceName ) ) { return defaultPermissionTypeService; } try { Object service = GlobalResourceLoader.getService(QName.valueOf(serviceName)); // if we have a service name, it must exist if ( service == null ) { throw new RuntimeException("null returned for permission type service for service name: " + serviceName); } // whatever we retrieved must be of the correct type if ( !(service instanceof PermissionTypeService) ) { throw new RuntimeException( "Service " + serviceName + " was not a PermissionTypeService. Was: " + service.getClass().getName() ); } return (PermissionTypeService)service; } catch( Exception ex ) { // sometimes service locators throw exceptions rather than returning null, handle that throw new RuntimeException( "Error retrieving service: " + serviceName + " from the KimImplServiceLocator.", ex ); } } @Override public boolean hasPermission(String principalId, String namespaceCode, String permissionName) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); return isAuthorized( principalId, namespaceCode, permissionName, Collections.<String, String>emptyMap() ); } @Override public boolean isAuthorized(String principalId, String namespaceCode, String permissionName, Map<String, String> qualification ) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); incomingParamCheck(qualification, "qualification"); if ( LOG.isDebugEnabled() ) { logAuthorizationCheck("Permission", principalId, namespaceCode, permissionName, qualification); } List<String> roleIds = getRoleIdsForPermission(namespaceCode, permissionName); if ( roleIds.isEmpty() ) { if ( LOG.isDebugEnabled() ) { LOG.debug( "Result: false"); } return false; } boolean isAuthorized = roleService.principalHasRole(principalId, roleIds, qualification); if ( LOG.isDebugEnabled() ) { LOG.debug( "Result: " + isAuthorized ); } return isAuthorized; } @Override public boolean hasPermissionByTemplate(String principalId, String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); return isAuthorizedByTemplate(principalId, namespaceCode, permissionTemplateName, permissionDetails, Collections.<String, String>emptyMap()); } @Override public boolean isAuthorizedByTemplate(String principalId, String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails, Map<String, String> qualification) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); incomingParamCheck(qualification, "qualification"); if ( LOG.isDebugEnabled() ) { logAuthorizationCheckByTemplate("Perm Templ", principalId, namespaceCode, permissionTemplateName, permissionDetails, qualification); } List<String> roleIds = getRoleIdsForPermissionTemplate(namespaceCode, permissionTemplateName, permissionDetails); if (roleIds.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Result: false"); } return false; } boolean isAuthorized = roleService.principalHasRole(principalId, roleIds, qualification); if (LOG.isDebugEnabled()) { LOG.debug( "Result: " + isAuthorized ); } return isAuthorized; } @Override public List<Permission> getAuthorizedPermissions( String principalId, String namespaceCode, String permissionName, Map<String, String> qualification ) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); incomingParamCheck(qualification, "qualification"); // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByName(namespaceCode, permissionName); // now, filter the full list by the detail passed List<Permission> applicablePermissions = getMatchingPermissions( permissions, null ); List<Permission> permissionsForUser = getPermissionsForUser(principalId, applicablePermissions, qualification); return permissionsForUser; } @Override public List<Permission> getAuthorizedPermissionsByTemplate(String principalId, String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails, Map<String, String> qualification) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); incomingParamCheck(qualification, "qualification"); // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByTemplateName(namespaceCode, permissionTemplateName); // now, filter the full list by the detail passed List<Permission> applicablePermissions = getMatchingPermissions( permissions, permissionDetails ); return getPermissionsForUser(principalId, applicablePermissions, qualification); } /** * Checks the list of permissions against the principal's roles and returns a subset of the list which match. */ protected List<Permission> getPermissionsForUser( String principalId, List<Permission> permissions, Map<String, String> qualification ) { List<Permission> results = new ArrayList<Permission>(); for ( Permission perm : permissions ) { List<String> roleIds = getRoleIdsForPermissions( Collections.singletonList(perm) ); if ( roleIds != null && !roleIds.isEmpty() ) { if ( roleService.principalHasRole( principalId, roleIds, qualification) ) { results.add( perm ); } } } return Collections.unmodifiableList(results); } protected Map<String,PermissionTypeService> getPermissionTypeServicesByTemplateId( Collection<Permission> permissions ) { Map<String,PermissionTypeService> permissionTypeServices = new HashMap<String, PermissionTypeService>( permissions.size() ); for (Permission perm : permissions) { if(!permissionTypeServices.containsKey(perm.getTemplate().getId())) { permissionTypeServices.put(perm.getTemplate().getId(), getPermissionTypeService(perm.getTemplate())); } } return permissionTypeServices; } protected Map<String,List<Permission>> groupPermissionsByTemplate(Collection<Permission> permissions) { Map<String,List<Permission>> results = new HashMap<String,List<Permission>>(); for (Permission perm : permissions) { List<Permission> perms = results.get(perm.getTemplate().getId()); if (perms == null) { perms = new ArrayList<Permission>(); results.put(perm.getTemplate().getId(), perms); } perms.add(perm); } return results; } /** * Compare each of the passed in permissions with the given permissionDetails. Those that * match are added to the result list. */ protected List<Permission> getMatchingPermissions( List<Permission> permissions, Map<String, String> permissionDetails ) { List<String> permissionIds = new ArrayList<String>(permissions.size()); for (Permission permission : permissions) { permissionIds.add(permission.getId()); } String cacheKey = new StringBuilder("{getMatchingPermissions}") .append("permissionIds=").append(CacheKeyUtils.key(permissionIds)).append("|") .append("permissionDetails=").append(CacheKeyUtils.mapKey(permissionDetails)).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<Permission>)cachedValue.get()); } List<Permission> applicablePermissions = new ArrayList<Permission>(); if ( permissionDetails == null || permissionDetails.isEmpty() ) { // if no details passed, assume that all match for ( Permission perm : permissions ) { applicablePermissions.add(perm); } } else { // otherwise, attempt to match the permission details // build a map of the template IDs to the type services Map<String,PermissionTypeService> permissionTypeServices = getPermissionTypeServicesByTemplateId(permissions); // build a map of permissions by template ID Map<String, List<Permission>> permissionMap = groupPermissionsByTemplate(permissions); // loop over the different templates, matching all of the same template against the type // service at once for ( Map.Entry<String,List<Permission>> entry : permissionMap.entrySet() ) { PermissionTypeService permissionTypeService = permissionTypeServices.get( entry.getKey() ); List<Permission> permissionList = entry.getValue(); applicablePermissions.addAll( permissionTypeService.getMatchingPermissions( permissionDetails, permissionList ) ); } } applicablePermissions = Collections.unmodifiableList(applicablePermissions); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, applicablePermissions); return applicablePermissions; } @Override public List<Assignee> getPermissionAssignees( String namespaceCode, String permissionName, Map<String, String> qualification ) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); incomingParamCheck(qualification, "qualification"); List<String> roleIds = getRoleIdsForPermission( namespaceCode, permissionName); if ( roleIds.isEmpty() ) { return Collections.emptyList(); } Collection<RoleMembership> roleMembers = roleService.getRoleMembers( roleIds,qualification ); List<Assignee> results = new ArrayList<Assignee>(); for ( RoleMembership rm : roleMembers ) { List<DelegateType.Builder> delegateBuilderList = new ArrayList<DelegateType.Builder>(); if (!rm.getDelegates().isEmpty()) { for (DelegateType delegate : rm.getDelegates()){ delegateBuilderList.add(DelegateType.Builder.create(delegate)); } } if ( MemberType.PRINCIPAL.equals(rm.getType()) ) { results.add (Assignee.Builder.create(rm.getMemberId(), null, delegateBuilderList).build()); } else if ( MemberType.GROUP.equals(rm.getType()) ) { results.add (Assignee.Builder.create(null, rm.getMemberId(), delegateBuilderList).build()); } } return Collections.unmodifiableList(results); } @Override public List<Assignee> getPermissionAssigneesByTemplate(String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails, Map<String, String> qualification) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); incomingParamCheck(qualification, "qualification"); List<String> roleIds = getRoleIdsForPermissionTemplate( namespaceCode, permissionTemplateName, permissionDetails); if ( roleIds.isEmpty() ) { return Collections.emptyList(); } Collection<RoleMembership> roleMembers = roleService.getRoleMembers( roleIds,qualification); List<Assignee> results = new ArrayList<Assignee>(); for ( RoleMembership rm : roleMembers ) { List<DelegateType.Builder> delegateBuilderList = new ArrayList<DelegateType.Builder>(); if (!rm.getDelegates().isEmpty()) { for (DelegateType delegate : rm.getDelegates()){ delegateBuilderList.add(DelegateType.Builder.create(delegate)); } } if ( MemberType.PRINCIPAL.equals(rm.getType()) ) { results.add (Assignee.Builder.create(rm.getMemberId(), null, delegateBuilderList).build()); } else { // a group membership results.add (Assignee.Builder.create(null, rm.getMemberId(), delegateBuilderList).build()); } } return Collections.unmodifiableList(results); } @Override public boolean isPermissionDefined( String namespaceCode, String permissionName ) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByName(namespaceCode, permissionName); // now, filter the full list by the detail passed return !getMatchingPermissions(permissions, null).isEmpty(); } @Override public boolean isPermissionDefinedByTemplate(String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByTemplateName(namespaceCode, permissionTemplateName); // now, filter the full list by the detail passed return !getMatchingPermissions(permissions, permissionDetails).isEmpty(); } @Override public List<String> getRoleIdsForPermission(String namespaceCode, String permissionName) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); // note...this method is cached at the RoleService interface level using an annotation, but it's called quite // a bit internally, so we'll reproduce the caching here using the same key to help optimize String cacheKey = new StringBuilder("{RoleIds}") .append("namespaceCode=").append(namespaceCode).append("|") .append("name=").append(permissionName).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<String>)cachedValue.get()); } // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByName(namespaceCode, permissionName); // now, filter the full list by the detail passed List<Permission> applicablePermissions = getMatchingPermissions(permissions, null); List<String> roleIds = getRoleIdsForPermissions(applicablePermissions); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, roleIds); return roleIds; } protected List<String> getRoleIdsForPermissionTemplate(String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails) { String cacheKey = new StringBuilder("{getRoleIdsForPermissionTemplate}") .append("namespaceCode=").append(namespaceCode).append("|") .append("permissionTemplateName=").append(permissionTemplateName).append("|") .append("permissionDetails=").append(CacheKeyUtils.mapKey(permissionDetails)).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<String>)cachedValue.get()); } // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByTemplateName(namespaceCode, permissionTemplateName); // now, filter the full list by the detail passed List<Permission> applicablePermissions = getMatchingPermissions(permissions, permissionDetails); List<String> roleIds = getRoleIdsForPermissions(applicablePermissions); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, roleIds); return roleIds; } // -------------------- // Permission Data // -------------------- @Override public Permission getPermission(String permissionId) throws RiceIllegalArgumentException { incomingParamCheck(permissionId, "permissionId"); PermissionBo impl = getPermissionImpl(permissionId); if (impl != null) { return PermissionBo.to(impl); } return null; } @Override public List<Permission> findPermissionsByTemplate(String namespaceCode, String permissionTemplateName) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); List<Permission> perms = getPermissionsByTemplateName(namespaceCode, permissionTemplateName); List<Permission> results = new ArrayList<Permission>(perms.size()); for (Permission perm : perms) { results.add(perm); } return Collections.unmodifiableList(results); } protected PermissionBo getPermissionImpl(String permissionId) throws RiceIllegalArgumentException { incomingParamCheck(permissionId, "permissionId"); HashMap<String,Object> pk = new HashMap<String,Object>( 1 ); pk.put( KimConstants.PrimaryKeyConstants.PERMISSION_ID, permissionId ); return businessObjectService.findByPrimaryKey( PermissionBo.class, pk ); } protected List<Permission> getPermissionsByTemplateName( String namespaceCode, String permissionTemplateName ){ String cacheKey = new StringBuilder("{getPermissionsByTemplateName}") .append("namespaceCode=").append(namespaceCode).append("|") .append("permissionTemplateName=").append(permissionTemplateName).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<Permission>)cachedValue.get()); } HashMap<String,Object> criteria = new HashMap<String,Object>(3); criteria.put("template.namespaceCode", namespaceCode); criteria.put("template.name", permissionTemplateName); criteria.put(KRADPropertyConstants.ACTIVE, "Y"); List<Permission> permissions = toPermissions(businessObjectService.findMatching(PermissionBo.class, criteria)); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, permissions); return permissions; } protected List<Permission> getPermissionsByName( String namespaceCode, String permissionName ) { String cacheKey = new StringBuilder("{getPermissionsByName}") .append("namespaceCode=").append(namespaceCode).append("|") .append("permissionName=").append(permissionName).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<Permission>)cachedValue.get()); } HashMap<String,Object> criteria = new HashMap<String,Object>(3); criteria.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode); criteria.put(KimConstants.UniqueKeyConstants.PERMISSION_NAME, permissionName); criteria.put(KRADPropertyConstants.ACTIVE, "Y"); List<Permission> permissions = toPermissions(businessObjectService.findMatching( PermissionBo.class, criteria )); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, permissions); return permissions; } @Override public Template getPermissionTemplate(String permissionTemplateId) throws RiceIllegalArgumentException { incomingParamCheck(permissionTemplateId, "permissionTemplateId"); PermissionTemplateBo impl = businessObjectService.findBySinglePrimaryKey( PermissionTemplateBo.class, permissionTemplateId ); if ( impl != null ) { return PermissionTemplateBo.to(impl); } return null; } @Override public Template findPermTemplateByNamespaceCodeAndName(String namespaceCode, String permissionTemplateName) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); Map<String,String> criteria = new HashMap<String,String>(2); criteria.put( KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode ); criteria.put( KimConstants.UniqueKeyConstants.PERMISSION_TEMPLATE_NAME, permissionTemplateName ); PermissionTemplateBo impl = businessObjectService.findByPrimaryKey( PermissionTemplateBo.class, criteria ); if ( impl != null ) { return PermissionTemplateBo.to(impl); } return null; } @Override public List<Template> getAllTemplates() { if ( allTemplates.isEmpty() ) { Map<String,String> criteria = new HashMap<String,String>(1); criteria.put( KRADPropertyConstants.ACTIVE, "Y" ); List<PermissionTemplateBo> impls = (List<PermissionTemplateBo>) businessObjectService.findMatching( PermissionTemplateBo.class, criteria ); List<Template> infos = new ArrayList<Template>( impls.size() ); for ( PermissionTemplateBo impl : impls ) { infos.add( PermissionTemplateBo.to(impl) ); } Collections.sort(infos, new Comparator<Template>() { @Override public int compare(Template tmpl1, Template tmpl2) { int result = tmpl1.getNamespaceCode().compareTo(tmpl2.getNamespaceCode()); if ( result != 0 ) { return result; } result = tmpl1.getName().compareTo(tmpl2.getName()); return result; } }); allTemplates.addAll(infos); } return Collections.unmodifiableList(allTemplates); } @Override public Permission createPermission(Permission permission) throws RiceIllegalArgumentException, RiceIllegalStateException { incomingParamCheck(permission, "permission"); if (StringUtils.isNotBlank(permission.getId()) && getPermission(permission.getId()) != null) { throw new RiceIllegalStateException("the permission to create already exists: " + permission); } List<PermissionAttributeBo> attrBos = Collections.emptyList(); if (permission.getTemplate() != null) { attrBos = KimAttributeDataBo.createFrom(PermissionAttributeBo.class, permission.getAttributes(), permission.getTemplate().getKimTypeId()); } PermissionBo bo = PermissionBo.from(permission); if (bo.getTemplate() == null && bo.getTemplateId() != null) { bo.setTemplate(PermissionTemplateBo.from(getPermissionTemplate(bo.getTemplateId()))); } bo.setAttributeDetails(attrBos); return PermissionBo.to(businessObjectService.save(bo)); } @Override public Permission updatePermission(Permission permission) throws RiceIllegalArgumentException, RiceIllegalStateException { incomingParamCheck(permission, "permission"); PermissionBo oldPermission = getPermissionImpl(permission.getId()); if (StringUtils.isBlank(permission.getId()) || oldPermission == null) { throw new RiceIllegalStateException("the permission does not exist: " + permission); } //List<PermissionAttributeBo> attrBos = KimAttributeDataBo.createFrom(PermissionAttributeBo.class, permission.getAttributes(), permission.getTemplate().getKimTypeId()); List<PermissionAttributeBo> oldAttrBos = oldPermission.getAttributeDetails(); //put old attributes in map for easier updating Map<String, PermissionAttributeBo> oldAttrMap = new HashMap<String, PermissionAttributeBo>(); for (PermissionAttributeBo oldAttr : oldAttrBos) { oldAttrMap.put(oldAttr.getKimAttribute().getAttributeName(), oldAttr); } List<PermissionAttributeBo> newAttrBos = new ArrayList<PermissionAttributeBo>(); for (String key : permission.getAttributes().keySet()) { if (oldAttrMap.containsKey(key)) { PermissionAttributeBo updatedAttr = oldAttrMap.get(key); updatedAttr.setAttributeValue(permission.getAttributes().get(key)); newAttrBos.add(updatedAttr); } else { //new attribute newAttrBos.addAll(KimAttributeDataBo.createFrom(PermissionAttributeBo.class, Collections.singletonMap(key, permission.getAttributes().get(key)), permission.getTemplate().getKimTypeId())); } } PermissionBo bo = PermissionBo.from(permission); if (CollectionUtils.isNotEmpty(newAttrBos)) { if(null!= bo.getAttributeDetails()) { bo.getAttributeDetails().clear(); } bo.setAttributeDetails(newAttrBos); } if (bo.getTemplate() == null && bo.getTemplateId() != null) { bo.setTemplate(PermissionTemplateBo.from(getPermissionTemplate(bo.getTemplateId()))); } return PermissionBo.to(businessObjectService.save(bo)); } @Override public Permission findPermByNamespaceCodeAndName(String namespaceCode, String permissionName) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); PermissionBo permissionBo = getPermissionBoByName(namespaceCode, permissionName); if (permissionBo != null) { return PermissionBo.to(permissionBo); } return null; } protected PermissionBo getPermissionBoByName(String namespaceCode, String permissionName) { if (StringUtils.isBlank(namespaceCode) || StringUtils.isBlank(permissionName)) { return null; } Map<String, String> criteria = new HashMap<String, String>(); criteria.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode); criteria.put(KimConstants.UniqueKeyConstants.NAME, permissionName); criteria.put(KRADPropertyConstants.ACTIVE, "Y"); // while this is not actually the primary key - there will be at most one row with these criteria return businessObjectService.findByPrimaryKey(PermissionBo.class, criteria); } @Override public PermissionQueryResults findPermissions(final QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException { incomingParamCheck(queryByCriteria, "queryByCriteria"); LookupCustomizer.Builder<PermissionBo> lc = LookupCustomizer.Builder.create(); lc.setPredicateTransform(AttributeTransform.getInstance()); GenericQueryResults<PermissionBo> results = criteriaLookupService.lookup(PermissionBo.class, queryByCriteria, lc.build()); PermissionQueryResults.Builder builder = PermissionQueryResults.Builder.create(); builder.setMoreResultsAvailable(results.isMoreResultsAvailable()); builder.setTotalRowCount(results.getTotalRowCount()); final List<Permission.Builder> ims = new ArrayList<Permission.Builder>(); for (PermissionBo bo : results.getResults()) { ims.add(Permission.Builder.create(bo)); } builder.setResults(ims); return builder.build(); } @Override public TemplateQueryResults findPermissionTemplates(final QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException { incomingParamCheck(queryByCriteria, "queryByCriteria"); GenericQueryResults<PermissionTemplateBo> results = criteriaLookupService.lookup(PermissionTemplateBo.class, queryByCriteria); TemplateQueryResults.Builder builder = TemplateQueryResults.Builder.create(); builder.setMoreResultsAvailable(results.isMoreResultsAvailable()); builder.setTotalRowCount(results.getTotalRowCount()); final List<Template.Builder> ims = new ArrayList<Template.Builder>(); for (PermissionTemplateBo bo : results.getResults()) { ims.add(Template.Builder.create(bo)); } builder.setResults(ims); return builder.build(); } private List<String> getRoleIdsForPermissions( Collection<Permission> permissions ) { if (CollectionUtils.isEmpty(permissions)) { return Collections.emptyList(); } List<String> ids = new ArrayList<String>(); for (Permission p : permissions) { ids.add(p.getId()); } return getRoleIdsForPermissionIds(ids); } private List<String> getRoleIdsForPermissionIds(Collection<String> permissionIds) { if (CollectionUtils.isEmpty(permissionIds)) { return Collections.emptyList(); } String cacheKey = new StringBuilder("{getRoleIdsForPermissionIds}") .append("permissionIds=").append(CacheKeyUtils.key(permissionIds)).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<String>)cachedValue.get()); } QueryByCriteria query = QueryByCriteria.Builder.fromPredicates(equal("active", "true"), in("permissionId", permissionIds.toArray(new String[]{}))); GenericQueryResults<RolePermissionBo> results = criteriaLookupService.lookup(RolePermissionBo.class, query); List<String> roleIds = new ArrayList<String>(); for (RolePermissionBo bo : results.getResults()) { roleIds.add(bo.getRoleId()); } roleIds = Collections.unmodifiableList(roleIds); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, roleIds); return roleIds; } /** * Sets the kimTypeInfoService attribute value. * * @param kimTypeInfoService The kimTypeInfoService to set. */ public void setKimTypeInfoService(KimTypeInfoService kimTypeInfoService) { this.kimTypeInfoService = kimTypeInfoService; } /** * Sets the defaultPermissionTypeService attribute value. * * @param defaultPermissionTypeService The defaultPermissionTypeService to set. */ public void setDefaultPermissionTypeService(PermissionTypeService defaultPermissionTypeService) { this.defaultPermissionTypeService = defaultPermissionTypeService; } /** * Sets the roleService attribute value. * * @param roleService The roleService to set. */ public void setRoleService(RoleService roleService) { this.roleService = roleService; } /** * Sets the businessObjectService attribute value. * * @param businessObjectService The businessObjectService to set. */ public void setBusinessObjectService(final BusinessObjectService businessObjectService) { this.businessObjectService = businessObjectService; } /** * Sets the criteriaLookupService attribute value. * * @param criteriaLookupService The criteriaLookupService to set. */ public void setCriteriaLookupService(final CriteriaLookupService criteriaLookupService) { this.criteriaLookupService = criteriaLookupService; } /** * Sets the cache manager which this service implementation can for internal caching. * Calling this setter is optional, though the value passed to it must not be null. * * @param cacheManager the cache manager to use for internal caching, must not be null * @throws IllegalArgumentException if a null cache manager is passed */ public void setCacheManager(final CacheManager cacheManager) { if (cacheManager == null) { throw new IllegalArgumentException("cacheManager must not be null"); } this.cacheManager = cacheManager; } private List<Permission> toPermissions(Collection<PermissionBo> permissionBos) { if (CollectionUtils.isEmpty(permissionBos)) { return new ArrayList<Permission>(); } List<Permission> permissions = new ArrayList<Permission>(permissionBos.size()); for (PermissionBo permissionBo : permissionBos) { permissions.add(PermissionBo.to(permissionBo)); } return permissions; } protected void logAuthorizationCheck(String checkType, String principalId, String namespaceCode, String permissionName, Map<String, String> qualification ) { StringBuilder sb = new StringBuilder(); sb.append( '\n' ); sb.append( "Is AuthZ for " ).append( checkType ).append( ": " ).append( namespaceCode ).append( "/" ).append( permissionName ).append( '\n' ); sb.append( " Principal: " ).append( principalId ); if ( principalId != null ) { Principal principal = KimApiServiceLocator.getIdentityService().getPrincipal(principalId); if ( principal != null ) { sb.append( " (" ).append( principal.getPrincipalName() ).append( ')' ); } } sb.append( '\n' ); sb.append( " Qualifiers:\n" ); if ( qualification != null && !qualification.isEmpty() ) { sb.append( qualification ); } else { sb.append( " [null]\n" ); } if (LOG.isTraceEnabled()) { LOG.trace( sb.append(ExceptionUtils.getStackTrace(new Throwable()))); } else { LOG.debug(sb.toString()); } } protected void logAuthorizationCheckByTemplate(String checkType, String principalId, String namespaceCode, String permissionName, Map<String, String> permissionDetails, Map<String, String> qualification ) { StringBuilder sb = new StringBuilder(); sb.append( '\n' ); sb.append( "Is AuthZ for " ).append( checkType ).append( ": " ).append( namespaceCode ).append( "/" ).append( permissionName ).append( '\n' ); sb.append( " Principal: " ).append( principalId ); if ( principalId != null ) { Principal principal = KimApiServiceLocator.getIdentityService().getPrincipal(principalId); if ( principal != null ) { sb.append( " (" ).append( principal.getPrincipalName() ).append( ')' ); } } sb.append( '\n' ); sb.append( " Details:\n" ); if ( permissionDetails != null ) { sb.append( permissionDetails ); } else { sb.append( " [null]\n" ); } sb.append( " Qualifiers:\n" ); if ( qualification != null && !qualification.isEmpty() ) { sb.append( qualification ); } else { sb.append( " [null]\n" ); } if (LOG.isTraceEnabled()) { LOG.trace( sb.append(ExceptionUtils.getStackTrace(new Throwable()))); } else { LOG.debug(sb.toString()); } } private void incomingParamCheck(Object object, String name) { if (object == null) { throw new RiceIllegalArgumentException(name + " was null"); } else if (object instanceof String && StringUtils.isBlank((String) object)) { throw new RiceIllegalArgumentException(name + " was blank"); } } }
kim/kim-impl/src/main/java/org/kuali/rice/kim/impl/permission/PermissionServiceImpl.java
/** * Copyright 2005-2012 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kim.impl.permission; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.log4j.Logger; import org.kuali.rice.core.api.cache.CacheKeyUtils; import org.kuali.rice.core.api.criteria.CriteriaLookupService; import org.kuali.rice.core.api.criteria.GenericQueryResults; import org.kuali.rice.core.api.criteria.LookupCustomizer; import org.kuali.rice.core.api.criteria.QueryByCriteria; import org.kuali.rice.core.api.exception.RiceIllegalArgumentException; import org.kuali.rice.core.api.exception.RiceIllegalStateException; import org.kuali.rice.core.api.membership.MemberType; import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader; import org.kuali.rice.kim.api.KimConstants; import org.kuali.rice.kim.api.common.assignee.Assignee; import org.kuali.rice.kim.api.common.delegate.DelegateType; import org.kuali.rice.kim.api.common.template.Template; import org.kuali.rice.kim.api.common.template.TemplateQueryResults; import org.kuali.rice.kim.api.identity.principal.Principal; import org.kuali.rice.kim.api.permission.Permission; import org.kuali.rice.kim.api.permission.PermissionQueryResults; import org.kuali.rice.kim.api.permission.PermissionService; import org.kuali.rice.kim.api.role.RoleMember; import org.kuali.rice.kim.api.role.RoleMembership; import org.kuali.rice.kim.api.role.RoleService; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.kim.api.type.KimType; import org.kuali.rice.kim.api.type.KimTypeInfoService; import org.kuali.rice.kim.framework.permission.PermissionTypeService; import org.kuali.rice.kim.impl.common.attribute.AttributeTransform; import org.kuali.rice.kim.impl.common.attribute.KimAttributeDataBo; import org.kuali.rice.kim.impl.role.RolePermissionBo; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.KRADPropertyConstants; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.support.NoOpCacheManager; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import static org.kuali.rice.core.api.criteria.PredicateFactory.equal; import static org.kuali.rice.core.api.criteria.PredicateFactory.in; public class PermissionServiceImpl implements PermissionService { private static final Logger LOG = Logger.getLogger( PermissionServiceImpl.class ); private RoleService roleService; private PermissionTypeService defaultPermissionTypeService; private KimTypeInfoService kimTypeInfoService; private BusinessObjectService businessObjectService; private CriteriaLookupService criteriaLookupService; private CacheManager cacheManager; private final CopyOnWriteArrayList<Template> allTemplates = new CopyOnWriteArrayList<Template>(); // -------------------- // Authorization Checks // -------------------- public PermissionServiceImpl() { this.cacheManager = new NoOpCacheManager(); } protected PermissionTypeService getPermissionTypeService(Template permissionTemplate) { if ( permissionTemplate == null ) { throw new IllegalArgumentException( "permissionTemplate may not be null" ); } KimType kimType = kimTypeInfoService.getKimType( permissionTemplate.getKimTypeId() ); String serviceName = kimType.getServiceName(); // if no service specified, return a default implementation if ( StringUtils.isBlank( serviceName ) ) { return defaultPermissionTypeService; } try { Object service = GlobalResourceLoader.getService(QName.valueOf(serviceName)); // if we have a service name, it must exist if ( service == null ) { throw new RuntimeException("null returned for permission type service for service name: " + serviceName); } // whatever we retrieved must be of the correct type if ( !(service instanceof PermissionTypeService) ) { throw new RuntimeException( "Service " + serviceName + " was not a PermissionTypeService. Was: " + service.getClass().getName() ); } return (PermissionTypeService)service; } catch( Exception ex ) { // sometimes service locators throw exceptions rather than returning null, handle that throw new RuntimeException( "Error retrieving service: " + serviceName + " from the KimImplServiceLocator.", ex ); } } @Override public boolean hasPermission(String principalId, String namespaceCode, String permissionName) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); return isAuthorized( principalId, namespaceCode, permissionName, Collections.<String, String>emptyMap() ); } @Override public boolean isAuthorized(String principalId, String namespaceCode, String permissionName, Map<String, String> qualification ) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); incomingParamCheck(qualification, "qualification"); if ( LOG.isDebugEnabled() ) { logAuthorizationCheck("Permission", principalId, namespaceCode, permissionName, qualification); } List<String> roleIds = getRoleIdsForPermission(namespaceCode, permissionName); if ( roleIds.isEmpty() ) { if ( LOG.isDebugEnabled() ) { LOG.debug( "Result: false"); } return false; } boolean isAuthorized = roleService.principalHasRole(principalId, roleIds, qualification); if ( LOG.isDebugEnabled() ) { LOG.debug( "Result: " + isAuthorized ); } return isAuthorized; } @Override public boolean hasPermissionByTemplate(String principalId, String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); return isAuthorizedByTemplate(principalId, namespaceCode, permissionTemplateName, permissionDetails, Collections.<String, String>emptyMap()); } @Override public boolean isAuthorizedByTemplate(String principalId, String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails, Map<String, String> qualification) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); incomingParamCheck(qualification, "qualification"); if ( LOG.isDebugEnabled() ) { logAuthorizationCheckByTemplate("Perm Templ", principalId, namespaceCode, permissionTemplateName, permissionDetails, qualification); } List<String> roleIds = getRoleIdsForPermissionTemplate(namespaceCode, permissionTemplateName, permissionDetails); if (roleIds.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Result: false"); } return false; } boolean isAuthorized = roleService.principalHasRole(principalId, roleIds, qualification); if (LOG.isDebugEnabled()) { LOG.debug( "Result: " + isAuthorized ); } return isAuthorized; } @Override public List<Permission> getAuthorizedPermissions( String principalId, String namespaceCode, String permissionName, Map<String, String> qualification ) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); incomingParamCheck(qualification, "qualification"); // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByName(namespaceCode, permissionName); // now, filter the full list by the detail passed List<Permission> applicablePermissions = getMatchingPermissions( permissions, null ); List<Permission> permissionsForUser = getPermissionsForUser(principalId, applicablePermissions, qualification); return permissionsForUser; } @Override public List<Permission> getAuthorizedPermissionsByTemplate(String principalId, String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails, Map<String, String> qualification) throws RiceIllegalArgumentException { incomingParamCheck(principalId, "principalId"); incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); incomingParamCheck(qualification, "qualification"); // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByTemplateName(namespaceCode, permissionTemplateName); // now, filter the full list by the detail passed List<Permission> applicablePermissions = getMatchingPermissions( permissions, permissionDetails ); return getPermissionsForUser(principalId, applicablePermissions, qualification); } /** * Checks the list of permissions against the principal's roles and returns a subset of the list which match. */ protected List<Permission> getPermissionsForUser( String principalId, List<Permission> permissions, Map<String, String> qualification ) { List<Permission> results = new ArrayList<Permission>(); for ( Permission perm : permissions ) { List<String> roleIds = getRoleIdsForPermissions( Collections.singletonList(perm) ); if ( roleIds != null && !roleIds.isEmpty() ) { if ( roleService.principalHasRole( principalId, roleIds, qualification) ) { results.add( perm ); } } } return Collections.unmodifiableList(results); } protected Map<String,PermissionTypeService> getPermissionTypeServicesByTemplateId( Collection<Permission> permissions ) { Map<String,PermissionTypeService> permissionTypeServices = new HashMap<String, PermissionTypeService>( permissions.size() ); for (Permission perm : permissions) { if(!permissionTypeServices.containsKey(perm.getTemplate().getId())) { permissionTypeServices.put(perm.getTemplate().getId(), getPermissionTypeService(perm.getTemplate())); } } return permissionTypeServices; } protected Map<String,List<Permission>> groupPermissionsByTemplate(Collection<Permission> permissions) { Map<String,List<Permission>> results = new HashMap<String,List<Permission>>(); for (Permission perm : permissions) { List<Permission> perms = results.get(perm.getTemplate().getId()); if (perms == null) { perms = new ArrayList<Permission>(); results.put(perm.getTemplate().getId(), perms); } perms.add(perm); } return results; } /** * Compare each of the passed in permissions with the given permissionDetails. Those that * match are added to the result list. */ protected List<Permission> getMatchingPermissions( List<Permission> permissions, Map<String, String> permissionDetails ) { List<String> permissionIds = new ArrayList<String>(permissions.size()); for (Permission permission : permissions) { permissionIds.add(permission.getId()); } String cacheKey = new StringBuilder("{getMatchingPermissions}") .append("permissionIds=").append(CacheKeyUtils.key(permissionIds)).append("|") .append("permissionDetails=").append(CacheKeyUtils.mapKey(permissionDetails)).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<Permission>)cachedValue.get()); } List<Permission> applicablePermissions = new ArrayList<Permission>(); if ( permissionDetails == null || permissionDetails.isEmpty() ) { // if no details passed, assume that all match for ( Permission perm : permissions ) { applicablePermissions.add(perm); } } else { // otherwise, attempt to match the permission details // build a map of the template IDs to the type services Map<String,PermissionTypeService> permissionTypeServices = getPermissionTypeServicesByTemplateId(permissions); // build a map of permissions by template ID Map<String, List<Permission>> permissionMap = groupPermissionsByTemplate(permissions); // loop over the different templates, matching all of the same template against the type // service at once for ( Map.Entry<String,List<Permission>> entry : permissionMap.entrySet() ) { PermissionTypeService permissionTypeService = permissionTypeServices.get( entry.getKey() ); List<Permission> permissionList = entry.getValue(); applicablePermissions.addAll( permissionTypeService.getMatchingPermissions( permissionDetails, permissionList ) ); } } applicablePermissions = Collections.unmodifiableList(applicablePermissions); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, applicablePermissions); return applicablePermissions; } @Override public List<Assignee> getPermissionAssignees( String namespaceCode, String permissionName, Map<String, String> qualification ) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); incomingParamCheck(qualification, "qualification"); List<String> roleIds = getRoleIdsForPermission( namespaceCode, permissionName); if ( roleIds.isEmpty() ) { return Collections.emptyList(); } Collection<RoleMembership> roleMembers = roleService.getRoleMembers( roleIds,qualification ); List<Assignee> results = new ArrayList<Assignee>(); for ( RoleMembership rm : roleMembers ) { List<DelegateType.Builder> delegateBuilderList = new ArrayList<DelegateType.Builder>(); if (!rm.getDelegates().isEmpty()) { for (DelegateType delegate : rm.getDelegates()){ delegateBuilderList.add(DelegateType.Builder.create(delegate)); } } if ( MemberType.PRINCIPAL.equals(rm.getType()) ) { results.add (Assignee.Builder.create(rm.getMemberId(), null, delegateBuilderList).build()); } else if ( MemberType.GROUP.equals(rm.getType()) ) { results.add (Assignee.Builder.create(null, rm.getMemberId(), delegateBuilderList).build()); } } return Collections.unmodifiableList(results); } @Override public List<Assignee> getPermissionAssigneesByTemplate(String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails, Map<String, String> qualification) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); incomingParamCheck(qualification, "qualification"); List<String> roleIds = getRoleIdsForPermissionTemplate( namespaceCode, permissionTemplateName, permissionDetails); if ( roleIds.isEmpty() ) { return Collections.emptyList(); } Collection<RoleMembership> roleMembers = roleService.getRoleMembers( roleIds,qualification); List<Assignee> results = new ArrayList<Assignee>(); for ( RoleMembership rm : roleMembers ) { List<DelegateType.Builder> delegateBuilderList = new ArrayList<DelegateType.Builder>(); if (!rm.getDelegates().isEmpty()) { for (DelegateType delegate : rm.getDelegates()){ delegateBuilderList.add(DelegateType.Builder.create(delegate)); } } if ( MemberType.PRINCIPAL.equals(rm.getType()) ) { results.add (Assignee.Builder.create(rm.getMemberId(), null, delegateBuilderList).build()); } else { // a group membership results.add (Assignee.Builder.create(null, rm.getMemberId(), delegateBuilderList).build()); } } return Collections.unmodifiableList(results); } @Override public boolean isPermissionDefined( String namespaceCode, String permissionName ) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByName(namespaceCode, permissionName); // now, filter the full list by the detail passed return !getMatchingPermissions(permissions, null).isEmpty(); } @Override public boolean isPermissionDefinedByTemplate(String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByTemplateName(namespaceCode, permissionTemplateName); // now, filter the full list by the detail passed return !getMatchingPermissions(permissions, permissionDetails).isEmpty(); } @Override public List<String> getRoleIdsForPermission(String namespaceCode, String permissionName) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); // note...this method is cached at the RoleService interface level using an annotation, but it's called quite // a bit internally, so we'll reproduce the caching here using the same key to help optimize String cacheKey = new StringBuilder("{RoleIds}") .append("namespaceCode=").append(namespaceCode).append("|") .append("name=").append(permissionName).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<String>)cachedValue.get()); } // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByName(namespaceCode, permissionName); // now, filter the full list by the detail passed List<Permission> applicablePermissions = getMatchingPermissions(permissions, null); List<String> roleIds = getRoleIdsForPermissions(applicablePermissions); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, roleIds); return roleIds; } protected List<String> getRoleIdsForPermissionTemplate(String namespaceCode, String permissionTemplateName, Map<String, String> permissionDetails) { String cacheKey = new StringBuilder("{getRoleIdsForPermissionTemplate}") .append("namespaceCode=").append(namespaceCode).append("|") .append("permissionTemplateName=").append(permissionTemplateName).append("|") .append("permissionDetails=").append(CacheKeyUtils.mapKey(permissionDetails)).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<String>)cachedValue.get()); } // get all the permission objects whose name match that requested List<Permission> permissions = getPermissionsByTemplateName(namespaceCode, permissionTemplateName); // now, filter the full list by the detail passed List<Permission> applicablePermissions = getMatchingPermissions(permissions, permissionDetails); List<String> roleIds = getRoleIdsForPermissions(applicablePermissions); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, roleIds); return roleIds; } // -------------------- // Permission Data // -------------------- @Override public Permission getPermission(String permissionId) throws RiceIllegalArgumentException { incomingParamCheck(permissionId, "permissionId"); PermissionBo impl = getPermissionImpl(permissionId); if (impl != null) { return PermissionBo.to(impl); } return null; } @Override public List<Permission> findPermissionsByTemplate(String namespaceCode, String permissionTemplateName) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); List<Permission> perms = getPermissionsByTemplateName(namespaceCode, permissionTemplateName); List<Permission> results = new ArrayList<Permission>(perms.size()); for (Permission perm : perms) { results.add(perm); } return Collections.unmodifiableList(results); } protected PermissionBo getPermissionImpl(String permissionId) throws RiceIllegalArgumentException { incomingParamCheck(permissionId, "permissionId"); HashMap<String,Object> pk = new HashMap<String,Object>( 1 ); pk.put( KimConstants.PrimaryKeyConstants.PERMISSION_ID, permissionId ); return businessObjectService.findByPrimaryKey( PermissionBo.class, pk ); } protected List<Permission> getPermissionsByTemplateName( String namespaceCode, String permissionTemplateName ){ String cacheKey = new StringBuilder("{getPermissionsByTemplateName}") .append("namespaceCode=").append(namespaceCode).append("|") .append("permissionTemplateName=").append(permissionTemplateName).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<Permission>)cachedValue.get()); } HashMap<String,Object> criteria = new HashMap<String,Object>(3); criteria.put("template.namespaceCode", namespaceCode); criteria.put("template.name", permissionTemplateName); criteria.put(KRADPropertyConstants.ACTIVE, "Y"); List<Permission> permissions = toPermissions(businessObjectService.findMatching(PermissionBo.class, criteria)); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, permissions); return permissions; } protected List<Permission> getPermissionsByName( String namespaceCode, String permissionName ) { String cacheKey = new StringBuilder("{getPermissionsByName}") .append("namespaceCode=").append(namespaceCode).append("|") .append("permissionName=").append(permissionName).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<Permission>)cachedValue.get()); } HashMap<String,Object> criteria = new HashMap<String,Object>(3); criteria.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode); criteria.put(KimConstants.UniqueKeyConstants.PERMISSION_NAME, permissionName); criteria.put(KRADPropertyConstants.ACTIVE, "Y"); List<Permission> permissions = toPermissions(businessObjectService.findMatching( PermissionBo.class, criteria )); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, permissions); return permissions; } @Override public Template getPermissionTemplate(String permissionTemplateId) throws RiceIllegalArgumentException { incomingParamCheck(permissionTemplateId, "permissionTemplateId"); PermissionTemplateBo impl = businessObjectService.findBySinglePrimaryKey( PermissionTemplateBo.class, permissionTemplateId ); if ( impl != null ) { return PermissionTemplateBo.to(impl); } return null; } @Override public Template findPermTemplateByNamespaceCodeAndName(String namespaceCode, String permissionTemplateName) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionTemplateName, "permissionTemplateName"); Map<String,String> criteria = new HashMap<String,String>(2); criteria.put( KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode ); criteria.put( KimConstants.UniqueKeyConstants.PERMISSION_TEMPLATE_NAME, permissionTemplateName ); PermissionTemplateBo impl = businessObjectService.findByPrimaryKey( PermissionTemplateBo.class, criteria ); if ( impl != null ) { return PermissionTemplateBo.to(impl); } return null; } @Override public List<Template> getAllTemplates() { if ( allTemplates.isEmpty() ) { Map<String,String> criteria = new HashMap<String,String>(1); criteria.put( KRADPropertyConstants.ACTIVE, "Y" ); List<PermissionTemplateBo> impls = (List<PermissionTemplateBo>) businessObjectService.findMatching( PermissionTemplateBo.class, criteria ); List<Template> infos = new ArrayList<Template>( impls.size() ); for ( PermissionTemplateBo impl : impls ) { infos.add( PermissionTemplateBo.to(impl) ); } Collections.sort(infos, new Comparator<Template>() { @Override public int compare(Template tmpl1, Template tmpl2) { int result = tmpl1.getNamespaceCode().compareTo(tmpl2.getNamespaceCode()); if ( result != 0 ) { return result; } result = tmpl1.getName().compareTo(tmpl2.getName()); return result; } }); allTemplates.addAll(infos); } return Collections.unmodifiableList(allTemplates); } @Override public Permission createPermission(Permission permission) throws RiceIllegalArgumentException, RiceIllegalStateException { incomingParamCheck(permission, "permission"); if (StringUtils.isNotBlank(permission.getId()) && getPermission(permission.getId()) != null) { throw new RiceIllegalStateException("the permission to create already exists: " + permission); } List<PermissionAttributeBo> attrBos = Collections.emptyList(); if (permission.getTemplate() != null) { attrBos = KimAttributeDataBo.createFrom(PermissionAttributeBo.class, permission.getAttributes(), permission.getTemplate().getKimTypeId()); } PermissionBo bo = PermissionBo.from(permission); if (bo.getTemplate() == null && bo.getTemplateId() != null) { bo.setTemplate(PermissionTemplateBo.from(getPermissionTemplate(bo.getTemplateId()))); } bo.setAttributeDetails(attrBos); return PermissionBo.to(businessObjectService.save(bo)); } @Override public Permission updatePermission(Permission permission) throws RiceIllegalArgumentException, RiceIllegalStateException { incomingParamCheck(permission, "permission"); PermissionBo oldPermission = getPermissionImpl(permission.getId()); if (StringUtils.isBlank(permission.getId()) || oldPermission == null) { throw new RiceIllegalStateException("the permission does not exist: " + permission); } //List<PermissionAttributeBo> attrBos = KimAttributeDataBo.createFrom(PermissionAttributeBo.class, permission.getAttributes(), permission.getTemplate().getKimTypeId()); List<PermissionAttributeBo> oldAttrBos = oldPermission.getAttributeDetails(); //put old attributes in map for easier updating Map<String, PermissionAttributeBo> oldAttrMap = new HashMap<String, PermissionAttributeBo>(); for (PermissionAttributeBo oldAttr : oldAttrBos) { oldAttrMap.put(oldAttr.getKimAttribute().getAttributeName(), oldAttr); } List<PermissionAttributeBo> newAttrBos = new ArrayList<PermissionAttributeBo>(); for (String key : permission.getAttributes().keySet()) { if (oldAttrMap.containsKey(key)) { PermissionAttributeBo updatedAttr = oldAttrMap.get(key); updatedAttr.setAttributeValue(permission.getAttributes().get(key)); newAttrBos.add(updatedAttr); } else { //new attribute newAttrBos.addAll(KimAttributeDataBo.createFrom(PermissionAttributeBo.class, Collections.singletonMap(key, permission.getAttributes().get(key)), permission.getTemplate().getKimTypeId())); } } PermissionBo bo = PermissionBo.from(permission); if (CollectionUtils.isNotEmpty(newAttrBos)) { if(null!= bo.getAttributeDetails()) { bo.getAttributeDetails().clear(); } bo.setAttributeDetails(newAttrBos); } if (bo.getTemplate() == null && bo.getTemplateId() != null) { bo.setTemplate(PermissionTemplateBo.from(getPermissionTemplate(bo.getTemplateId()))); } return PermissionBo.to(businessObjectService.save(bo)); } @Override public Permission findPermByNamespaceCodeAndName(String namespaceCode, String permissionName) throws RiceIllegalArgumentException { incomingParamCheck(namespaceCode, "namespaceCode"); incomingParamCheck(permissionName, "permissionName"); PermissionBo permissionBo = getPermissionBoByName(namespaceCode, permissionName); if (permissionBo != null) { return PermissionBo.to(permissionBo); } return null; } protected PermissionBo getPermissionBoByName(String namespaceCode, String permissionName) { if (StringUtils.isBlank(namespaceCode) || StringUtils.isBlank(permissionName)) { return null; } Map<String, String> criteria = new HashMap<String, String>(); criteria.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode); criteria.put(KimConstants.UniqueKeyConstants.NAME, permissionName); criteria.put(KRADPropertyConstants.ACTIVE, "Y"); // while this is not actually the primary key - there will be at most one row with these criteria return businessObjectService.findByPrimaryKey(PermissionBo.class, criteria); } @Override public PermissionQueryResults findPermissions(final QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException { incomingParamCheck(queryByCriteria, "queryByCriteria"); LookupCustomizer.Builder<PermissionBo> lc = LookupCustomizer.Builder.create(); lc.setPredicateTransform(AttributeTransform.getInstance()); GenericQueryResults<PermissionBo> results = criteriaLookupService.lookup(PermissionBo.class, queryByCriteria, lc.build()); PermissionQueryResults.Builder builder = PermissionQueryResults.Builder.create(); builder.setMoreResultsAvailable(results.isMoreResultsAvailable()); builder.setTotalRowCount(results.getTotalRowCount()); final List<Permission.Builder> ims = new ArrayList<Permission.Builder>(); for (PermissionBo bo : results.getResults()) { ims.add(Permission.Builder.create(bo)); } builder.setResults(ims); return builder.build(); } @Override public TemplateQueryResults findPermissionTemplates(final QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException { incomingParamCheck(queryByCriteria, "queryByCriteria"); GenericQueryResults<PermissionTemplateBo> results = criteriaLookupService.lookup(PermissionTemplateBo.class, queryByCriteria); TemplateQueryResults.Builder builder = TemplateQueryResults.Builder.create(); builder.setMoreResultsAvailable(results.isMoreResultsAvailable()); builder.setTotalRowCount(results.getTotalRowCount()); final List<Template.Builder> ims = new ArrayList<Template.Builder>(); for (PermissionTemplateBo bo : results.getResults()) { ims.add(Template.Builder.create(bo)); } builder.setResults(ims); return builder.build(); } private List<String> getRoleIdsForPermissions( Collection<Permission> permissions ) { if (CollectionUtils.isEmpty(permissions)) { return Collections.emptyList(); } List<String> ids = new ArrayList<String>(); for (Permission p : permissions) { ids.add(p.getId()); } return getRoleIdsForPermissionIds(ids); } private List<String> getRoleIdsForPermissionIds(Collection<String> permissionIds) { if (CollectionUtils.isEmpty(permissionIds)) { return Collections.emptyList(); } String cacheKey = new StringBuilder("{getRoleIdsForPermissionIds}") .append("permissionIds=").append(CacheKeyUtils.key(permissionIds)).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<String>)cachedValue.get()); } QueryByCriteria query = QueryByCriteria.Builder.fromPredicates(equal("active", "true"), in("permissionId", permissionIds.toArray(new String[]{}))); GenericQueryResults<RolePermissionBo> results = criteriaLookupService.lookup(RolePermissionBo.class, query); List<String> roleIds = new ArrayList<String>(); for (RolePermissionBo bo : results.getResults()) { roleIds.add(bo.getRoleId()); } roleIds = Collections.unmodifiableList(roleIds); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, roleIds); return roleIds; } /** * Sets the kimTypeInfoService attribute value. * * @param kimTypeInfoService The kimTypeInfoService to set. */ public void setKimTypeInfoService(KimTypeInfoService kimTypeInfoService) { this.kimTypeInfoService = kimTypeInfoService; } /** * Sets the defaultPermissionTypeService attribute value. * * @param defaultPermissionTypeService The defaultPermissionTypeService to set. */ public void setDefaultPermissionTypeService(PermissionTypeService defaultPermissionTypeService) { this.defaultPermissionTypeService = defaultPermissionTypeService; } /** * Sets the roleService attribute value. * * @param roleService The roleService to set. */ public void setRoleService(RoleService roleService) { this.roleService = roleService; } /** * Sets the businessObjectService attribute value. * * @param businessObjectService The businessObjectService to set. */ public void setBusinessObjectService(final BusinessObjectService businessObjectService) { this.businessObjectService = businessObjectService; } /** * Sets the criteriaLookupService attribute value. * * @param criteriaLookupService The criteriaLookupService to set. */ public void setCriteriaLookupService(final CriteriaLookupService criteriaLookupService) { this.criteriaLookupService = criteriaLookupService; } /** * Sets the cache manager which this service implementation can for internal caching. * Calling this setter is optional, though the value passed to it must not be null. * * @param cacheManager the cache manager to use for internal caching, must not be null * @throws IllegalArgumentException if a null cache manager is passed */ public void setCacheManager(final CacheManager cacheManager) { if (cacheManager == null) { throw new IllegalArgumentException("cacheManager must not be null"); } this.cacheManager = cacheManager; } private List<Permission> toPermissions(Collection<PermissionBo> permissionBos) { if (CollectionUtils.isEmpty(permissionBos)) { return new ArrayList<Permission>(); } List<Permission> permissions = new ArrayList<Permission>(permissionBos.size()); for (PermissionBo permissionBo : permissionBos) { permissions.add(PermissionBo.to(permissionBo)); } return permissions; } protected void logAuthorizationCheck(String checkType, String principalId, String namespaceCode, String permissionName, Map<String, String> qualification ) { StringBuilder sb = new StringBuilder(); sb.append( '\n' ); sb.append( "Is AuthZ for " ).append( checkType ).append( ": " ).append( namespaceCode ).append( "/" ).append( permissionName ).append( '\n' ); sb.append( " Principal: " ).append( principalId ); if ( principalId != null ) { Principal principal = KimApiServiceLocator.getIdentityService().getPrincipal(principalId); if ( principal != null ) { sb.append( " (" ).append( principal.getPrincipalName() ).append( ')' ); } } sb.append( '\n' ); sb.append( " Qualifiers:\n" ); if ( qualification != null && !qualification.isEmpty() ) { sb.append( qualification ); } else { sb.append( " [null]\n" ); } if (LOG.isTraceEnabled()) { LOG.trace( sb.append(ExceptionUtils.getStackTrace(new Throwable()))); } else { LOG.debug(sb.toString()); } } protected void logAuthorizationCheckByTemplate(String checkType, String principalId, String namespaceCode, String permissionName, Map<String, String> permissionDetails, Map<String, String> qualification ) { StringBuilder sb = new StringBuilder(); sb.append( '\n' ); sb.append( "Is AuthZ for " ).append( checkType ).append( ": " ).append( namespaceCode ).append( "/" ).append( permissionName ).append( '\n' ); sb.append( " Principal: " ).append( principalId ); if ( principalId != null ) { Principal principal = KimApiServiceLocator.getIdentityService().getPrincipal(principalId); if ( principal != null ) { sb.append( " (" ).append( principal.getPrincipalName() ).append( ')' ); } } sb.append( '\n' ); sb.append( " Details:\n" ); if ( permissionDetails != null ) { sb.append( permissionDetails ); } else { sb.append( " [null]\n" ); } sb.append( " Qualifiers:\n" ); if ( qualification != null && !qualification.isEmpty() ) { sb.append( qualification ); } else { sb.append( " [null]\n" ); } if (LOG.isTraceEnabled()) { LOG.trace( sb.append(ExceptionUtils.getStackTrace(new Throwable()))); } else { LOG.debug(sb.toString()); } } private void incomingParamCheck(Object object, String name) { if (object == null) { throw new RiceIllegalArgumentException(name + " was null"); } else if (object instanceof String && StringUtils.isBlank((String) object)) { throw new RiceIllegalArgumentException(name + " was blank"); } } }
minor import optimization
kim/kim-impl/src/main/java/org/kuali/rice/kim/impl/permission/PermissionServiceImpl.java
minor import optimization
<ide><path>im/kim-impl/src/main/java/org/kuali/rice/kim/impl/permission/PermissionServiceImpl.java <ide> import org.kuali.rice.kim.api.permission.Permission; <ide> import org.kuali.rice.kim.api.permission.PermissionQueryResults; <ide> import org.kuali.rice.kim.api.permission.PermissionService; <del>import org.kuali.rice.kim.api.role.RoleMember; <ide> import org.kuali.rice.kim.api.role.RoleMembership; <ide> import org.kuali.rice.kim.api.role.RoleService; <ide> import org.kuali.rice.kim.api.services.KimApiServiceLocator;
Java
mit
d3a103cb6e969c7481fec978ea2af8a36042a824
0
VKCOM/vk-java-sdk,VKCOM/vk-java-sdk
package com.vk.api.sdk.queries.upload; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.objects.app.widgets.responses.UploadImageResponse; import java.io.File; public class UploadAppImageQuery extends UploadQueryBuilder<UploadAppImageQuery, UploadImageResponse> { public UploadAppImageQuery(VkApiClient client, String uploadUrl, File file) { super(client, uploadUrl, "image", UploadImageResponse.class); file(file); } @Override protected UploadAppImageQuery getThis() { return this; } }
sdk/src/main/java/com/vk/api/sdk/queries/upload/UploadAppImageQuery.java
package com.vk.api.sdk.queries.upload; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.objects.app.widgets.responses.UploadImageResponse; import java.io.File; public class UploadAppImageQuery extends UploadQueryBuilder<UploadAppImageQuery, UploadImageResponse> { public UploadAppImageQuery(VkApiClient client, String uploadUrl, File file) { super(client, uploadUrl, "image", UploadImageResponse.class); file(file); } @Override protected UploadAppImageQuery getThis() { return this; } }
Fix code style
sdk/src/main/java/com/vk/api/sdk/queries/upload/UploadAppImageQuery.java
Fix code style
<ide><path>dk/src/main/java/com/vk/api/sdk/queries/upload/UploadAppImageQuery.java <ide> import java.io.File; <ide> <ide> public class UploadAppImageQuery extends UploadQueryBuilder<UploadAppImageQuery, UploadImageResponse> { <del> <ide> <ide> public UploadAppImageQuery(VkApiClient client, String uploadUrl, File file) { <ide> super(client, uploadUrl, "image", UploadImageResponse.class);
Java
mit
cac6b78368caa736a65466f31f482b60aa820cb3
0
CS2103JAN2017-W14-B4/main,CS2103JAN2017-W14-B4/main
package seedu.ezdo.storage; import java.io.IOException; import java.util.Optional; import java.util.logging.Logger; import com.google.common.eventbus.Subscribe; import seedu.ezdo.commons.core.ComponentManager; import seedu.ezdo.commons.core.Config; import seedu.ezdo.commons.core.LogsCenter; import seedu.ezdo.commons.events.model.EzDoChangedEvent; import seedu.ezdo.commons.events.storage.DataSavingExceptionEvent; import seedu.ezdo.commons.events.storage.EzDoDirectoryChangedEvent; import seedu.ezdo.commons.exceptions.DataConversionException; import seedu.ezdo.commons.util.ConfigUtil; import seedu.ezdo.model.ReadOnlyEzDo; import seedu.ezdo.model.UserPrefs; /** * Manages storage of EzDo data in local storage. */ public class StorageManager extends ComponentManager implements Storage { private static final Logger logger = LogsCenter.getLogger(StorageManager.class); // private ConfigStorage configStorage; private EzDoStorage ezDoStorage; private UserPrefsStorage userPrefsStorage; private Config config; // public StorageManager(EzDoStorage ezDoStorage, UserPrefsStorage userPrefsStorage, ConfigStorage configStorage) { // super(); // this.configStorage = configStorage; // this.ezDoStorage = ezDoStorage; // this.userPrefsStorage = userPrefsStorage; // } public StorageManager(EzDoStorage ezDoStorage, UserPrefsStorage userPrefsStorage, Config config) { super(); this.config = config; this.ezDoStorage = ezDoStorage; this.userPrefsStorage = userPrefsStorage; } public StorageManager(String ezDoFilePath, String userPrefsFilePath, Config config) { this(new XmlEzDoStorage(ezDoFilePath), new JsonUserPrefsStorage(userPrefsFilePath), config); } // public StorageManager(String ezDoFilePath, String userPrefsFilePath, String configFilePath) { // this(new XmlEzDoStorage(ezDoFilePath), new JsonUserPrefsStorage(userPrefsFilePath), // new JsonConfigStorage(configFilePath)); // } // ================ UserPrefs methods ============================== // ================ UserPrefs methods ============================== @Override public Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException { return userPrefsStorage.readUserPrefs(); } @Override public void saveUserPrefs(UserPrefs userPrefs) throws IOException { userPrefsStorage.saveUserPrefs(userPrefs); } // ================ EzDo methods ============================== @Override public String getEzDoFilePath() { return ezDoStorage.getEzDoFilePath(); } @Override public void setEzDoFilePath(String path) { ezDoStorage.setEzDoFilePath(path); } @Override public Optional<ReadOnlyEzDo> readEzDo() throws DataConversionException, IOException { return readEzDo(ezDoStorage.getEzDoFilePath()); } @Override public Optional<ReadOnlyEzDo> readEzDo(String filePath) throws DataConversionException, IOException { logger.fine("Attempting to read data from file: " + filePath); return ezDoStorage.readEzDo(filePath); } @Override public void saveEzDo(ReadOnlyEzDo ezDo) throws IOException { saveEzDo(ezDo, ezDoStorage.getEzDoFilePath()); } @Override public void saveEzDo(ReadOnlyEzDo ezDo, String filePath) throws IOException { logger.fine("Attempting to write to data file: " + filePath); ezDoStorage.saveEzDo(ezDo, filePath); } @Override @Subscribe public void handleEzDoChangedEvent(EzDoChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Local data changed, saving to file")); try { saveEzDo(event.data); } catch (IOException e) { raise(new DataSavingExceptionEvent(e)); } } @Override @Subscribe public void handleEzDoDirectoryChangedEvent(EzDoDirectoryChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Directory changed, saving to new directory at: " + event.getPath())); String oldPath = config.getEzDoFilePath(); try { moveEzDo(oldPath, event.getPath()); config.setEzDoFilePath(event.getPath()); setEzDoFilePath(event.getPath()); ConfigUtil.saveConfig(config, Config.DEFAULT_CONFIG_FILE); } catch (IOException ioe) { config.setEzDoFilePath(oldPath); raise (new DataSavingExceptionEvent(ioe)); } } @Override public void moveEzDo(String oldPath, String newPath) throws IOException { ezDoStorage.moveEzDo(oldPath, newPath); } }
src/main/java/seedu/ezdo/storage/StorageManager.java
package seedu.ezdo.storage; import java.io.IOException; import java.util.Optional; import java.util.logging.Logger; import com.google.common.eventbus.Subscribe; import seedu.ezdo.commons.core.ComponentManager; import seedu.ezdo.commons.core.Config; import seedu.ezdo.commons.core.LogsCenter; import seedu.ezdo.commons.events.model.EzDoChangedEvent; import seedu.ezdo.commons.events.storage.DataSavingExceptionEvent; import seedu.ezdo.commons.events.storage.EzDoDirectoryChangedEvent; import seedu.ezdo.commons.exceptions.DataConversionException; import seedu.ezdo.commons.util.ConfigUtil; import seedu.ezdo.model.ReadOnlyEzDo; import seedu.ezdo.model.UserPrefs; /** * Manages storage of EzDo data in local storage. */ public class StorageManager extends ComponentManager implements Storage { private static final Logger logger = LogsCenter.getLogger(StorageManager.class); // private ConfigStorage configStorage; private EzDoStorage ezDoStorage; private UserPrefsStorage userPrefsStorage; private Config config; // public StorageManager(EzDoStorage ezDoStorage, UserPrefsStorage userPrefsStorage, ConfigStorage configStorage) { // super(); // this.configStorage = configStorage; // this.ezDoStorage = ezDoStorage; // this.userPrefsStorage = userPrefsStorage; // } public StorageManager(EzDoStorage ezDoStorage, UserPrefsStorage userPrefsStorage, Config config) { super(); this.config = config; this.ezDoStorage = ezDoStorage; this.userPrefsStorage = userPrefsStorage; } public StorageManager(String ezDoFilePath, String userPrefsFilePath, Config config) { this(new XmlEzDoStorage(ezDoFilePath), new JsonUserPrefsStorage(userPrefsFilePath), config); } // public StorageManager(String ezDoFilePath, String userPrefsFilePath, String configFilePath) { // this(new XmlEzDoStorage(ezDoFilePath), new JsonUserPrefsStorage(userPrefsFilePath), new JsonConfigStorage(configFilePath)); // } // ================ UserPrefs methods ============================== // ================ UserPrefs methods ============================== @Override public Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException { return userPrefsStorage.readUserPrefs(); } @Override public void saveUserPrefs(UserPrefs userPrefs) throws IOException { userPrefsStorage.saveUserPrefs(userPrefs); } // ================ EzDo methods ============================== @Override public String getEzDoFilePath() { return ezDoStorage.getEzDoFilePath(); } @Override public void setEzDoFilePath(String path) { ezDoStorage.setEzDoFilePath(path); } @Override public Optional<ReadOnlyEzDo> readEzDo() throws DataConversionException, IOException { return readEzDo(ezDoStorage.getEzDoFilePath()); } @Override public Optional<ReadOnlyEzDo> readEzDo(String filePath) throws DataConversionException, IOException { logger.fine("Attempting to read data from file: " + filePath); return ezDoStorage.readEzDo(filePath); } @Override public void saveEzDo(ReadOnlyEzDo ezDo) throws IOException { saveEzDo(ezDo, ezDoStorage.getEzDoFilePath()); } @Override public void saveEzDo(ReadOnlyEzDo ezDo, String filePath) throws IOException { logger.fine("Attempting to write to data file: " + filePath); ezDoStorage.saveEzDo(ezDo, filePath); } @Override @Subscribe public void handleEzDoChangedEvent(EzDoChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Local data changed, saving to file")); try { saveEzDo(event.data); } catch (IOException e) { raise(new DataSavingExceptionEvent(e)); } } @Override @Subscribe public void handleEzDoDirectoryChangedEvent(EzDoDirectoryChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Directory changed, saving to new directory at: " + event.getPath())); String oldPath = config.getEzDoFilePath(); try { moveEzDo(oldPath, event.getPath()); config.setEzDoFilePath(event.getPath()); setEzDoFilePath(event.getPath()); ConfigUtil.saveConfig(config, Config.DEFAULT_CONFIG_FILE); } catch (IOException ioe) { config.setEzDoFilePath(oldPath); raise (new DataSavingExceptionEvent(ioe)); } } @Override public void moveEzDo(String oldPath, String newPath) throws IOException { ezDoStorage.moveEzDo(oldPath, newPath); } }
Wrap line for readability
src/main/java/seedu/ezdo/storage/StorageManager.java
Wrap line for readability
<ide><path>rc/main/java/seedu/ezdo/storage/StorageManager.java <ide> this(new XmlEzDoStorage(ezDoFilePath), new JsonUserPrefsStorage(userPrefsFilePath), config); <ide> } <ide> // public StorageManager(String ezDoFilePath, String userPrefsFilePath, String configFilePath) { <del>// this(new XmlEzDoStorage(ezDoFilePath), new JsonUserPrefsStorage(userPrefsFilePath), new JsonConfigStorage(configFilePath)); <add>// this(new XmlEzDoStorage(ezDoFilePath), new JsonUserPrefsStorage(userPrefsFilePath), <add>// new JsonConfigStorage(configFilePath)); <ide> // } <ide> // ================ UserPrefs methods ============================== <ide>
Java
mit
cba77fd4d764230fbd66057d4c418cb412958998
0
fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg
package ua.com.fielden.platform.web.centre; import static java.lang.String.format; import static ua.com.fielden.platform.web.centre.EgiConfigurations.CHECKBOX_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.CHECKBOX_VISIBLE; import static ua.com.fielden.platform.web.centre.EgiConfigurations.CHECKBOX_WITH_PRIMARY_ACTION_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.HEADER_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.SECONDARY_ACTION_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.SUMMARY_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.TOOLBAR_VISIBLE; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import org.apache.log4j.Logger; import com.google.common.collect.ListMultimap; import com.google.inject.Injector; import ua.com.fielden.platform.basic.IValueMatcherWithCentreContext; import ua.com.fielden.platform.basic.autocompleter.FallbackValueMatcherWithCentreContext; import ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector; import ua.com.fielden.platform.dao.IEntityDao; import ua.com.fielden.platform.data.generator.IGenerator; import ua.com.fielden.platform.dom.DomContainer; import ua.com.fielden.platform.dom.DomElement; import ua.com.fielden.platform.dom.InnerTextElement; import ua.com.fielden.platform.domaintree.ICalculatedProperty.CalculatedPropertyAttribute; import ua.com.fielden.platform.domaintree.IGlobalDomainTreeManager; import ua.com.fielden.platform.domaintree.IServerGlobalDomainTreeManager; import ua.com.fielden.platform.domaintree.centre.ICentreDomainTreeManager; import ua.com.fielden.platform.domaintree.centre.ICentreDomainTreeManager.ICentreDomainTreeManagerAndEnhancer; import ua.com.fielden.platform.domaintree.impl.AbstractDomainTree; import ua.com.fielden.platform.domaintree.impl.CalculatedProperty; import ua.com.fielden.platform.domaintree.impl.GlobalDomainTreeManager; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder; import ua.com.fielden.platform.entity.fetch.IFetchProvider; import ua.com.fielden.platform.reflection.PropertyTypeDeterminator; import ua.com.fielden.platform.reflection.asm.impl.DynamicEntityClassLoader; import ua.com.fielden.platform.security.user.IUserProvider; import ua.com.fielden.platform.security.user.User; import ua.com.fielden.platform.serialisation.api.ISerialiser; import ua.com.fielden.platform.serialisation.jackson.DefaultValueContract; import ua.com.fielden.platform.types.Money; import ua.com.fielden.platform.ui.menu.MiWithConfigurationSupport; import ua.com.fielden.platform.utils.EntityUtils; import ua.com.fielden.platform.utils.Pair; import ua.com.fielden.platform.utils.ResourceLoader; import ua.com.fielden.platform.web.centre.api.EntityCentreConfig; import ua.com.fielden.platform.web.centre.api.EntityCentreConfig.OrderDirection; import ua.com.fielden.platform.web.centre.api.EntityCentreConfig.ResultSetProp; import ua.com.fielden.platform.web.centre.api.EntityCentreConfig.SummaryPropDef; import ua.com.fielden.platform.web.centre.api.ICentre; import ua.com.fielden.platform.web.centre.api.actions.EntityActionConfig; import ua.com.fielden.platform.web.centre.api.context.CentreContextConfig; import ua.com.fielden.platform.web.centre.api.crit.defaults.assigners.IValueAssigner; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.MultiCritBooleanValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.MultiCritStringValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.RangeCritDateValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.RangeCritOtherValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.SingleCritDateValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.SingleCritOtherValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.impl.AbstractCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.BooleanCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.BooleanSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.DateCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.DateSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.DecimalCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.DecimalSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.EntityCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.EntitySingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.IntegerCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.IntegerSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.MoneyCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.MoneySingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.StringCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.StringSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.insertion_points.InsertionPoints; import ua.com.fielden.platform.web.centre.api.resultset.ICustomPropsAssignmentHandler; import ua.com.fielden.platform.web.centre.api.resultset.IRenderingCustomiser; import ua.com.fielden.platform.web.centre.api.resultset.PropDef; import ua.com.fielden.platform.web.centre.api.resultset.impl.FunctionalActionElement; import ua.com.fielden.platform.web.centre.api.resultset.impl.FunctionalActionKind; import ua.com.fielden.platform.web.centre.api.resultset.impl.PropertyColumnElement; import ua.com.fielden.platform.web.centre.exceptions.PropertyDefinitionException; import ua.com.fielden.platform.web.interfaces.ILayout.Device; import ua.com.fielden.platform.web.interfaces.IRenderable; import ua.com.fielden.platform.web.layout.FlexLayout; import ua.com.fielden.platform.web.view.master.api.impl.SimpleMasterBuilder; import ua.com.fielden.snappy.DateRangeConditionEnum; /** * Represents the entity centre. * * @author TG Team * */ public class EntityCentre<T extends AbstractEntity<?>> implements ICentre<T> { private final String IMPORTS = "<!--@imports-->"; private final String FULL_ENTITY_TYPE = "@full_entity_type"; private final String FULL_MI_TYPE = "@full_mi_type"; private final String MI_TYPE = "@mi_type"; //egi related properties private final String EGI_LAYOUT = "@gridLayout"; private final String EGI_LAYOUT_CONFIG = "//gridLayoutConfig"; private final String EGI_SHORTCUTS = "@customShortcuts"; private final String EGI_TOOLBAR_VISIBLE = "@toolbarVisible"; private final String EGI_CHECKBOX_VISIBILITY = "@checkboxVisible"; private final String EGI_CHECKBOX_FIXED = "@checkboxesFixed"; private final String EGI_CHECKBOX_WITH_PRIMARY_ACTION_FIXED = "@checkboxesWithPrimaryActionsFixed"; private final String EGI_NUM_OF_FIXED_COLUMNS = "@numOfFixedCols"; private final String EGI_SECONDARY_ACTION_FIXED = "@secondaryActionsFixed"; private final String EGI_HEADER_FIXED = "@headerFixed"; private final String EGI_SUMMARY_FIXED = "@summaryFixed"; private final String EGI_VISIBLE_ROW_COUNT = "@visibleRowCount"; private final String EGI_PAGE_CAPACITY = "@pageCapacity"; private final String EGI_ACTIONS = "//generatedActionObjects"; private final String EGI_PRIMARY_ACTION = "//generatedPrimaryAction"; private final String EGI_SECONDARY_ACTIONS = "//generatedSecondaryActions"; private final String EGI_PROPERTY_ACTIONS = "//generatedPropActions"; private final String EGI_DOM = "<!--@egi_columns-->"; private final String EGI_FUNCTIONAL_ACTION_DOM = "<!--@functional_actions-->"; private final String EGI_PRIMARY_ACTION_DOM = "<!--@primary_action-->"; private final String EGI_SECONDARY_ACTIONS_DOM = "<!--@secondary_actions-->"; //Toolbar related private final String TOOLBAR_DOM = "<!--@toolbar-->"; private final String TOOLBAR_JS = "//toolbarGeneratedFunction"; private final String TOOLBAR_STYLES = "/*toolbarStyles*/"; //Selection criteria related private final String QUERY_ENHANCER_CONFIG = "@queryEnhancerContextConfig"; private final String CRITERIA_DOM = "<!--@criteria_editors-->"; private final String SELECTION_CRITERIA_LAYOUT_CONFIG = "//@layoutConfig"; //Insertion points private final String INSERTION_POINT_ACTIONS = "//generatedInsertionPointActions"; private final String INSERTION_POINT_ACTIONS_DOM = "<!--@insertion_point_actions-->"; private final String LEFT_INSERTION_POINT_DOM = "<!--@left_insertion_points-->"; private final String RIGHT_INSERTION_POINT_DOM = "<!--@right_insertion_points-->"; private final String BOTTOM_INSERTION_POINT_DOM = "<!--@bottom_insertion_points-->"; private final Logger logger = Logger.getLogger(getClass()); private final Class<? extends MiWithConfigurationSupport<?>> menuItemType; private final String name; private final EntityCentreConfig<T> dslDefaultConfig; private final Injector injector; private final Class<T> entityType; private final Class<? extends MiWithConfigurationSupport<?>> miType; private final ICompanionObjectFinder coFinder; private final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated; private ICentreDomainTreeManagerAndEnhancer defaultCentre; /** * Creates new {@link EntityCentre} instance for the menu item type and with specified name. * * @param miType * - the menu item type for which this entity centre is to be created. * @param name * - the name for this entity centre. * @param dslDefaultConfig * -- default configuration taken from Centre DSL */ public EntityCentre(final Class<? extends MiWithConfigurationSupport<?>> miType, final String name, final EntityCentreConfig<T> dslDefaultConfig, final Injector injector, final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated) { this.menuItemType = miType; this.name = name; this.dslDefaultConfig = dslDefaultConfig; this.injector = injector; this.miType = miType; this.entityType = CentreUtils.getEntityType(miType); this.coFinder = this.injector.getInstance(ICompanionObjectFinder.class); this.postCentreCreated = postCentreCreated; } /** * Generates default centre from DSL config and postCentreCreated callback (user unspecific). * * @param dslDefaultConfig * @param postCentreCreated * @return */ private ICentreDomainTreeManagerAndEnhancer createUserUnspecificDefaultCentre(final EntityCentreConfig<T> dslDefaultConfig, final ISerialiser serialiser, final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated) { return createDefaultCentre0(dslDefaultConfig, serialiser, postCentreCreated, false); } /** * Generates default centre from DSL config and postCentreCreated callback (user specific). * * @param dslDefaultConfig * @param postCentreCreated * @return */ private ICentreDomainTreeManagerAndEnhancer createDefaultCentre(final EntityCentreConfig<T> dslDefaultConfig, final ISerialiser serialiser, final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated) { return createDefaultCentre0(dslDefaultConfig, serialiser, postCentreCreated, true); } private ICentreDomainTreeManagerAndEnhancer createDefaultCentre0(final EntityCentreConfig<T> dslDefaultConfig, final ISerialiser serialiser, final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated, final boolean userSpecific) { final ICentreDomainTreeManagerAndEnhancer cdtmae = GlobalDomainTreeManager.createEmptyCentre(entityType, serialiser); final Optional<List<String>> selectionCriteria = dslDefaultConfig.getSelectionCriteria(); if (selectionCriteria.isPresent()) { for (final String property : selectionCriteria.get()) { cdtmae.getFirstTick().check(entityType, treeName(property), true); if (userSpecific) { provideDefaultsFor(property, cdtmae, dslDefaultConfig); } } } final Optional<List<ResultSetProp>> resultSetProps = dslDefaultConfig.getResultSetProperties(); final Optional<ListMultimap<String, SummaryPropDef>> summaryExpressions = dslDefaultConfig.getSummaryExpressions(); if (resultSetProps.isPresent()) { for (final ResultSetProp property : resultSetProps.get()) { if (property.propName.isPresent()) { } else { if (property.propDef.isPresent()) { // represents the 'custom' property final String customPropName = CalculatedProperty.generateNameFrom(property.propDef.get().title); enhanceCentreManagerWithCustomProperty(cdtmae, entityType, customPropName, property.propDef.get(), dslDefaultConfig.getResultSetCustomPropAssignmentHandlerType()); } else { throw new IllegalStateException(String.format("The state of result-set property [%s] definition is not correct, need to exist either a 'propName' for the property or 'propDef'.", property)); } } } } if (summaryExpressions.isPresent()) { for (final Entry<String, Collection<SummaryPropDef>> entry : summaryExpressions.get().asMap().entrySet()) { final String originationProperty = treeName(entry.getKey()); for (final SummaryPropDef summaryProp : entry.getValue()) { cdtmae.getEnhancer().addCalculatedProperty(entityType, "", summaryProp.alias, summaryProp.expression, summaryProp.title, summaryProp.desc, CalculatedPropertyAttribute.NO_ATTR, "".equals(originationProperty) ? "SELF" : originationProperty); } } } cdtmae.getEnhancer().apply(); if (resultSetProps.isPresent()) { final Map<String, Integer> growFactors = calculateGrowFactors(resultSetProps.get()); for (final ResultSetProp property : resultSetProps.get()) { final String propertyName = getPropName(property); cdtmae.getSecondTick().check(entityType, propertyName, true); cdtmae.getSecondTick().setWidth(entityType, propertyName, property.width); if (growFactors.containsKey(propertyName)) { cdtmae.getSecondTick().setGrowFactor(entityType, propertyName, growFactors.get(propertyName)); } if (property.tooltipProp.isPresent()) { cdtmae.getSecondTick().check(entityType, treeName(property.tooltipProp.get()), true); } } } if (summaryExpressions.isPresent()) { for (final Entry<String, Collection<SummaryPropDef>> entry : summaryExpressions.get().asMap().entrySet()) { for (final SummaryPropDef summaryProp : entry.getValue()) { cdtmae.getSecondTick().check(entityType, summaryProp.alias, true); } } } final Optional<Map<String, OrderDirection>> propOrdering = dslDefaultConfig.getResultSetOrdering(); if (propOrdering.isPresent()) { // by default ordering occurs by "this" that is why it needs to be switched off in the presence of alternative ordering configuration if (cdtmae.getSecondTick().isChecked(entityType, "")) { cdtmae.getSecondTick().toggleOrdering(entityType, ""); cdtmae.getSecondTick().toggleOrdering(entityType, ""); } // let's now apply the ordering as per configuration for (final Map.Entry<String, OrderDirection> propAndOrderDirection : propOrdering.get().entrySet()) { if (OrderDirection.ASC == propAndOrderDirection.getValue()) { cdtmae.getSecondTick().toggleOrdering(entityType, treeName(propAndOrderDirection.getKey())); } else { // OrderDirection.DESC cdtmae.getSecondTick().toggleOrdering(entityType, treeName(propAndOrderDirection.getKey())).toggleOrdering(entityType, treeName(propAndOrderDirection.getKey())); } } } return postCentreCreated == null ? cdtmae : postCentreCreated.apply(cdtmae); } /** * Returns the property name for specified {@link ResultSetProp} instance. The returned property name can be used for retrieving and altering data in * {@link ICentreDomainTreeManager}. * * @param property * @return */ private static String getPropName(final ResultSetProp property) { if (property.propName.isPresent()) { return treeName(property.propName.get()); } else { if (property.propDef.isPresent()) { // represents the 'custom' property final String customPropName = CalculatedProperty.generateNameFrom(property.propDef.get().title); return treeName(customPropName); } else { throw new PropertyDefinitionException(format("The state of result-set property [%s] definition is not correct, need to exist either a 'propName' for the property or 'propDef'.", property)); } } } /** * Returns the 'managed type' for the 'centre' manager. * * @param root * @param centre * @return */ private Class<?> managedType(final ICentreDomainTreeManagerAndEnhancer centre) { return centre.getEnhancer().getManagedType(entityType); } private void provideDefaultsFor(final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae, final EntityCentreConfig<T> dslDefaultConfig) { final String property = treeName(dslProperty); final boolean isEntityItself = "".equals(property); // empty property means "entity itself" final Class<?> propertyType = isEntityItself ? managedType(cdtmae) : PropertyTypeDeterminator.determinePropertyType(managedType(cdtmae), property); if (AbstractDomainTree.isCritOnlySingle(managedType(cdtmae), property)) { if (EntityUtils.isEntityType(propertyType)) { provideDefaultsEntitySingle(() -> dslDefaultConfig.getDefaultSingleValuesForEntitySelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForEntitySelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isString(propertyType)) { provideDefaultsSingle(() -> dslDefaultConfig.getDefaultSingleValuesForStringSelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForStringSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isBoolean(propertyType)) { provideDefaultsSingle(() -> dslDefaultConfig.getDefaultSingleValuesForBooleanSelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForBooleanSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isInteger(propertyType)) { provideDefaultsSingle(() -> dslDefaultConfig.getDefaultSingleValuesForIntegerSelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForIntegerSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isRangeType(propertyType) && !EntityUtils.isDate(propertyType)) { provideDefaultsSingle(() -> dslDefaultConfig.getDefaultSingleValuesForBigDecimalAndMoneySelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForBigDecimalAndMoneySelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isDate(propertyType)) { provideDefaultsDateSingle(() -> dslDefaultConfig.getDefaultSingleValuesForDateSelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForDateSelectionCriteria(), dslProperty, cdtmae); } else { throw new UnsupportedOperationException(String.format("The single-crit type [%s] is currently unsupported.", propertyType)); } } else { if (EntityUtils.isEntityType(propertyType) || EntityUtils.isString(propertyType)) { provideDefaultsEntityOrString(() -> dslDefaultConfig.getDefaultMultiValuesForEntityAndStringSelectionCriteria(), () -> dslDefaultConfig.getDefaultMultiValueAssignersForEntityAndStringSelectionCriteria(), dslProperty, cdtmae, EntityUtils.isString(propertyType)); } else if (EntityUtils.isBoolean(propertyType)) { provideDefaultsBoolean(() -> dslDefaultConfig.getDefaultMultiValuesForBooleanSelectionCriteria(), () -> dslDefaultConfig.getDefaultMultiValueAssignersForBooleanSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isInteger(propertyType)) { provideDefaultsRange(() -> dslDefaultConfig.getDefaultRangeValuesForIntegerSelectionCriteria(), () -> dslDefaultConfig.getDefaultRangeValueAssignersForIntegerSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isRangeType(propertyType) && !EntityUtils.isDate(propertyType)) { provideDefaultsRange(() -> dslDefaultConfig.getDefaultRangeValuesForBigDecimalAndMoneySelectionCriteria(), () -> dslDefaultConfig.getDefaultRangeValueAssignersForBigDecimalAndMoneySelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isDate(propertyType)) { provideDefaultsDateRange(() -> dslDefaultConfig.getDefaultRangeValuesForDateSelectionCriteria(), () -> dslDefaultConfig.getDefaultRangeValueAssignersForDateSelectionCriteria(), dslProperty, cdtmae); } else { throw new UnsupportedOperationException(String.format("The multi-crit type [%s] is currently unsupported.", propertyType)); } } } private void provideDefaultsEntityOrString(final Supplier<Optional<Map<String, MultiCritStringValueMnemonic>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<MultiCritStringValueMnemonic, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae, final boolean isString) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsEntityOrString(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property, isString); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsEntityOrString(assignerSupplier.get().get().get(dslProperty), cdtmae, property, isString); } else { } } } private void provideDefaultsBoolean(final Supplier<Optional<Map<String, MultiCritBooleanValueMnemonic>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<MultiCritBooleanValueMnemonic, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsBoolean(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsBoolean(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private void provideDefaultsEntitySingle(final Supplier<Optional<Map<String, SingleCritOtherValueMnemonic<? extends AbstractEntity<?>>>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<? extends SingleCritOtherValueMnemonic<? extends AbstractEntity<?>>, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsSingle(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsEntitySingle(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private void provideDefaultsDateSingle(final Supplier<Optional<Map<String, SingleCritDateValueMnemonic>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<SingleCritDateValueMnemonic, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsDateSingle(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsDateSingle(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private void provideDefaultsDateRange(final Supplier<Optional<Map<String, RangeCritDateValueMnemonic>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<RangeCritDateValueMnemonic, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsDateRange(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsDateRange(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private <M> void provideDefaultsSingle(final Supplier<Optional<Map<String, SingleCritOtherValueMnemonic<M>>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<SingleCritOtherValueMnemonic<M>, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsSingle(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsSingle(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private <M> void provideDefaultsRange(final Supplier<Optional<Map<String, RangeCritOtherValueMnemonic<M>>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<RangeCritOtherValueMnemonic<M>, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsRange(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsRange(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private void provideAssignerDefaultsEntityOrString(final Class<? extends IValueAssigner<MultiCritStringValueMnemonic, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property, final boolean isString) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<MultiCritStringValueMnemonic> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsEntityOrString(value.get(), cdtmae, property, isString); } } private void provideAssignerDefaultsBoolean(final Class<? extends IValueAssigner<MultiCritBooleanValueMnemonic, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<MultiCritBooleanValueMnemonic> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsBoolean(value.get(), cdtmae, property); } } private void provideAssignerDefaultsDateSingle(final Class<? extends IValueAssigner<SingleCritDateValueMnemonic, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<SingleCritDateValueMnemonic> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsDateSingle(value.get(), cdtmae, property); } } private void provideAssignerDefaultsDateRange(final Class<? extends IValueAssigner<RangeCritDateValueMnemonic, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<RangeCritDateValueMnemonic> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsDateRange(value.get(), cdtmae, property); } } private <M> void provideAssignerDefaultsSingle(final Class<? extends IValueAssigner<? extends SingleCritOtherValueMnemonic<M>, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<? extends SingleCritOtherValueMnemonic<M>> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsSingle(value.get(), cdtmae, property); } } private void provideAssignerDefaultsEntitySingle(final Class<? extends IValueAssigner<? extends SingleCritOtherValueMnemonic<? extends AbstractEntity<?>>, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<? extends SingleCritOtherValueMnemonic<? extends AbstractEntity<?>>> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsSingle(value.get(), cdtmae, property); } } private <M> void provideAssignerDefaultsRange(final Class<? extends IValueAssigner<? extends RangeCritOtherValueMnemonic<M>, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<? extends RangeCritOtherValueMnemonic<M>> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsRange(value.get(), cdtmae, property); } } private void provideMnemonicDefaultsEntityOrString(final MultiCritStringValueMnemonic mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property, final boolean isString) { if (mnemonic.values.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, isString ? String.join(",", mnemonic.values.get()) : mnemonic.values.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } } private void provideMnemonicDefaultsBoolean(final MultiCritBooleanValueMnemonic mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.isValue.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.isValue.get()); } if (mnemonic.isNotValue.isPresent()) { cdtmae.getFirstTick().setValue2(entityType, property, mnemonic.isNotValue.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } } private void provideMnemonicDefaultsDateSingle(final SingleCritDateValueMnemonic mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.value.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.value.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } // date mnemonics if (mnemonic.prefix.isPresent()) { cdtmae.getFirstTick().setDatePrefix(entityType, property, mnemonic.prefix.get()); } if (mnemonic.period.isPresent()) { cdtmae.getFirstTick().setDateMnemonic(entityType, property, mnemonic.period.get()); } if (mnemonic.beforeOrAfter.isPresent()) { cdtmae.getFirstTick().setAndBefore(entityType, property, DateRangeConditionEnum.BEFORE.equals(mnemonic.beforeOrAfter.get()) ? Boolean.TRUE : Boolean.FALSE); } // exclusiveness if (mnemonic.excludeFrom.isPresent()) { cdtmae.getFirstTick().setExclusive(entityType, property, mnemonic.excludeFrom.get()); } if (mnemonic.excludeTo.isPresent()) { cdtmae.getFirstTick().setExclusive2(entityType, property, mnemonic.excludeTo.get()); } } private void provideMnemonicDefaultsDateRange(final RangeCritDateValueMnemonic mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.fromValue.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.fromValue.get()); } if (mnemonic.toValue.isPresent()) { cdtmae.getFirstTick().setValue2(entityType, property, mnemonic.toValue.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } // date mnemonics if (mnemonic.prefix.isPresent()) { cdtmae.getFirstTick().setDatePrefix(entityType, property, mnemonic.prefix.get()); } if (mnemonic.period.isPresent()) { cdtmae.getFirstTick().setDateMnemonic(entityType, property, mnemonic.period.get()); } if (mnemonic.beforeOrAfter.isPresent()) { cdtmae.getFirstTick().setAndBefore(entityType, property, DateRangeConditionEnum.BEFORE.equals(mnemonic.beforeOrAfter.get()) ? Boolean.TRUE : Boolean.FALSE); } // exclusiveness if (mnemonic.excludeFrom.isPresent()) { cdtmae.getFirstTick().setExclusive(entityType, property, mnemonic.excludeFrom.get()); } if (mnemonic.excludeTo.isPresent()) { cdtmae.getFirstTick().setExclusive2(entityType, property, mnemonic.excludeTo.get()); } } private <M> void provideMnemonicDefaultsSingle(final SingleCritOtherValueMnemonic<M> mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.value.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.value.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } } private <M> void provideMnemonicDefaultsRange(final RangeCritOtherValueMnemonic<M> mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.fromValue.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.fromValue.get()); } if (mnemonic.toValue.isPresent()) { cdtmae.getFirstTick().setValue2(entityType, property, mnemonic.toValue.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } if (mnemonic.excludeFrom.isPresent()) { cdtmae.getFirstTick().setExclusive(entityType, property, mnemonic.excludeFrom.get()); } if (mnemonic.excludeTo.isPresent()) { cdtmae.getFirstTick().setExclusive2(entityType, property, mnemonic.excludeTo.get()); } } /** * Returns the menu item type for this {@link EntityCentre} instance. * * @return */ public Class<? extends MiWithConfigurationSupport<?>> getMenuItemType() { return this.menuItemType; } /** * Returns the entity type for which this entity centre was created. * * @return */ public Class<T> getEntityType() { return entityType; } /** * Returns the entity centre name. * * @return */ public String getName() { return name; } /** * Returns action configuration for concrete action kind and its number in that kind's space. * * @param actionKind * @param actionNumber * @return */ public EntityActionConfig actionConfig(final FunctionalActionKind actionKind, final int actionNumber) { return dslDefaultConfig.actionConfig(actionKind, actionNumber); } /** * Returns the value that indicates whether centre must run automatically or not. * * @return */ public boolean isRunAutomatically() { return dslDefaultConfig.isRunAutomatically(); } /** * Indicates whether centre should forcibly refresh the current page upon successful saving of a related entity. * * @return */ public boolean shouldEnforcePostSaveRefresh() { return dslDefaultConfig.shouldEnforcePostSaveRefresh(); } /** * Return an optional Event Source URI. * * @return */ public Optional<String> eventSourceUri() { return dslDefaultConfig.getSseUri(); } /** * Returns the instance of rendering customiser for this entity centre. * * @return */ public Optional<IRenderingCustomiser<?>> getRenderingCustomiser() { if (dslDefaultConfig.getResultSetRenderingCustomiserType().isPresent()) { return Optional.of(injector.getInstance(dslDefaultConfig.getResultSetRenderingCustomiserType().get())); } else { return Optional.empty(); } } @Override public IRenderable build() { logger.debug("Initiating fresh centre..."); return createRenderableRepresentation(getAssociatedEntityCentreManager()); } private final ICentreDomainTreeManagerAndEnhancer getAssociatedEntityCentreManager() { final IGlobalDomainTreeManager userSpecificGlobalManager = getUserSpecificGlobalManager(); if (userSpecificGlobalManager == null) { return createUserUnspecificDefaultCentre(dslDefaultConfig, injector.getInstance(ISerialiser.class), postCentreCreated); } else { return CentreUpdater.updateCentre(userSpecificGlobalManager, this.menuItemType, CentreUpdater.FRESH_CENTRE_NAME); } } private String egiRepresentationFor(final Class<?> propertyType, final Optional<String> timeZone, final Optional<String> timePortionToDisplay) { final Class<?> type = DynamicEntityClassLoader.getOriginalType(propertyType); String typeRes = EntityUtils.isEntityType(type) ? type.getName() : (EntityUtils.isBoolean(type) ? "Boolean" : type.getSimpleName()); if (Date.class.isAssignableFrom(type)) { typeRes += ":" + timeZone.orElse(""); typeRes += ":" + timePortionToDisplay.orElse(""); } return typeRes; } /** * Returns default centre manager that was formed using DSL configuration and postCentreCreated hook. * * @return */ public ICentreDomainTreeManagerAndEnhancer getDefaultCentre() { if (defaultCentre == null) { defaultCentre = createDefaultCentre(dslDefaultConfig, injector.getInstance(ISerialiser.class), postCentreCreated); } return defaultCentre; } private IRenderable createRenderableRepresentation(final ICentreDomainTreeManagerAndEnhancer centre) { final LinkedHashSet<String> importPaths = new LinkedHashSet<>(); importPaths.add("polymer/polymer/polymer"); importPaths.add("master/tg-entity-master"); logger.debug("Initiating layout..."); final FlexLayout layout = this.dslDefaultConfig.getSelectionCriteriaLayout(); final DomElement editorContainer = layout.render().attr("context", "[[_currEntity]]"); importPaths.add(layout.importPath()); final Class<?> root = this.entityType; logger.debug("Initiating criteria widgets..."); final List<AbstractCriterionWidget> criteriaWidgets = createCriteriaWidgets(centre, root); criteriaWidgets.forEach(widget -> { importPaths.add(widget.importPath()); importPaths.addAll(widget.editorsImportPaths()); editorContainer.add(widget.render()); }); final String prefix = ",\n"; logger.debug("Initiating property columns..."); final List<PropertyColumnElement> propertyColumns = new ArrayList<>(); final Optional<List<ResultSetProp>> resultProps = dslDefaultConfig.getResultSetProperties(); final Optional<ListMultimap<String, SummaryPropDef>> summaryProps = dslDefaultConfig.getSummaryExpressions(); final Class<?> managedType = centre.getEnhancer().getManagedType(root); if (resultProps.isPresent()) { int actionIndex = 0; for (final ResultSetProp resultProp : resultProps.get()) { final String tooltipProp = resultProp.tooltipProp.isPresent() ? resultProp.tooltipProp.get() : null; final String resultPropName = getPropName(resultProp); final boolean isEntityItself = "".equals(resultPropName); // empty property means "entity itself" final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, resultPropName); final Optional<FunctionalActionElement> action; if (resultProp.propAction.isPresent()) { action = Optional.of(new FunctionalActionElement(resultProp.propAction.get(), actionIndex, resultPropName)); actionIndex += 1; } else { action = Optional.empty(); } final PropertyColumnElement el = new PropertyColumnElement(resultPropName, null, resultProp.width, centre.getSecondTick().getGrowFactor(root, resultPropName), resultProp.isFlexible, tooltipProp, egiRepresentationFor( propertyType, Optional.ofNullable(EntityUtils.isDate(propertyType) ? DefaultValueContract.getTimeZone(managedType, resultPropName) : null), Optional.ofNullable(EntityUtils.isDate(propertyType) ? DefaultValueContract.getTimePortionToDisplay(managedType, resultPropName) : null)), CriteriaReflector.getCriteriaTitleAndDesc(managedType, resultPropName), action); if (summaryProps.isPresent() && summaryProps.get().containsKey(dslName(resultPropName))) { final List<SummaryPropDef> summaries = summaryProps.get().get(dslName(resultPropName)); summaries.forEach(summary -> el.addSummary(summary.alias, PropertyTypeDeterminator.determinePropertyType(managedType, summary.alias), new Pair<>(summary.title, summary.desc))); } propertyColumns.add(el); } } logger.debug("Initiating prop actions..."); final DomContainer egiColumns = new DomContainer(); final StringBuilder propActionsObject = new StringBuilder(); propertyColumns.forEach(column -> { importPaths.add(column.importPath()); if (column.hasSummary()) { importPaths.add(column.getSummary(0).importPath()); } if (column.getAction().isPresent()) { importPaths.add(column.getAction().get().importPath()); propActionsObject.append(prefix + createActionObject(column.getAction().get())); } egiColumns.add(column.render()); }); logger.debug("Initiating top-level actions..."); final Optional<List<Pair<EntityActionConfig, Optional<String>>>> topLevelActions = this.dslDefaultConfig.getTopLevelActions(); final List<List<FunctionalActionElement>> actionGroups = new ArrayList<>(); if (topLevelActions.isPresent()) { final String currentGroup = null; for (int i = 0; i < topLevelActions.get().size(); i++) { final Pair<EntityActionConfig, Optional<String>> topLevelAction = topLevelActions.get().get(i); final String cg = getGroup(topLevelAction.getValue()); if (!EntityUtils.equalsEx(cg, currentGroup)) { actionGroups.add(new ArrayList<>()); } addToLastGroup(actionGroups, topLevelAction.getKey(), i); } } logger.debug("Initiating functional actions..."); final StringBuilder functionalActionsObjects = new StringBuilder(); final DomContainer functionalActionsDom = new DomContainer(); for (final List<FunctionalActionElement> group : actionGroups) { final DomElement groupElement = new DomElement("div").clazz("entity-specific-action", "group"); for (final FunctionalActionElement el : group) { importPaths.add(el.importPath()); groupElement.add(el.render()); functionalActionsObjects.append(prefix + createActionObject(el)); } functionalActionsDom.add(groupElement); } logger.debug("Initiating primary actions..."); //////////////////// Primary result-set action //////////////////// final Optional<EntityActionConfig> resultSetPrimaryEntityAction = this.dslDefaultConfig.getResultSetPrimaryEntityAction(); final DomContainer primaryActionDom = new DomContainer(); final StringBuilder primaryActionObject = new StringBuilder(); if (resultSetPrimaryEntityAction.isPresent() && !resultSetPrimaryEntityAction.get().isNoAction()) { final FunctionalActionElement el = new FunctionalActionElement(resultSetPrimaryEntityAction.get(), 0, FunctionalActionKind.PRIMARY_RESULT_SET); importPaths.add(el.importPath()); primaryActionDom.add(el.render().clazz("primary-action").attr("hidden", null)); primaryActionObject.append(prefix + createActionObject(el)); } //////////////////// Primary result-set action [END] ////////////// logger.debug("Initiating secondary actions..."); final List<FunctionalActionElement> secondaryActionElements = new ArrayList<>(); final Optional<List<EntityActionConfig>> resultSetSecondaryEntityActions = this.dslDefaultConfig.getResultSetSecondaryEntityActions(); if (resultSetSecondaryEntityActions.isPresent()) { for (int i = 0; i < resultSetSecondaryEntityActions.get().size(); i++) { final FunctionalActionElement el = new FunctionalActionElement(resultSetSecondaryEntityActions.get().get(i), i, FunctionalActionKind.SECONDARY_RESULT_SET); secondaryActionElements.add(el); } } final DomContainer secondaryActionsDom = new DomContainer(); final StringBuilder secondaryActionsObjects = new StringBuilder(); for (final FunctionalActionElement el : secondaryActionElements) { importPaths.add(el.importPath()); secondaryActionsDom.add(el.render().clazz("secondary-action").attr("hidden", null)); secondaryActionsObjects.append(prefix + createActionObject(el)); } logger.debug("Initiating insertion point actions..."); final List<FunctionalActionElement> insertionPointActionsElements = new ArrayList<>(); final Optional<List<EntityActionConfig>> insertionPointActions = this.dslDefaultConfig.getInsertionPointActions(); if (insertionPointActions.isPresent()) { for (int index = 0; index < insertionPointActions.get().size(); index++) { final FunctionalActionElement el = new FunctionalActionElement(insertionPointActions.get().get(index), index, FunctionalActionKind.INSERTION_POINT); insertionPointActionsElements.add(el); } } final DomContainer insertionPointActionsDom = new DomContainer(); final StringBuilder insertionPointActionsObjects = new StringBuilder(); for (final FunctionalActionElement el : insertionPointActionsElements) { importPaths.add(el.importPath()); insertionPointActionsDom.add(el.render().clazz("insertion-point-action").attr("hidden", null)); insertionPointActionsObjects.append(prefix + createActionObject(el)); } importPaths.add(dslDefaultConfig.getToolbarConfig().importPath()); final DomContainer leftInsertionPointsDom = new DomContainer(); final DomContainer rightInsertionPointsDom = new DomContainer(); final DomContainer bottomInsertionPointsDom = new DomContainer(); for (final FunctionalActionElement el : insertionPointActionsElements) { final DomElement insertionPoint = new DomElement("tg-entity-centre-insertion-point") .attr("id", "ip" + el.numberOfAction) .attr("short-desc", el.conf().shortDesc.orElse("")) .attr("long-desc", el.conf().longDesc.orElse("")) .attr("retrieved-entities", "{{retrievedEntities}}") .attr("retrieved-totals", "{{retrievedTotals}}") .attr("retrieved-entity-selection", "{{retrievedEntitySelection}}") .attr("column-properties-mapper", "{{columnPropertiesMapper}}"); if (el.entityActionConfig.whereToInsertView.get() == InsertionPoints.LEFT) { leftInsertionPointsDom.add(insertionPoint); } else if (el.entityActionConfig.whereToInsertView.get() == InsertionPoints.RIGHT) { rightInsertionPointsDom.add(insertionPoint); } else if (el.entityActionConfig.whereToInsertView.get() == InsertionPoints.BOTTOM) { bottomInsertionPointsDom.add(insertionPoint); } else { throw new IllegalArgumentException("Unexpected insertion point type."); } } //Generating shortcuts for EGI final StringBuilder shortcuts = new StringBuilder(); for (final String shortcut : dslDefaultConfig.getToolbarConfig().getAvailableShortcuts()) { shortcuts.append(shortcut + " "); } if (topLevelActions.isPresent()) { for (int i = 0; i < topLevelActions.get().size(); i++) { final Pair<EntityActionConfig, Optional<String>> topLevelAction = topLevelActions.get().get(i); final EntityActionConfig config = topLevelAction.getKey(); if (config.shortcut.isPresent()) { shortcuts.append(config.shortcut.get() + " "); } } } /////////////////////////////////////// final String funcActionString = functionalActionsObjects.toString(); final String secondaryActionString = secondaryActionsObjects.toString(); final String insertionPointActionsString = insertionPointActionsObjects.toString(); final String primaryActionObjectString = primaryActionObject.toString(); final String propActionsString = propActionsObject.toString(); final Pair<String, String> gridLayoutConfig = generateGridLayoutConfig(); final int prefixLength = prefix.length(); logger.debug("Initiating template..."); final String text = ResourceLoader.getText("ua/com/fielden/platform/web/centre/tg-entity-centre-template.html"); logger.debug("Replacing some parts..."); final String entityCentreStr = text. replace(IMPORTS, SimpleMasterBuilder.createImports(importPaths)). replace(EGI_LAYOUT, gridLayoutConfig.getKey()). replace(FULL_ENTITY_TYPE, entityType.getName()). replace(MI_TYPE, miType.getSimpleName()). //egi related properties replace(EGI_SHORTCUTS, shortcuts). replace(EGI_TOOLBAR_VISIBLE, TOOLBAR_VISIBLE.eval(!dslDefaultConfig.shouldHideToolbar())). replace(EGI_CHECKBOX_VISIBILITY, CHECKBOX_VISIBLE.eval(!dslDefaultConfig.shouldHideCheckboxes())). replace(EGI_CHECKBOX_FIXED, CHECKBOX_FIXED.eval(dslDefaultConfig.getScrollConfig().isCheckboxesFixed())). replace(EGI_CHECKBOX_WITH_PRIMARY_ACTION_FIXED, CHECKBOX_WITH_PRIMARY_ACTION_FIXED.eval(dslDefaultConfig.getScrollConfig().isCheckboxesWithPrimaryActionsFixed())). replace(EGI_NUM_OF_FIXED_COLUMNS, Integer.toString(dslDefaultConfig.getScrollConfig().getNumberOfFixedColumns())). replace(EGI_SECONDARY_ACTION_FIXED, SECONDARY_ACTION_FIXED.eval(dslDefaultConfig.getScrollConfig().isSecondaryActionsFixed())). replace(EGI_HEADER_FIXED, HEADER_FIXED.eval(dslDefaultConfig.getScrollConfig().isHeaderFixed())). replace(EGI_SUMMARY_FIXED, SUMMARY_FIXED.eval(dslDefaultConfig.getScrollConfig().isSummaryFixed())). replace(EGI_VISIBLE_ROW_COUNT, dslDefaultConfig.getVisibleRowsCount() + ""). /////////////////////// replace(TOOLBAR_DOM, dslDefaultConfig.getToolbarConfig().render().toString()). replace(TOOLBAR_JS, dslDefaultConfig.getToolbarConfig().code(entityType).toString()). replace(TOOLBAR_STYLES, dslDefaultConfig.getToolbarConfig().styles().toString()). replace(FULL_MI_TYPE, miType.getName()). replace(EGI_PAGE_CAPACITY, Integer.toString(dslDefaultConfig.getPageCapacity())). replace(QUERY_ENHANCER_CONFIG, queryEnhancerContextConfigString()). replace(CRITERIA_DOM, editorContainer.toString()). replace(EGI_DOM, egiColumns.toString()). replace(EGI_ACTIONS, funcActionString.length() > prefixLength ? funcActionString.substring(prefixLength) : funcActionString). replace(EGI_SECONDARY_ACTIONS, secondaryActionString.length() > prefixLength ? secondaryActionString.substring(prefixLength) : secondaryActionString). replace(INSERTION_POINT_ACTIONS, insertionPointActionsString.length() > prefixLength ? insertionPointActionsString.substring(prefixLength) : insertionPointActionsString). replace(EGI_PRIMARY_ACTION, primaryActionObjectString.length() > prefixLength ? primaryActionObjectString.substring(prefixLength) : primaryActionObjectString). replace(EGI_PROPERTY_ACTIONS, propActionsString.length() > prefixLength ? propActionsString.substring(prefixLength) : propActionsString). replace(SELECTION_CRITERIA_LAYOUT_CONFIG, layout.code().toString()). replace(EGI_LAYOUT_CONFIG, gridLayoutConfig.getValue()). replace(EGI_FUNCTIONAL_ACTION_DOM, functionalActionsDom.toString()). replace(EGI_PRIMARY_ACTION_DOM, primaryActionDom.toString()). replace(EGI_SECONDARY_ACTIONS_DOM, secondaryActionsDom.toString()). replace(INSERTION_POINT_ACTIONS_DOM, insertionPointActionsDom.toString()). replace(LEFT_INSERTION_POINT_DOM, leftInsertionPointsDom.toString()). replace(RIGHT_INSERTION_POINT_DOM, rightInsertionPointsDom.toString()). replace(BOTTOM_INSERTION_POINT_DOM, bottomInsertionPointsDom.toString()); logger.debug("Finishing..."); final IRenderable representation = new IRenderable() { @Override public DomElement render() { return new InnerTextElement(entityCentreStr); } }; logger.debug("Done."); return representation; } /** * Calculates the relative grow factor for all columns. */ private Map<String, Integer> calculateGrowFactors(final List<ResultSetProp> propertyColumns) { //Searching for the minimal column width which are not flexible and their width is greater than 0. final int minWidth = propertyColumns.stream() .filter(column -> column.isFlexible && column.width > 0) .reduce(Integer.MAX_VALUE, (min, column) -> min > column.width ? column.width : min, (min1, min2) -> min1 < min2 ? min1 : min2); //Map each resultSetProp which is not flexible and has width greater than 0 to it's grow factor. return propertyColumns.stream() .filter(column -> column.isFlexible && column.width > 0) .collect(Collectors.toMap( column -> getPropName(column), column -> Math.round((float) column.width / minWidth))); } private Pair<String, String> generateGridLayoutConfig() { final StringBuilder resultsetLayoutJs = new StringBuilder(); final StringBuilder resultsetLayoutHtml = new StringBuilder(); final FlexLayout collapseLayout = dslDefaultConfig.getResultsetCollapsedCardLayout(); final FlexLayout expandLayout = dslDefaultConfig.getResultsetExpansionCardLayout(); final FlexLayout summaryLayout = dslDefaultConfig.getResultsetSummaryCardLayout(); final StringBuilder shortLayout = new StringBuilder(); if (collapseLayout.hasLayoutFor(Device.DESKTOP, null)) { shortLayout.append("desktop: " + collapseLayout.getLayout(Device.DESKTOP, null).get()); } if (collapseLayout.hasLayoutFor(Device.TABLET, null)) { shortLayout.append((shortLayout.length() > 0 ? ",\n" : "") + "tablet: " + collapseLayout.getLayout(Device.TABLET, null).get()); } if (collapseLayout.hasLayoutFor(Device.MOBILE, null)) { shortLayout.append((shortLayout.length() > 0 ? ",\n" : "") + "mobile: " + collapseLayout.getLayout(Device.MOBILE, null).get()); } if (shortLayout.length() > 0) { resultsetLayoutJs.append("self.gridShortLayout={\n" + shortLayout.toString() + "\n};"); resultsetLayoutHtml.append("short-layout='[[gridShortLayout]]'"); } final StringBuilder longLayout = new StringBuilder(); if (expandLayout.hasLayoutFor(Device.DESKTOP, null)) { longLayout.append("desktop: " + expandLayout.getLayout(Device.DESKTOP, null).get()); } if (expandLayout.hasLayoutFor(Device.TABLET, null)) { longLayout.append((longLayout.length() > 0 ? ",\n" : "") + "tablet: " + expandLayout.getLayout(Device.TABLET, null).get()); } if (expandLayout.hasLayoutFor(Device.MOBILE, null)) { longLayout.append((longLayout.length() > 0 ? ",\n" : "") + "mobile: " + expandLayout.getLayout(Device.MOBILE, null).get()); } if (longLayout.length() > 0) { resultsetLayoutJs.append("self.gridLongLayout={\n" + longLayout.toString() + "\n};"); resultsetLayoutHtml.append(" long-layout='[[gridLongLayout]]'"); } final StringBuilder gridSummaryLayout = new StringBuilder(); if (summaryLayout.hasLayoutFor(Device.DESKTOP, null)) { gridSummaryLayout.append("desktop: " + summaryLayout.getLayout(Device.DESKTOP, null).get()); } if (summaryLayout.hasLayoutFor(Device.TABLET, null)) { gridSummaryLayout.append((gridSummaryLayout.length() > 0 ? ",\n" : "") + "tablet: " + summaryLayout.getLayout(Device.TABLET, null).get()); } if (summaryLayout.hasLayoutFor(Device.MOBILE, null)) { gridSummaryLayout.append((gridSummaryLayout.length() > 0 ? ",\n" : "") + "mobile: " + summaryLayout.getLayout(Device.MOBILE, null).get()); } if (gridSummaryLayout.length() > 0) { resultsetLayoutJs.append("self.summaryLayout={\n" + gridSummaryLayout.toString() + "\n};"); resultsetLayoutHtml.append(" summary-layout='[[summaryLayout]]'"); } return new Pair<>(resultsetLayoutHtml.toString(), resultsetLayoutJs.toString()); } /** * Returns the global manager for the user for this concrete thread (the user has been populated through the Web UI authentication mechanism -- see DefaultWebResourceGuard). * * @return */ private IGlobalDomainTreeManager getUserSpecificGlobalManager() { final IServerGlobalDomainTreeManager serverGdtm = injector.getInstance(IServerGlobalDomainTreeManager.class); final User user = injector.getInstance(IUserProvider.class).getUser(); if (user == null) { // the user is unknown at this stage! return null; // no user-specific global exists for unknown user! } final String userName = user.getKey(); return serverGdtm.get(userName); } private String queryEnhancerContextConfigString() { final StringBuilder sb = new StringBuilder(); if (dslDefaultConfig.getQueryEnhancerConfig().isPresent() && dslDefaultConfig.getQueryEnhancerConfig().get().getValue().isPresent()) { final CentreContextConfig centreContextConfig = dslDefaultConfig.getQueryEnhancerConfig().get().getValue().get(); if (centreContextConfig.withSelectionCrit) { // disregarded -- sends every time, because the selection criteria is needed for running the centre query } sb.append("require-selected-entities=\"" + (centreContextConfig.withCurrentEtity ? "ONE" : (centreContextConfig.withAllSelectedEntities ? "ALL" : "NONE")) + "\" "); sb.append("require-master-entity=\"" + (centreContextConfig.withMasterEntity ? "true" : "false") + "\""); } else { sb.append("require-selected-entities=\"NONE\" "); sb.append("require-master-entity=\"false\""); } return sb.toString(); } /** * Enhances the type of centre entity with custom property definition. * * @param centre * @param root * @param propDef * @param resultSetCustomPropAssignmentHandlerType */ private void enhanceCentreManagerWithCustomProperty(final ICentreDomainTreeManagerAndEnhancer centre, final Class<?> root, final String propName, final PropDef<?> propDef, final Optional<Class<? extends ICustomPropsAssignmentHandler>> resultSetCustomPropAssignmentHandlerType) { centre.getEnhancer().addCustomProperty(root, "" /* this is the contextPath */, propName, propDef.title, propDef.desc, propDef.type); } /** * Creates the widgets for criteria. * * @param centre * @param root * @return */ private List<AbstractCriterionWidget> createCriteriaWidgets(final ICentreDomainTreeManagerAndEnhancer centre, final Class<?> root) { final Class<?> managedType = centre.getEnhancer().getManagedType(root); final List<AbstractCriterionWidget> criteriaWidgets = new ArrayList<>(); for (final String critProp : centre.getFirstTick().checkedProperties(root)) { if (!AbstractDomainTree.isPlaceholder(critProp)) { final boolean isEntityItself = "".equals(critProp); // empty property means "entity itself" final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, critProp); final AbstractCriterionWidget criterionWidget; if (AbstractDomainTree.isCritOnlySingle(managedType, critProp)) { if (EntityUtils.isEntityType(propertyType)) { final List<Pair<String, Boolean>> additionalProps = dslDefaultConfig.getAdditionalPropsForAutocompleter(critProp); criterionWidget = new EntitySingleCriterionWidget(root, managedType, critProp, additionalProps, getCentreContextConfigFor(critProp)); } else if (EntityUtils.isString(propertyType)) { criterionWidget = new StringSingleCriterionWidget(root, managedType, critProp); } else if (EntityUtils.isBoolean(propertyType)) { criterionWidget = new BooleanSingleCriterionWidget(root, managedType, critProp); } else if (Integer.class.isAssignableFrom(propertyType) || Long.class.isAssignableFrom(propertyType)) { criterionWidget = new IntegerSingleCriterionWidget(root, managedType, critProp); } else if (BigDecimal.class.isAssignableFrom(propertyType)) { criterionWidget = new DecimalSingleCriterionWidget(root, managedType, critProp); } else if (Money.class.isAssignableFrom(propertyType)) { criterionWidget = new MoneySingleCriterionWidget(root, managedType, critProp); } else if (EntityUtils.isDate(propertyType)) { criterionWidget = new DateSingleCriterionWidget(root, managedType, critProp); } else { throw new UnsupportedOperationException(String.format("The crit-only single editor type [%s] is currently unsupported.", propertyType)); } } else { if (EntityUtils.isEntityType(propertyType)) { final List<Pair<String, Boolean>> additionalProps = dslDefaultConfig.getAdditionalPropsForAutocompleter(critProp); criterionWidget = new EntityCriterionWidget(root, managedType, critProp, additionalProps, getCentreContextConfigFor(critProp)); } else if (EntityUtils.isString(propertyType)) { criterionWidget = new StringCriterionWidget(root, managedType, critProp); } else if (EntityUtils.isBoolean(propertyType)) { criterionWidget = new BooleanCriterionWidget(root, managedType, critProp); } else if (Integer.class.isAssignableFrom(propertyType) || Long.class.isAssignableFrom(propertyType)) { criterionWidget = new IntegerCriterionWidget(root, managedType, critProp); } else if (BigDecimal.class.isAssignableFrom(propertyType)) { // TODO do not forget about Money later (after Money widget will be available) criterionWidget = new DecimalCriterionWidget(root, managedType, critProp); } else if (Money.class.isAssignableFrom(propertyType)) { criterionWidget = new MoneyCriterionWidget(root, managedType, critProp); } else if (EntityUtils.isDate(propertyType)) { criterionWidget = new DateCriterionWidget(root, managedType, critProp); } else { throw new UnsupportedOperationException(String.format("The multi / range editor type [%s] is currently unsupported.", propertyType)); } } criteriaWidgets.add(criterionWidget); } } return criteriaWidgets; } private void addToLastGroup(final List<List<FunctionalActionElement>> actionGroups, final EntityActionConfig actionConfig, final int i) { if (actionGroups.isEmpty()) { actionGroups.add(new ArrayList<>()); } final FunctionalActionElement el = new FunctionalActionElement(actionConfig, i, FunctionalActionKind.TOP_LEVEL); actionGroups.get(actionGroups.size() - 1).add(el); } private String getGroup(final Optional<String> groupIfAny) { return groupIfAny.isPresent() ? groupIfAny.get() : null; } private String createActionObject(final FunctionalActionElement element) { return element.createActionObject(); } /** * Return DSL representation for property name. * * @param name * @return */ private static String dslName(final String name) { return name.equals("") ? "this" : name; } /** * Return domain tree representation for property name. * * @param name * @return */ private static String treeName(final String name) { return name.equals("this") ? "" : name; } private CentreContextConfig getCentreContextConfigFor(final String critProp) { final String dslProp = dslName(critProp); return dslDefaultConfig.getValueMatchersForSelectionCriteria().isPresent() && dslDefaultConfig.getValueMatchersForSelectionCriteria().get().get(dslProp) != null && dslDefaultConfig.getValueMatchersForSelectionCriteria().get().get(dslProp).getValue() != null && dslDefaultConfig.getValueMatchersForSelectionCriteria().get().get(dslProp).getValue().isPresent() ? dslDefaultConfig.getValueMatchersForSelectionCriteria().get().get(dslProp).getValue().get() : new CentreContextConfig(false, false, false, false, null); } /** * Creates value matcher instance. * * @param injector * @return */ public <V extends AbstractEntity<?>> Pair<IValueMatcherWithCentreContext<V>, Optional<CentreContextConfig>> createValueMatcherAndContextConfig(final Class<? extends AbstractEntity<?>> criteriaType, final String criterionPropertyName) { final Optional<Map<String, Pair<Class<? extends IValueMatcherWithCentreContext<? extends AbstractEntity<?>>>, Optional<CentreContextConfig>>>> matchers = dslDefaultConfig.getValueMatchersForSelectionCriteria(); final String originalPropertyName = CentreUtils.getOriginalPropertyName(criteriaType, criterionPropertyName); final String dslProp = dslName(originalPropertyName); logger.debug("createValueMatcherAndContextConfig: propertyName = " + criterionPropertyName + " originalPropertyName = " + dslProp); final Class<? extends IValueMatcherWithCentreContext<V>> matcherType = matchers.isPresent() && matchers.get().containsKey(dslProp) ? (Class<? extends IValueMatcherWithCentreContext<V>>) matchers.get().get(dslProp).getKey() : null; final Pair<IValueMatcherWithCentreContext<V>, Optional<CentreContextConfig>> matcherAndContextConfig; if (matcherType != null) { matcherAndContextConfig = new Pair<>(injector.getInstance(matcherType), matchers.get().get(dslProp).getValue()); } else { matcherAndContextConfig = createDefaultValueMatcherAndContextConfig(CentreUtils.getOriginalType(criteriaType), originalPropertyName, coFinder); } return matcherAndContextConfig; } /** * Creates default value matcher and context config for the specified entity property. * * @param propertyName * @param criteriaType * @param coFinder * @return */ private <V extends AbstractEntity<?>> Pair<IValueMatcherWithCentreContext<V>, Optional<CentreContextConfig>> createDefaultValueMatcherAndContextConfig(final Class<? extends AbstractEntity<?>> originalType, final String originalPropertyName, final ICompanionObjectFinder coFinder) { final boolean isEntityItself = "".equals(originalPropertyName); // empty property means "entity itself" final Class<V> propertyType = (Class<V>) (isEntityItself ? originalType : PropertyTypeDeterminator.determinePropertyType(originalType, originalPropertyName)); final IEntityDao<V> co = coFinder.find(propertyType); return new Pair<>(new FallbackValueMatcherWithCentreContext<V>(co), Optional.empty()); } public Optional<Class<? extends ICustomPropsAssignmentHandler>> getCustomPropertiesAsignmentHandler() { return dslDefaultConfig.getResultSetCustomPropAssignmentHandlerType(); } public Optional<List<ResultSetProp>> getCustomPropertiesDefinitions() { return dslDefaultConfig.getResultSetProperties(); } public ICustomPropsAssignmentHandler createAssignmentHandlerInstance(final Class<? extends ICustomPropsAssignmentHandler> assignmentHandlerType) { return injector.getInstance(assignmentHandlerType); } public Optional<IFetchProvider<T>> getAdditionalFetchProvider() { return dslDefaultConfig.getFetchProvider(); } public Optional<Pair<IQueryEnhancer<T>, Optional<CentreContextConfig>>> getQueryEnhancerConfig() { final Optional<Pair<Class<? extends IQueryEnhancer<T>>, Optional<CentreContextConfig>>> queryEnhancerConfig = dslDefaultConfig.getQueryEnhancerConfig(); if (queryEnhancerConfig.isPresent()) { final Class<? extends IQueryEnhancer<T>> queryEnhancerType = queryEnhancerConfig.get().getKey(); return Optional.of(new Pair<>(injector.getInstance(queryEnhancerType), queryEnhancerConfig.get().getValue())); } else { return Optional.empty(); } } public Optional<Pair<Class<?>, Class<?>>> getGeneratorTypes() { return dslDefaultConfig.getGeneratorTypes(); } /** * Creates generic {@link IGenerator} instance from injector based on assumption that <code>generatorType</code> is of appropriate type (such checks are performed on API implementation level). * * @param generatorType * @return */ @SuppressWarnings("rawtypes") public IGenerator createGeneratorInstance(final Class<?> generatorType) { return (IGenerator) injector.getInstance(generatorType); } }
platform-web-ui/src/main/java/ua/com/fielden/platform/web/centre/EntityCentre.java
package ua.com.fielden.platform.web.centre; import static java.lang.String.format; import static ua.com.fielden.platform.web.centre.EgiConfigurations.CHECKBOX_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.CHECKBOX_VISIBLE; import static ua.com.fielden.platform.web.centre.EgiConfigurations.CHECKBOX_WITH_PRIMARY_ACTION_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.HEADER_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.SECONDARY_ACTION_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.SUMMARY_FIXED; import static ua.com.fielden.platform.web.centre.EgiConfigurations.TOOLBAR_VISIBLE; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import org.apache.log4j.Logger; import com.google.common.collect.ListMultimap; import com.google.inject.Injector; import ua.com.fielden.platform.basic.IValueMatcherWithCentreContext; import ua.com.fielden.platform.basic.autocompleter.FallbackValueMatcherWithCentreContext; import ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector; import ua.com.fielden.platform.dao.IEntityDao; import ua.com.fielden.platform.data.generator.IGenerator; import ua.com.fielden.platform.dom.DomContainer; import ua.com.fielden.platform.dom.DomElement; import ua.com.fielden.platform.dom.InnerTextElement; import ua.com.fielden.platform.domaintree.ICalculatedProperty.CalculatedPropertyAttribute; import ua.com.fielden.platform.domaintree.IGlobalDomainTreeManager; import ua.com.fielden.platform.domaintree.IServerGlobalDomainTreeManager; import ua.com.fielden.platform.domaintree.centre.ICentreDomainTreeManager; import ua.com.fielden.platform.domaintree.centre.ICentreDomainTreeManager.ICentreDomainTreeManagerAndEnhancer; import ua.com.fielden.platform.domaintree.impl.AbstractDomainTree; import ua.com.fielden.platform.domaintree.impl.CalculatedProperty; import ua.com.fielden.platform.domaintree.impl.GlobalDomainTreeManager; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder; import ua.com.fielden.platform.entity.fetch.IFetchProvider; import ua.com.fielden.platform.reflection.PropertyTypeDeterminator; import ua.com.fielden.platform.reflection.asm.impl.DynamicEntityClassLoader; import ua.com.fielden.platform.security.user.IUserProvider; import ua.com.fielden.platform.security.user.User; import ua.com.fielden.platform.serialisation.api.ISerialiser; import ua.com.fielden.platform.serialisation.jackson.DefaultValueContract; import ua.com.fielden.platform.types.Money; import ua.com.fielden.platform.ui.menu.MiWithConfigurationSupport; import ua.com.fielden.platform.utils.EntityUtils; import ua.com.fielden.platform.utils.Pair; import ua.com.fielden.platform.utils.ResourceLoader; import ua.com.fielden.platform.web.centre.api.EntityCentreConfig; import ua.com.fielden.platform.web.centre.api.EntityCentreConfig.OrderDirection; import ua.com.fielden.platform.web.centre.api.EntityCentreConfig.ResultSetProp; import ua.com.fielden.platform.web.centre.api.EntityCentreConfig.SummaryPropDef; import ua.com.fielden.platform.web.centre.api.ICentre; import ua.com.fielden.platform.web.centre.api.actions.EntityActionConfig; import ua.com.fielden.platform.web.centre.api.context.CentreContextConfig; import ua.com.fielden.platform.web.centre.api.crit.defaults.assigners.IValueAssigner; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.MultiCritBooleanValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.MultiCritStringValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.RangeCritDateValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.RangeCritOtherValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.SingleCritDateValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.SingleCritOtherValueMnemonic; import ua.com.fielden.platform.web.centre.api.crit.impl.AbstractCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.BooleanCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.BooleanSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.DateCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.DateSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.DecimalCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.DecimalSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.EntityCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.EntitySingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.IntegerCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.IntegerSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.MoneyCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.MoneySingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.StringCriterionWidget; import ua.com.fielden.platform.web.centre.api.crit.impl.StringSingleCriterionWidget; import ua.com.fielden.platform.web.centre.api.insertion_points.InsertionPoints; import ua.com.fielden.platform.web.centre.api.resultset.ICustomPropsAssignmentHandler; import ua.com.fielden.platform.web.centre.api.resultset.IRenderingCustomiser; import ua.com.fielden.platform.web.centre.api.resultset.PropDef; import ua.com.fielden.platform.web.centre.api.resultset.impl.FunctionalActionElement; import ua.com.fielden.platform.web.centre.api.resultset.impl.FunctionalActionKind; import ua.com.fielden.platform.web.centre.api.resultset.impl.PropertyColumnElement; import ua.com.fielden.platform.web.centre.exceptions.PropertyDefinitionException; import ua.com.fielden.platform.web.interfaces.ILayout.Device; import ua.com.fielden.platform.web.interfaces.IRenderable; import ua.com.fielden.platform.web.layout.FlexLayout; import ua.com.fielden.platform.web.view.master.api.impl.SimpleMasterBuilder; import ua.com.fielden.snappy.DateRangeConditionEnum; /** * Represents the entity centre. * * @author TG Team * */ public class EntityCentre<T extends AbstractEntity<?>> implements ICentre<T> { private final String IMPORTS = "<!--@imports-->"; private final String FULL_ENTITY_TYPE = "@full_entity_type"; private final String FULL_MI_TYPE = "@full_mi_type"; private final String MI_TYPE = "@mi_type"; //egi related properties private final String EGI_LAYOUT = "@gridLayout"; private final String EGI_LAYOUT_CONFIG = "//gridLayoutConfig"; private final String EGI_SHORTCUTS = "@customShortcuts"; private final String EGI_TOOLBAR_VISIBLE = "@toolbarVisible"; private final String EGI_CHECKBOX_VISIBILITY = "@checkboxVisible"; private final String EGI_CHECKBOX_FIXED = "@checkboxesFixed"; private final String EGI_CHECKBOX_WITH_PRIMARY_ACTION_FIXED = "@checkboxesWithPrimaryActionsFixed"; private final String EGI_NUM_OF_FIXED_COLUMNS = "@numOfFixedCols"; private final String EGI_SECONDARY_ACTION_FIXED = "@secondaryActionsFixed"; private final String EGI_HEADER_FIXED = "@headerFixed"; private final String EGI_SUMMARY_FIXED = "@summaryFixed"; private final String EGI_VISIBLE_ROW_COUNT = "@visibleRowCount"; private final String EGI_PAGE_CAPACITY = "@pageCapacity"; private final String EGI_ACTIONS = "//generatedActionObjects"; private final String EGI_PRIMARY_ACTION = "//generatedPrimaryAction"; private final String EGI_SECONDARY_ACTIONS = "//generatedSecondaryActions"; private final String EGI_PROPERTY_ACTIONS = "//generatedPropActions"; private final String EGI_DOM = "<!--@egi_columns-->"; private final String EGI_FUNCTIONAL_ACTION_DOM = "<!--@functional_actions-->"; private final String EGI_PRIMARY_ACTION_DOM = "<!--@primary_action-->"; private final String EGI_SECONDARY_ACTIONS_DOM = "<!--@secondary_actions-->"; //Toolbar related private final String TOOLBAR_DOM = "<!--@toolbar-->"; private final String TOOLBAR_JS = "//toolbarGeneratedFunction"; private final String TOOLBAR_STYLES = "/*toolbarStyles*/"; //Selection criteria related private final String QUERY_ENHANCER_CONFIG = "@queryEnhancerContextConfig"; private final String CRITERIA_DOM = "<!--@criteria_editors-->"; private final String SELECTION_CRITERIA_LAYOUT_CONFIG = "//@layoutConfig"; //Insertion points private final String INSERTION_POINT_ACTIONS = "//generatedInsertionPointActions"; private final String INSERTION_POINT_ACTIONS_DOM = "<!--@insertion_point_actions-->"; private final String LEFT_INSERTION_POINT_DOM = "<!--@left_insertion_points-->"; private final String RIGHT_INSERTION_POINT_DOM = "<!--@right_insertion_points-->"; private final String BOTTOM_INSERTION_POINT_DOM = "<!--@bottom_insertion_points-->"; private final Logger logger = Logger.getLogger(getClass()); private final Class<? extends MiWithConfigurationSupport<?>> menuItemType; private final String name; private final EntityCentreConfig<T> dslDefaultConfig; private final Injector injector; private final Class<T> entityType; private final Class<? extends MiWithConfigurationSupport<?>> miType; private final ICompanionObjectFinder coFinder; private final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated; private ICentreDomainTreeManagerAndEnhancer defaultCentre; /** * Creates new {@link EntityCentre} instance for the menu item type and with specified name. * * @param miType * - the menu item type for which this entity centre is to be created. * @param name * - the name for this entity centre. * @param dslDefaultConfig * -- default configuration taken from Centre DSL */ public EntityCentre(final Class<? extends MiWithConfigurationSupport<?>> miType, final String name, final EntityCentreConfig<T> dslDefaultConfig, final Injector injector, final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated) { this.menuItemType = miType; this.name = name; this.dslDefaultConfig = dslDefaultConfig; this.injector = injector; this.miType = miType; this.entityType = CentreUtils.getEntityType(miType); this.coFinder = this.injector.getInstance(ICompanionObjectFinder.class); this.postCentreCreated = postCentreCreated; } /** * Generates default centre from DSL config and postCentreCreated callback (user unspecific). * * @param dslDefaultConfig * @param postCentreCreated * @return */ private ICentreDomainTreeManagerAndEnhancer createUserUnspecificDefaultCentre(final EntityCentreConfig<T> dslDefaultConfig, final ISerialiser serialiser, final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated) { return createDefaultCentre0(dslDefaultConfig, serialiser, postCentreCreated, false); } /** * Generates default centre from DSL config and postCentreCreated callback (user specific). * * @param dslDefaultConfig * @param postCentreCreated * @return */ private ICentreDomainTreeManagerAndEnhancer createDefaultCentre(final EntityCentreConfig<T> dslDefaultConfig, final ISerialiser serialiser, final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated) { return createDefaultCentre0(dslDefaultConfig, serialiser, postCentreCreated, true); } private ICentreDomainTreeManagerAndEnhancer createDefaultCentre0(final EntityCentreConfig<T> dslDefaultConfig, final ISerialiser serialiser, final UnaryOperator<ICentreDomainTreeManagerAndEnhancer> postCentreCreated, final boolean userSpecific) { final ICentreDomainTreeManagerAndEnhancer cdtmae = GlobalDomainTreeManager.createEmptyCentre(entityType, serialiser); final Optional<List<String>> selectionCriteria = dslDefaultConfig.getSelectionCriteria(); if (selectionCriteria.isPresent()) { for (final String property : selectionCriteria.get()) { cdtmae.getFirstTick().check(entityType, treeName(property), true); if (userSpecific) { provideDefaultsFor(property, cdtmae, dslDefaultConfig); } } } final Optional<List<ResultSetProp>> resultSetProps = dslDefaultConfig.getResultSetProperties(); final Optional<ListMultimap<String, SummaryPropDef>> summaryExpressions = dslDefaultConfig.getSummaryExpressions(); if (resultSetProps.isPresent()) { for (final ResultSetProp property : resultSetProps.get()) { if (property.propName.isPresent()) { } else { if (property.propDef.isPresent()) { // represents the 'custom' property final String customPropName = CalculatedProperty.generateNameFrom(property.propDef.get().title); enhanceCentreManagerWithCustomProperty(cdtmae, entityType, customPropName, property.propDef.get(), dslDefaultConfig.getResultSetCustomPropAssignmentHandlerType()); } else { throw new IllegalStateException(String.format("The state of result-set property [%s] definition is not correct, need to exist either a 'propName' for the property or 'propDef'.", property)); } } } } if (summaryExpressions.isPresent()) { for (final Entry<String, Collection<SummaryPropDef>> entry : summaryExpressions.get().asMap().entrySet()) { final String originationProperty = treeName(entry.getKey()); for (final SummaryPropDef summaryProp : entry.getValue()) { cdtmae.getEnhancer().addCalculatedProperty(entityType, "", summaryProp.alias, summaryProp.expression, summaryProp.title, summaryProp.desc, CalculatedPropertyAttribute.NO_ATTR, "".equals(originationProperty) ? "SELF" : originationProperty); } } } cdtmae.getEnhancer().apply(); if (resultSetProps.isPresent()) { final Map<String, Integer> growFactors = calculateGrowFactors(resultSetProps.get()); for (final ResultSetProp property : resultSetProps.get()) { final String propertyName = getPropName(property); cdtmae.getSecondTick().check(entityType, propertyName, true); cdtmae.getSecondTick().setWidth(entityType, propertyName, property.width); if (growFactors.containsKey(propertyName)) { cdtmae.getSecondTick().setGrowFactor(entityType, propertyName, growFactors.get(propertyName)); } if (property.tooltipProp.isPresent()) { cdtmae.getSecondTick().check(entityType, treeName(property.tooltipProp.get()), true); } } } if (summaryExpressions.isPresent()) { for (final Entry<String, Collection<SummaryPropDef>> entry : summaryExpressions.get().asMap().entrySet()) { for (final SummaryPropDef summaryProp : entry.getValue()) { cdtmae.getSecondTick().check(entityType, summaryProp.alias, true); } } } final Optional<Map<String, OrderDirection>> propOrdering = dslDefaultConfig.getResultSetOrdering(); if (propOrdering.isPresent()) { // by default ordering occurs by "this" that is why it needs to be switched off in the presence of alternative ordering configuration if (cdtmae.getSecondTick().isChecked(entityType, "")) { cdtmae.getSecondTick().toggleOrdering(entityType, ""); cdtmae.getSecondTick().toggleOrdering(entityType, ""); } // let's now apply the ordering as per configuration for (final Map.Entry<String, OrderDirection> propAndOrderDirection : propOrdering.get().entrySet()) { if (OrderDirection.ASC == propAndOrderDirection.getValue()) { cdtmae.getSecondTick().toggleOrdering(entityType, treeName(propAndOrderDirection.getKey())); } else { // OrderDirection.DESC cdtmae.getSecondTick().toggleOrdering(entityType, treeName(propAndOrderDirection.getKey())).toggleOrdering(entityType, treeName(propAndOrderDirection.getKey())); } } } return postCentreCreated == null ? cdtmae : postCentreCreated.apply(cdtmae); } /** * Returns the property name for specified {@link ResultSetProp} instance. The returned property name can be used for retrieving and altering data in * {@link ICentreDomainTreeManager}. * * @param property * @return */ private static String getPropName(final ResultSetProp property) { if (property.propName.isPresent()) { return treeName(property.propName.get()); } else { if (property.propDef.isPresent()) { // represents the 'custom' property final String customPropName = CalculatedProperty.generateNameFrom(property.propDef.get().title); return treeName(customPropName); } else { throw new PropertyDefinitionException(format("The state of result-set property [%s] definition is not correct, need to exist either a 'propName' for the property or 'propDef'.", property)); } } } /** * Returns the 'managed type' for the 'centre' manager. * * @param root * @param centre * @return */ private Class<?> managedType(final ICentreDomainTreeManagerAndEnhancer centre) { return centre.getEnhancer().getManagedType(entityType); } private void provideDefaultsFor(final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae, final EntityCentreConfig<T> dslDefaultConfig) { final String property = treeName(dslProperty); final boolean isEntityItself = "".equals(property); // empty property means "entity itself" final Class<?> propertyType = isEntityItself ? managedType(cdtmae) : PropertyTypeDeterminator.determinePropertyType(managedType(cdtmae), property); if (AbstractDomainTree.isCritOnlySingle(managedType(cdtmae), property)) { if (EntityUtils.isEntityType(propertyType)) { provideDefaultsEntitySingle(() -> dslDefaultConfig.getDefaultSingleValuesForEntitySelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForEntitySelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isString(propertyType)) { provideDefaultsSingle(() -> dslDefaultConfig.getDefaultSingleValuesForStringSelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForStringSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isBoolean(propertyType)) { provideDefaultsSingle(() -> dslDefaultConfig.getDefaultSingleValuesForBooleanSelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForBooleanSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isInteger(propertyType)) { provideDefaultsSingle(() -> dslDefaultConfig.getDefaultSingleValuesForIntegerSelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForIntegerSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isRangeType(propertyType) && !EntityUtils.isDate(propertyType)) { provideDefaultsSingle(() -> dslDefaultConfig.getDefaultSingleValuesForBigDecimalAndMoneySelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForBigDecimalAndMoneySelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isDate(propertyType)) { provideDefaultsDateSingle(() -> dslDefaultConfig.getDefaultSingleValuesForDateSelectionCriteria(), () -> dslDefaultConfig.getDefaultSingleValueAssignersForDateSelectionCriteria(), dslProperty, cdtmae); } else { throw new UnsupportedOperationException(String.format("The single-crit type [%s] is currently unsupported.", propertyType)); } } else { if (EntityUtils.isEntityType(propertyType) || EntityUtils.isString(propertyType)) { provideDefaultsEntityOrString(() -> dslDefaultConfig.getDefaultMultiValuesForEntityAndStringSelectionCriteria(), () -> dslDefaultConfig.getDefaultMultiValueAssignersForEntityAndStringSelectionCriteria(), dslProperty, cdtmae, EntityUtils.isString(propertyType)); } else if (EntityUtils.isBoolean(propertyType)) { provideDefaultsBoolean(() -> dslDefaultConfig.getDefaultMultiValuesForBooleanSelectionCriteria(), () -> dslDefaultConfig.getDefaultMultiValueAssignersForBooleanSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isInteger(propertyType)) { provideDefaultsRange(() -> dslDefaultConfig.getDefaultRangeValuesForIntegerSelectionCriteria(), () -> dslDefaultConfig.getDefaultRangeValueAssignersForIntegerSelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isRangeType(propertyType) && !EntityUtils.isDate(propertyType)) { provideDefaultsRange(() -> dslDefaultConfig.getDefaultRangeValuesForBigDecimalAndMoneySelectionCriteria(), () -> dslDefaultConfig.getDefaultRangeValueAssignersForBigDecimalAndMoneySelectionCriteria(), dslProperty, cdtmae); } else if (EntityUtils.isDate(propertyType)) { provideDefaultsDateRange(() -> dslDefaultConfig.getDefaultRangeValuesForDateSelectionCriteria(), () -> dslDefaultConfig.getDefaultRangeValueAssignersForDateSelectionCriteria(), dslProperty, cdtmae); } else { throw new UnsupportedOperationException(String.format("The multi-crit type [%s] is currently unsupported.", propertyType)); } } } private void provideDefaultsEntityOrString(final Supplier<Optional<Map<String, MultiCritStringValueMnemonic>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<MultiCritStringValueMnemonic, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae, final boolean isString) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsEntityOrString(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property, isString); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsEntityOrString(assignerSupplier.get().get().get(dslProperty), cdtmae, property, isString); } else { } } } private void provideDefaultsBoolean(final Supplier<Optional<Map<String, MultiCritBooleanValueMnemonic>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<MultiCritBooleanValueMnemonic, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsBoolean(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsBoolean(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private void provideDefaultsEntitySingle(final Supplier<Optional<Map<String, SingleCritOtherValueMnemonic<? extends AbstractEntity<?>>>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<? extends SingleCritOtherValueMnemonic<? extends AbstractEntity<?>>, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsSingle(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsEntitySingle(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private void provideDefaultsDateSingle(final Supplier<Optional<Map<String, SingleCritDateValueMnemonic>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<SingleCritDateValueMnemonic, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsDateSingle(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsDateSingle(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private void provideDefaultsDateRange(final Supplier<Optional<Map<String, RangeCritDateValueMnemonic>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<RangeCritDateValueMnemonic, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsDateRange(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsDateRange(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private <M> void provideDefaultsSingle(final Supplier<Optional<Map<String, SingleCritOtherValueMnemonic<M>>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<SingleCritOtherValueMnemonic<M>, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsSingle(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsSingle(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private <M> void provideDefaultsRange(final Supplier<Optional<Map<String, RangeCritOtherValueMnemonic<M>>>> mnemonicSupplier, final Supplier<Optional<Map<String, Class<? extends IValueAssigner<RangeCritOtherValueMnemonic<M>, T>>>>> assignerSupplier, final String dslProperty, final ICentreDomainTreeManagerAndEnhancer cdtmae) { final String property = treeName(dslProperty); if (mnemonicSupplier.get().isPresent() && mnemonicSupplier.get().get().get(dslProperty) != null) { provideMnemonicDefaultsRange(mnemonicSupplier.get().get().get(dslProperty), cdtmae, property); } else { if (assignerSupplier.get().isPresent() && assignerSupplier.get().get().get(dslProperty) != null) { provideAssignerDefaultsRange(assignerSupplier.get().get().get(dslProperty), cdtmae, property); } else { } } } private void provideAssignerDefaultsEntityOrString(final Class<? extends IValueAssigner<MultiCritStringValueMnemonic, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property, final boolean isString) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<MultiCritStringValueMnemonic> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsEntityOrString(value.get(), cdtmae, property, isString); } } private void provideAssignerDefaultsBoolean(final Class<? extends IValueAssigner<MultiCritBooleanValueMnemonic, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<MultiCritBooleanValueMnemonic> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsBoolean(value.get(), cdtmae, property); } } private void provideAssignerDefaultsDateSingle(final Class<? extends IValueAssigner<SingleCritDateValueMnemonic, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<SingleCritDateValueMnemonic> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsDateSingle(value.get(), cdtmae, property); } } private void provideAssignerDefaultsDateRange(final Class<? extends IValueAssigner<RangeCritDateValueMnemonic, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<RangeCritDateValueMnemonic> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsDateRange(value.get(), cdtmae, property); } } private <M> void provideAssignerDefaultsSingle(final Class<? extends IValueAssigner<? extends SingleCritOtherValueMnemonic<M>, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<? extends SingleCritOtherValueMnemonic<M>> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsSingle(value.get(), cdtmae, property); } } private void provideAssignerDefaultsEntitySingle(final Class<? extends IValueAssigner<? extends SingleCritOtherValueMnemonic<? extends AbstractEntity<?>>, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<? extends SingleCritOtherValueMnemonic<? extends AbstractEntity<?>>> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsSingle(value.get(), cdtmae, property); } } private <M> void provideAssignerDefaultsRange(final Class<? extends IValueAssigner<? extends RangeCritOtherValueMnemonic<M>, T>> assignerType, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { /* TODO at this stage there is no implementation for centre context processing -- master entity for dependent centres is the only applicable context -- will be implemented later */ final Optional<? extends RangeCritOtherValueMnemonic<M>> value = injector.getInstance(assignerType).getValue(null, dslName(property)); if (value.isPresent()) { provideMnemonicDefaultsRange(value.get(), cdtmae, property); } } private void provideMnemonicDefaultsEntityOrString(final MultiCritStringValueMnemonic mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property, final boolean isString) { if (mnemonic.values.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, isString ? String.join(",", mnemonic.values.get()) : mnemonic.values.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } } private void provideMnemonicDefaultsBoolean(final MultiCritBooleanValueMnemonic mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.isValue.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.isValue.get()); } if (mnemonic.isNotValue.isPresent()) { cdtmae.getFirstTick().setValue2(entityType, property, mnemonic.isNotValue.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } } private void provideMnemonicDefaultsDateSingle(final SingleCritDateValueMnemonic mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.value.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.value.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } // date mnemonics if (mnemonic.prefix.isPresent()) { cdtmae.getFirstTick().setDatePrefix(entityType, property, mnemonic.prefix.get()); } if (mnemonic.period.isPresent()) { cdtmae.getFirstTick().setDateMnemonic(entityType, property, mnemonic.period.get()); } if (mnemonic.beforeOrAfter.isPresent()) { cdtmae.getFirstTick().setAndBefore(entityType, property, DateRangeConditionEnum.BEFORE.equals(mnemonic.beforeOrAfter.get()) ? Boolean.TRUE : Boolean.FALSE); } // exclusiveness if (mnemonic.excludeFrom.isPresent()) { cdtmae.getFirstTick().setExclusive(entityType, property, mnemonic.excludeFrom.get()); } if (mnemonic.excludeTo.isPresent()) { cdtmae.getFirstTick().setExclusive2(entityType, property, mnemonic.excludeTo.get()); } } private void provideMnemonicDefaultsDateRange(final RangeCritDateValueMnemonic mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.fromValue.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.fromValue.get()); } if (mnemonic.toValue.isPresent()) { cdtmae.getFirstTick().setValue2(entityType, property, mnemonic.toValue.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } // date mnemonics if (mnemonic.prefix.isPresent()) { cdtmae.getFirstTick().setDatePrefix(entityType, property, mnemonic.prefix.get()); } if (mnemonic.period.isPresent()) { cdtmae.getFirstTick().setDateMnemonic(entityType, property, mnemonic.period.get()); } if (mnemonic.beforeOrAfter.isPresent()) { cdtmae.getFirstTick().setAndBefore(entityType, property, DateRangeConditionEnum.BEFORE.equals(mnemonic.beforeOrAfter.get()) ? Boolean.TRUE : Boolean.FALSE); } // exclusiveness if (mnemonic.excludeFrom.isPresent()) { cdtmae.getFirstTick().setExclusive(entityType, property, mnemonic.excludeFrom.get()); } if (mnemonic.excludeTo.isPresent()) { cdtmae.getFirstTick().setExclusive2(entityType, property, mnemonic.excludeTo.get()); } } private <M> void provideMnemonicDefaultsSingle(final SingleCritOtherValueMnemonic<M> mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.value.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.value.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } } private <M> void provideMnemonicDefaultsRange(final RangeCritOtherValueMnemonic<M> mnemonic, final ICentreDomainTreeManagerAndEnhancer cdtmae, final String property) { if (mnemonic.fromValue.isPresent()) { cdtmae.getFirstTick().setValue(entityType, property, mnemonic.fromValue.get()); } if (mnemonic.toValue.isPresent()) { cdtmae.getFirstTick().setValue2(entityType, property, mnemonic.toValue.get()); } if (mnemonic.checkForMissingValue) { cdtmae.getFirstTick().setOrNull(entityType, property, true); } if (mnemonic.negateCondition) { cdtmae.getFirstTick().setNot(entityType, property, true); } if (mnemonic.excludeFrom.isPresent()) { cdtmae.getFirstTick().setExclusive(entityType, property, mnemonic.excludeFrom.get()); } if (mnemonic.excludeTo.isPresent()) { cdtmae.getFirstTick().setExclusive2(entityType, property, mnemonic.excludeTo.get()); } } /** * Returns the menu item type for this {@link EntityCentre} instance. * * @return */ public Class<? extends MiWithConfigurationSupport<?>> getMenuItemType() { return this.menuItemType; } /** * Returns the entity type for which this entity centre was created. * * @return */ public Class<T> getEntityType() { return entityType; } /** * Returns the entity centre name. * * @return */ public String getName() { return name; } /** * Returns action configuration for concrete action kind and its number in that kind's space. * * @param actionKind * @param actionNumber * @return */ public EntityActionConfig actionConfig(final FunctionalActionKind actionKind, final int actionNumber) { return dslDefaultConfig.actionConfig(actionKind, actionNumber); } /** * Returns the value that indicates whether centre must run automatically or not. * * @return */ public boolean isRunAutomatically() { return dslDefaultConfig.isRunAutomatically(); } /** * Indicates whether centre should forcibly refresh the current page upon successful saving of a related entity. * * @return */ public boolean shouldEnforcePostSaveRefresh() { return dslDefaultConfig.shouldEnforcePostSaveRefresh(); } /** * Return an optional Event Source URI. * * @return */ public Optional<String> eventSourceUri() { return dslDefaultConfig.getSseUri(); } /** * Returns the instance of rendering customiser for this entity centre. * * @return */ public Optional<IRenderingCustomiser<?>> getRenderingCustomiser() { if (dslDefaultConfig.getResultSetRenderingCustomiserType().isPresent()) { return Optional.of(injector.getInstance(dslDefaultConfig.getResultSetRenderingCustomiserType().get())); } else { return Optional.empty(); } } @Override public IRenderable build() { logger.debug("Initiating fresh centre..."); return createRenderableRepresentation(getAssociatedEntityCentreManager()); } private final ICentreDomainTreeManagerAndEnhancer getAssociatedEntityCentreManager() { final IGlobalDomainTreeManager userSpecificGlobalManager = getUserSpecificGlobalManager(); if (userSpecificGlobalManager == null) { return createUserUnspecificDefaultCentre(dslDefaultConfig, injector.getInstance(ISerialiser.class), postCentreCreated); } else { return CentreUpdater.updateCentre(userSpecificGlobalManager, this.menuItemType, CentreUpdater.FRESH_CENTRE_NAME); } } private String egiRepresentationFor(final Class<?> propertyType, final Optional<String> timeZone, final Optional<String> timePortionToDisplay) { final Class<?> type = DynamicEntityClassLoader.getOriginalType(propertyType); String typeRes = EntityUtils.isEntityType(type) ? type.getName() : (EntityUtils.isBoolean(type) ? "Boolean" : type.getSimpleName()); if (Date.class.isAssignableFrom(type)) { typeRes += ":" + timeZone.orElse(""); typeRes += ":" + timePortionToDisplay.orElse(""); } return typeRes; } /** * Returns default centre manager that was formed using DSL configuration and postCentreCreated hook. * * @return */ public ICentreDomainTreeManagerAndEnhancer getDefaultCentre() { if (defaultCentre == null) { defaultCentre = createDefaultCentre(dslDefaultConfig, injector.getInstance(ISerialiser.class), postCentreCreated); } return defaultCentre; } private IRenderable createRenderableRepresentation(final ICentreDomainTreeManagerAndEnhancer centre) { final LinkedHashSet<String> importPaths = new LinkedHashSet<>(); importPaths.add("polymer/polymer/polymer"); importPaths.add("master/tg-entity-master"); logger.debug("Initiating layout..."); final FlexLayout layout = this.dslDefaultConfig.getSelectionCriteriaLayout(); final DomElement editorContainer = layout.render().attr("context", "[[_currEntity]]"); importPaths.add(layout.importPath()); final Class<?> root = this.entityType; logger.debug("Initiating criteria widgets..."); final List<AbstractCriterionWidget> criteriaWidgets = createCriteriaWidgets(centre, root); criteriaWidgets.forEach(widget -> { importPaths.add(widget.importPath()); importPaths.addAll(widget.editorsImportPaths()); editorContainer.add(widget.render()); }); final String prefix = ",\n"; logger.debug("Initiating property columns..."); final List<PropertyColumnElement> propertyColumns = new ArrayList<>(); final Optional<List<ResultSetProp>> resultProps = dslDefaultConfig.getResultSetProperties(); final Optional<ListMultimap<String, SummaryPropDef>> summaryProps = dslDefaultConfig.getSummaryExpressions(); final Class<?> managedType = centre.getEnhancer().getManagedType(root); if (resultProps.isPresent()) { int actionIndex = 0; for (final ResultSetProp resultProp : resultProps.get()) { final String tooltipProp = resultProp.tooltipProp.isPresent() ? resultProp.tooltipProp.get() : null; final String resultPropName = getPropName(resultProp); final boolean isEntityItself = "".equals(resultPropName); // empty property means "entity itself" final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, resultPropName); final Optional<FunctionalActionElement> action; if (resultProp.propAction.isPresent()) { action = Optional.of(new FunctionalActionElement(resultProp.propAction.get(), actionIndex, resultPropName)); actionIndex += 1; } else { action = Optional.empty(); } final PropertyColumnElement el = new PropertyColumnElement(resultPropName, null, resultProp.width, centre.getSecondTick().getGrowFactor(root, resultPropName), resultProp.isFlexible, tooltipProp, egiRepresentationFor( propertyType, Optional.ofNullable(EntityUtils.isDate(propertyType) ? DefaultValueContract.getTimeZone(managedType, resultPropName) : null), Optional.ofNullable(EntityUtils.isDate(propertyType) ? DefaultValueContract.getTimePortionToDisplay(managedType, resultPropName) : null)), CriteriaReflector.getCriteriaTitleAndDesc(managedType, resultPropName), action); if (summaryProps.isPresent() && summaryProps.get().containsKey(dslName(resultPropName))) { final List<SummaryPropDef> summaries = summaryProps.get().get(dslName(resultPropName)); summaries.forEach(summary -> el.addSummary(summary.alias, PropertyTypeDeterminator.determinePropertyType(managedType, summary.alias), new Pair<>(summary.title, summary.desc))); } propertyColumns.add(el); } } logger.debug("Initiating prop actions..."); final DomContainer egiColumns = new DomContainer(); final StringBuilder propActionsObject = new StringBuilder(); propertyColumns.forEach(column -> { importPaths.add(column.importPath()); if (column.hasSummary()) { importPaths.add(column.getSummary(0).importPath()); } if (column.getAction().isPresent()) { importPaths.add(column.getAction().get().importPath()); propActionsObject.append(prefix + createActionObject(column.getAction().get())); } egiColumns.add(column.render()); }); logger.debug("Initiating top-level actions..."); final Optional<List<Pair<EntityActionConfig, Optional<String>>>> topLevelActions = this.dslDefaultConfig.getTopLevelActions(); final List<List<FunctionalActionElement>> actionGroups = new ArrayList<>(); if (topLevelActions.isPresent()) { final String currentGroup = null; for (int i = 0; i < topLevelActions.get().size(); i++) { final Pair<EntityActionConfig, Optional<String>> topLevelAction = topLevelActions.get().get(i); final String cg = getGroup(topLevelAction.getValue()); if (!EntityUtils.equalsEx(cg, currentGroup)) { actionGroups.add(new ArrayList<>()); } addToLastGroup(actionGroups, topLevelAction.getKey(), i); } } logger.debug("Initiating functional actions..."); final StringBuilder functionalActionsObjects = new StringBuilder(); final DomContainer functionalActionsDom = new DomContainer(); for (final List<FunctionalActionElement> group : actionGroups) { final DomElement groupElement = new DomElement("div").clazz("entity-specific-action", "group"); for (final FunctionalActionElement el : group) { importPaths.add(el.importPath()); groupElement.add(el.render()); functionalActionsObjects.append(prefix + createActionObject(el)); } functionalActionsDom.add(groupElement); } logger.debug("Initiating primary actions..."); //////////////////// Primary result-set action //////////////////// final Optional<EntityActionConfig> resultSetPrimaryEntityAction = this.dslDefaultConfig.getResultSetPrimaryEntityAction(); final DomContainer primaryActionDom = new DomContainer(); final StringBuilder primaryActionObject = new StringBuilder(); if (resultSetPrimaryEntityAction.isPresent() && !resultSetPrimaryEntityAction.get().isNoAction()) { final FunctionalActionElement el = new FunctionalActionElement(resultSetPrimaryEntityAction.get(), 0, FunctionalActionKind.PRIMARY_RESULT_SET); importPaths.add(el.importPath()); primaryActionDom.add(el.render().clazz("primary-action").attr("hidden", null)); primaryActionObject.append(prefix + createActionObject(el)); } //////////////////// Primary result-set action [END] ////////////// logger.debug("Initiating secondary actions..."); final List<FunctionalActionElement> secondaryActionElements = new ArrayList<>(); final Optional<List<EntityActionConfig>> resultSetSecondaryEntityActions = this.dslDefaultConfig.getResultSetSecondaryEntityActions(); if (resultSetSecondaryEntityActions.isPresent()) { for (int i = 0; i < resultSetSecondaryEntityActions.get().size(); i++) { final FunctionalActionElement el = new FunctionalActionElement(resultSetSecondaryEntityActions.get().get(i), i, FunctionalActionKind.SECONDARY_RESULT_SET); secondaryActionElements.add(el); } } final DomContainer secondaryActionsDom = new DomContainer(); final StringBuilder secondaryActionsObjects = new StringBuilder(); for (final FunctionalActionElement el : secondaryActionElements) { importPaths.add(el.importPath()); secondaryActionsDom.add(el.render().clazz("secondary-action").attr("hidden", null)); secondaryActionsObjects.append(prefix + createActionObject(el)); } logger.debug("Initiating insertion point actions..."); final List<FunctionalActionElement> insertionPointActionsElements = new ArrayList<>(); final Optional<List<EntityActionConfig>> insertionPointActions = this.dslDefaultConfig.getInsertionPointActions(); if (insertionPointActions.isPresent()) { for (int index = 0; index < insertionPointActions.get().size(); index++) { final FunctionalActionElement el = new FunctionalActionElement(insertionPointActions.get().get(index), index, FunctionalActionKind.INSERTION_POINT); insertionPointActionsElements.add(el); } } final DomContainer insertionPointActionsDom = new DomContainer(); final StringBuilder insertionPointActionsObjects = new StringBuilder(); for (final FunctionalActionElement el : insertionPointActionsElements) { importPaths.add(el.importPath()); insertionPointActionsDom.add(el.render().clazz("insertion-point-action").attr("hidden", null)); insertionPointActionsObjects.append(prefix + createActionObject(el)); } importPaths.add(dslDefaultConfig.getToolbarConfig().importPath()); final DomContainer leftInsertionPointsDom = new DomContainer(); final DomContainer rightInsertionPointsDom = new DomContainer(); final DomContainer bottomInsertionPointsDom = new DomContainer(); for (final FunctionalActionElement el : insertionPointActionsElements) { final DomElement insertionPoint = new DomElement("tg-entity-centre-insertion-point") .attr("id", "ip" + el.numberOfAction) .attr("short-desc", el.conf().shortDesc.orElse("")) .attr("long-desc", el.conf().longDesc.orElse("")) .attr("retrieved-entities", "{{retrievedEntities}}") .attr("retrieved-totals", "{{retrievedTotals}}") .attr("retrieved-entity-selection", "{{retrievedEntitySelection}}") .attr("column-properties-mapper", "{{columnPropertiesMapper}}"); if (el.entityActionConfig.whereToInsertView.get() == InsertionPoints.LEFT) { leftInsertionPointsDom.add(insertionPoint); } else if (el.entityActionConfig.whereToInsertView.get() == InsertionPoints.RIGHT) { rightInsertionPointsDom.add(insertionPoint); } else if (el.entityActionConfig.whereToInsertView.get() == InsertionPoints.BOTTOM) { bottomInsertionPointsDom.add(insertionPoint); } else { throw new IllegalArgumentException("Unexpected insertion point type."); } } //Generating shortcuts for EGI final StringBuilder shortcuts = new StringBuilder(); for (final String shortcut : dslDefaultConfig.getToolbarConfig().getAvailableShortcuts()) { shortcuts.append(shortcut + " "); } if (topLevelActions.isPresent()) { for (int i = 0; i < topLevelActions.get().size(); i++) { final Pair<EntityActionConfig, Optional<String>> topLevelAction = topLevelActions.get().get(i); final EntityActionConfig config = topLevelAction.getKey(); if (config.shortcut.isPresent()) { shortcuts.append(config.shortcut.get() + " "); } } } /////////////////////////////////////// final String funcActionString = functionalActionsObjects.toString(); final String secondaryActionString = secondaryActionsObjects.toString(); final String insertionPointActionsString = insertionPointActionsObjects.toString(); final String primaryActionObjectString = primaryActionObject.toString(); final String propActionsString = propActionsObject.toString(); final Pair<String, String> gridLayoutConfig = generateGridLayoutConfig(); final int prefixLength = prefix.length(); logger.debug("Initiating template..."); final String text = ResourceLoader.getText("ua/com/fielden/platform/web/centre/tg-entity-centre-template.html"); logger.debug("Replacing some parts..."); final String entityCentreStr = text. replace(IMPORTS, SimpleMasterBuilder.createImports(importPaths)). replace(EGI_LAYOUT, gridLayoutConfig.getKey()). replace(FULL_ENTITY_TYPE, entityType.getName()). replace(MI_TYPE, miType.getSimpleName()). //egi related properties replace(EGI_SHORTCUTS, shortcuts). replace(EGI_TOOLBAR_VISIBLE, TOOLBAR_VISIBLE.eval(!dslDefaultConfig.shouldHideToolbar())). replace(EGI_CHECKBOX_VISIBILITY, CHECKBOX_VISIBLE.eval(!dslDefaultConfig.shouldHideCheckboxes())). replace(EGI_CHECKBOX_FIXED, CHECKBOX_FIXED.eval(dslDefaultConfig.getScrollConfig().isCheckboxesFixed())).replace(EGI_CHECKBOX_WITH_PRIMARY_ACTION_FIXED, CHECKBOX_WITH_PRIMARY_ACTION_FIXED.eval(dslDefaultConfig.getScrollConfig().isCheckboxesWithPrimaryActionsFixed())). replace(EGI_NUM_OF_FIXED_COLUMNS, Integer.toString(dslDefaultConfig.getScrollConfig().getNumberOfFixedColumns())). replace(EGI_SECONDARY_ACTION_FIXED, SECONDARY_ACTION_FIXED.eval(dslDefaultConfig.getScrollConfig().isSecondaryActionsFixed())). replace(EGI_HEADER_FIXED, HEADER_FIXED.eval(dslDefaultConfig.getScrollConfig().isHeaderFixed())). replace(EGI_SUMMARY_FIXED, SUMMARY_FIXED.eval(dslDefaultConfig.getScrollConfig().isSummaryFixed())). replace(EGI_VISIBLE_ROW_COUNT, dslDefaultConfig.getVisibleRowsCount() + ""). /////////////////////// replace(TOOLBAR_DOM, dslDefaultConfig.getToolbarConfig().render().toString()). replace(TOOLBAR_JS, dslDefaultConfig.getToolbarConfig().code(entityType).toString()). replace(TOOLBAR_STYLES, dslDefaultConfig.getToolbarConfig().styles().toString()). replace(FULL_MI_TYPE, miType.getName()). replace(EGI_PAGE_CAPACITY, Integer.toString(dslDefaultConfig.getPageCapacity())). replace(QUERY_ENHANCER_CONFIG, queryEnhancerContextConfigString()). replace(CRITERIA_DOM, editorContainer.toString()). replace(EGI_DOM, egiColumns.toString()). replace(EGI_ACTIONS, funcActionString.length() > prefixLength ? funcActionString.substring(prefixLength) : funcActionString). replace(EGI_SECONDARY_ACTIONS, secondaryActionString.length() > prefixLength ? secondaryActionString.substring(prefixLength) : secondaryActionString). replace(INSERTION_POINT_ACTIONS, insertionPointActionsString.length() > prefixLength ? insertionPointActionsString.substring(prefixLength) : insertionPointActionsString). replace(EGI_PRIMARY_ACTION, primaryActionObjectString.length() > prefixLength ? primaryActionObjectString.substring(prefixLength) : primaryActionObjectString). replace(EGI_PROPERTY_ACTIONS, propActionsString.length() > prefixLength ? propActionsString.substring(prefixLength) : propActionsString). replace(SELECTION_CRITERIA_LAYOUT_CONFIG, layout.code().toString()). replace(EGI_LAYOUT_CONFIG, gridLayoutConfig.getValue()). replace(EGI_FUNCTIONAL_ACTION_DOM, functionalActionsDom.toString()). replace(EGI_PRIMARY_ACTION_DOM, primaryActionDom.toString()). replace(EGI_SECONDARY_ACTIONS_DOM, secondaryActionsDom.toString()). replace(INSERTION_POINT_ACTIONS_DOM, insertionPointActionsDom.toString()). replace(LEFT_INSERTION_POINT_DOM, leftInsertionPointsDom.toString()). replace(RIGHT_INSERTION_POINT_DOM, rightInsertionPointsDom.toString()). replace(BOTTOM_INSERTION_POINT_DOM, bottomInsertionPointsDom.toString()); logger.debug("Finishing..."); final IRenderable representation = new IRenderable() { @Override public DomElement render() { return new InnerTextElement(entityCentreStr); } }; logger.debug("Done."); return representation; } /** * Calculates the relative grow factor for all columns. */ private Map<String, Integer> calculateGrowFactors(final List<ResultSetProp> propertyColumns) { //Searching for the minimal column width which are not flexible and their width is greater than 0. final int minWidth = propertyColumns.stream() .filter(column -> column.isFlexible && column.width > 0) .reduce(Integer.MAX_VALUE, (min, column) -> min > column.width ? column.width : min, (min1, min2) -> min1 < min2 ? min1 : min2); //Map each resultSetProp which is not flexible and has width greater than 0 to it's grow factor. return propertyColumns.stream() .filter(column -> column.isFlexible && column.width > 0) .collect(Collectors.toMap( column -> getPropName(column), column -> Math.round((float) column.width / minWidth))); } private Pair<String, String> generateGridLayoutConfig() { final StringBuilder resultsetLayoutJs = new StringBuilder(); final StringBuilder resultsetLayoutHtml = new StringBuilder(); final FlexLayout collapseLayout = dslDefaultConfig.getResultsetCollapsedCardLayout(); final FlexLayout expandLayout = dslDefaultConfig.getResultsetExpansionCardLayout(); final FlexLayout summaryLayout = dslDefaultConfig.getResultsetSummaryCardLayout(); final StringBuilder shortLayout = new StringBuilder(); if (collapseLayout.hasLayoutFor(Device.DESKTOP, null)) { shortLayout.append("desktop: " + collapseLayout.getLayout(Device.DESKTOP, null).get()); } if (collapseLayout.hasLayoutFor(Device.TABLET, null)) { shortLayout.append((shortLayout.length() > 0 ? ",\n" : "") + "tablet: " + collapseLayout.getLayout(Device.TABLET, null).get()); } if (collapseLayout.hasLayoutFor(Device.MOBILE, null)) { shortLayout.append((shortLayout.length() > 0 ? ",\n" : "") + "mobile: " + collapseLayout.getLayout(Device.MOBILE, null).get()); } if (shortLayout.length() > 0) { resultsetLayoutJs.append("self.gridShortLayout={\n" + shortLayout.toString() + "\n};"); resultsetLayoutHtml.append("short-layout='[[gridShortLayout]]'"); } final StringBuilder longLayout = new StringBuilder(); if (expandLayout.hasLayoutFor(Device.DESKTOP, null)) { longLayout.append("desktop: " + expandLayout.getLayout(Device.DESKTOP, null).get()); } if (expandLayout.hasLayoutFor(Device.TABLET, null)) { longLayout.append((longLayout.length() > 0 ? ",\n" : "") + "tablet: " + expandLayout.getLayout(Device.TABLET, null).get()); } if (expandLayout.hasLayoutFor(Device.MOBILE, null)) { longLayout.append((longLayout.length() > 0 ? ",\n" : "") + "mobile: " + expandLayout.getLayout(Device.MOBILE, null).get()); } if (longLayout.length() > 0) { resultsetLayoutJs.append("self.gridLongLayout={\n" + longLayout.toString() + "\n};"); resultsetLayoutHtml.append(" long-layout='[[gridLongLayout]]'"); } final StringBuilder gridSummaryLayout = new StringBuilder(); if (summaryLayout.hasLayoutFor(Device.DESKTOP, null)) { gridSummaryLayout.append("desktop: " + summaryLayout.getLayout(Device.DESKTOP, null).get()); } if (summaryLayout.hasLayoutFor(Device.TABLET, null)) { gridSummaryLayout.append((gridSummaryLayout.length() > 0 ? ",\n" : "") + "tablet: " + summaryLayout.getLayout(Device.TABLET, null).get()); } if (summaryLayout.hasLayoutFor(Device.MOBILE, null)) { gridSummaryLayout.append((gridSummaryLayout.length() > 0 ? ",\n" : "") + "mobile: " + summaryLayout.getLayout(Device.MOBILE, null).get()); } if (gridSummaryLayout.length() > 0) { resultsetLayoutJs.append("self.summaryLayout={\n" + gridSummaryLayout.toString() + "\n};"); resultsetLayoutHtml.append(" summary-layout='[[summaryLayout]]'"); } return new Pair<>(resultsetLayoutHtml.toString(), resultsetLayoutJs.toString()); } /** * Returns the global manager for the user for this concrete thread (the user has been populated through the Web UI authentication mechanism -- see DefaultWebResourceGuard). * * @return */ private IGlobalDomainTreeManager getUserSpecificGlobalManager() { final IServerGlobalDomainTreeManager serverGdtm = injector.getInstance(IServerGlobalDomainTreeManager.class); final User user = injector.getInstance(IUserProvider.class).getUser(); if (user == null) { // the user is unknown at this stage! return null; // no user-specific global exists for unknown user! } final String userName = user.getKey(); return serverGdtm.get(userName); } private String queryEnhancerContextConfigString() { final StringBuilder sb = new StringBuilder(); if (dslDefaultConfig.getQueryEnhancerConfig().isPresent() && dslDefaultConfig.getQueryEnhancerConfig().get().getValue().isPresent()) { final CentreContextConfig centreContextConfig = dslDefaultConfig.getQueryEnhancerConfig().get().getValue().get(); if (centreContextConfig.withSelectionCrit) { // disregarded -- sends every time, because the selection criteria is needed for running the centre query } sb.append("require-selected-entities=\"" + (centreContextConfig.withCurrentEtity ? "ONE" : (centreContextConfig.withAllSelectedEntities ? "ALL" : "NONE")) + "\" "); sb.append("require-master-entity=\"" + (centreContextConfig.withMasterEntity ? "true" : "false") + "\""); } else { sb.append("require-selected-entities=\"NONE\" "); sb.append("require-master-entity=\"false\""); } return sb.toString(); } /** * Enhances the type of centre entity with custom property definition. * * @param centre * @param root * @param propDef * @param resultSetCustomPropAssignmentHandlerType */ private void enhanceCentreManagerWithCustomProperty(final ICentreDomainTreeManagerAndEnhancer centre, final Class<?> root, final String propName, final PropDef<?> propDef, final Optional<Class<? extends ICustomPropsAssignmentHandler>> resultSetCustomPropAssignmentHandlerType) { centre.getEnhancer().addCustomProperty(root, "" /* this is the contextPath */, propName, propDef.title, propDef.desc, propDef.type); } /** * Creates the widgets for criteria. * * @param centre * @param root * @return */ private List<AbstractCriterionWidget> createCriteriaWidgets(final ICentreDomainTreeManagerAndEnhancer centre, final Class<?> root) { final Class<?> managedType = centre.getEnhancer().getManagedType(root); final List<AbstractCriterionWidget> criteriaWidgets = new ArrayList<>(); for (final String critProp : centre.getFirstTick().checkedProperties(root)) { if (!AbstractDomainTree.isPlaceholder(critProp)) { final boolean isEntityItself = "".equals(critProp); // empty property means "entity itself" final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, critProp); final AbstractCriterionWidget criterionWidget; if (AbstractDomainTree.isCritOnlySingle(managedType, critProp)) { if (EntityUtils.isEntityType(propertyType)) { final List<Pair<String, Boolean>> additionalProps = dslDefaultConfig.getAdditionalPropsForAutocompleter(critProp); criterionWidget = new EntitySingleCriterionWidget(root, managedType, critProp, additionalProps, getCentreContextConfigFor(critProp)); } else if (EntityUtils.isString(propertyType)) { criterionWidget = new StringSingleCriterionWidget(root, managedType, critProp); } else if (EntityUtils.isBoolean(propertyType)) { criterionWidget = new BooleanSingleCriterionWidget(root, managedType, critProp); } else if (Integer.class.isAssignableFrom(propertyType) || Long.class.isAssignableFrom(propertyType)) { criterionWidget = new IntegerSingleCriterionWidget(root, managedType, critProp); } else if (BigDecimal.class.isAssignableFrom(propertyType)) { criterionWidget = new DecimalSingleCriterionWidget(root, managedType, critProp); } else if (Money.class.isAssignableFrom(propertyType)) { criterionWidget = new MoneySingleCriterionWidget(root, managedType, critProp); } else if (EntityUtils.isDate(propertyType)) { criterionWidget = new DateSingleCriterionWidget(root, managedType, critProp); } else { throw new UnsupportedOperationException(String.format("The crit-only single editor type [%s] is currently unsupported.", propertyType)); } } else { if (EntityUtils.isEntityType(propertyType)) { final List<Pair<String, Boolean>> additionalProps = dslDefaultConfig.getAdditionalPropsForAutocompleter(critProp); criterionWidget = new EntityCriterionWidget(root, managedType, critProp, additionalProps, getCentreContextConfigFor(critProp)); } else if (EntityUtils.isString(propertyType)) { criterionWidget = new StringCriterionWidget(root, managedType, critProp); } else if (EntityUtils.isBoolean(propertyType)) { criterionWidget = new BooleanCriterionWidget(root, managedType, critProp); } else if (Integer.class.isAssignableFrom(propertyType) || Long.class.isAssignableFrom(propertyType)) { criterionWidget = new IntegerCriterionWidget(root, managedType, critProp); } else if (BigDecimal.class.isAssignableFrom(propertyType)) { // TODO do not forget about Money later (after Money widget will be available) criterionWidget = new DecimalCriterionWidget(root, managedType, critProp); } else if (Money.class.isAssignableFrom(propertyType)) { criterionWidget = new MoneyCriterionWidget(root, managedType, critProp); } else if (EntityUtils.isDate(propertyType)) { criterionWidget = new DateCriterionWidget(root, managedType, critProp); } else { throw new UnsupportedOperationException(String.format("The multi / range editor type [%s] is currently unsupported.", propertyType)); } } criteriaWidgets.add(criterionWidget); } } return criteriaWidgets; } private void addToLastGroup(final List<List<FunctionalActionElement>> actionGroups, final EntityActionConfig actionConfig, final int i) { if (actionGroups.isEmpty()) { actionGroups.add(new ArrayList<>()); } final FunctionalActionElement el = new FunctionalActionElement(actionConfig, i, FunctionalActionKind.TOP_LEVEL); actionGroups.get(actionGroups.size() - 1).add(el); } private String getGroup(final Optional<String> groupIfAny) { return groupIfAny.isPresent() ? groupIfAny.get() : null; } private String createActionObject(final FunctionalActionElement element) { return element.createActionObject(); } /** * Return DSL representation for property name. * * @param name * @return */ private static String dslName(final String name) { return name.equals("") ? "this" : name; } /** * Return domain tree representation for property name. * * @param name * @return */ private static String treeName(final String name) { return name.equals("this") ? "" : name; } private CentreContextConfig getCentreContextConfigFor(final String critProp) { final String dslProp = dslName(critProp); return dslDefaultConfig.getValueMatchersForSelectionCriteria().isPresent() && dslDefaultConfig.getValueMatchersForSelectionCriteria().get().get(dslProp) != null && dslDefaultConfig.getValueMatchersForSelectionCriteria().get().get(dslProp).getValue() != null && dslDefaultConfig.getValueMatchersForSelectionCriteria().get().get(dslProp).getValue().isPresent() ? dslDefaultConfig.getValueMatchersForSelectionCriteria().get().get(dslProp).getValue().get() : new CentreContextConfig(false, false, false, false, null); } /** * Creates value matcher instance. * * @param injector * @return */ public <V extends AbstractEntity<?>> Pair<IValueMatcherWithCentreContext<V>, Optional<CentreContextConfig>> createValueMatcherAndContextConfig(final Class<? extends AbstractEntity<?>> criteriaType, final String criterionPropertyName) { final Optional<Map<String, Pair<Class<? extends IValueMatcherWithCentreContext<? extends AbstractEntity<?>>>, Optional<CentreContextConfig>>>> matchers = dslDefaultConfig.getValueMatchersForSelectionCriteria(); final String originalPropertyName = CentreUtils.getOriginalPropertyName(criteriaType, criterionPropertyName); final String dslProp = dslName(originalPropertyName); logger.debug("createValueMatcherAndContextConfig: propertyName = " + criterionPropertyName + " originalPropertyName = " + dslProp); final Class<? extends IValueMatcherWithCentreContext<V>> matcherType = matchers.isPresent() && matchers.get().containsKey(dslProp) ? (Class<? extends IValueMatcherWithCentreContext<V>>) matchers.get().get(dslProp).getKey() : null; final Pair<IValueMatcherWithCentreContext<V>, Optional<CentreContextConfig>> matcherAndContextConfig; if (matcherType != null) { matcherAndContextConfig = new Pair<>(injector.getInstance(matcherType), matchers.get().get(dslProp).getValue()); } else { matcherAndContextConfig = createDefaultValueMatcherAndContextConfig(CentreUtils.getOriginalType(criteriaType), originalPropertyName, coFinder); } return matcherAndContextConfig; } /** * Creates default value matcher and context config for the specified entity property. * * @param propertyName * @param criteriaType * @param coFinder * @return */ private <V extends AbstractEntity<?>> Pair<IValueMatcherWithCentreContext<V>, Optional<CentreContextConfig>> createDefaultValueMatcherAndContextConfig(final Class<? extends AbstractEntity<?>> originalType, final String originalPropertyName, final ICompanionObjectFinder coFinder) { final boolean isEntityItself = "".equals(originalPropertyName); // empty property means "entity itself" final Class<V> propertyType = (Class<V>) (isEntityItself ? originalType : PropertyTypeDeterminator.determinePropertyType(originalType, originalPropertyName)); final IEntityDao<V> co = coFinder.find(propertyType); return new Pair<>(new FallbackValueMatcherWithCentreContext<V>(co), Optional.empty()); } public Optional<Class<? extends ICustomPropsAssignmentHandler>> getCustomPropertiesAsignmentHandler() { return dslDefaultConfig.getResultSetCustomPropAssignmentHandlerType(); } public Optional<List<ResultSetProp>> getCustomPropertiesDefinitions() { return dslDefaultConfig.getResultSetProperties(); } public ICustomPropsAssignmentHandler createAssignmentHandlerInstance(final Class<? extends ICustomPropsAssignmentHandler> assignmentHandlerType) { return injector.getInstance(assignmentHandlerType); } public Optional<IFetchProvider<T>> getAdditionalFetchProvider() { return dslDefaultConfig.getFetchProvider(); } public Optional<Pair<IQueryEnhancer<T>, Optional<CentreContextConfig>>> getQueryEnhancerConfig() { final Optional<Pair<Class<? extends IQueryEnhancer<T>>, Optional<CentreContextConfig>>> queryEnhancerConfig = dslDefaultConfig.getQueryEnhancerConfig(); if (queryEnhancerConfig.isPresent()) { final Class<? extends IQueryEnhancer<T>> queryEnhancerType = queryEnhancerConfig.get().getKey(); return Optional.of(new Pair<>(injector.getInstance(queryEnhancerType), queryEnhancerConfig.get().getValue())); } else { return Optional.empty(); } } public Optional<Pair<Class<?>, Class<?>>> getGeneratorTypes() { return dslDefaultConfig.getGeneratorTypes(); } /** * Creates generic {@link IGenerator} instance from injector based on assumption that <code>generatorType</code> is of appropriate type (such checks are performed on API implementation level). * * @param generatorType * @return */ @SuppressWarnings("rawtypes") public IGenerator createGeneratorInstance(final Class<?> generatorType) { return (IGenerator) injector.getInstance(generatorType); } }
#833 fixed formating in entity centre generation.
platform-web-ui/src/main/java/ua/com/fielden/platform/web/centre/EntityCentre.java
#833 fixed formating in entity centre generation.
<ide><path>latform-web-ui/src/main/java/ua/com/fielden/platform/web/centre/EntityCentre.java <ide> replace(EGI_SHORTCUTS, shortcuts). <ide> replace(EGI_TOOLBAR_VISIBLE, TOOLBAR_VISIBLE.eval(!dslDefaultConfig.shouldHideToolbar())). <ide> replace(EGI_CHECKBOX_VISIBILITY, CHECKBOX_VISIBLE.eval(!dslDefaultConfig.shouldHideCheckboxes())). <del> replace(EGI_CHECKBOX_FIXED, CHECKBOX_FIXED.eval(dslDefaultConfig.getScrollConfig().isCheckboxesFixed())).replace(EGI_CHECKBOX_WITH_PRIMARY_ACTION_FIXED, CHECKBOX_WITH_PRIMARY_ACTION_FIXED.eval(dslDefaultConfig.getScrollConfig().isCheckboxesWithPrimaryActionsFixed())). <add> replace(EGI_CHECKBOX_FIXED, CHECKBOX_FIXED.eval(dslDefaultConfig.getScrollConfig().isCheckboxesFixed())). <add> replace(EGI_CHECKBOX_WITH_PRIMARY_ACTION_FIXED, CHECKBOX_WITH_PRIMARY_ACTION_FIXED.eval(dslDefaultConfig.getScrollConfig().isCheckboxesWithPrimaryActionsFixed())). <ide> replace(EGI_NUM_OF_FIXED_COLUMNS, Integer.toString(dslDefaultConfig.getScrollConfig().getNumberOfFixedColumns())). <ide> replace(EGI_SECONDARY_ACTION_FIXED, SECONDARY_ACTION_FIXED.eval(dslDefaultConfig.getScrollConfig().isSecondaryActionsFixed())). <ide> replace(EGI_HEADER_FIXED, HEADER_FIXED.eval(dslDefaultConfig.getScrollConfig().isHeaderFixed())).
Java
apache-2.0
477698192988aa413fdd82eb2559e0c2a282faba
0
shapesecurity/salvation
package com.shapesecurity.salvation; import com.shapesecurity.salvation.data.*; import com.shapesecurity.salvation.directiveValues.*; import com.shapesecurity.salvation.directives.*; import com.shapesecurity.salvation.tokens.*; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Parser { private static final DirectiveParseException MISSING_DIRECTIVE_NAME = new DirectiveParseException("Missing directive-name"); private static final DirectiveParseException INVALID_DIRECTIVE_NAME = new DirectiveParseException("Invalid directive-name"); private static final DirectiveParseException INVALID_DIRECTIVE_VALUE = new DirectiveParseException("Invalid directive-value"); private static final DirectiveParseException INVALID_MEDIA_TYPE_LIST = new DirectiveParseException("Invalid media-type-list"); private static final DirectiveValueParseException INVALID_MEDIA_TYPE = new DirectiveValueParseException("Invalid media-type"); private static final DirectiveParseException INVALID_SOURCE_LIST = new DirectiveParseException("Invalid source-list"); private static final DirectiveValueParseException INVALID_SOURCE_EXPR = new DirectiveValueParseException("Invalid source-expression"); private static final DirectiveParseException INVALID_ANCESTOR_SOURCE_LIST = new DirectiveParseException("Invalid ancestor-source-list"); private static final DirectiveValueParseException INVALID_ANCESTOR_SOURCE = new DirectiveValueParseException("Invalid ancestor-source"); private static final DirectiveParseException INVALID_REFERRER_TOKEN = new DirectiveParseException("Invalid referrer-token"); private static final DirectiveParseException INVALID_REPORT_TO_TOKEN = new DirectiveParseException("Invalid report-to token"); private static final DirectiveParseException INVALID_SANDBOX_TOKEN_LIST = new DirectiveParseException("Invalid sandbox-token list"); private static final DirectiveValueParseException INVALID_SANDBOX_TOKEN = new DirectiveValueParseException("Invalid sandbox-token"); private static final DirectiveParseException INVALID_URI_REFERENCE_LIST = new DirectiveParseException("Invalid uri-reference list"); private static final DirectiveValueParseException INVALID_URI_REFERENCE = new DirectiveValueParseException("Invalid uri-reference"); private static final DirectiveParseException NON_EMPTY_VALUE_TOKEN_LIST = new DirectiveParseException("Non-empty directive-value list"); @Nonnull protected final Token[] tokens; @Nonnull private final Origin origin; protected int index = 0; @Nullable protected Collection<Notice> noticesOut; protected Parser(@Nonnull Token[] tokens, @Nonnull Origin origin, @Nullable Collection<Notice> noticesOut) { this.origin = origin; this.tokens = tokens; this.noticesOut = noticesOut; } @Nonnull public static Policy parse(@Nonnull String sourceText, @Nonnull Origin origin) { return new Parser(Tokeniser.tokenise(sourceText), origin, null).parsePolicyAndAssertEOF(); } @Nonnull public static Policy parse(@Nonnull String sourceText, @Nonnull String origin) { return new Parser(Tokeniser.tokenise(sourceText), URI.parse(origin), null).parsePolicyAndAssertEOF(); } @Nonnull public static Policy parse(@Nonnull String sourceText, @Nonnull Origin origin, @Nonnull Collection<Notice> warningsOut) { return new Parser(Tokeniser.tokenise(sourceText), origin, warningsOut).parsePolicyAndAssertEOF(); } @Nonnull public static Policy parse(@Nonnull String sourceText, @Nonnull String origin, @Nonnull Collection<Notice> warningsOut) { return new Parser(Tokeniser.tokenise(sourceText), URI.parse(origin), warningsOut).parsePolicyAndAssertEOF(); } @Nonnull public static List<Policy> parseMulti(@Nonnull String sourceText, @Nonnull Origin origin) { return new Parser(Tokeniser.tokenise(sourceText), origin, null).parsePolicyListAndAssertEOF(); } @Nonnull public static List<Policy> parseMulti(@Nonnull String sourceText, @Nonnull String origin) { return new Parser(Tokeniser.tokenise(sourceText), URI.parse(origin), null).parsePolicyListAndAssertEOF(); } @Nonnull public static List<Policy> parseMulti(@Nonnull String sourceText, @Nonnull Origin origin, @Nonnull Collection<Notice> warningsOut) { return new Parser(Tokeniser.tokenise(sourceText), origin, warningsOut).parsePolicyListAndAssertEOF(); } @Nonnull public static List<Policy> parseMulti(@Nonnull String sourceText, @Nonnull String origin, @Nonnull Collection<Notice> warningsOut) { return new Parser(Tokeniser.tokenise(sourceText), URI.parse(origin), warningsOut).parsePolicyListAndAssertEOF(); } @Nonnull protected Notice createNotice(@Nonnull Notice.Type type, @Nonnull String message) { return new Notice(type, message); } @Nonnull protected Notice createNotice(@Nullable Token token, @Nonnull Notice.Type type, @Nonnull String message) { return new Notice(type, message); } private void warn(@Nullable Token token, @Nonnull String message) { if (this.noticesOut != null) { this.noticesOut.add(this.createNotice(token, Notice.Type.WARNING, message)); } } private void error(@Nullable Token token, @Nonnull String message) { if (this.noticesOut != null) { this.noticesOut.add(this.createNotice(token, Notice.Type.ERROR, message)); } } private void info(@Nullable Token token, @Nonnull String message) { if (this.noticesOut != null) { this.noticesOut.add(this.createNotice(token, Notice.Type.INFO, message)); } } @Nonnull private Token advance() { return this.tokens[this.index++]; } protected boolean hasNext() { return this.index < this.tokens.length; } private boolean hasNext(@Nonnull Class<? extends Token> c) { return this.hasNext() && c.isAssignableFrom(this.tokens[this.index].getClass()); } private boolean eat(@Nonnull Class<? extends Token> c) { if (this.hasNext(c)) { this.advance(); return true; } return false; } @Nonnull protected DirectiveValueParseException createError(@Nonnull String message) { return new DirectiveValueParseException(message); } @Nonnull protected Policy parsePolicy() { Policy policy = new Policy(this.origin); while (this.hasNext()) { if (this.hasNext(PolicySeparatorToken.class)) break; if (this.eat(DirectiveSeparatorToken.class)) continue; try { policy.addDirective(this.parseDirective()); } catch (DirectiveParseException ignored) { } } return policy; } @Nonnull protected Policy parsePolicyAndAssertEOF() { Policy policy = this.parsePolicy(); if (this.hasNext()) { Token t = this.advance(); this.error(t, "Expecting end of policy but found \"" + t.value + "\"."); } return policy; } @Nonnull protected List<Policy> parsePolicyList() { List<Policy> policies = new ArrayList<>(); policies.add(this.parsePolicy()); while (this.hasNext(PolicySeparatorToken.class)) { while (this.eat(PolicySeparatorToken.class)) ; policies.add(this.parsePolicy()); } return policies; } @Nonnull protected List<Policy> parsePolicyListAndAssertEOF() { List<Policy> policies = this.parsePolicyList(); if (this.hasNext()) { Token t = this.advance(); this.error(t, "Expecting end of policy list but found \"" + t.value + "\"."); } return policies; } @Nonnull private Directive<?> parseDirective() throws DirectiveParseException { if (!this.hasNext(DirectiveNameToken.class)) { Token t = this.advance(); this.error(t, "Expecting directive-name but found \"" + t.value.split(" ", 2)[0] + "\"."); throw MISSING_DIRECTIVE_NAME; } Directive result; DirectiveNameToken token = (DirectiveNameToken) this.advance(); try { switch (token.subtype) { case BaseUri: result = new BaseUriDirective(this.parseSourceList()); break; case BlockAllMixedContent: warnFutureDirective(token); this.enforceMissingDirectiveValue(token); result = new BlockAllMixedContentDirective(); break; case ChildSrc: result = new ChildSrcDirective(this.parseSourceList()); break; case ConnectSrc: result = new ConnectSrcDirective(this.parseSourceList()); break; case DefaultSrc: result = new DefaultSrcDirective(this.parseSourceList()); break; case FontSrc: result = new FontSrcDirective(this.parseSourceList()); break; case FormAction: result = new FormActionDirective(this.parseSourceList()); break; case FrameAncestors: result = new FrameAncestorsDirective(this.parseAncestorSourceList()); break; case ImgSrc: result = new ImgSrcDirective(this.parseSourceList()); break; case ManifestSrc: warnFutureDirective(token); result = new ManifestSrcDirective(this.parseSourceList()); break; case MediaSrc: result = new MediaSrcDirective(this.parseSourceList()); break; case ObjectSrc: result = new ObjectSrcDirective(this.parseSourceList()); break; case PluginTypes: Set<MediaType> mediaTypes = this.parseMediaTypeList(); if (mediaTypes.isEmpty()) { this.error(token, "The media-type-list must contain at least one media-type."); throw INVALID_MEDIA_TYPE_LIST; } result = new PluginTypesDirective(mediaTypes); break; case Referrer: warnFutureDirective(token); result = new ReferrerDirective(this.parseReferrerToken(token)); break; case ReportTo: result = new ReportToDirective(this.parseReportToToken(token)); break; case ReportUri: // TODO: bump to .warn once CSP3 becomes RC this.info(token, "A draft of the next version of CSP deprecates report-uri in favour of a new report-to directive."); Set<URI> uriList = this.parseUriList(); if (uriList.isEmpty()) { this.error(token, "The report-uri directive must contain at least one uri-reference."); throw INVALID_URI_REFERENCE_LIST; } result = new ReportUriDirective(uriList); break; case Sandbox: result = new SandboxDirective(this.parseSandboxTokenList()); break; case ScriptSrc: result = new ScriptSrcDirective(this.parseSourceList()); break; case StyleSrc: result = new StyleSrcDirective(this.parseSourceList()); break; case UpgradeInsecureRequests: warnFutureDirective(token); this.enforceMissingDirectiveValue(token); result = new UpgradeInsecureRequestsDirective(); break; case Allow: this.error(token, "The allow directive has been replaced with default-src and is not in the CSP specification."); this.eat(DirectiveValueToken.class); throw INVALID_DIRECTIVE_NAME; case FrameSrc: this.warn(token, "The frame-src directive is deprecated as of CSP version 1.1. Authors who wish to govern nested browsing contexts SHOULD use the child-src directive instead."); result = new FrameSrcDirective(this.parseSourceList()); break; case Options: this.error(token, "The options directive has been replaced with 'unsafe-inline' and 'unsafe-eval' and is not in the CSP specification."); this.eat(DirectiveValueToken.class); throw INVALID_DIRECTIVE_NAME; case Unrecognised: default: this.error(token, "Unrecognised directive-name: \"" + token.value + "\"."); this.eat(DirectiveValueToken.class); throw INVALID_DIRECTIVE_NAME; } } finally { if (this.hasNext(UnknownToken.class)) { Token t = this.advance(); int cp = t.value.codePointAt(0); this.error(t, String.format( "Expecting directive-value but found U+%04X (%s). Non-ASCII and non-printable characters must be percent-encoded.", cp, new String(new int[] {cp}, 0, 1))); throw INVALID_DIRECTIVE_VALUE; } } return result; } private void warnFutureDirective(DirectiveNameToken token) { this.warn(token, "The " + token.value + " directive is an experimental directive that will be likely added to the CSP specification."); } private void enforceMissingDirectiveValue(@Nonnull Token directiveNameToken) throws DirectiveParseException { if (this.eat(DirectiveValueToken.class)) { this.error(directiveNameToken, "The " + directiveNameToken.value + " directive must not contain any value."); throw NON_EMPTY_VALUE_TOKEN_LIST; } } @Nonnull private Set<MediaType> parseMediaTypeList() throws DirectiveParseException { Set<MediaType> mediaTypes = new LinkedHashSet<>(); boolean parseException = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { mediaTypes.add(this.parseMediaType()); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_MEDIA_TYPE_LIST; } return mediaTypes; } @Nonnull private MediaType parseMediaType() throws DirectiveValueParseException { Token token = this.advance(); Matcher matcher = Constants.mediaTypePattern.matcher(token.value); if (matcher.find()) { return new MediaType(matcher.group("type"), matcher.group("subtype")); } this.error(token, "Expecting media-type but found \"" + token.value + "\"."); throw INVALID_MEDIA_TYPE; } @Nonnull private Set<SourceExpression> parseSourceList() throws DirectiveParseException { Set<SourceExpression> sourceExpressions = new LinkedHashSet<>(); boolean parseException = false; boolean seenNone = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { SourceExpression se = this.parseSourceExpression(seenNone, !sourceExpressions.isEmpty()); if (se == None.INSTANCE) { seenNone = true; } sourceExpressions.add(se); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_SOURCE_LIST; } return sourceExpressions; } @Nonnull private SourceExpression parseSourceExpression(boolean seenNone, boolean seenSome) throws DirectiveValueParseException { Token token = this.advance(); if (seenNone || seenSome && token.value.equalsIgnoreCase("'none'")) { this.error(token, "'none' must not be combined with any other source-expression."); throw INVALID_SOURCE_EXPR; } switch (token.value.toLowerCase()) { case "'none'": return None.INSTANCE; case "'self'": return KeywordSource.Self; case "'unsafe-inline'": return KeywordSource.UnsafeInline; case "'unsafe-eval'": return KeywordSource.UnsafeEval; case "'unsafe-redirect'": this.warn(token, "'unsafe-redirect' has been removed from CSP as of version 2.0."); return KeywordSource.UnsafeRedirect; case "self": case "unsafe-inline": case "unsafe-eval": case "unsafe-redirect": case "none": this.warn(token, "This host name is unusual, and likely meant to be a keyword that is missing the required quotes: \'" + token.value.toLowerCase() + "\'."); default: if (token.value.startsWith("'nonce-")) { String nonce = token.value.substring(7, token.value.length() - 1); NonceSource nonceSource = new NonceSource(nonce); nonceSource.validationErrors().forEach(str -> this.warn(token, str)); return nonceSource; } else if (token.value.toLowerCase().startsWith("'sha")) { HashSource.HashAlgorithm algorithm; switch (token.value.substring(4, 7)) { case "256": algorithm = HashSource.HashAlgorithm.SHA256; break; case "384": algorithm = HashSource.HashAlgorithm.SHA384; break; case "512": algorithm = HashSource.HashAlgorithm.SHA512; break; default: this.error(token, "Unrecognised hash algorithm: \"" + token.value.substring(1, 7) + "\"."); throw INVALID_SOURCE_EXPR; } String value = token.value.substring(8, token.value.length() - 1); // convert url-safe base64 to RFC4648 base64 String safeValue = value.replace('-', '+').replace('_', '/'); Base64Value base64Value; try { base64Value = new Base64Value(safeValue); } catch (IllegalArgumentException e) { this.error(token, e.getMessage()); throw INVALID_SOURCE_EXPR; } // warn if value is not RFC4648 if (value.contains("-") || value.contains("_")) { this.warn(token, "Invalid base64-value (characters are not in the base64-value grammar). Consider using RFC4648 compliant base64 encoding implementation."); } HashSource hashSource = new HashSource(algorithm, base64Value); try { hashSource.validationErrors(); } catch (IllegalArgumentException e) { this.error(token, e.getMessage()); throw INVALID_SOURCE_EXPR; } return hashSource; } else if (token.value.matches("^" + Constants.schemePart + ":$")) { return new SchemeSource(token.value.substring(0, token.value.length() - 1)); } else { Matcher matcher = Constants.hostSourcePattern.matcher(token.value); if (matcher.find()) { String scheme = matcher.group("scheme"); if (scheme != null) scheme = scheme.substring(0, scheme.length() - 3); String portString = matcher.group("port"); int port; if (portString == null) { port = scheme == null ? Constants.EMPTY_PORT : SchemeHostPortTriple.defaultPortForProtocol(scheme); } else { port = portString.equals(":*") ? Constants.WILDCARD_PORT : Integer.parseInt(portString.substring(1)); } String host = matcher.group("host"); String path = matcher.group("path"); return new HostSource(scheme, host, port, path); } } } this.error(token, "Expecting source-expression but found \"" + token.value + "\"."); throw INVALID_SOURCE_EXPR; } @Nonnull private Set<AncestorSource> parseAncestorSourceList() throws DirectiveParseException { Set<AncestorSource> ancestorSources = new LinkedHashSet<>(); boolean parseException = false; boolean seenNone = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { AncestorSource ancestorSource = this.parseAncestorSource(seenNone, !ancestorSources.isEmpty()); if (ancestorSource == None.INSTANCE) { seenNone = true; } ancestorSources.add(ancestorSource); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_ANCESTOR_SOURCE_LIST; } return ancestorSources; } @Nonnull private AncestorSource parseAncestorSource(boolean seenNone, boolean seenSome) throws DirectiveValueParseException { Token token = this.advance(); if (seenNone || seenSome && token.value.equalsIgnoreCase("'none'")) { this.error(token, "'none' must not be combined with any other ancestor-source."); throw INVALID_ANCESTOR_SOURCE; } if (token.value.equalsIgnoreCase("'none'")) { return None.INSTANCE; } if (token.value.equalsIgnoreCase("'self'")) { return KeywordSource.Self; } if (token.value.matches("^" + Constants.schemePart + ":$")) { return new SchemeSource(token.value.substring(0, token.value.length() - 1)); } else { Matcher matcher = Constants.hostSourcePattern.matcher(token.value); if (matcher.find()) { String scheme = matcher.group("scheme"); if (scheme != null) scheme = scheme.substring(0, scheme.length() - 3); String portString = matcher.group("port"); int port; if (portString == null) { port = scheme == null ? Constants.EMPTY_PORT : SchemeHostPortTriple.defaultPortForProtocol(scheme); } else { port = portString.equals(":*") ? Constants.WILDCARD_PORT : Integer.parseInt(portString.substring(1)); } String host = matcher.group("host"); String path = matcher.group("path"); return new HostSource(scheme, host, port, path); } } this.error(token, "Expecting ancestor-source but found \"" + token.value + "\"."); throw INVALID_ANCESTOR_SOURCE; } @Nonnull private ReferrerValue parseReferrerToken(@Nonnull Token directiveNameToken) throws DirectiveParseException { if (this.hasNext(DirectiveValueToken.class)) { Token token = this.advance(); Matcher matcher = Constants.referrerTokenPattern.matcher(Tokeniser.trimRHSWS(token.value)); if (matcher.find()) { return new ReferrerValue(token.value); } this.error(token, "Expecting referrer directive value but found \"" + token.value + "\"."); } else { this.error(directiveNameToken, "The referrer directive must contain exactly one referrer directive value."); throw INVALID_DIRECTIVE_VALUE; } throw INVALID_REFERRER_TOKEN; } @Nonnull private ReportToValue parseReportToToken(@Nonnull Token directiveNameToken) throws DirectiveParseException { if (this.hasNext(DirectiveValueToken.class)) { Token token = this.advance(); Matcher matcher = Constants.rfc7230TokenPattern.matcher(Tokeniser.trimRHSWS(token.value)); if (matcher.find()) { return new ReportToValue(token.value); } this.error(token, "Expecting RFC 7230 token but found \"" + token.value + "\"."); } else { this.error(directiveNameToken, "The report-to must contain exactly one RFC 7230 token."); } throw INVALID_REPORT_TO_TOKEN; } @Nonnull private Set<SandboxValue> parseSandboxTokenList() throws DirectiveParseException { Set<SandboxValue> sandboxTokens = new LinkedHashSet<>(); boolean parseException = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { sandboxTokens.add(this.parseSandboxToken()); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_SANDBOX_TOKEN_LIST; } return sandboxTokens; } @Nonnull private SandboxValue parseSandboxToken() throws DirectiveValueParseException { Token token = this.advance(); Matcher matcher = Constants.sandboxEnumeratedTokenPattern.matcher(token.value); if (matcher.find()) { return new SandboxValue(token.value); } else { this.warn(token, "The sandbox directive should contain only allow-forms, allow-modals, " + "allow-pointer-lock, allow-popups, allow-popups-to-escape-sandbox, " + "allow-same-origin, allow-scripts, or allow-top-navigation."); matcher = Constants.rfc7230TokenPattern.matcher(token.value); if (matcher.find()) { return new SandboxValue(token.value); } } this.error(token, "Expecting RFC 7230 token but found \"" + token.value + "\"."); throw INVALID_SANDBOX_TOKEN; } @Nonnull private Set<URI> parseUriList() throws DirectiveParseException { Set<URI> uriList = new LinkedHashSet<>(); boolean parseException = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { uriList.add(this.parseUri()); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_URI_REFERENCE_LIST; } return uriList; } @Nonnull private URI parseUri() throws DirectiveValueParseException { Token token = this.advance(); try { return URI.parseWithOrigin(this.origin, token.value); } catch (IllegalArgumentException ignored) { this.error(token, "Expecting uri-reference but found \"" + token.value + "\"."); throw INVALID_URI_REFERENCE; } } private static class DirectiveParseException extends Exception { @Nullable Location startLocation; @Nullable Location endLocation; private DirectiveParseException(@Nonnull String message) { super(message); } @Nonnull @Override public String getMessage() { if (startLocation == null) { return super.getMessage(); } return startLocation.show() + ": " + super.getMessage(); } } protected static class DirectiveValueParseException extends Exception { @Nullable Location startLocation; @Nullable Location endLocation; private DirectiveValueParseException(@Nonnull String message) { super(message); } @Nonnull @Override public String getMessage() { if (startLocation == null) { return super.getMessage(); } return startLocation.show() + ": " + super.getMessage(); } } }
src/main/java/com/shapesecurity/salvation/Parser.java
package com.shapesecurity.salvation; import com.shapesecurity.salvation.data.*; import com.shapesecurity.salvation.directiveValues.*; import com.shapesecurity.salvation.directives.*; import com.shapesecurity.salvation.tokens.*; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Parser { private static final DirectiveParseException MISSING_DIRECTIVE_NAME = new DirectiveParseException("Missing directive-name"); private static final DirectiveParseException INVALID_DIRECTIVE_NAME = new DirectiveParseException("Invalid directive-name"); private static final DirectiveParseException INVALID_DIRECTIVE_VALUE = new DirectiveParseException("Invalid directive-value"); private static final DirectiveParseException INVALID_MEDIA_TYPE_LIST = new DirectiveParseException("Invalid media-type-list"); private static final DirectiveValueParseException INVALID_MEDIA_TYPE = new DirectiveValueParseException("Invalid media-type"); private static final DirectiveParseException INVALID_SOURCE_LIST = new DirectiveParseException("Invalid source-list"); private static final DirectiveValueParseException INVALID_SOURCE_EXPR = new DirectiveValueParseException("Invalid source-expression"); private static final DirectiveParseException INVALID_ANCESTOR_SOURCE_LIST = new DirectiveParseException("Invalid ancestor-source-list"); private static final DirectiveValueParseException INVALID_ANCESTOR_SOURCE = new DirectiveValueParseException("Invalid ancestor-source"); private static final DirectiveParseException INVALID_REFERRER_TOKEN = new DirectiveParseException("Invalid referrer-token"); private static final DirectiveParseException INVALID_REPORT_TO_TOKEN = new DirectiveParseException("Invalid report-to token"); private static final DirectiveParseException INVALID_SANDBOX_TOKEN_LIST = new DirectiveParseException("Invalid sandbox-token list"); private static final DirectiveValueParseException INVALID_SANDBOX_TOKEN = new DirectiveValueParseException("Invalid sandbox-token"); private static final DirectiveParseException INVALID_URI_REFERENCE_LIST = new DirectiveParseException("Invalid uri-reference list"); private static final DirectiveValueParseException INVALID_URI_REFERENCE = new DirectiveValueParseException("Invalid uri-reference"); private static final DirectiveParseException NON_EMPTY_VALUE_TOKEN_LIST = new DirectiveParseException("Non-empty directive-value list"); @Nonnull protected final Token[] tokens; @Nonnull private final Origin origin; protected int index = 0; @Nullable protected Collection<Notice> noticesOut; protected Parser(@Nonnull Token[] tokens, @Nonnull Origin origin, @Nullable Collection<Notice> noticesOut) { this.origin = origin; this.tokens = tokens; this.noticesOut = noticesOut; } @Nonnull public static Policy parse(@Nonnull String sourceText, @Nonnull Origin origin) { return new Parser(Tokeniser.tokenise(sourceText), origin, null).parsePolicyAndAssertEOF(); } @Nonnull public static Policy parse(@Nonnull String sourceText, @Nonnull String origin) { return new Parser(Tokeniser.tokenise(sourceText), URI.parse(origin), null).parsePolicyAndAssertEOF(); } @Nonnull public static Policy parse(@Nonnull String sourceText, @Nonnull Origin origin, @Nonnull Collection<Notice> warningsOut) { return new Parser(Tokeniser.tokenise(sourceText), origin, warningsOut).parsePolicyAndAssertEOF(); } @Nonnull public static Policy parse(@Nonnull String sourceText, @Nonnull String origin, @Nonnull Collection<Notice> warningsOut) { return new Parser(Tokeniser.tokenise(sourceText), URI.parse(origin), warningsOut).parsePolicyAndAssertEOF(); } @Nonnull public static List<Policy> parseMulti(@Nonnull String sourceText, @Nonnull Origin origin) { return new Parser(Tokeniser.tokenise(sourceText), origin, null).parsePolicyListAndAssertEOF(); } @Nonnull public static List<Policy> parseMulti(@Nonnull String sourceText, @Nonnull String origin) { return new Parser(Tokeniser.tokenise(sourceText), URI.parse(origin), null).parsePolicyListAndAssertEOF(); } @Nonnull public static List<Policy> parseMulti(@Nonnull String sourceText, @Nonnull Origin origin, @Nonnull Collection<Notice> warningsOut) { return new Parser(Tokeniser.tokenise(sourceText), origin, warningsOut).parsePolicyListAndAssertEOF(); } @Nonnull public static List<Policy> parseMulti(@Nonnull String sourceText, @Nonnull String origin, @Nonnull Collection<Notice> warningsOut) { return new Parser(Tokeniser.tokenise(sourceText), URI.parse(origin), warningsOut).parsePolicyListAndAssertEOF(); } @Nonnull protected Notice createNotice(@Nonnull Notice.Type type, @Nonnull String message) { return new Notice(type, message); } @Nonnull protected Notice createNotice(@Nullable Token token, @Nonnull Notice.Type type, @Nonnull String message) { return new Notice(type, message); } private void warn(@Nullable Token token, @Nonnull String message) { if (this.noticesOut != null) { this.noticesOut.add(this.createNotice(token, Notice.Type.WARNING, message)); } } private void error(@Nullable Token token, @Nonnull String message) { if (this.noticesOut != null) { this.noticesOut.add(this.createNotice(token, Notice.Type.ERROR, message)); } } private void info(@Nullable Token token, @Nonnull String message) { if (this.noticesOut != null) { this.noticesOut.add(this.createNotice(token, Notice.Type.INFO, message)); } } @Nonnull private Token advance() { return this.tokens[this.index++]; } protected boolean hasNext() { return this.index < this.tokens.length; } private boolean hasNext(@Nonnull Class<? extends Token> c) { return this.hasNext() && c.isAssignableFrom(this.tokens[this.index].getClass()); } private boolean eat(@Nonnull Class<? extends Token> c) { if (this.hasNext(c)) { this.advance(); return true; } return false; } @Nonnull protected DirectiveValueParseException createError(@Nonnull String message) { return new DirectiveValueParseException(message); } @Nonnull protected Policy parsePolicy() { Policy policy = new Policy(this.origin); while (this.hasNext()) { if (this.hasNext(PolicySeparatorToken.class)) break; if (this.eat(DirectiveSeparatorToken.class)) continue; try { policy.addDirective(this.parseDirective()); } catch (DirectiveParseException ignored) { } } return policy; } @Nonnull protected Policy parsePolicyAndAssertEOF() { Policy policy = this.parsePolicy(); if (this.hasNext()) { Token t = this.advance(); this.error(t, "Expecting end of policy but found \"" + t.value + "\"."); } return policy; } @Nonnull protected List<Policy> parsePolicyList() { List<Policy> policies = new ArrayList<>(); policies.add(this.parsePolicy()); while (this.hasNext(PolicySeparatorToken.class)) { while (this.eat(PolicySeparatorToken.class)) ; policies.add(this.parsePolicy()); } return policies; } @Nonnull protected List<Policy> parsePolicyListAndAssertEOF() { List<Policy> policies = this.parsePolicyList(); if (this.hasNext()) { Token t = this.advance(); this.error(t, "Expecting end of policy list but found \"" + t.value + "\"."); } return policies; } @Nonnull private Directive<?> parseDirective() throws DirectiveParseException { if (!this.hasNext(DirectiveNameToken.class)) { Token t = this.advance(); this.error(t, "Expecting directive-name but found \"" + t.value.split(" ", 2)[0] + "\"."); throw MISSING_DIRECTIVE_NAME; } Directive result; DirectiveNameToken token = (DirectiveNameToken) this.advance(); try { switch (token.subtype) { case BaseUri: result = new BaseUriDirective(this.parseSourceList()); break; case BlockAllMixedContent: warnFutureDirective(token); this.enforceMissingDirectiveValue(token); result = new BlockAllMixedContentDirective(); break; case ChildSrc: result = new ChildSrcDirective(this.parseSourceList()); break; case ConnectSrc: result = new ConnectSrcDirective(this.parseSourceList()); break; case DefaultSrc: result = new DefaultSrcDirective(this.parseSourceList()); break; case FontSrc: result = new FontSrcDirective(this.parseSourceList()); break; case FormAction: result = new FormActionDirective(this.parseSourceList()); break; case FrameAncestors: result = new FrameAncestorsDirective(this.parseAncestorSourceList()); break; case ImgSrc: result = new ImgSrcDirective(this.parseSourceList()); break; case ManifestSrc: warnFutureDirective(token); result = new ManifestSrcDirective(this.parseSourceList()); break; case MediaSrc: result = new MediaSrcDirective(this.parseSourceList()); break; case ObjectSrc: result = new ObjectSrcDirective(this.parseSourceList()); break; case PluginTypes: Set<MediaType> mediaTypes = this.parseMediaTypeList(); if (mediaTypes.isEmpty()) { this.error(token, "The media-type-list must contain at least one media-type."); throw INVALID_MEDIA_TYPE_LIST; } result = new PluginTypesDirective(mediaTypes); break; case Referrer: warnFutureDirective(token); result = new ReferrerDirective(this.parseReferrerToken(token)); break; case ReportTo: result = new ReportToDirective(this.parseReportToToken(token)); break; case ReportUri: // TODO: bump to .warn once CSP3 becomes RC this.info(token, "A draft of the next version of CSP deprecates report-uri in favour of a new report-to directive."); Set<URI> uriList = this.parseUriList(); if (uriList.isEmpty()) { this.error(token, "The report-uri directive must contain at least one uri-reference."); throw INVALID_URI_REFERENCE_LIST; } result = new ReportUriDirective(uriList); break; case Sandbox: result = new SandboxDirective(this.parseSandboxTokenList()); break; case ScriptSrc: result = new ScriptSrcDirective(this.parseSourceList()); break; case StyleSrc: result = new StyleSrcDirective(this.parseSourceList()); break; case UpgradeInsecureRequests: warnFutureDirective(token); this.enforceMissingDirectiveValue(token); result = new UpgradeInsecureRequestsDirective(); break; case Allow: this.error(token, "The allow directive has been replaced with default-src and is not in the CSP specification."); if (this.hasNext(DirectiveValueToken.class)) this.advance(); throw INVALID_DIRECTIVE_NAME; case FrameSrc: this.warn(token, "The frame-src directive is deprecated as of CSP version 1.1. Authors who wish to govern nested browsing contexts SHOULD use the child-src directive instead."); result = new FrameSrcDirective(this.parseSourceList()); break; case Options: this.error(token, "The options directive has been replaced with 'unsafe-inline' and 'unsafe-eval' and is not in the CSP specification."); if (this.hasNext(DirectiveValueToken.class)) this.advance(); throw INVALID_DIRECTIVE_NAME; case Unrecognised: default: this.error(token, "Unrecognised directive-name: \"" + token.value + "\"."); if (this.hasNext(DirectiveValueToken.class)) this.advance(); throw INVALID_DIRECTIVE_NAME; } } finally { if (this.hasNext(UnknownToken.class)) { Token t = this.advance(); int cp = t.value.codePointAt(0); this.error(t, String.format( "Expecting directive-value but found U+%04X (%s). Non-ASCII and non-printable characters must be percent-encoded.", cp, new String(new int[] {cp}, 0, 1))); throw INVALID_DIRECTIVE_VALUE; } } return result; } private void warnFutureDirective(DirectiveNameToken token) { this.warn(token, "The " + token.value + " directive is an experimental directive that will be likely added to the CSP specification."); } private void enforceMissingDirectiveValue(@Nonnull Token directiveNameToken) throws DirectiveParseException { if (this.eat(DirectiveValueToken.class)) { this.error(directiveNameToken, "The " + directiveNameToken.value + " directive must not contain any value."); throw NON_EMPTY_VALUE_TOKEN_LIST; } } @Nonnull private Set<MediaType> parseMediaTypeList() throws DirectiveParseException { Set<MediaType> mediaTypes = new LinkedHashSet<>(); boolean parseException = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { mediaTypes.add(this.parseMediaType()); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_MEDIA_TYPE_LIST; } return mediaTypes; } @Nonnull private MediaType parseMediaType() throws DirectiveValueParseException { Token token = this.advance(); Matcher matcher = Constants.mediaTypePattern.matcher(token.value); if (matcher.find()) { return new MediaType(matcher.group("type"), matcher.group("subtype")); } this.error(token, "Expecting media-type but found \"" + token.value + "\"."); throw INVALID_MEDIA_TYPE; } @Nonnull private Set<SourceExpression> parseSourceList() throws DirectiveParseException { Set<SourceExpression> sourceExpressions = new LinkedHashSet<>(); boolean parseException = false; boolean seenNone = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { SourceExpression se = this.parseSourceExpression(seenNone, !sourceExpressions.isEmpty()); if (se == None.INSTANCE) { seenNone = true; } sourceExpressions.add(se); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_SOURCE_LIST; } return sourceExpressions; } @Nonnull private SourceExpression parseSourceExpression(boolean seenNone, boolean seenSome) throws DirectiveValueParseException { Token token = this.advance(); if (seenNone || seenSome && token.value.equalsIgnoreCase("'none'")) { this.error(token, "'none' must not be combined with any other source-expression."); throw INVALID_SOURCE_EXPR; } switch (token.value.toLowerCase()) { case "'none'": return None.INSTANCE; case "'self'": return KeywordSource.Self; case "'unsafe-inline'": return KeywordSource.UnsafeInline; case "'unsafe-eval'": return KeywordSource.UnsafeEval; case "'unsafe-redirect'": this.warn(token, "'unsafe-redirect' has been removed from CSP as of version 2.0."); return KeywordSource.UnsafeRedirect; case "self": case "unsafe-inline": case "unsafe-eval": case "unsafe-redirect": case "none": this.warn(token, "This host name is unusual, and likely meant to be a keyword that is missing the required quotes: \'" + token.value.toLowerCase() + "\'."); default: if (token.value.startsWith("'nonce-")) { String nonce = token.value.substring(7, token.value.length() - 1); NonceSource nonceSource = new NonceSource(nonce); nonceSource.validationErrors().forEach(str -> this.warn(token, str)); return nonceSource; } else if (token.value.toLowerCase().startsWith("'sha")) { HashSource.HashAlgorithm algorithm; switch (token.value.substring(4, 7)) { case "256": algorithm = HashSource.HashAlgorithm.SHA256; break; case "384": algorithm = HashSource.HashAlgorithm.SHA384; break; case "512": algorithm = HashSource.HashAlgorithm.SHA512; break; default: this.error(token, "Unrecognised hash algorithm: \"" + token.value.substring(1, 7) + "\"."); throw INVALID_SOURCE_EXPR; } String value = token.value.substring(8, token.value.length() - 1); // convert url-safe base64 to RFC4648 base64 String safeValue = value.replace('-', '+').replace('_', '/'); Base64Value base64Value; try { base64Value = new Base64Value(safeValue); } catch (IllegalArgumentException e) { this.error(token, e.getMessage()); throw INVALID_SOURCE_EXPR; } // warn if value is not RFC4648 if (value.contains("-") || value.contains("_")) { this.warn(token, "Invalid base64-value (characters are not in the base64-value grammar). Consider using RFC4648 compliant base64 encoding implementation."); } HashSource hashSource = new HashSource(algorithm, base64Value); try { hashSource.validationErrors(); } catch (IllegalArgumentException e) { this.error(token, e.getMessage()); throw INVALID_SOURCE_EXPR; } return hashSource; } else if (token.value.matches("^" + Constants.schemePart + ":$")) { return new SchemeSource(token.value.substring(0, token.value.length() - 1)); } else { Matcher matcher = Constants.hostSourcePattern.matcher(token.value); if (matcher.find()) { String scheme = matcher.group("scheme"); if (scheme != null) scheme = scheme.substring(0, scheme.length() - 3); String portString = matcher.group("port"); int port; if (portString == null) { port = scheme == null ? Constants.EMPTY_PORT : SchemeHostPortTriple.defaultPortForProtocol(scheme); } else { port = portString.equals(":*") ? Constants.WILDCARD_PORT : Integer.parseInt(portString.substring(1)); } String host = matcher.group("host"); String path = matcher.group("path"); return new HostSource(scheme, host, port, path); } } } this.error(token, "Expecting source-expression but found \"" + token.value + "\"."); throw INVALID_SOURCE_EXPR; } @Nonnull private Set<AncestorSource> parseAncestorSourceList() throws DirectiveParseException { Set<AncestorSource> ancestorSources = new LinkedHashSet<>(); boolean parseException = false; boolean seenNone = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { AncestorSource ancestorSource = this.parseAncestorSource(seenNone, !ancestorSources.isEmpty()); if (ancestorSource == None.INSTANCE) { seenNone = true; } ancestorSources.add(ancestorSource); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_ANCESTOR_SOURCE_LIST; } return ancestorSources; } @Nonnull private AncestorSource parseAncestorSource(boolean seenNone, boolean seenSome) throws DirectiveValueParseException { Token token = this.advance(); if (seenNone || seenSome && token.value.equalsIgnoreCase("'none'")) { this.error(token, "'none' must not be combined with any other ancestor-source."); throw INVALID_ANCESTOR_SOURCE; } if (token.value.equalsIgnoreCase("'none'")) { return None.INSTANCE; } if (token.value.equalsIgnoreCase("'self'")) { return KeywordSource.Self; } if (token.value.matches("^" + Constants.schemePart + ":$")) { return new SchemeSource(token.value.substring(0, token.value.length() - 1)); } else { Matcher matcher = Constants.hostSourcePattern.matcher(token.value); if (matcher.find()) { String scheme = matcher.group("scheme"); if (scheme != null) scheme = scheme.substring(0, scheme.length() - 3); String portString = matcher.group("port"); int port; if (portString == null) { port = scheme == null ? Constants.EMPTY_PORT : SchemeHostPortTriple.defaultPortForProtocol(scheme); } else { port = portString.equals(":*") ? Constants.WILDCARD_PORT : Integer.parseInt(portString.substring(1)); } String host = matcher.group("host"); String path = matcher.group("path"); return new HostSource(scheme, host, port, path); } } this.error(token, "Expecting ancestor-source but found \"" + token.value + "\"."); throw INVALID_ANCESTOR_SOURCE; } @Nonnull private ReferrerValue parseReferrerToken(@Nonnull Token directiveNameToken) throws DirectiveParseException { if (this.hasNext(DirectiveValueToken.class)) { Token token = this.advance(); Matcher matcher = Constants.referrerTokenPattern.matcher(Tokeniser.trimRHSWS(token.value)); if (matcher.find()) { return new ReferrerValue(token.value); } this.error(token, "Expecting referrer directive value but found \"" + token.value + "\"."); } else { this.error(directiveNameToken, "The referrer directive must contain exactly one referrer directive value."); throw INVALID_DIRECTIVE_VALUE; } throw INVALID_REFERRER_TOKEN; } @Nonnull private ReportToValue parseReportToToken(@Nonnull Token directiveNameToken) throws DirectiveParseException { if (this.hasNext(DirectiveValueToken.class)) { Token token = this.advance(); Matcher matcher = Constants.rfc7230TokenPattern.matcher(Tokeniser.trimRHSWS(token.value)); if (matcher.find()) { return new ReportToValue(token.value); } this.error(token, "Expecting RFC 7230 token but found \"" + token.value + "\"."); } else { this.error(directiveNameToken, "The report-to must contain exactly one RFC 7230 token."); } throw INVALID_REPORT_TO_TOKEN; } @Nonnull private Set<SandboxValue> parseSandboxTokenList() throws DirectiveParseException { Set<SandboxValue> sandboxTokens = new LinkedHashSet<>(); boolean parseException = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { sandboxTokens.add(this.parseSandboxToken()); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_SANDBOX_TOKEN_LIST; } return sandboxTokens; } @Nonnull private SandboxValue parseSandboxToken() throws DirectiveValueParseException { Token token = this.advance(); Matcher matcher = Constants.sandboxEnumeratedTokenPattern.matcher(token.value); if (matcher.find()) { return new SandboxValue(token.value); } else { this.warn(token, "The sandbox directive should contain only allow-forms, allow-modals, " + "allow-pointer-lock, allow-popups, allow-popups-to-escape-sandbox, " + "allow-same-origin, allow-scripts, or allow-top-navigation."); matcher = Constants.rfc7230TokenPattern.matcher(token.value); if (matcher.find()) { return new SandboxValue(token.value); } } this.error(token, "Expecting RFC 7230 token but found \"" + token.value + "\"."); throw INVALID_SANDBOX_TOKEN; } @Nonnull private Set<URI> parseUriList() throws DirectiveParseException { Set<URI> uriList = new LinkedHashSet<>(); boolean parseException = false; while (this.hasNext(SubDirectiveValueToken.class)) { try { uriList.add(this.parseUri()); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_URI_REFERENCE_LIST; } return uriList; } @Nonnull private URI parseUri() throws DirectiveValueParseException { Token token = this.advance(); try { return URI.parseWithOrigin(this.origin, token.value); } catch (IllegalArgumentException ignored) { this.error(token, "Expecting uri-reference but found \"" + token.value + "\"."); throw INVALID_URI_REFERENCE; } } private static class DirectiveParseException extends Exception { @Nullable Location startLocation; @Nullable Location endLocation; private DirectiveParseException(@Nonnull String message) { super(message); } @Nonnull @Override public String getMessage() { if (startLocation == null) { return super.getMessage(); } return startLocation.show() + ": " + super.getMessage(); } } protected static class DirectiveValueParseException extends Exception { @Nullable Location startLocation; @Nullable Location endLocation; private DirectiveValueParseException(@Nonnull String message) { super(message); } @Nonnull @Override public String getMessage() { if (startLocation == null) { return super.getMessage(); } return startLocation.show() + ": " + super.getMessage(); } } }
use `eat` when applicable
src/main/java/com/shapesecurity/salvation/Parser.java
use `eat` when applicable
<ide><path>rc/main/java/com/shapesecurity/salvation/Parser.java <ide> case Allow: <ide> this.error(token, <ide> "The allow directive has been replaced with default-src and is not in the CSP specification."); <del> if (this.hasNext(DirectiveValueToken.class)) <del> this.advance(); <add> this.eat(DirectiveValueToken.class); <ide> throw INVALID_DIRECTIVE_NAME; <ide> case FrameSrc: <ide> this.warn(token, <ide> case Options: <ide> this.error(token, <ide> "The options directive has been replaced with 'unsafe-inline' and 'unsafe-eval' and is not in the CSP specification."); <del> if (this.hasNext(DirectiveValueToken.class)) <del> this.advance(); <add> this.eat(DirectiveValueToken.class); <ide> throw INVALID_DIRECTIVE_NAME; <ide> case Unrecognised: <ide> default: <ide> this.error(token, "Unrecognised directive-name: \"" + token.value + "\"."); <del> if (this.hasNext(DirectiveValueToken.class)) <del> this.advance(); <add> this.eat(DirectiveValueToken.class); <ide> throw INVALID_DIRECTIVE_NAME; <ide> } <ide> } finally {
Java
apache-2.0
a3bdaedbfe3aa053157095550969e3a1df2899d7
0
spring-cloud/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.dataflow.composedtaskrunner; import java.net.URI; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.cloud.dataflow.composedtaskrunner.properties.ComposedTaskProperties; import org.springframework.cloud.dataflow.core.dsl.TaskAppNode; import org.springframework.cloud.dataflow.core.dsl.TaskParser; import org.springframework.cloud.dataflow.core.dsl.TaskVisitor; import org.springframework.cloud.dataflow.core.dsl.TransitionNode; import org.springframework.cloud.dataflow.rest.util.DeploymentPropertiesUtils; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotationMetadata; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.util.StringUtils; /** * Creates the Steps necessary to execute the directed graph of a Composed * Task. * * @author Michael Minella * @author Glenn Renfro * @author Ilayaperumal Gopinathan */ public class StepBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware { private final static Logger log = LoggerFactory.getLogger(StepBeanDefinitionRegistrar.class); private Environment env; private boolean firstAdd; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { ComposedTaskProperties properties = composedTaskProperties(); String ctrName = this.env.getProperty("spring.cloud.task.name"); if(ctrName == null) { throw new IllegalStateException("spring.cloud.task.name property must have a value."); } TaskParser taskParser = new TaskParser("bean-registration", properties.getGraph(), false, true); Map<String, TaskAppNodeHolder> taskSuffixMap = getTaskApps(taskParser); for (String taskName : taskSuffixMap.keySet()) { // handles the possibility that multiple instances of // task definition exist in a composed task for (int taskSuffix = 0; taskSuffixMap.get(taskName).count >= taskSuffix; taskSuffix++) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .rootBeanDefinition(ComposedTaskRunnerStepFactory.class); builder.addConstructorArgValue(properties); builder.addConstructorArgValue(String.format("%s_%s", taskName, taskSuffix)); builder.addConstructorArgValue(taskName.replaceFirst(ctrName + "-", "")); builder.addPropertyValue("taskSpecificProps", getPropertiesForTask(taskName, properties, taskSuffixMap.get(taskName))); String args = getCommandLineArgsForTask(properties.getComposedTaskArguments(), taskName, taskSuffixMap, ctrName); builder.addPropertyValue("arguments", args); registry.registerBeanDefinition(String.format("%s_%s", taskName, taskSuffix), builder.getBeanDefinition()); } } } private String getCommandLineArgsForTask(String arguments, String taskName, Map<String, TaskAppNodeHolder> taskSuffixMap, String ctrName ) { String result = ""; if(!StringUtils.hasText(arguments)) { return arguments; } if(arguments.startsWith("\"") && arguments.endsWith("\"")) { arguments = arguments.substring(1, arguments.length() - 1); } arguments = arguments.replace('\n', ' ').replace('\t', ' '); this.firstAdd = true; try { String[] args = CommandLineUtils.translateCommandline(arguments); String taskNamePrefix = taskName + "."; String taskNameNonIdentify = "--" + taskNamePrefix; for(String commandLineArg : Arrays.asList(args)) { String userPrefix = getPrefix(commandLineArg); String commandLineArgPrefix = ctrName + "-" + userPrefix; String commandLineArgToken = commandLineArgPrefix + "."; if(commandLineArgToken.equals(taskNameNonIdentify) || commandLineArgToken.equals(taskNamePrefix)) { result = addBlankToCommandLineArgs(result); if(commandLineArg.startsWith(userPrefix)) { result = result.concat(commandLineArg.substring(userPrefix.length() + 1)); } else { result = result + "--" + commandLineArg.substring(userPrefix.length() + 3); } continue; } if(!taskSuffixMap.containsKey(commandLineArgPrefix)) { result = addBlankToCommandLineArgs(result); if(commandLineArg.contains(" ")) { commandLineArg = commandLineArg.substring(0, commandLineArg.indexOf("=")) + "=\"" + commandLineArg.substring(commandLineArg.indexOf("=") + 1 )+ "\""; } result = result.concat(commandLineArg); } } } catch (Exception e) { throw new IllegalArgumentException("Unable to extract command line args for task " + taskName, e); } return result; } private String addBlankToCommandLineArgs(String commandArgs) { String result = commandArgs; if(firstAdd) { this.firstAdd = false; } else { result = result.concat(" "); } return result; } private String getPrefix(String commandLineArg) { String commandLineArgPrefix = (!commandLineArg.contains("="))? commandLineArg : commandLineArg.substring(0, commandLineArg.indexOf("=")); int indexOfSeparator = commandLineArgPrefix.indexOf("."); if(indexOfSeparator > -1) { commandLineArgPrefix = commandLineArg.substring(0, indexOfSeparator); } if(commandLineArgPrefix.startsWith("--")) { commandLineArgPrefix = commandLineArgPrefix.substring(2); } return commandLineArgPrefix; } private Map<String, String> getPropertiesForTask(String taskName, ComposedTaskProperties properties, TaskAppNodeHolder holder) { Map<String, String> taskDeploymentProperties = DeploymentPropertiesUtils.parse(properties.getComposedTaskProperties()); Map<String, String> deploymentProperties = new HashMap<>(); updateDeploymentProperties(String.format("app.%s.", taskName), taskDeploymentProperties, deploymentProperties); updateDeploymentProperties(String.format("deployer.%s.", taskName), taskDeploymentProperties, deploymentProperties); String subTaskName = taskName.substring(taskName.indexOf('-') + 1); updateVersionDeploymentProperties(taskName, subTaskName, taskDeploymentProperties, deploymentProperties); return deploymentProperties; } private void updateDeploymentProperties(String prefix, Map<String, String> taskDeploymentProperties, Map<String, String> deploymentProperties) { for (Map.Entry<String, String> entry : taskDeploymentProperties.entrySet()) { if (entry.getKey().startsWith(prefix)) { deploymentProperties.put(entry.getKey() .substring(prefix.length()), entry.getValue()); } } } private void updateVersionDeploymentProperties(String taskName,String subTaskName, Map<String, String> taskDeploymentProperties, Map<String, String> deploymentProperties) { String prefix = String.format("version.%s", taskName); String key = String.format("version.%s", subTaskName); for (Map.Entry<String, String> entry : taskDeploymentProperties.entrySet()) { if (entry.getKey().startsWith(prefix)) { String realkey = String.format("version%s", entry.getKey().replaceFirst("^" + prefix, "")); log.debug("updateVersionDeploymentProperties {} {} {}", key, entry.getValue(), realkey); deploymentProperties.put(realkey, entry.getValue()); } } } @Override public void setEnvironment(Environment environment) { this.env = environment; } private ComposedTaskProperties composedTaskProperties() { ComposedTaskProperties properties = new ComposedTaskProperties(); String skipTlsCertificateVerification = getPropertyValue("skip-tls-certificate-verification"); if (skipTlsCertificateVerification != null) { properties.setSkipTlsCertificateVerification(Boolean.parseBoolean(skipTlsCertificateVerification)); } String dataFlowUriString = getPropertyValue("dataflow-server-uri"); if (dataFlowUriString != null) { properties.setDataflowServerUri(URI.create(dataFlowUriString)); } String maxWaitTime = getPropertyValue("max-wait-time"); if (maxWaitTime != null) { properties.setMaxWaitTime(Integer.parseInt(maxWaitTime)); } String intervalTimeBetweenChecks = getPropertyValue("interval-time-between-checks"); if (intervalTimeBetweenChecks != null) { properties.setIntervalTimeBetweenChecks(Integer.parseInt(intervalTimeBetweenChecks)); } properties.setGraph(getPropertyValue("graph")); properties.setComposedTaskArguments(getPropertyValue("composed-task-arguments")); properties.setPlatformName(getPropertyValue("platform-name")); properties.setComposedTaskProperties(getPropertyValue("composed-task-properties")); properties.setDataflowServerAccessToken(getPropertyValue("dataflow-server-access-token")); properties.setDataflowServerPassword(getPropertyValue("dataflow-server-password")); properties.setDataflowServerUsername(getPropertyValue("dataflow-server-username")); properties.setOauth2ClientCredentialsClientId(getPropertyValue("oauth2-client-credentials-client-id")); properties.setOauth2ClientCredentialsClientSecret(getPropertyValue("oauth2-client-credential-client-secret")); String oauth2ClientCredentialsClientAuthenticationMethodAsString = getPropertyValue("oauth2-client-credential-client-authentication-method"); if (oauth2ClientCredentialsClientAuthenticationMethodAsString != null) { properties.setOauth2ClientCredentialsClientAuthenticationMethod(new ClientAuthenticationMethod(oauth2ClientCredentialsClientAuthenticationMethodAsString)); } properties.setOauth2ClientCredentialsScopes(StringUtils.commaDelimitedListToSet(getPropertyValue("oauth2-client-credentials-scopes"))); return properties; } /** * @return a {@link Map} of task app name as the key and the number of times it occurs * as the value. */ private Map<String, TaskAppNodeHolder> getTaskApps(TaskParser taskParser) { TaskAppsMapCollector collector = new TaskAppsMapCollector(); taskParser.parse().accept(collector); return collector.getTaskApps(); } private String getPropertyValue(String key) { RelaxedNames relaxedNames = new RelaxedNames(key); String result = null; Iterator<String> iter = relaxedNames.iterator(); while(iter.hasNext()) { String relaxedName = iter.next(); if (this.env.containsProperty(relaxedName)) { result = this.env.getProperty(relaxedName); break; } } return result; } /** * Simple visitor that discovers all the tasks in use in the composed * task definition. */ static class TaskAppsMapCollector extends TaskVisitor { Map<String, TaskAppNodeHolder> taskApps = new HashMap<>(); @Override public void visit(TaskAppNode taskApp) { if (taskApps.containsKey(taskApp.getName())) { int updatedCount = taskApps.get(taskApp.getName()).count + 1; taskApps.put(taskApp.getName(), new TaskAppNodeHolder(taskApp, updatedCount)); } else { taskApps.put(taskApp.getName(), new TaskAppNodeHolder(taskApp, 0)); } } @Override public void visit(TransitionNode transition) { if (transition.isTargetApp()) { if (taskApps.containsKey(transition.getTargetApp().getName())) { int updatedCount = taskApps.get(transition.getTargetApp().getName()).count + 1; taskApps.put(transition.getTargetApp().getName(), new TaskAppNodeHolder(transition.getTargetApp(), updatedCount)); } else { taskApps.put(transition.getTargetApp().getName(), new TaskAppNodeHolder(transition.getTargetApp(), 0)); } } } public Map<String, TaskAppNodeHolder> getTaskApps() { return taskApps; } } static class TaskAppNodeHolder { TaskAppNode taskAppNode; int count; TaskAppNodeHolder(TaskAppNode taskAppNode, int count) { this.taskAppNode = taskAppNode; this.count = count; } } }
spring-cloud-dataflow-composed-task-runner/src/main/java/org/springframework/cloud/dataflow/composedtaskrunner/StepBeanDefinitionRegistrar.java
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.dataflow.composedtaskrunner; import java.net.URI; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.cloud.dataflow.composedtaskrunner.properties.ComposedTaskProperties; import org.springframework.cloud.dataflow.core.dsl.TaskAppNode; import org.springframework.cloud.dataflow.core.dsl.TaskParser; import org.springframework.cloud.dataflow.core.dsl.TaskVisitor; import org.springframework.cloud.dataflow.core.dsl.TransitionNode; import org.springframework.cloud.dataflow.rest.util.DeploymentPropertiesUtils; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.StringUtils; /** * Creates the Steps necessary to execute the directed graph of a Composed * Task. * * @author Michael Minella * @author Glenn Renfro * @author Ilayaperumal Gopinathan */ public class StepBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware { private final static Logger log = LoggerFactory.getLogger(StepBeanDefinitionRegistrar.class); private Environment env; private boolean firstAdd; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { ComposedTaskProperties properties = composedTaskProperties(); String ctrName = this.env.getProperty("spring.cloud.task.name"); if(ctrName == null) { throw new IllegalStateException("spring.cloud.task.name property must have a value."); } TaskParser taskParser = new TaskParser("bean-registration", properties.getGraph(), false, true); Map<String, TaskAppNodeHolder> taskSuffixMap = getTaskApps(taskParser); for (String taskName : taskSuffixMap.keySet()) { // handles the possibility that multiple instances of // task definition exist in a composed task for (int taskSuffix = 0; taskSuffixMap.get(taskName).count >= taskSuffix; taskSuffix++) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .rootBeanDefinition(ComposedTaskRunnerStepFactory.class); builder.addConstructorArgValue(properties); builder.addConstructorArgValue(String.format("%s_%s", taskName, taskSuffix)); builder.addConstructorArgValue(taskName.replaceFirst(ctrName + "-", "")); builder.addPropertyValue("taskSpecificProps", getPropertiesForTask(taskName, properties, taskSuffixMap.get(taskName))); String args = getCommandLineArgsForTask(properties.getComposedTaskArguments(), taskName, taskSuffixMap, ctrName); builder.addPropertyValue("arguments", args); registry.registerBeanDefinition(String.format("%s_%s", taskName, taskSuffix), builder.getBeanDefinition()); } } } private String getCommandLineArgsForTask(String arguments, String taskName, Map<String, TaskAppNodeHolder> taskSuffixMap, String ctrName ) { String result = ""; if(!StringUtils.hasText(arguments)) { return arguments; } if(arguments.startsWith("\"") && arguments.endsWith("\"")) { arguments = arguments.substring(1, arguments.length() - 1); } arguments = arguments.replace('\n', ' ').replace('\t', ' '); this.firstAdd = true; try { String[] args = CommandLineUtils.translateCommandline(arguments); String taskNamePrefix = taskName + "."; String taskNameNonIdentify = "--" + taskNamePrefix; for(String commandLineArg : Arrays.asList(args)) { String userPrefix = getPrefix(commandLineArg); String commandLineArgPrefix = ctrName + "-" + userPrefix; String commandLineArgToken = commandLineArgPrefix + "."; if(commandLineArgToken.equals(taskNameNonIdentify) || commandLineArgToken.equals(taskNamePrefix)) { result = addBlankToCommandLineArgs(result); if(commandLineArg.startsWith(userPrefix)) { result = result.concat(commandLineArg.substring(userPrefix.length() + 1)); } else { result = result + "--" + commandLineArg.substring(userPrefix.length() + 3); } continue; } if(!taskSuffixMap.containsKey(commandLineArgPrefix)) { result = addBlankToCommandLineArgs(result); if(commandLineArg.contains(" ")) { commandLineArg = commandLineArg.substring(0, commandLineArg.indexOf("=")) + "=\"" + commandLineArg.substring(commandLineArg.indexOf("=") + 1 )+ "\""; } result = result.concat(commandLineArg); } } } catch (Exception e) { throw new IllegalArgumentException("Unable to extract command line args for task " + taskName, e); } return result; } private String addBlankToCommandLineArgs(String commandArgs) { String result = commandArgs; if(firstAdd) { this.firstAdd = false; } else { result = result.concat(" "); } return result; } private String getPrefix(String commandLineArg) { String commandLineArgPrefix = (!commandLineArg.contains("="))? commandLineArg : commandLineArg.substring(0, commandLineArg.indexOf("=")); int indexOfSeparator = commandLineArgPrefix.indexOf("."); if(indexOfSeparator > -1) { commandLineArgPrefix = commandLineArg.substring(0, indexOfSeparator); } if(commandLineArgPrefix.startsWith("--")) { commandLineArgPrefix = commandLineArgPrefix.substring(2); } return commandLineArgPrefix; } private Map<String, String> getPropertiesForTask(String taskName, ComposedTaskProperties properties, TaskAppNodeHolder holder) { Map<String, String> taskDeploymentProperties = DeploymentPropertiesUtils.parse(properties.getComposedTaskProperties()); Map<String, String> deploymentProperties = new HashMap<>(); updateDeploymentProperties(String.format("app.%s.", taskName), taskDeploymentProperties, deploymentProperties); updateDeploymentProperties(String.format("deployer.%s.", taskName), taskDeploymentProperties, deploymentProperties); String subTaskName = taskName.substring(taskName.indexOf('-') + 1); updateVersionDeploymentProperties(taskName, subTaskName, taskDeploymentProperties, deploymentProperties); return deploymentProperties; } private void updateDeploymentProperties(String prefix, Map<String, String> taskDeploymentProperties, Map<String, String> deploymentProperties) { for (Map.Entry<String, String> entry : taskDeploymentProperties.entrySet()) { if (entry.getKey().startsWith(prefix)) { deploymentProperties.put(entry.getKey() .substring(prefix.length()), entry.getValue()); } } } private void updateVersionDeploymentProperties(String taskName,String subTaskName, Map<String, String> taskDeploymentProperties, Map<String, String> deploymentProperties) { String prefix = String.format("version.%s", taskName); String key = String.format("version.%s", subTaskName); for (Map.Entry<String, String> entry : taskDeploymentProperties.entrySet()) { if (entry.getKey().startsWith(prefix)) { String realkey = String.format("version%s", entry.getKey().replaceFirst("^" + prefix, "")); log.debug("updateVersionDeploymentProperties {} {} {}", key, entry.getValue(), realkey); deploymentProperties.put(realkey, entry.getValue()); } } } @Override public void setEnvironment(Environment environment) { this.env = environment; } private ComposedTaskProperties composedTaskProperties() { ComposedTaskProperties properties = new ComposedTaskProperties(); String skipTlsCertificateVerification = getPropertyValue("skip-tls-certificate-verification"); if (skipTlsCertificateVerification != null) { properties.setSkipTlsCertificateVerification(Boolean.parseBoolean(skipTlsCertificateVerification)); } String dataFlowUriString = getPropertyValue("dataflow-server-uri"); if (dataFlowUriString != null) { properties.setDataflowServerUri(URI.create(dataFlowUriString)); } String maxWaitTime = getPropertyValue("max-wait-time"); if (maxWaitTime != null) { properties.setMaxWaitTime(Integer.parseInt(maxWaitTime)); } String intervalTimeBetweenChecks = getPropertyValue("interval-time-between-checks"); if (intervalTimeBetweenChecks != null) { properties.setIntervalTimeBetweenChecks(Integer.parseInt(intervalTimeBetweenChecks)); } properties.setGraph(getPropertyValue("graph")); properties.setComposedTaskArguments(getPropertyValue("composed-task-arguments")); properties.setPlatformName(getPropertyValue("platform-name")); properties.setComposedTaskProperties(getPropertyValue("composed-task-properties")); properties.setDataflowServerAccessToken(getPropertyValue("dataflow-server-access-token")); properties.setDataflowServerPassword(getPropertyValue("dataflow-server-password")); properties.setDataflowServerUsername(getPropertyValue("dataflow-server-username")); properties.setOauth2ClientCredentialsClientId(getPropertyValue("oauth2-client-credentials-client-id")); properties.setOauth2ClientCredentialsClientSecret(getPropertyValue("oauth2-client-credential-client-secret")); properties.setOauth2ClientCredentialsScopes(StringUtils.commaDelimitedListToSet(getPropertyValue("oauth2-client-credentials-scopes"))); return properties; } /** * @return a {@link Map} of task app name as the key and the number of times it occurs * as the value. */ private Map<String, TaskAppNodeHolder> getTaskApps(TaskParser taskParser) { TaskAppsMapCollector collector = new TaskAppsMapCollector(); taskParser.parse().accept(collector); return collector.getTaskApps(); } private String getPropertyValue(String key) { RelaxedNames relaxedNames = new RelaxedNames(key); String result = null; Iterator<String> iter = relaxedNames.iterator(); while(iter.hasNext()) { String relaxedName = iter.next(); if (this.env.containsProperty(relaxedName)) { result = this.env.getProperty(relaxedName); break; } } return result; } /** * Simple visitor that discovers all the tasks in use in the composed * task definition. */ static class TaskAppsMapCollector extends TaskVisitor { Map<String, TaskAppNodeHolder> taskApps = new HashMap<>(); @Override public void visit(TaskAppNode taskApp) { if (taskApps.containsKey(taskApp.getName())) { int updatedCount = taskApps.get(taskApp.getName()).count + 1; taskApps.put(taskApp.getName(), new TaskAppNodeHolder(taskApp, updatedCount)); } else { taskApps.put(taskApp.getName(), new TaskAppNodeHolder(taskApp, 0)); } } @Override public void visit(TransitionNode transition) { if (transition.isTargetApp()) { if (taskApps.containsKey(transition.getTargetApp().getName())) { int updatedCount = taskApps.get(transition.getTargetApp().getName()).count + 1; taskApps.put(transition.getTargetApp().getName(), new TaskAppNodeHolder(transition.getTargetApp(), updatedCount)); } else { taskApps.put(transition.getTargetApp().getName(), new TaskAppNodeHolder(transition.getTargetApp(), 0)); } } } public Map<String, TaskAppNodeHolder> getTaskApps() { return taskApps; } } static class TaskAppNodeHolder { TaskAppNode taskAppNode; int count; TaskAppNodeHolder(TaskAppNode taskAppNode, int count) { this.taskAppNode = taskAppNode; this.count = count; } } }
Add OAuth2 client auth method property to StepBeanDefinitionRegistrar (#5058)
spring-cloud-dataflow-composed-task-runner/src/main/java/org/springframework/cloud/dataflow/composedtaskrunner/StepBeanDefinitionRegistrar.java
Add OAuth2 client auth method property to StepBeanDefinitionRegistrar (#5058)
<ide><path>pring-cloud-dataflow-composed-task-runner/src/main/java/org/springframework/cloud/dataflow/composedtaskrunner/StepBeanDefinitionRegistrar.java <ide> import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; <ide> import org.springframework.core.env.Environment; <ide> import org.springframework.core.type.AnnotationMetadata; <add>import org.springframework.security.oauth2.core.ClientAuthenticationMethod; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <ide> properties.setDataflowServerUsername(getPropertyValue("dataflow-server-username")); <ide> properties.setOauth2ClientCredentialsClientId(getPropertyValue("oauth2-client-credentials-client-id")); <ide> properties.setOauth2ClientCredentialsClientSecret(getPropertyValue("oauth2-client-credential-client-secret")); <add> <add> String oauth2ClientCredentialsClientAuthenticationMethodAsString = getPropertyValue("oauth2-client-credential-client-authentication-method"); <add> if (oauth2ClientCredentialsClientAuthenticationMethodAsString != null) { <add> properties.setOauth2ClientCredentialsClientAuthenticationMethod(new ClientAuthenticationMethod(oauth2ClientCredentialsClientAuthenticationMethodAsString)); <add> } <add> <ide> properties.setOauth2ClientCredentialsScopes(StringUtils.commaDelimitedListToSet(getPropertyValue("oauth2-client-credentials-scopes"))); <ide> return properties; <ide> }
JavaScript
apache-2.0
6330641088d2e07f69e72f636637e1ba14f0d10e
0
soajs/soajs.dashboard
'use strict'; var colName = "environment"; var templatesColName = "templates"; var hostsColName = "hosts"; var controllesColl = "controllers"; var tenantColName = "tenants"; var cdColName = 'cicd'; var fs = require('fs'); var async = require('async'); const config = require("../../config.js"); var utils = require("../../utils/utils.js"); var envHelper = require("./helper.js"); var envDeployStatus = require("./status.js"); var platformsHelper = require("./platform.js"); function validateId(soajs, cb) { BL.model.validateId(soajs, cb); } function checkReturnError(req, mainCb, data, cb) { if (data.error) { if (typeof (data.error) === 'object') { req.soajs.log.error(data.error); } if (!data.config){ data.config = config; } let message = data.config.errors[data.code]; if(!message && data.error.message){ message = data.error.message; } return mainCb({ "code": data.code, "msg": message }); } else { if (cb) { return cb(); } } } function checkCanEdit(soajs, cb) { let locked = soajs.tenant.locked; let opts = {}; opts.collection = colName; opts.conditions = { '_id': soajs.inputmaskData.id }; BL.model.findEntry(soajs, opts, function (error, envRecord) { if (error) { return cb(600); } //i am root if(locked){ return cb(null, {}); } else{ //i am not root but this is a locked environment if(envRecord && envRecord.locked){ return cb(501); } //i am not root and this is not a locked environment else{ return cb(null, {}); } } }); } function initBLModel(BLModule, modelName, cb) { BLModule.init(modelName, cb); } const databaseModules = require("./dbs"); const keyModules = require("./key"); var BL = { model: null, /** * Function that adds an environment record in the database, creates a deployment template for it and triggers deploy environment from that template * @param config * @param req * @param res * @param cbMain * @returns {*} */ "add": function (config, req, res, cbMain) { let pendingEnvironment = true; if (req.soajs.inputmaskData.data.soajsFrmwrk) { if (!req.soajs.inputmaskData.data.cookiesecret || !req.soajs.inputmaskData.data.sessionName || !req.soajs.inputmaskData.data.sessionSecret) { return cbMain({ code: 408, msg: config.errors[408] }); } } if (!req.soajs.inputmaskData.data.deployPortal) { if (['DASHBOARD', 'PORTAL'].indexOf(req.soajs.inputmaskData.data.code.toUpperCase()) !== -1) { return cbMain({ code: 457, msg: config.errors[457] }); } } req.soajs.inputmaskData.data.code = req.soajs.inputmaskData.data.code.toUpperCase(); checkSAASSettings(() => { let opts = { collection: colName, conditions: { 'code': req.soajs.inputmaskData.data.code } }; BL.model.countEntries(req.soajs, opts, function (error, count) { checkReturnError(req, cbMain, { config: config, error: error, code: 400 }, () => { checkReturnError(req, cbMain, { config: config, error: count > 0, code: 403 }, () => { let envRecord; let envTemplate; let selectedProvider; async.auto({ "checkPreviousEnvironment": (mCb) =>{ if(req.soajs.inputmaskData.data.deploy && req.soajs.inputmaskData.data.deploy.previousEnvironment){ let condition = { 'code': req.soajs.inputmaskData.data.deploy.previousEnvironment.toUpperCase() }; BL.model.findEntry(req.soajs, { collection: colName, conditions: condition }, (error, envDBRecord) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { return mCb(null, envHelper.getDefaultRegistryServicesConfig(envDBRecord)); }); }); } else{ return mCb(null, envHelper.getDefaultRegistryServicesConfig()); } }, "removePreviousTemplateifAny": (mCb) => { BL.model.removeEntry(req.soajs, { collection: templatesColName, conditions: { envCode: req.soajs.inputmaskData.data.code } }, (error) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { return mCb(); }); }); }, "getInfraProvider": (mCb) => { if(!req.soajs.inputmaskData.data.infraId){ return mCb(); } let opts = { collection: "infra", conditions: { "_id": new BL.model.getDb(req.soajs).ObjectId(req.soajs.inputmaskData.data.infraId) } }; BL.model.findEntry(req.soajs, opts, (error, infraRecord) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { checkReturnError(req, mCb, { config: config, error: !infraRecord, code: 400 }, () => { selectedProvider = infraRecord; return mCb(null, infraRecord); }); }); }); }, "getRequestedTemplate": (mCb) =>{ let opts = { collection: templatesColName, conditions: { "type": "_template", "_id": new BL.model.getDb(req.soajs).ObjectId(req.soajs.inputmaskData.data.templateId) } }; BL.model.findEntry(req.soajs, opts, (error, template) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { checkReturnError(req, mCb, { config: config, error: !template, code: 400 }, () => { if (template.reusable === false) { let envOpts = { collection: "templates", conditions : { "name": template.name, "envCode" : { "$exists": true } } }; BL.model.countEntries(req.soajs, envOpts, (error, envCount) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { if (envCount > 0) { let error = []; error.push({code: 173, msg: `Template ${template.name}: Already used to deploy another environment`}); return mCb (error); } else { return mCb(null, template); } }); }); } else { return mCb(null, template); } }); }); }); }, "prepareEnvRecord": ["checkPreviousEnvironment", "getInfraProvider", (info, mCb) => { let envRecord = info.checkPreviousEnvironment; let record = envHelper.prepareEnvRecord(config, req.soajs.inputmaskData.data, envRecord, info.getInfraProvider); record.services = envRecord.services; record.services.config.key.password = req.soajs.inputmaskData.data.tKeyPass; if (req.soajs.inputmaskData.data.soajsFrmwrk) { record.services.config.cookie.secret = req.soajs.inputmaskData.data.cookiesecret; record.services.config.session.name = req.soajs.inputmaskData.data.sessionName; record.services.config.session.secret = req.soajs.inputmaskData.data.sessionSecret; } else { //auto generate values and fill the db record.services.config.cookie.secret = envHelper.generateRandomString(); record.services.config.session.name = envHelper.generateRandomString(); record.services.config.session.secret = envHelper.generateRandomString(); } if(record.deployer.type === 'manual'){ pendingEnvironment = false; } record.pending = pendingEnvironment; return mCb(null, record); }], "insertEnvironment": ["prepareEnvRecord", (info, mCb) => { let opts = { collection: colName, record: info.prepareEnvRecord }; BL.model.insertEntry(req.soajs, opts, mCb); }], "checkTemplate": ["insertEnvironment", "getRequestedTemplate", "getInfraProvider", function(info, mCb){ envRecord = info.insertEnvironment[0]; let template = info.getRequestedTemplate; delete template.type; delete template._id; delete template.deletable; //append the user inputs to the template and insert a new record to deploy the environment from template.deploy = req.soajs.inputmaskData.template.deploy; //validate template schema before resuming let schema = require("../../schemas/template"); let myValidator = new req.soajs.validator.Validator(); let status = myValidator.validate(template, schema); if (!status.valid) { let errors = []; status.errors.forEach(function (err) { errors.push({code: 173, msg: `Template ${req.soajs.inputmaskData.template.name}: ` + err.stack}); }); return mCb(errors); } if(process.env.SOAJS_SAAS && req.soajs.servicesConfig && req.soajs.inputmaskData.soajs_project){ template.soajs_project = req.soajs.inputmaskData.soajs_project; } template.envCode = req.soajs.inputmaskData.data.code; template.type = "_environment_" + template.envCode; if(info.getInfraProvider){ template.infra = info.getInfraProvider._id.toString(); } //transform the . -> __dot__ for(let stage in template.deploy){ for (let group in template.deploy[stage]){ for(let section in template.deploy[stage][group]){ if(section.indexOf(".") !== -1){ let newSection = section.replace(/\./g, "__dot__"); template.deploy[stage][group][newSection] = JSON.parse(JSON.stringify(template.deploy[stage][group][section])); delete template.deploy[stage][group][section]; } } } } //save template and resume deployment envTemplate = template; BL.model.insertEntry(req.soajs, { collection: templatesColName, record: template }, mCb); }] }, (error) =>{ checkReturnError(req, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 400 }, function () { //check template inputs envDeployStatus.validateDeploymentInputs(req, BL, config, envRecord, envTemplate, selectedProvider, (error) =>{ if(error){ //array of errors detected, soajs response mw will parse it //remove the environment opts = { collection: colName, conditions: { code: envRecord.code.toUpperCase() } }; BL.model.removeEntry(req.soajs, opts, (err) =>{ if(err){ req.soajs.log.error(err); } }); return cbMain(error); } //resume deployment of environment from template envDeployStatus.resumeDeployment(req, BL, config, envRecord, envTemplate, selectedProvider, (error) =>{ checkReturnError(req, cbMain, { config: config, error: error, code: 400 }, function () { return cbMain(null, envRecord._id); }); }); }); }); }); }); }); }); }); function checkSAASSettings(cb){ if (process.env.SOAJS_SAAS && !req.soajs.tenant.locked && req.soajs.servicesConfig) { let serviceConfig = req.soajs.servicesConfig.SOAJS_SAAS; //if soajs_project is found in one of the applications configuration, then use ONLY that ext key if(serviceConfig && serviceConfig[req.soajs.inputmaskData.soajs_project]){ let valid = true; let limit = null; if(serviceConfig[req.soajs.inputmaskData.soajs_project]['SOAJS_SAAS_environments']) { limit = serviceConfig[req.soajs.inputmaskData.soajs_project]['SOAJS_SAAS_environments'].limit; } if(!limit){ return cb(); } //get the limit value //count the environment //if fail, return res //if ok return cb let opts = { collection: colName, conditions: {} }; BL.model.countEntries(req.soajs, opts, (error, count) => { checkReturnError(req, cbMain, { config: config, error: error, code: 400 }, () => { if(count && count >= limit){ valid = false; } if(!valid){ return cbMain({"code": 999, "msg": config.errors[999] }); } else return cb(); }); }); } else return cb(); } else return cb(); } }, /** * Function that returns the environment deployment status * @param config * @param req * @param res * @param cbMain */ "getDeploymentStatus": function(config, req, res, cbMain){ let opts = { collection: colName, conditions: {} }; if (req.soajs.inputmaskData.code) { req.soajs.inputmaskData.code = req.soajs.inputmaskData.code.toUpperCase(); opts.conditions.code = req.soajs.inputmaskData.code; getEnv(); } else { validateId(req.soajs, function (err) { checkReturnError(req, cbMain, { config: config, error: err, code: 405 }, function () { opts.conditions['_id'] = req.soajs.inputmaskData.id; getEnv(); }); }); } function getEnv() { BL.model.findEntry(req.soajs, opts, function (error, record) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { checkReturnError(req, cbMain, { config: config, error: !record, code: 405 }, function () { //environment has been deployment if(record.error && !req.soajs.inputmaskData.rollback && !req.soajs.inputmaskData.activate){ return cbMain({code: 400, msg: record.error}); } //activate the environment if(req.soajs.inputmaskData.activate){ delete record.error; delete record.pending; BL.model.saveEntry(req.soajs, {collection: colName, record: record}, function (error) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { return cbMain(null, {"completed": true}); }); }); } //return environment deployment progress else{ loadAndProcessTemplate(record); } }); }); }); } function loadAndProcessTemplate(environmentRecord){ BL.model.findEntry(req.soajs, {collection:templatesColName, conditions: { envCode: req.soajs.inputmaskData.code } }, function(error, template) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { checkReturnError(req, cbMain, { config: config, error: !template, code: 600 }, function () { //get infra provider if(template.infra){ let infraId = new BL.model.getDb(req.soajs).ObjectId(template.infra); BL.model.findEntry(req.soajs, {collection:'infra', conditions: { _id: infraId } }, function(error, selectedProvider) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { checkReturnError(req, cbMain, { config: config, error: !selectedProvider, code: 600 }, function () { //resume deployment if resume is triggered else return deployment status let statusMethod = ((environmentRecord.pending || environmentRecord.error) && req.soajs.inputmaskData.resume) ? "resumeDeployment" : "checkProgress"; envDeployStatus[statusMethod](req, BL, config, environmentRecord, template, selectedProvider, cbMain); }); }); }); } else{ //resume deployment if resume is triggered else return deployment status let statusMethod = ((environmentRecord.pending || environmentRecord.error) && req.soajs.inputmaskData.resume) ? "resumeDeployment" : "checkProgress"; envDeployStatus[statusMethod](req, BL, config, environmentRecord, template, null, cbMain); } }); }); }); } }, "get": function (config, req, res, cbMain) { var opts = {}; opts.collection = colName; opts.conditions = {}; if (req.soajs.inputmaskData.code) { req.soajs.inputmaskData.code = req.soajs.inputmaskData.code.toUpperCase(); opts.conditions.code = req.soajs.inputmaskData.code; getEnv(); } else { validateId(req.soajs, function (err) { checkReturnError(req, cbMain, { config: config, error: err, code: 405 }, function () { opts.conditions['_id'] = req.soajs.inputmaskData.id; getEnv(); }); }); } function getEnv() { BL.model.findEntry(req.soajs, opts, function (error, record) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { if (!record) { req.soajs.log.error('No env record found'); return cbMain(null, null); } BL.model.findEntry(req.soajs, { collection: templatesColName, conditions: { envCode: record.code } }, function (error, template) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { if (!record) { req.soajs.log.error('No env record found'); } record.template = template; return cbMain(null, record); }); }); }); }); } }, "delete": function (config, req, deployer, cbMain) { let envRecord; var opts = {}; opts.collection = colName; if(req.soajs.inputmaskData.id){ try{ opts.conditions = { '_id': new BL.model.getDb(req.soajs).ObjectId(req.soajs.inputmaskData.id) }; } catch(e){ return cbMain({code: 405, msg: e.toString() }); } } if(req.soajs.inputmaskData.code){ opts.conditions = { 'code': req.soajs.inputmaskData.code.toUpperCase() }; } checkReturnError(req, cbMain, { config: config, error: !opts.conditions, code: 405 }, function () { BL.model.findEntry(req.soajs, opts, function (error, record) { checkReturnError(req, cbMain, { config: config, error: error || !record || record.code === process.env.SOAJS_ENV.toUpperCase(), code: 404 }, function () { checkReturnError(req, cbMain, { config: config, error: record.locked, code: 500 }, function () { // return error msg that this record is locked envRecord = record; if (record.deployer.type === 'manual') { deleteHostsControllers(record, deleteEnv); } else { checkContainerDeployments(record, deleteEnv); } }); }); }); }); function deleteEnv() { async.series({ "removeCustomRegistries": (vCb) => { opts = {}; opts.collection = "custom_registry"; opts.conditions = { 'created': envRecord.code.toUpperCase()}; BL.model.removeEntry(req.soajs, opts, vCb); }, "removeResources": (vCb) => { opts = {}; opts.collection = "resources"; opts.conditions = { 'created': envRecord.code.toUpperCase()}; BL.model.removeEntry(req.soajs, opts, vCb); }, "removeTemplate": (vCb) => { opts = {}; opts.collection = templatesColName; opts.conditions = { 'envCode': envRecord.code.toUpperCase()}; BL.model.removeEntry(req.soajs, opts, vCb); }, "cleanUpInfra": (vCb) =>{ function initBLModel(BLModule, modelName, cb) { BLModule.init(modelName, cb); } req.soajs.inputmaskData = { envCode: envRecord.code.toUpperCase() }; req.soajs.log.debug("Cleaning up Cluster deployments ..."); initBLModel(require("../cloud/infra/index.js"), "mongo", (error, infraModule) => { checkReturnError(req, vCb, { config: config, error: error, code: 600 }, function () { infraModule.removeEnvFromDeployment(config, req, req.soajs, deployer, (error) =>{ if(error){ req.soajs.log.error(error); } return vCb(); }); }); }); }, "removeEnv": (vCb) => { opts = {}; opts.collection = colName; opts.conditions = { 'code': envRecord.code.toUpperCase(), 'locked': { $ne: true } }; BL.model.removeEntry(req.soajs, opts, vCb); } }, (error) => { checkReturnError(req, cbMain, { config: config, error: error, code: 404 }, function () { return cbMain(null, "environment delete successful"); }); }); } function deleteCdInfo(envRecord, cb) { opts = {}; opts.collection = cdColName; opts.conditions = { type: 'cd' }; opts.fields = { $unset: { [envRecord.code.toUpperCase()]: '' } }; BL.model.updateEntry(req.soajs, opts, function(error) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, cb); }); } function deleteHostsControllers(envRecord, cb) { opts = {}; opts.conditions = { env: envRecord.code.toLowerCase() }; async.parallel({ hosts : function(callback) { opts.collection = hostsColName; BL.model.removeEntry(req.soajs, opts, callback); }, controllers : function (callback) { opts.collection = controllesColl; BL.model.removeEntry(req.soajs, opts, callback); } }, function (err) { checkReturnError(req, cbMain, { config: config, error: err, code: 600 }, cb); }); } function checkContainerDeployments(envRecord, cb) { let cbToUse = (req.soajs.inputmaskData.force) ? cb : cbMain; initBLModel(require(__dirname + "/../cloud/services/index.js"), 'mongo', (error, serviceModule) => { checkReturnError(req, cbToUse, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, () => { req.soajs.inputmaskData.env = envRecord.code; serviceModule.listServices(config, req.soajs, deployer, (error, services) => { utils.checkErrorReturn(req.soajs, cbToUse, { config: config, error: error }, () => { //clean all services & secrets if (req.soajs.inputmaskData.force) { let deployerInfo = envRecord.deployer.selected.split("."); if(envRecord.deployer.selected.indexOf("container.kubernetes") !== -1){ let namespace = envRecord.deployer[deployerInfo[0]][deployerInfo[1]][deployerInfo[2]].namespace.default; req.soajs.inputmaskData.namespace = namespace; } async.series({ "deleteServices": (mCb) => { async.eachSeries(services, (oneService, sCb) => { req.soajs.inputmaskData.technology = deployerInfo[1]; req.soajs.inputmaskData.serviceId = oneService.id; req.soajs.inputmaskData.mode = oneService.labels['soajs.service.mode']; req.soajs.inputmaskData.group = oneService.labels['soajs.service.group']; serviceModule.deleteService(config, req, deployer, sCb); }, mCb); }, "deleteSecrets": (mCb) => { initBLModel(require(__dirname + "/../cloud/secrets/index.js"), 'mongo', (error, secretsModule) => { checkReturnError(req, mCb, { config: config, error: error, code: 600 }, () => { secretsModule.list(config, req.soajs, deployer, (error, secrets) => { checkReturnError(req, mCb, { config: config, error: error, code: 600 }, () => { async.eachSeries(secrets, (oneSecret, sCb) => { req.soajs.inputmaskData.name = oneSecret.name; secretsModule.delete(config, req.soajs, deployer, sCb); }, mCb); }); }); }); }); } }, (error) => { //if error, just log it if(error){ req.soajs.log.error(error); } //close Database Connection BL.model.closeConnection(req.soajs); }); //don't wait for async to finish, return the cb return cb(null, true); } else{ checkReturnError(req, cbToUse, { config: config, error: services.length > 0, code: 906 }, () => { return deleteCdInfo(envRecord, cb); }); } }); }); }); }); } }, "update": function (config, req, res, cbMain) { validateId(req.soajs, function (err) { checkReturnError(req, cbMain, { config: config, error: err, code: 405 }, function () { checkCanEdit(req.soajs, function(errCode) { checkReturnError(req, cbMain, { config: config, error: config.errors[errCode], code: errCode}, function () { let opts = {}; opts.collection = colName; opts.conditions = { "_id": req.soajs.inputmaskData.id }; BL.model.findEntry(req.soajs, opts, function(error, environment){ checkReturnError(req, cbMain, { config: config, error: error, code: 405 }, function () { switch (req.soajs.inputmaskData.services.config.session.proxy) { case "true": req.soajs.inputmaskData.services.config.session.proxy = true; break; case "false": req.soajs.inputmaskData.services.config.session.proxy = false; break; case "undefined": delete req.soajs.inputmaskData.services.config.session.proxy; break; } req.soajs.inputmaskData.services.config.oauth.grants = ['password', 'refresh_token']; environment.domain = req.soajs.inputmaskData.domain || ""; environment.apiPrefix = req.soajs.inputmaskData.apiPrefix; environment.sitePrefix = req.soajs.inputmaskData.sitePrefix; environment.description = req.soajs.inputmaskData.description; environment.sensitive = req.soajs.inputmaskData.sensitive; environment.services = req.soajs.inputmaskData.services; environment.profile = config.profileLocation + "profile.js"; if (req.soajs.inputmaskData.portalPrefix) { environment["portalPrefix"] = req.soajs.inputmaskData.portalPrefix; } //update machine ip if(environment.deployer && environment.deployer.type === 'manual'){ environment.deployer.manual = { nodes: req.soajs.inputmaskData.machineip }; } else { let deployerInfo = req.soajs.inputmaskData.deployer.selected.split("."); if(deployerInfo[1] !== 'docker' && deployerInfo[2] !== 'local'){ environment.deployer[deployerInfo[0]][deployerInfo[1]][deployerInfo[2]].nodes = req.soajs.inputmaskData.machineip; } } opts.record = environment; BL.model.saveEntry(req.soajs, opts, function (err, data) { checkReturnError(req, cbMain, { config: config, error: err, code: 401 }, function () { return cbMain(null, "environment update successful"); }); }); }); }); }); }); }); }); }, "list": function (config, req, res, cbMain) { var opts = { collection: colName }; BL.model.findEntries(req.soajs, opts, function (err, records) { checkReturnError(req, cbMain, { config: config, error: err, code: 402 }, function () { return cbMain(null, records); }); }); }, "keyUpdate": function (config, soajsCore, req, res, cbMain) { keyModules.keyUpdate(config, soajsCore, req, res, BL, cbMain); }, "listDbs": function (config, req, res, cbMain) { databaseModules.listDbs(config, req, res, BL, cbMain); }, "addDb": function (config, req, res, cbMain) { databaseModules.addDb(config, req, res, BL, cbMain); }, "updateDb": function (config, req, res, cbMain) { databaseModules.updateDb(config, req, res, BL, cbMain); }, "deleteDb": function (config, req, res, cbMain) { databaseModules.deleteDb(config, req, res, BL, cbMain); }, "updateDbsPrefix": function (config, req, res, cbMain) { databaseModules.updateDbsPrefix(config, req, res, BL, cbMain); }, "listPlatforms": function (config, req, res, deployer, cbMain) { platformsHelper.listPlatforms(config, req, res, BL, envHelper, deployer, cbMain); }, "updateDeployerConfig": function (config, req, deployer, cbMain) { platformsHelper.updateDeployerConfig(config, req, BL, deployer, cbMain); }, "attachContainer": function( config, req, deployer, cbMain) { platformsHelper.attachContainer(config, req, BL, deployer, cbMain); }, "detachContainer": function( config, req, deployer, cbMain) { platformsHelper.detachContainer(config, req, BL, deployer, cbMain); } }; module.exports = { "init": function (modelName, cb) { var modelPath; if (!modelName) { return cb(new Error("No Model Requested!")); } modelPath = __dirname + "/../../models/" + modelName + ".js"; return requireModel(modelPath, cb); /** * checks if model file exists, requires it and returns it. * @param filePath * @param cb */ function requireModel(filePath, cb) { //check if file exist. if not return error fs.exists(filePath, function (exists) { if (!exists) { return cb(new Error("Requested Model Not Found!")); } BL.model = require(filePath); return cb(null, BL); }); } } };
lib/environment/index.js
'use strict'; var colName = "environment"; var templatesColName = "templates"; var hostsColName = "hosts"; var controllesColl = "controllers"; var tenantColName = "tenants"; var cdColName = 'cicd'; var fs = require('fs'); var async = require('async'); const config = require("../../config.js"); var utils = require("../../utils/utils.js"); var envHelper = require("./helper.js"); var envDeployStatus = require("./status.js"); var platformsHelper = require("./platform.js"); function validateId(soajs, cb) { BL.model.validateId(soajs, cb); } function checkReturnError(req, mainCb, data, cb) { if (data.error) { if (typeof (data.error) === 'object') { req.soajs.log.error(data.error); } if (!data.config){ data.config = config; } let message = data.config.errors[data.code]; if(!message && data.error.message){ message = data.error.message; } return mainCb({ "code": data.code, "msg": message }); } else { if (cb) { return cb(); } } } function checkCanEdit(soajs, cb) { let locked = soajs.tenant.locked; let opts = {}; opts.collection = colName; opts.conditions = { '_id': soajs.inputmaskData.id }; BL.model.findEntry(soajs, opts, function (error, envRecord) { if (error) { return cb(600); } //i am root if(locked){ return cb(null, {}); } else{ //i am not root but this is a locked environment if(envRecord && envRecord.locked){ return cb(501); } //i am not root and this is not a locked environment else{ return cb(null, {}); } } }); } function initBLModel(BLModule, modelName, cb) { BLModule.init(modelName, cb); } const databaseModules = require("./dbs"); const keyModules = require("./key"); var BL = { model: null, /** * Function that adds an environment record in the database, creates a deployment template for it and triggers deploy environment from that template * @param config * @param req * @param res * @param cbMain * @returns {*} */ "add": function (config, req, res, cbMain) { let pendingEnvironment = true; if (req.soajs.inputmaskData.data.soajsFrmwrk) { if (!req.soajs.inputmaskData.data.cookiesecret || !req.soajs.inputmaskData.data.sessionName || !req.soajs.inputmaskData.data.sessionSecret) { return cbMain({ code: 408, msg: config.errors[408] }); } } if (!req.soajs.inputmaskData.data.deployPortal) { if (['DASHBOARD', 'PORTAL'].indexOf(req.soajs.inputmaskData.data.code.toUpperCase()) !== -1) { return cbMain({ code: 457, msg: config.errors[457] }); } } req.soajs.inputmaskData.data.code = req.soajs.inputmaskData.data.code.toUpperCase(); checkSAASSettings(() => { let opts = { collection: colName, conditions: { 'code': req.soajs.inputmaskData.data.code } }; BL.model.countEntries(req.soajs, opts, function (error, count) { checkReturnError(req, cbMain, { config: config, error: error, code: 400 }, () => { checkReturnError(req, cbMain, { config: config, error: count > 0, code: 403 }, () => { let envRecord; let envTemplate; let selectedProvider; async.auto({ "checkPreviousEnvironment": (mCb) =>{ if(req.soajs.inputmaskData.data.deploy && req.soajs.inputmaskData.data.deploy.previousEnvironment){ let condition = { 'code': req.soajs.inputmaskData.data.deploy.previousEnvironment.toUpperCase() }; BL.model.findEntry(req.soajs, { collection: colName, conditions: condition }, (error, envDBRecord) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { return mCb(null, envHelper.getDefaultRegistryServicesConfig(envDBRecord)); }); }); } else{ return mCb(null, envHelper.getDefaultRegistryServicesConfig()); } }, "removePreviousTemplateifAny": (mCb) => { BL.model.removeEntry(req.soajs, { collection: templatesColName, conditions: { envCode: req.soajs.inputmaskData.data.code } }, (error) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { return mCb(); }); }); }, "getInfraProvider": (mCb) => { if(!req.soajs.inputmaskData.data.infraId){ return mCb(); } let opts = { collection: "infra", conditions: { "_id": new BL.model.getDb(req.soajs).ObjectId(req.soajs.inputmaskData.data.infraId) } }; BL.model.findEntry(req.soajs, opts, (error, infraRecord) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { checkReturnError(req, mCb, { config: config, error: !infraRecord, code: 400 }, () => { selectedProvider = infraRecord; return mCb(null, infraRecord); }); }); }); }, "getRequestedTemplate": (mCb) =>{ let opts = { collection: templatesColName, conditions: { "type": "_template", "_id": new BL.model.getDb(req.soajs).ObjectId(req.soajs.inputmaskData.data.templateId) } }; BL.model.findEntry(req.soajs, opts, (error, template) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { checkReturnError(req, mCb, { config: config, error: !template, code: 400 }, () => { if (template.reusable === false) { let envOpts = { collection: "templates", conditions : { "name": template.name, "envCode" : { "$exists": true } } }; BL.model.countEntries(req.soajs, envOpts, (error, envCount) => { checkReturnError(req, mCb, { config: config, error: error, code: 400 }, () => { if (envCount > 0) { let error = []; error.push({code: 173, msg: `Template ${template.name}: Already used to deploy another environment`}); return mCb (error); } else { return mCb(null, template); } }); }); } else { return mCb(null, template); } }); }); }); }, "prepareEnvRecord": ["checkPreviousEnvironment", "getInfraProvider", (info, mCb) => { let envRecord = info.checkPreviousEnvironment; let record = envHelper.prepareEnvRecord(config, req.soajs.inputmaskData.data, envRecord, info.getInfraProvider); record.services = envRecord.services; record.services.config.key.password = req.soajs.inputmaskData.data.tKeyPass; if (req.soajs.inputmaskData.data.soajsFrmwrk) { record.services.config.cookie.secret = req.soajs.inputmaskData.data.cookiesecret; record.services.config.session.name = req.soajs.inputmaskData.data.sessionName; record.services.config.session.secret = req.soajs.inputmaskData.data.sessionSecret; } else { //auto generate values and fill the db record.services.config.cookie.secret = envHelper.generateRandomString(); record.services.config.session.name = envHelper.generateRandomString(); record.services.config.session.secret = envHelper.generateRandomString(); } if(record.deployer.type === 'manual'){ pendingEnvironment = false; } record.pending = pendingEnvironment; return mCb(null, record); }], "insertEnvironment": ["prepareEnvRecord", (info, mCb) => { let opts = { collection: colName, record: info.prepareEnvRecord }; BL.model.insertEntry(req.soajs, opts, mCb); }], "checkTemplate": ["insertEnvironment", "getRequestedTemplate", "getInfraProvider", function(info, mCb){ envRecord = info.insertEnvironment[0]; let template = info.getRequestedTemplate; delete template.type; delete template._id; delete template.deletable; //append the user inputs to the template and insert a new record to deploy the environment from template.deploy = req.soajs.inputmaskData.template.deploy; //validate template schema before resuming let schema = require("../../schemas/template"); let myValidator = new req.soajs.validator.Validator(); let status = myValidator.validate(template, schema); if (!status.valid) { let errors = []; status.errors.forEach(function (err) { errors.push({code: 173, msg: `Template ${req.soajs.inputmaskData.template.name}: ` + err.stack}); }); return mCb(errors); } if(process.env.SOAJS_SAAS && req.soajs.servicesConfig && req.soajs.inputmaskData.soajs_project){ template.soajs_project = req.soajs.inputmaskData.soajs_project; } template.envCode = req.soajs.inputmaskData.data.code; template.type = "_environment_" + template.envCode; if(info.getInfraProvider){ template.infra = info.getInfraProvider._id.toString(); } //transform the . -> __dot__ for(let stage in template.deploy){ for (let group in template.deploy[stage]){ for(let section in template.deploy[stage][group]){ if(section.indexOf(".") !== -1){ let newSection = section.replace(/\./g, "__dot__"); template.deploy[stage][group][newSection] = JSON.parse(JSON.stringify(template.deploy[stage][group][section])); delete template.deploy[stage][group][section]; } } } } //save template and resume deployment envTemplate = template; BL.model.insertEntry(req.soajs, { collection: templatesColName, record: template }, mCb); }] }, (error) =>{ checkReturnError(req, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 400 }, function () { //check template inputs envDeployStatus.validateDeploymentInputs(req, BL, config, envRecord, envTemplate, selectedProvider, (error) =>{ if(error){ //array of errors detected, soajs response mw will parse it //remove the environment opts = { collection: colName, conditions: { code: envRecord.code.toUpperCase() } }; BL.model.removeEntry(req.soajs, opts, (err) =>{ if(err){ req.soajs.log.error(err); } }); return cbMain(error); } //resume deployment of environment from template envDeployStatus.resumeDeployment(req, BL, config, envRecord, envTemplate, selectedProvider, (error) =>{ checkReturnError(req, cbMain, { config: config, error: error, code: 400 }, function () { return cbMain(null, envRecord._id); }); }); }); }); }); }); }); }); }); function checkSAASSettings(cb){ if (process.env.SOAJS_SAAS && !req.soajs.tenant.locked && req.soajs.servicesConfig) { let serviceConfig = req.soajs.servicesConfig.SOAJS_SAAS; //if soajs_project is found in one of the applications configuration, then use ONLY that ext key if(serviceConfig && serviceConfig[req.soajs.inputmaskData.soajs_project]){ let valid = true; let limit = null; if(serviceConfig[req.soajs.inputmaskData.soajs_project]['SOAJS_SAAS_environments']) { limit = serviceConfig[req.soajs.inputmaskData.soajs_project]['SOAJS_SAAS_environments'].limit; } if(!limit){ return cb(); } //get the limit value //count the environment //if fail, return res //if ok return cb let opts = { collection: colName, conditions: {} }; BL.model.countEntries(req.soajs, opts, (error, count) => { checkReturnError(req, cbMain, { config: config, error: error, code: 400 }, () => { if(count && count >= limit){ valid = false; } if(!valid){ return cbMain({"code": 999, "msg": config.errors[999] }); } else return cb(); }); }); } else return cb(); } else return cb(); } }, /** * Function that returns the environment deployment status * @param config * @param req * @param res * @param cbMain */ "getDeploymentStatus": function(config, req, res, cbMain){ let opts = { collection: colName, conditions: {} }; if (req.soajs.inputmaskData.code) { req.soajs.inputmaskData.code = req.soajs.inputmaskData.code.toUpperCase(); opts.conditions.code = req.soajs.inputmaskData.code; getEnv(); } else { validateId(req.soajs, function (err) { checkReturnError(req, cbMain, { config: config, error: err, code: 405 }, function () { opts.conditions['_id'] = req.soajs.inputmaskData.id; getEnv(); }); }); } function getEnv() { BL.model.findEntry(req.soajs, opts, function (error, record) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { checkReturnError(req, cbMain, { config: config, error: !record, code: 405 }, function () { //environment has been deployment if(record.error && !req.soajs.inputmaskData.rollback && !req.soajs.inputmaskData.activate){ return cbMain({code: 400, msg: record.error}); } //activate the environment if(req.soajs.inputmaskData.activate){ delete record.error; delete record.pending; BL.model.saveEntry(req.soajs, {collection: colName, record: record}, function (error) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { return cbMain(null, {"completed": true}); }); }); } //return environment deployment progress else{ loadAndProcessTemplate(record); } }); }); }); } function loadAndProcessTemplate(environmentRecord){ BL.model.findEntry(req.soajs, {collection:templatesColName, conditions: { envCode: req.soajs.inputmaskData.code } }, function(error, template) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { checkReturnError(req, cbMain, { config: config, error: !template, code: 600 }, function () { //get infra provider if(template.infra){ let infraId = new BL.model.getDb(req.soajs).ObjectId(template.infra); BL.model.findEntry(req.soajs, {collection:'infra', conditions: { _id: infraId } }, function(error, selectedProvider) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { checkReturnError(req, cbMain, { config: config, error: !selectedProvider, code: 600 }, function () { //resume deployment if resume is triggered else return deployment status let statusMethod = ((environmentRecord.pending || environmentRecord.error) && req.soajs.inputmaskData.resume) ? "resumeDeployment" : "checkProgress"; envDeployStatus[statusMethod](req, BL, config, environmentRecord, template, selectedProvider, cbMain); }); }); }); } else{ //resume deployment if resume is triggered else return deployment status let statusMethod = ((environmentRecord.pending || environmentRecord.error) && req.soajs.inputmaskData.resume) ? "resumeDeployment" : "checkProgress"; envDeployStatus[statusMethod](req, BL, config, environmentRecord, template, null, cbMain); } }); }); }); } }, "get": function (config, req, res, cbMain) { var opts = {}; opts.collection = colName; opts.conditions = {}; if (req.soajs.inputmaskData.code) { req.soajs.inputmaskData.code = req.soajs.inputmaskData.code.toUpperCase(); opts.conditions.code = req.soajs.inputmaskData.code; getEnv(); } else { validateId(req.soajs, function (err) { checkReturnError(req, cbMain, { config: config, error: err, code: 405 }, function () { opts.conditions['_id'] = req.soajs.inputmaskData.id; getEnv(); }); }); } function getEnv() { BL.model.findEntry(req.soajs, opts, function (error, record) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { if (!record) { req.soajs.log.error('No env record found'); return cbMain(null, null); } BL.model.findEntry(req.soajs, { collection: templatesColName, conditions: { envCode: record.code } }, function (error, template) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, function () { if (!record) { req.soajs.log.error('No env record found'); } record.template = template; return cbMain(null, record); }); }); }); }); } }, "delete": function (config, req, deployer, cbMain) { let envRecord; var opts = {}; opts.collection = colName; if(req.soajs.inputmaskData.id){ try{ opts.conditions = { '_id': new BL.model.getDb(req.soajs).ObjectId(req.soajs.inputmaskData.id) }; } catch(e){ return cbMain({code: 405, msg: e.toString() }); } } if(req.soajs.inputmaskData.code){ opts.conditions = { 'code': req.soajs.inputmaskData.code.toUpperCase() }; } checkReturnError(req, cbMain, { config: config, error: !opts.conditions, code: 405 }, function () { BL.model.findEntry(req.soajs, opts, function (error, record) { checkReturnError(req, cbMain, { config: config, error: error || !record || record.code === process.env.SOAJS_ENV.toUpperCase(), code: 404 }, function () { checkReturnError(req, cbMain, { config: config, error: record.locked, code: 500 }, function () { // return error msg that this record is locked envRecord = record; if (record.deployer.type === 'manual') { deleteHostsControllers(record, deleteEnv); } else { checkContainerDeployments(record, deleteEnv); } }); }); }); }); function deleteEnv() { async.series({ "removeCustomRegistries": (vCb) => { opts = {}; opts.collection = "custom_registry"; opts.conditions = { 'created': envRecord.code.toUpperCase()}; BL.model.removeEntry(req.soajs, opts, vCb); }, "removeResources": (vCb) => { opts = {}; opts.collection = "resources"; opts.conditions = { 'created': envRecord.code.toUpperCase()}; BL.model.removeEntry(req.soajs, opts, vCb); }, "removeTemplate": (vCb) => { opts = {}; opts.collection = templatesColName; opts.conditions = { 'envCode': envRecord.code.toUpperCase()}; BL.model.removeEntry(req.soajs, opts, vCb); }, "cleanUpInfra": (vCb) =>{ function initBLModel(BLModule, modelName, cb) { BLModule.init(modelName, cb); } req.soajs.inputmaskData = { envCode: envRecord.code.toUpperCase() }; req.soajs.log.debug("Cleaning up Cluster deployments ..."); initBLModel(require("../cloud/infra/index.js"), "mongo", (error, infraModule) => { checkReturnError(req, vCb, { config: config, error: error, code: 600 }, function () { infraModule.removeEnvFromDeployment(config, req, req.soajs, deployer, (error) =>{ if(error){ req.soajs.log.error(error); } return vCb(); }); }); }); }, "removeEnv": (vCb) => { opts = {}; opts.collection = colName; opts.conditions = { 'code': envRecord.code.toUpperCase(), 'locked': { $ne: true } }; BL.model.removeEntry(req.soajs, opts, vCb); } }, (error) => { checkReturnError(req, cbMain, { config: config, error: error, code: 404 }, function () { return cbMain(null, "environment delete successful"); }); }); } function deleteCdInfo(envRecord, cb) { opts = {}; opts.collection = cdColName; opts.conditions = { type: 'cd' }; opts.fields = { $unset: { [envRecord.code.toUpperCase()]: '' } }; BL.model.updateEntry(req.soajs, opts, function(error) { checkReturnError(req, cbMain, { config: config, error: error, code: 600 }, cb); }); } function deleteHostsControllers(envRecord, cb) { opts = {}; opts.conditions = { env: envRecord.code.toLowerCase() }; async.parallel({ hosts : function(callback) { opts.collection = hostsColName; BL.model.removeEntry(req.soajs, opts, callback); }, controllers : function (callback) { opts.collection = controllesColl; BL.model.removeEntry(req.soajs, opts, callback); } }, function (err) { checkReturnError(req, cbMain, { config: config, error: err, code: 600 }, cb); }); } function checkContainerDeployments(envRecord, cb) { initBLModel(require(__dirname + "/../cloud/services/index.js"), 'mongo', (error, serviceModule) => { checkReturnError(req, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, () => { req.soajs.inputmaskData.env = envRecord.code; serviceModule.listServices(config, req.soajs, deployer, (error, services) => { utils.checkErrorReturn(req.soajs, cbMain, { config: config, error: error }, () => { //clean all services & secrets if (req.soajs.inputmaskData.force) { let deployerInfo = envRecord.deployer.selected.split("."); if(envRecord.deployer.selected.indexOf("container.kubernetes") !== -1){ let namespace = envRecord.deployer[deployerInfo[0]][deployerInfo[1]][deployerInfo[2]].namespace.default; req.soajs.inputmaskData.namespace = namespace; } async.series({ "deleteServices": (mCb) => { async.eachSeries(services, (oneService, sCb) => { req.soajs.inputmaskData.technology = deployerInfo[1]; req.soajs.inputmaskData.serviceId = oneService.id; req.soajs.inputmaskData.mode = oneService.labels['soajs.service.mode']; req.soajs.inputmaskData.group = oneService.labels['soajs.service.group']; serviceModule.deleteService(config, req, deployer, sCb); }, mCb); }, "deleteSecrets": (mCb) => { initBLModel(require(__dirname + "/../cloud/secrets/index.js"), 'mongo', (error, secretsModule) => { checkReturnError(req, mCb, { config: config, error: error, code: 600 }, () => { secretsModule.list(config, req.soajs, deployer, (error, secrets) => { checkReturnError(req, mCb, { config: config, error: error, code: 600 }, () => { async.eachSeries(secrets, (oneSecret, sCb) => { req.soajs.inputmaskData.name = oneSecret.name; secretsModule.delete(config, req.soajs, deployer, sCb); }, mCb); }); }); }); }); } }, (error) => { //if error, just log it if(error){ req.soajs.log.error(error); } //close Database Connection BL.model.closeConnection(req.soajs); }); //don't wait for async to finish, return the cb return cb(null, true); } else{ checkReturnError(req, cbMain, { config: config, error: services.length > 0, code: 906 }, () => { return deleteCdInfo(envRecord, cb); }); } }); }); }); }); } }, "update": function (config, req, res, cbMain) { validateId(req.soajs, function (err) { checkReturnError(req, cbMain, { config: config, error: err, code: 405 }, function () { checkCanEdit(req.soajs, function(errCode) { checkReturnError(req, cbMain, { config: config, error: config.errors[errCode], code: errCode}, function () { let opts = {}; opts.collection = colName; opts.conditions = { "_id": req.soajs.inputmaskData.id }; BL.model.findEntry(req.soajs, opts, function(error, environment){ checkReturnError(req, cbMain, { config: config, error: error, code: 405 }, function () { switch (req.soajs.inputmaskData.services.config.session.proxy) { case "true": req.soajs.inputmaskData.services.config.session.proxy = true; break; case "false": req.soajs.inputmaskData.services.config.session.proxy = false; break; case "undefined": delete req.soajs.inputmaskData.services.config.session.proxy; break; } req.soajs.inputmaskData.services.config.oauth.grants = ['password', 'refresh_token']; environment.domain = req.soajs.inputmaskData.domain || ""; environment.apiPrefix = req.soajs.inputmaskData.apiPrefix; environment.sitePrefix = req.soajs.inputmaskData.sitePrefix; environment.description = req.soajs.inputmaskData.description; environment.sensitive = req.soajs.inputmaskData.sensitive; environment.services = req.soajs.inputmaskData.services; environment.profile = config.profileLocation + "profile.js"; if (req.soajs.inputmaskData.portalPrefix) { environment["portalPrefix"] = req.soajs.inputmaskData.portalPrefix; } //update machine ip if(environment.deployer && environment.deployer.type === 'manual'){ environment.deployer.manual = { nodes: req.soajs.inputmaskData.machineip }; } else { let deployerInfo = req.soajs.inputmaskData.deployer.selected.split("."); if(deployerInfo[1] !== 'docker' && deployerInfo[2] !== 'local'){ environment.deployer[deployerInfo[0]][deployerInfo[1]][deployerInfo[2]].nodes = req.soajs.inputmaskData.machineip; } } opts.record = environment; BL.model.saveEntry(req.soajs, opts, function (err, data) { checkReturnError(req, cbMain, { config: config, error: err, code: 401 }, function () { return cbMain(null, "environment update successful"); }); }); }); }); }); }); }); }); }, "list": function (config, req, res, cbMain) { var opts = { collection: colName }; BL.model.findEntries(req.soajs, opts, function (err, records) { checkReturnError(req, cbMain, { config: config, error: err, code: 402 }, function () { return cbMain(null, records); }); }); }, "keyUpdate": function (config, soajsCore, req, res, cbMain) { keyModules.keyUpdate(config, soajsCore, req, res, BL, cbMain); }, "listDbs": function (config, req, res, cbMain) { databaseModules.listDbs(config, req, res, BL, cbMain); }, "addDb": function (config, req, res, cbMain) { databaseModules.addDb(config, req, res, BL, cbMain); }, "updateDb": function (config, req, res, cbMain) { databaseModules.updateDb(config, req, res, BL, cbMain); }, "deleteDb": function (config, req, res, cbMain) { databaseModules.deleteDb(config, req, res, BL, cbMain); }, "updateDbsPrefix": function (config, req, res, cbMain) { databaseModules.updateDbsPrefix(config, req, res, BL, cbMain); }, "listPlatforms": function (config, req, res, deployer, cbMain) { platformsHelper.listPlatforms(config, req, res, BL, envHelper, deployer, cbMain); }, "updateDeployerConfig": function (config, req, deployer, cbMain) { platformsHelper.updateDeployerConfig(config, req, BL, deployer, cbMain); }, "attachContainer": function( config, req, deployer, cbMain) { platformsHelper.attachContainer(config, req, BL, deployer, cbMain); }, "detachContainer": function( config, req, deployer, cbMain) { platformsHelper.detachContainer(config, req, BL, deployer, cbMain); } }; module.exports = { "init": function (modelName, cb) { var modelPath; if (!modelName) { return cb(new Error("No Model Requested!")); } modelPath = __dirname + "/../../models/" + modelName + ".js"; return requireModel(modelPath, cb); /** * checks if model file exists, requires it and returns it. * @param filePath * @param cb */ function requireModel(filePath, cb) { //check if file exist. if not return error fs.exists(filePath, function (exists) { if (!exists) { return cb(new Error("Requested Model Not Found!")); } BL.model = require(filePath); return cb(null, BL); }); } } };
bug fix when removing environment with force
lib/environment/index.js
bug fix when removing environment with force
<ide><path>ib/environment/index.js <ide> if(req.soajs.inputmaskData.code){ <ide> opts.conditions = { 'code': req.soajs.inputmaskData.code.toUpperCase() }; <ide> } <del> <add> <ide> checkReturnError(req, cbMain, { config: config, error: !opts.conditions, code: 405 }, function () { <ide> BL.model.findEntry(req.soajs, opts, function (error, record) { <ide> checkReturnError(req, cbMain, { <ide> } <ide> <ide> function checkContainerDeployments(envRecord, cb) { <add> let cbToUse = (req.soajs.inputmaskData.force) ? cb : cbMain; <ide> initBLModel(require(__dirname + "/../cloud/services/index.js"), 'mongo', (error, serviceModule) => { <del> checkReturnError(req, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, () => { <add> checkReturnError(req, cbToUse, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, () => { <ide> req.soajs.inputmaskData.env = envRecord.code; <ide> serviceModule.listServices(config, req.soajs, deployer, (error, services) => { <del> utils.checkErrorReturn(req.soajs, cbMain, { config: config, error: error }, () => { <add> utils.checkErrorReturn(req.soajs, cbToUse, { config: config, error: error }, () => { <ide> <ide> //clean all services & secrets <ide> if (req.soajs.inputmaskData.force) { <ide> return cb(null, true); <ide> } <ide> else{ <del> checkReturnError(req, cbMain, { config: config, error: services.length > 0, code: 906 }, () => { <add> checkReturnError(req, cbToUse, { config: config, error: services.length > 0, code: 906 }, () => { <ide> return deleteCdInfo(envRecord, cb); <ide> }); <ide> }
Java
apache-2.0
327307458bd2050ebd488c1d5c3f9b17a7149a62
0
sksamuel/scrimage,sksamuel/scrimage
package com.sksamuel.scrimage; import com.drew.metadata.exif.ExifIFD0Directory; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; public class Orientation { public static Boolean requiresReorientation(ImageMetadata metadata) { Set<String> imageOrientations = imageOrientationsOf(metadata); String first = imageOrientations.stream().findFirst().orElse("-1"); switch (first) { case "2": case "3": case "4": case "5": case "6": case "7": case "8": return true; default: return false; } } public static Image reorient(Image image, ImageMetadata metadata) { Set<String> imageOrientations = imageOrientationsOf(metadata); String first = imageOrientations.stream().findFirst().orElse("-1"); switch (first) { // normal case "1": return image; // Flip horizontally case "2": // Rotate 180 degrees return image.flipX(); case "3": // Rotate 180 degrees and flip horizontally return image.rotateLeft().rotateLeft(); case "4": // Rotate 90 degrees clockwise and flip horizontally return image.rotateLeft().rotateLeft().flipX(); case "5": // Rotate 90 degrees clockwise return image.rotateRight().flipX(); case "6": // Rotate 90 degrees anti-clockwise and flip horizontally return image.rotateRight(); case "7": // Rotate 90 degrees anti-clockwise return image.rotateLeft().flipX(); case "8": return image.rotateLeft(); // Unknown, keep the orginal image default: return image; } } // returns the values of the orientation tag private static Set<String> imageOrientationsOf(ImageMetadata metadata) { String exifIFD0DirName = new ExifIFD0Directory().getName(); Tag[] tags = Arrays.stream(metadata.directories()) .filter(dir -> dir.name().equals(exifIFD0DirName)) .findFirst() .map(Directory::tags) .orElseGet(() -> new Tag[0]); return Arrays.stream(tags) .filter(tag -> tag.type() == 274) .map(Tag::rawValue) .collect(Collectors.toSet()); } }
scrimage-core/src/main/java/com/sksamuel/scrimage/Orientation.java
package com.sksamuel.scrimage; import com.drew.metadata.exif.ExifIFD0Directory; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; public class Orientation { public static Boolean requiresReorientation(ImageMetadata metadata) { Set<String> imageOrientations = imageOrientationsOf(metadata); String first = imageOrientations.stream().findFirst().orElse("-1"); switch (first) { case "2": case "3": case "4": case "5": case "6": case "7": case "8": return true; default: return false; } } public static Image reorient(Image image, ImageMetadata metadata) { Set<String> imageOrientations = imageOrientationsOf(metadata); String first = imageOrientations.stream().findFirst().orElse("-1"); switch (first) { // normal case "1": return image; // Flip horizontally case "2": // Rotate 180 degrees image.flipX(); case "3": // Rotate 180 degrees and flip horizontally image.rotateLeft().rotateLeft(); case "4": // Rotate 90 degrees clockwise and flip horizontally image.rotateLeft().rotateLeft().flipX(); case "5": // Rotate 90 degrees clockwise image.rotateRight().flipX(); case "6": // Rotate 90 degrees anti-clockwise and flip horizontally image.rotateRight(); case "7": // Rotate 90 degrees anti-clockwise return image.rotateLeft().flipX(); case "8": return image.rotateLeft(); // Unknown, keep the orginal image default: return image; } } // returns the values of the orientation tag private static Set<String> imageOrientationsOf(ImageMetadata metadata) { String exifIFD0DirName = new ExifIFD0Directory().getName(); Tag[] tags = Arrays.stream(metadata.directories()) .filter(dir -> dir.name().equals(exifIFD0DirName)) .findFirst() .map(Directory::tags) .orElseGet(() -> new Tag[0]); return Arrays.stream(tags) .filter(tag -> tag.type() == 274) .map(Tag::rawValue) .collect(Collectors.toSet()); } }
Fixed orientation
scrimage-core/src/main/java/com/sksamuel/scrimage/Orientation.java
Fixed orientation
<ide><path>crimage-core/src/main/java/com/sksamuel/scrimage/Orientation.java <ide> // Flip horizontally <ide> case "2": <ide> // Rotate 180 degrees <del> image.flipX(); <add> return image.flipX(); <ide> case "3": <ide> // Rotate 180 degrees and flip horizontally <del> image.rotateLeft().rotateLeft(); <add> return image.rotateLeft().rotateLeft(); <ide> case "4": <ide> // Rotate 90 degrees clockwise and flip horizontally <del> image.rotateLeft().rotateLeft().flipX(); <add> return image.rotateLeft().rotateLeft().flipX(); <ide> case "5": <ide> // Rotate 90 degrees clockwise <del> image.rotateRight().flipX(); <add> return image.rotateRight().flipX(); <ide> case "6": <ide> // Rotate 90 degrees anti-clockwise and flip horizontally <del> image.rotateRight(); <add> return image.rotateRight(); <ide> case "7": <ide> // Rotate 90 degrees anti-clockwise <ide> return image.rotateLeft().flipX();
Java
apache-2.0
e634340201ea5bd38bb0a1806d63d7f1e8a7ff6f
0
xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services
package org.sagebionetworks.javadoc; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URL; import com.sun.javadoc.RootDoc; import com.sun.tools.javadoc.Main; /** * This utility helps create a real RootDoc from a source file for testing. * @author jmhill * */ public class JavaDocTestUtil { public static RootDoc buildRootDoc(String sourceFile) throws IOException { // Lookup the test files. File sampleSourceFile = findFileOnClasspath(sourceFile); // Find the classpath file generated by the maven-dependency-plugin String propertyValue = System.getProperty("auto.generated.classpath"); if(propertyValue == null){ // this occurs when run in eclipse. propertyValue = "target/gen/auto-generated-classpath.txt"; } System.out.println(propertyValue); File classpathFile = new File(propertyValue); assertTrue("Classpath files does not exist: "+classpathFile.getAbsolutePath(), classpathFile.exists()); // Lookup the output directory. propertyValue = System.getProperty("test.javadoc.output.directory"); if(propertyValue == null){ // this occurs when run in eclipse. propertyValue = "target/javadoc"; } File outputDirectory = new File(propertyValue); File additionalClasspathDirectory = findFileOnClasspath("org/sagebionetworks/javadoc/testclasses/"); additionalClasspathDirectory = additionalClasspathDirectory.getParentFile().getParentFile().getParentFile().getParentFile(); BufferedReader reader = new BufferedReader(new FileReader(classpathFile)); String classpath = reader.readLine(); reader.close(); classpath += File.pathSeparator + additionalClasspathDirectory.getAbsolutePath(); int result = Main.execute(JavaDocTestUtil.class.getClassLoader(), new String[]{ "-d", outputDirectory.getAbsolutePath(), "-doclet", TestDoclet.class.getName(), "-classpath", classpath, "-verbose", sampleSourceFile.getAbsolutePath() }); return TestDoclet.getLastRoot(); } public static File findFileOnClasspath(String fileName){ URL url = JavaDocTestUtil.class.getClassLoader().getResource(fileName); assertNotNull("Failed to find: "+fileName+" on the classpath", url); File file = new File(url.getFile().replaceAll("%20", " ")); assertTrue(file.exists()); return file; } }
lib/lib-javadoc/src/test/java/org/sagebionetworks/javadoc/JavaDocTestUtil.java
package org.sagebionetworks.javadoc; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URL; import com.sun.javadoc.RootDoc; import com.sun.tools.javadoc.Main; /** * This utility helps create a real RootDoc from a source file for testing. * @author jmhill * */ public class JavaDocTestUtil { public static RootDoc buildRootDoc(String sourceFile) throws IOException { // Lookup the test files. File sampleSourceFile = findFileOnClasspath(sourceFile); // Find the classpath file generated by the maven-dependency-plugin String propertyValue = System.getProperty("auto.generated.classpath"); if(propertyValue == null){ // this occurs when run in eclipse. propertyValue = "target/gen/auto-generated-classpath.txt"; } System.out.println(propertyValue); File classpathFile = new File(propertyValue); assertTrue("Classpath files does not exist: "+classpathFile.getAbsolutePath(), classpathFile.exists()); // Lookup the output directory. propertyValue = System.getProperty("test.javadoc.output.directory"); if(propertyValue == null){ // this occurs when run in eclipse. propertyValue = "target/javadoc"; } File outputDirectory = new File(propertyValue); File additionalClasspathDirectory = findFileOnClasspath("org/sagebionetworks/javadoc/testclasses/"); additionalClasspathDirectory = additionalClasspathDirectory.getParentFile().getParentFile().getParentFile().getParentFile(); BufferedReader reader = new BufferedReader(new FileReader(classpathFile)); String classpath = reader.readLine(); reader.close(); classpath += File.pathSeparator + additionalClasspathDirectory.getAbsolutePath() + File.separator; int result = Main.execute(JavaDocTestUtil.class.getClassLoader(), new String[]{ "-d", outputDirectory.getAbsolutePath(), "-doclet", TestDoclet.class.getName(), "-classpath", classpath, "-verbose", sampleSourceFile.getAbsolutePath() }); return TestDoclet.getLastRoot(); } public static File findFileOnClasspath(String fileName){ URL url = JavaDocTestUtil.class.getClassLoader().getResource(fileName); assertNotNull("Failed to find: "+fileName+" on the classpath", url); File file = new File(url.getFile().replaceAll("%20", " ")); assertTrue(file.exists()); return file; } }
Remove extra separator
lib/lib-javadoc/src/test/java/org/sagebionetworks/javadoc/JavaDocTestUtil.java
Remove extra separator
<ide><path>ib/lib-javadoc/src/test/java/org/sagebionetworks/javadoc/JavaDocTestUtil.java <ide> BufferedReader reader = new BufferedReader(new FileReader(classpathFile)); <ide> String classpath = reader.readLine(); <ide> reader.close(); <del> classpath += File.pathSeparator + additionalClasspathDirectory.getAbsolutePath() + File.separator; <add> classpath += File.pathSeparator + additionalClasspathDirectory.getAbsolutePath(); <ide> <ide> int result = Main.execute(JavaDocTestUtil.class.getClassLoader(), new String[]{ <ide> "-d",
Java
apache-2.0
5d479dc645959f51ed7c56696d70e8e779f07d88
0
OpenVidu/openvidu,OpenVidu/openvidu,OpenVidu/openvidu,OpenVidu/openvidu,OpenVidu/openvidu,OpenVidu/openvidu
/* * (C) Copyright 2017-2020 OpenVidu (https://openvidu.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.openvidu.server.recording.service; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Volume; import io.openvidu.client.OpenViduException; import io.openvidu.client.OpenViduException.Code; import io.openvidu.java.client.RecordingLayout; import io.openvidu.java.client.RecordingProperties; import io.openvidu.server.cdr.CallDetailRecord; import io.openvidu.server.config.OpenviduConfig; import io.openvidu.server.core.EndReason; import io.openvidu.server.core.Participant; import io.openvidu.server.core.Session; import io.openvidu.server.kurento.core.KurentoParticipant; import io.openvidu.server.kurento.core.KurentoSession; import io.openvidu.server.recording.CompositeWrapper; import io.openvidu.server.recording.Recording; import io.openvidu.server.recording.RecordingDownloader; import io.openvidu.server.recording.RecordingInfoUtils; import io.openvidu.server.recording.RecordingUploader; import io.openvidu.server.rest.RequestMappings; import io.openvidu.server.utils.CustomFileManager; import io.openvidu.server.utils.DockerManager; public class ComposedRecordingService extends RecordingService { private static final Logger log = LoggerFactory.getLogger(ComposedRecordingService.class); protected Map<String, String> containers = new ConcurrentHashMap<>(); protected Map<String, String> sessionsContainers = new ConcurrentHashMap<>(); private Map<String, CompositeWrapper> composites = new ConcurrentHashMap<>(); protected DockerManager dockerManager; public ComposedRecordingService(RecordingManager recordingManager, RecordingDownloader recordingDownloader, RecordingUploader recordingUploader, CustomFileManager fileManager, OpenviduConfig openviduConfig, CallDetailRecord cdr, DockerManager dockerManager) { super(recordingManager, recordingDownloader, recordingUploader, fileManager, openviduConfig, cdr); this.dockerManager = dockerManager; } @Override public Recording startRecording(Session session, RecordingProperties properties) throws OpenViduException { PropertiesRecordingId updatePropertiesAndRecordingId = this.setFinalRecordingNameAndGetFreeRecordingId(session, properties); properties = updatePropertiesAndRecordingId.properties; String recordingId = updatePropertiesAndRecordingId.recordingId; // Instantiate and store recording object Recording recording = new Recording(session.getSessionId(), recordingId, properties); this.recordingManager.recordingToStarting(recording); if (properties.hasVideo()) { // Docker container used recording = this.startRecordingWithVideo(session, recording, properties); } else { // Kurento composite used recording = this.startRecordingAudioOnly(session, recording, properties); } return recording; } @Override public Recording stopRecording(Session session, Recording recording, EndReason reason) { if (recording.hasVideo()) { return this.stopRecordingWithVideo(session, recording, reason); } else { return this.stopRecordingAudioOnly(session, recording, reason, null); } } public Recording stopRecording(Session session, Recording recording, EndReason reason, Long kmsDisconnectionTime) { if (recording.hasVideo()) { return this.stopRecordingWithVideo(session, recording, reason); } else { return this.stopRecordingAudioOnly(session, recording, reason, kmsDisconnectionTime); } } public void joinPublisherEndpointToComposite(Session session, String recordingId, Participant participant) throws OpenViduException { log.info("Joining single stream {} to Composite in session {}", participant.getPublisherStreamId(), session.getSessionId()); KurentoParticipant kurentoParticipant = (KurentoParticipant) participant; CompositeWrapper compositeWrapper = this.composites.get(session.getSessionId()); try { compositeWrapper.connectPublisherEndpoint(kurentoParticipant.getPublisher()); } catch (OpenViduException e) { if (Code.RECORDING_START_ERROR_CODE.getValue() == e.getCodeValue()) { // First user publishing triggered RecorderEnpoint start, but it failed throw e; } } } public void removePublisherEndpointFromComposite(String sessionId, String streamId) { CompositeWrapper compositeWrapper = this.composites.get(sessionId); compositeWrapper.disconnectPublisherEndpoint(streamId); } protected Recording startRecordingWithVideo(Session session, Recording recording, RecordingProperties properties) throws OpenViduException { log.info("Starting composed ({}) recording {} of session {}", properties.hasAudio() ? "video + audio" : "video-only", recording.getId(), recording.getSessionId()); List<String> envs = new ArrayList<>(); String layoutUrl = this.getLayoutUrl(recording); envs.add("DEBUG_MODE=" + openviduConfig.isOpenViduRecordingDebug()); envs.add("URL=" + layoutUrl); envs.add("ONLY_VIDEO=" + !properties.hasAudio()); envs.add("RESOLUTION=" + properties.resolution()); envs.add("FRAMERATE=30"); envs.add("VIDEO_ID=" + recording.getId()); envs.add("VIDEO_NAME=" + properties.name()); envs.add("VIDEO_FORMAT=mp4"); envs.add("RECORDING_JSON=" + recording.toJson().toString()); log.info(recording.toJson().toString()); log.info("Recorder connecting to url {}", layoutUrl); String containerId; try { final String container = RecordingManager.IMAGE_NAME + ":" + RecordingManager.IMAGE_TAG; final String containerName = "recording_" + recording.getId(); Volume volume1 = new Volume("/recordings"); List<Volume> volumes = new ArrayList<>(); volumes.add(volume1); Bind bind1 = new Bind(openviduConfig.getOpenViduRecordingPath(), volume1); List<Bind> binds = new ArrayList<>(); binds.add(bind1); containerId = dockerManager.runContainer(properties.mediaNode(), container, containerName, null, volumes, binds, "host", envs, null, properties.shmSize(), false, null); containers.put(containerId, containerName); } catch (Exception e) { this.cleanRecordingMaps(recording); throw this.failStartRecording(session, recording, "Couldn't initialize recording container. Error: " + e.getMessage()); } this.sessionsContainers.put(session.getSessionId(), containerId); try { this.waitForVideoFileNotEmpty(recording); } catch (Exception e) { this.cleanRecordingMaps(recording); throw this.failStartRecording(session, recording, "Couldn't initialize recording container. Error: " + e.getMessage()); } if (this.openviduConfig.isRecordingComposedExternal()) { this.generateRecordingMetadataFile(recording); } return recording; } private Recording startRecordingAudioOnly(Session session, Recording recording, RecordingProperties properties) throws OpenViduException { log.info("Starting composed (audio-only) recording {} of session {}", recording.getId(), recording.getSessionId()); CompositeWrapper compositeWrapper = new CompositeWrapper((KurentoSession) session, "file://" + this.openviduConfig.getOpenViduRecordingPath() + recording.getId() + "/" + properties.name() + ".webm"); this.composites.put(session.getSessionId(), compositeWrapper); for (Participant p : session.getParticipants()) { if (p.isStreaming()) { try { this.joinPublisherEndpointToComposite(session, recording.getId(), p); } catch (OpenViduException e) { log.error("Error waiting for RecorderEndpooint of Composite to start in session {}", session.getSessionId()); throw this.failStartRecording(session, recording, e.getMessage()); } } } this.generateRecordingMetadataFile(recording); return recording; } protected Recording stopRecordingWithVideo(Session session, Recording recording, EndReason reason) { log.info("Stopping composed ({}) recording {} of session {}. Reason: {}", recording.hasAudio() ? "video + audio" : "video-only", recording.getId(), recording.getSessionId(), RecordingManager.finalReason(reason)); String containerId = this.sessionsContainers.remove(recording.getSessionId()); final String recordingId = recording.getId(); if (session == null) { log.warn( "Existing recording {} does not have an active session associated. This usually means a custom recording" + " layout did not join a recorded participant or the recording has been automatically" + " stopped after last user left and timeout passed", recording.getId()); } if (containerId == null) { if (this.recordingManager.startingRecordings.containsKey(recordingId)) { // Session was closed while recording container was initializing // Wait until containerId is available and force its stop and deletion final Recording recordingAux = recording; new Thread(() -> { log.warn("Session closed while starting recording container"); boolean containerClosed = false; String containerIdAux; int i = 0; final int timeout = 30; while (!containerClosed && (i < timeout)) { containerIdAux = this.sessionsContainers.remove(session.getSessionId()); if (containerIdAux == null) { try { log.warn("Waiting for container to be launched..."); i++; Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } else { log.warn("Removing container {} for closed session {}...", containerIdAux, session.getSessionId()); dockerManager.removeContainer(recordingAux.getRecordingProperties().mediaNode(), containerIdAux, true); containers.remove(containerId); containerClosed = true; log.warn("Container {} for closed session {} succesfully stopped and removed", containerIdAux, session.getSessionId()); log.warn("Deleting unusable files for recording {}", recordingId); if (HttpStatus.NO_CONTENT .equals(this.recordingManager.deleteRecordingFromHost(recordingId, true))) { log.warn("Files properly deleted for recording {}", recordingId); } else { log.warn("No files found for recording {}", recordingId); } } } cleanRecordingMaps(recordingAux); if (i == timeout) { log.error("Container did not launched in {} seconds", timeout / 2); return; } // Decrement active recordings ((KurentoSession) session).getKms().decrementActiveRecordings(); }).start(); } } else { stopAndRemoveRecordingContainer(recording, containerId, 30); if (session != null && reason != null) { this.recordingManager.sessionHandler.sendRecordingStoppedNotification(session, recording, reason); } downloadComposedRecording(session, recording, reason); } return recording; } private Recording stopRecordingAudioOnly(Session session, Recording recording, EndReason reason, Long kmsDisconnectionTime) { log.info("Stopping composed (audio-only) recording {} of session {}. Reason: {}", recording.getId(), recording.getSessionId(), reason); String sessionId; if (session == null) { log.warn( "Existing recording {} does not have an active session associated. This means the recording " + "has been automatically stopped after last user left and {} seconds timeout passed", recording.getId(), this.openviduConfig.getOpenviduRecordingAutostopTimeout()); sessionId = recording.getSessionId(); } else { sessionId = session.getSessionId(); } CompositeWrapper compositeWrapper = this.composites.remove(sessionId); final CountDownLatch stoppedCountDown = new CountDownLatch(1); compositeWrapper.stopCompositeRecording(stoppedCountDown, kmsDisconnectionTime); try { if (!stoppedCountDown.await(5, TimeUnit.SECONDS)) { recording.setStatus(io.openvidu.java.client.Recording.Status.failed); log.error("Error waiting for RecorderEndpoint of Composite to stop in session {}", recording.getSessionId()); } } catch (InterruptedException e) { recording.setStatus(io.openvidu.java.client.Recording.Status.failed); log.error("Exception while waiting for state change", e); } compositeWrapper.disconnectAllPublisherEndpoints(); this.cleanRecordingMaps(recording); final Recording[] finalRecordingArray = new Recording[1]; finalRecordingArray[0] = recording; try { this.recordingDownloader.downloadRecording(finalRecordingArray[0], null, () -> { String filesPath = this.openviduConfig.getOpenViduRecordingPath() + finalRecordingArray[0].getId() + "/"; File videoFile = new File(filesPath + finalRecordingArray[0].getName() + ".webm"); long finalSize = videoFile.length(); double finalDuration = (double) compositeWrapper.getDuration() / 1000; this.updateFilePermissions(filesPath); finalRecordingArray[0] = this.sealRecordingMetadataFileAsReady(finalRecordingArray[0], finalSize, finalDuration, filesPath + RecordingService.RECORDING_ENTITY_FILE + finalRecordingArray[0].getId()); // Decrement active recordings once it is downloaded. This method will also drop // the Media Node if no more sessions or recordings and status is // waiting-idle-to-terminate ((KurentoSession) session).getKms().decrementActiveRecordings(); // Upload if necessary this.uploadRecording(finalRecordingArray[0], reason); }); } catch (IOException e) { log.error("Error while downloading recording {}: {}", finalRecordingArray[0].getName(), e.getMessage()); } if (reason != null && session != null) { this.recordingManager.sessionHandler.sendRecordingStoppedNotification(session, finalRecordingArray[0], reason); } return finalRecordingArray[0]; } private void stopAndRemoveRecordingContainer(Recording recording, String containerId, int secondsOfWait) { // Gracefully stop ffmpeg process try { dockerManager.runCommandInContainerAsync(recording.getRecordingProperties().mediaNode(), containerId, "echo 'q' > stop"); } catch (IOException e1) { e1.printStackTrace(); } // Wait for the container to be gracefully self-stopped final int timeOfWait = 30; try { dockerManager.waitForContainerStopped(recording.getRecordingProperties().mediaNode(), containerId, timeOfWait); } catch (Exception e) { failRecordingCompletion(recording, containerId, true, new OpenViduException(Code.RECORDING_COMPLETION_ERROR_CODE, "The recording completion process couldn't finish in " + timeOfWait + " seconds")); } // Remove container dockerManager.removeContainer(recording.getRecordingProperties().mediaNode(), containerId, false); containers.remove(containerId); } protected void updateRecordingAttributes(Recording recording) { try { RecordingInfoUtils infoUtils = new RecordingInfoUtils(this.openviduConfig.getOpenViduRecordingPath() + recording.getId() + "/" + recording.getId() + RecordingService.COMPOSED_INFO_FILE_EXTENSION); if (!infoUtils.hasVideo()) { log.error("COMPOSED recording {} with hasVideo=true has not video track", recording.getId()); recording.setStatus(io.openvidu.java.client.Recording.Status.failed); } else { recording.setStatus(io.openvidu.java.client.Recording.Status.ready); recording.setDuration(infoUtils.getDurationInSeconds()); recording.setSize(infoUtils.getSizeInBytes()); recording.setResolution(infoUtils.videoWidth() + "x" + infoUtils.videoHeight()); recording.setHasAudio(infoUtils.hasAudio()); recording.setHasVideo(infoUtils.hasVideo()); } infoUtils.deleteFilePath(); } catch (IOException e) { recording.setStatus(io.openvidu.java.client.Recording.Status.failed); throw new OpenViduException(Code.RECORDING_REPORT_ERROR_CODE, "There was an error generating the metadata report file for the recording: " + e.getMessage()); } } protected void waitForVideoFileNotEmpty(Recording recording) throws Exception { final String VIDEO_FILE = this.openviduConfig.getOpenViduRecordingPath() + recording.getId() + "/" + recording.getName() + RecordingService.COMPOSED_RECORDING_EXTENSION; int SECONDS_MAX_WAIT = 20; this.fileManager.waitForFileToExistAndNotEmpty(recording.getRecordingProperties().mediaNode(), VIDEO_FILE, SECONDS_MAX_WAIT); } protected void failRecordingCompletion(Recording recording, String containerId, boolean removeContainer, OpenViduException e) throws OpenViduException { recording.setStatus(io.openvidu.java.client.Recording.Status.failed); if (removeContainer) { dockerManager.removeContainer(recording.getRecordingProperties().mediaNode(), containerId, true); containers.remove(containerId); } sealRecordingMetadataFileAsReady(recording, recording.getSize(), recording.getDuration(), getMetadataFilePath(recording)); cleanRecordingMaps(recording); throw e; } protected String getLayoutUrl(Recording recording) throws OpenViduException { String secret = openviduConfig.getOpenViduSecret(); // Check if "customLayout" property defines a final URL if (RecordingLayout.CUSTOM.equals(recording.getRecordingLayout())) { String layout = recording.getCustomLayout(); if (!layout.isEmpty()) { try { URL url = new URL(layout); log.info("\"customLayout\" property has a URL format ({}). Using it to connect to custom layout", url.toString()); return this.processCustomLayoutUrlFormat(url, recording.getSessionId()); } catch (MalformedURLException e) { String layoutPath = openviduConfig.getOpenviduRecordingCustomLayout() + layout; layoutPath = layoutPath.endsWith("/") ? layoutPath : (layoutPath + "/"); log.info( "\"customLayout\" property is defined as \"{}\". Using a different custom layout than the default one. Expected path: {}", layout, layoutPath + "index.html"); try { final File indexHtml = new File(layoutPath + "index.html"); if (!indexHtml.exists()) { throw new IOException(); } log.info("Custom layout path \"{}\" is valid. Found file {}", layout, indexHtml.getAbsolutePath()); } catch (IOException e1) { final String error = "Custom layout path " + layout + " is not valid. Expected file " + layoutPath + "index.html to exist and be readable"; log.error(error); throw new OpenViduException(Code.RECORDING_PATH_NOT_VALID, error); } } } } boolean recordingComposedUrlDefined = openviduConfig.getOpenViduRecordingComposedUrl() != null && !openviduConfig.getOpenViduRecordingComposedUrl().isEmpty(); String recordingUrl = recordingComposedUrlDefined ? openviduConfig.getOpenViduRecordingComposedUrl() : openviduConfig.getFinalUrl(); recordingUrl = recordingUrl.replaceFirst("https://", ""); boolean startsWithHttp = recordingUrl.startsWith("http://"); if (startsWithHttp) { recordingUrl = recordingUrl.replaceFirst("http://", ""); } if (recordingUrl.endsWith("/")) { recordingUrl = recordingUrl.substring(0, recordingUrl.length() - 1); } String layout, finalUrl; final String basicauth = openviduConfig.isOpenviduRecordingComposedBasicauth() ? ("OPENVIDUAPP:" + secret + "@") : ""; if (RecordingLayout.CUSTOM.equals(recording.getRecordingLayout())) { layout = recording.getCustomLayout(); if (!layout.isEmpty()) { layout = layout.startsWith("/") ? layout : ("/" + layout); layout = layout.endsWith("/") ? layout.substring(0, layout.length() - 1) : layout; } layout += "/index.html"; finalUrl = (startsWithHttp ? "http" : "https") + "://" + basicauth + recordingUrl + RequestMappings.CUSTOM_LAYOUTS + layout + "?sessionId=" + recording.getSessionId() + "&secret=" + secret; } else { layout = recording.getRecordingLayout().name().toLowerCase().replaceAll("_", "-"); int port = startsWithHttp ? 80 : 443; try { port = new URL(openviduConfig.getFinalUrl()).getPort(); } catch (MalformedURLException e) { log.error(e.getMessage()); } String defaultPathForDefaultLayout = recordingComposedUrlDefined ? "" : (openviduConfig.getOpenViduFrontendDefaultPath()); finalUrl = (startsWithHttp ? "http" : "https") + "://" + basicauth + recordingUrl + defaultPathForDefaultLayout + "/#/layout-" + layout + "/" + recording.getSessionId() + "/" + secret + "/" + port + "/" + !recording.hasAudio(); } return finalUrl; } private String processCustomLayoutUrlFormat(URL url, String shortSessionId) { String finalUrl = url.getProtocol() + "://" + url.getAuthority(); if (!url.getPath().isEmpty()) { finalUrl += url.getPath(); } finalUrl = finalUrl.endsWith("/") ? finalUrl.substring(0, finalUrl.length() - 1) : finalUrl; if (url.getQuery() != null) { URI uri; try { uri = url.toURI(); finalUrl += "?"; } catch (URISyntaxException e) { String error = "\"customLayout\" property has URL format and query params (" + url.toString() + "), but does not comply with RFC2396 URI format"; log.error(error); throw new OpenViduException(Code.RECORDING_PATH_NOT_VALID, error); } List<NameValuePair> params = URLEncodedUtils.parse(uri, Charset.forName("UTF-8")); Iterator<NameValuePair> it = params.iterator(); boolean hasSessionId = false; boolean hasSecret = false; while (it.hasNext()) { NameValuePair param = it.next(); finalUrl += param.getName() + "=" + param.getValue(); if (it.hasNext()) { finalUrl += "&"; } if (!hasSessionId) { hasSessionId = param.getName().equals("sessionId"); } if (!hasSecret) { hasSecret = param.getName().equals("secret"); } } if (!hasSessionId) { finalUrl += "&sessionId=" + shortSessionId; } if (!hasSecret) { finalUrl += "&secret=" + openviduConfig.getOpenViduSecret(); } } if (url.getRef() != null) { finalUrl += "#" + url.getRef(); } return finalUrl; } protected void downloadComposedRecording(final Session session, final Recording recording, final EndReason reason) { try { this.recordingDownloader.downloadRecording(recording, null, () -> { updateRecordingAttributes(recording); this.sealRecordingMetadataFileAsReady(recording, recording.getSize(), recording.getDuration(), getMetadataFilePath(recording)); cleanRecordingMaps(recording); // Decrement active recordings once it is downloaded. This method will also drop // the Media Node if no more sessions or recordings and status is // waiting-idle-to-terminate ((KurentoSession) session).getKms().decrementActiveRecordings(); // Upload if necessary this.uploadRecording(recording, reason); }); } catch (IOException e) { log.error("Error while downloading recording {}: {}", recording.getName(), e.getMessage()); } } }
openvidu-server/src/main/java/io/openvidu/server/recording/service/ComposedRecordingService.java
/* * (C) Copyright 2017-2020 OpenVidu (https://openvidu.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.openvidu.server.recording.service; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Volume; import io.openvidu.client.OpenViduException; import io.openvidu.client.OpenViduException.Code; import io.openvidu.java.client.RecordingLayout; import io.openvidu.java.client.RecordingProperties; import io.openvidu.server.cdr.CallDetailRecord; import io.openvidu.server.config.OpenviduConfig; import io.openvidu.server.core.EndReason; import io.openvidu.server.core.Participant; import io.openvidu.server.core.Session; import io.openvidu.server.kurento.core.KurentoParticipant; import io.openvidu.server.kurento.core.KurentoSession; import io.openvidu.server.recording.CompositeWrapper; import io.openvidu.server.recording.Recording; import io.openvidu.server.recording.RecordingDownloader; import io.openvidu.server.recording.RecordingInfoUtils; import io.openvidu.server.recording.RecordingUploader; import io.openvidu.server.rest.RequestMappings; import io.openvidu.server.utils.CustomFileManager; import io.openvidu.server.utils.DockerManager; public class ComposedRecordingService extends RecordingService { private static final Logger log = LoggerFactory.getLogger(ComposedRecordingService.class); protected Map<String, String> containers = new ConcurrentHashMap<>(); protected Map<String, String> sessionsContainers = new ConcurrentHashMap<>(); private Map<String, CompositeWrapper> composites = new ConcurrentHashMap<>(); protected DockerManager dockerManager; public ComposedRecordingService(RecordingManager recordingManager, RecordingDownloader recordingDownloader, RecordingUploader recordingUploader, CustomFileManager fileManager, OpenviduConfig openviduConfig, CallDetailRecord cdr, DockerManager dockerManager) { super(recordingManager, recordingDownloader, recordingUploader, fileManager, openviduConfig, cdr); this.dockerManager = dockerManager; } @Override public Recording startRecording(Session session, RecordingProperties properties) throws OpenViduException { PropertiesRecordingId updatePropertiesAndRecordingId = this.setFinalRecordingNameAndGetFreeRecordingId(session, properties); properties = updatePropertiesAndRecordingId.properties; String recordingId = updatePropertiesAndRecordingId.recordingId; // Instantiate and store recording object Recording recording = new Recording(session.getSessionId(), recordingId, properties); this.recordingManager.recordingToStarting(recording); if (properties.hasVideo()) { // Docker container used recording = this.startRecordingWithVideo(session, recording, properties); } else { // Kurento composite used recording = this.startRecordingAudioOnly(session, recording, properties); } return recording; } @Override public Recording stopRecording(Session session, Recording recording, EndReason reason) { if (recording.hasVideo()) { return this.stopRecordingWithVideo(session, recording, reason); } else { return this.stopRecordingAudioOnly(session, recording, reason, null); } } public Recording stopRecording(Session session, Recording recording, EndReason reason, Long kmsDisconnectionTime) { if (recording.hasVideo()) { return this.stopRecordingWithVideo(session, recording, reason); } else { return this.stopRecordingAudioOnly(session, recording, reason, kmsDisconnectionTime); } } public void joinPublisherEndpointToComposite(Session session, String recordingId, Participant participant) throws OpenViduException { log.info("Joining single stream {} to Composite in session {}", participant.getPublisherStreamId(), session.getSessionId()); KurentoParticipant kurentoParticipant = (KurentoParticipant) participant; CompositeWrapper compositeWrapper = this.composites.get(session.getSessionId()); try { compositeWrapper.connectPublisherEndpoint(kurentoParticipant.getPublisher()); } catch (OpenViduException e) { if (Code.RECORDING_START_ERROR_CODE.getValue() == e.getCodeValue()) { // First user publishing triggered RecorderEnpoint start, but it failed throw e; } } } public void removePublisherEndpointFromComposite(String sessionId, String streamId) { CompositeWrapper compositeWrapper = this.composites.get(sessionId); compositeWrapper.disconnectPublisherEndpoint(streamId); } protected Recording startRecordingWithVideo(Session session, Recording recording, RecordingProperties properties) throws OpenViduException { log.info("Starting composed ({}) recording {} of session {}", properties.hasAudio() ? "video + audio" : "audio-only", recording.getId(), recording.getSessionId()); List<String> envs = new ArrayList<>(); String layoutUrl = this.getLayoutUrl(recording); envs.add("DEBUG_MODE=" + openviduConfig.isOpenViduRecordingDebug()); envs.add("URL=" + layoutUrl); envs.add("ONLY_VIDEO=" + !properties.hasAudio()); envs.add("RESOLUTION=" + properties.resolution()); envs.add("FRAMERATE=30"); envs.add("VIDEO_ID=" + recording.getId()); envs.add("VIDEO_NAME=" + properties.name()); envs.add("VIDEO_FORMAT=mp4"); envs.add("RECORDING_JSON=" + recording.toJson().toString()); log.info(recording.toJson().toString()); log.info("Recorder connecting to url {}", layoutUrl); String containerId; try { final String container = RecordingManager.IMAGE_NAME + ":" + RecordingManager.IMAGE_TAG; final String containerName = "recording_" + recording.getId(); Volume volume1 = new Volume("/recordings"); List<Volume> volumes = new ArrayList<>(); volumes.add(volume1); Bind bind1 = new Bind(openviduConfig.getOpenViduRecordingPath(), volume1); List<Bind> binds = new ArrayList<>(); binds.add(bind1); containerId = dockerManager.runContainer(properties.mediaNode(), container, containerName, null, volumes, binds, "host", envs, null, properties.shmSize(), false, null); containers.put(containerId, containerName); } catch (Exception e) { this.cleanRecordingMaps(recording); throw this.failStartRecording(session, recording, "Couldn't initialize recording container. Error: " + e.getMessage()); } this.sessionsContainers.put(session.getSessionId(), containerId); try { this.waitForVideoFileNotEmpty(recording); } catch (Exception e) { this.cleanRecordingMaps(recording); throw this.failStartRecording(session, recording, "Couldn't initialize recording container. Error: " + e.getMessage()); } if (this.openviduConfig.isRecordingComposedExternal()) { this.generateRecordingMetadataFile(recording); } return recording; } private Recording startRecordingAudioOnly(Session session, Recording recording, RecordingProperties properties) throws OpenViduException { log.info("Starting composed (audio-only) recording {} of session {}", recording.getId(), recording.getSessionId()); CompositeWrapper compositeWrapper = new CompositeWrapper((KurentoSession) session, "file://" + this.openviduConfig.getOpenViduRecordingPath() + recording.getId() + "/" + properties.name() + ".webm"); this.composites.put(session.getSessionId(), compositeWrapper); for (Participant p : session.getParticipants()) { if (p.isStreaming()) { try { this.joinPublisherEndpointToComposite(session, recording.getId(), p); } catch (OpenViduException e) { log.error("Error waiting for RecorderEndpooint of Composite to start in session {}", session.getSessionId()); throw this.failStartRecording(session, recording, e.getMessage()); } } } this.generateRecordingMetadataFile(recording); return recording; } protected Recording stopRecordingWithVideo(Session session, Recording recording, EndReason reason) { log.info("Stopping composed ({}) recording {} of session {}. Reason: {}", recording.hasAudio() ? "video + audio" : "audio-only", recording.getId(), recording.getSessionId(), RecordingManager.finalReason(reason)); String containerId = this.sessionsContainers.remove(recording.getSessionId()); final String recordingId = recording.getId(); if (session == null) { log.warn( "Existing recording {} does not have an active session associated. This usually means a custom recording" + " layout did not join a recorded participant or the recording has been automatically" + " stopped after last user left and timeout passed", recording.getId()); } if (containerId == null) { if (this.recordingManager.startingRecordings.containsKey(recordingId)) { // Session was closed while recording container was initializing // Wait until containerId is available and force its stop and deletion final Recording recordingAux = recording; new Thread(() -> { log.warn("Session closed while starting recording container"); boolean containerClosed = false; String containerIdAux; int i = 0; final int timeout = 30; while (!containerClosed && (i < timeout)) { containerIdAux = this.sessionsContainers.remove(session.getSessionId()); if (containerIdAux == null) { try { log.warn("Waiting for container to be launched..."); i++; Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } else { log.warn("Removing container {} for closed session {}...", containerIdAux, session.getSessionId()); dockerManager.removeContainer(recordingAux.getRecordingProperties().mediaNode(), containerIdAux, true); containers.remove(containerId); containerClosed = true; log.warn("Container {} for closed session {} succesfully stopped and removed", containerIdAux, session.getSessionId()); log.warn("Deleting unusable files for recording {}", recordingId); if (HttpStatus.NO_CONTENT .equals(this.recordingManager.deleteRecordingFromHost(recordingId, true))) { log.warn("Files properly deleted for recording {}", recordingId); } else { log.warn("No files found for recording {}", recordingId); } } } cleanRecordingMaps(recordingAux); if (i == timeout) { log.error("Container did not launched in {} seconds", timeout / 2); return; } // Decrement active recordings ((KurentoSession) session).getKms().decrementActiveRecordings(); }).start(); } } else { stopAndRemoveRecordingContainer(recording, containerId, 30); if (session != null && reason != null) { this.recordingManager.sessionHandler.sendRecordingStoppedNotification(session, recording, reason); } downloadComposedRecording(session, recording, reason); } return recording; } private Recording stopRecordingAudioOnly(Session session, Recording recording, EndReason reason, Long kmsDisconnectionTime) { log.info("Stopping composed (audio-only) recording {} of session {}. Reason: {}", recording.getId(), recording.getSessionId(), reason); String sessionId; if (session == null) { log.warn( "Existing recording {} does not have an active session associated. This means the recording " + "has been automatically stopped after last user left and {} seconds timeout passed", recording.getId(), this.openviduConfig.getOpenviduRecordingAutostopTimeout()); sessionId = recording.getSessionId(); } else { sessionId = session.getSessionId(); } CompositeWrapper compositeWrapper = this.composites.remove(sessionId); final CountDownLatch stoppedCountDown = new CountDownLatch(1); compositeWrapper.stopCompositeRecording(stoppedCountDown, kmsDisconnectionTime); try { if (!stoppedCountDown.await(5, TimeUnit.SECONDS)) { recording.setStatus(io.openvidu.java.client.Recording.Status.failed); log.error("Error waiting for RecorderEndpoint of Composite to stop in session {}", recording.getSessionId()); } } catch (InterruptedException e) { recording.setStatus(io.openvidu.java.client.Recording.Status.failed); log.error("Exception while waiting for state change", e); } compositeWrapper.disconnectAllPublisherEndpoints(); this.cleanRecordingMaps(recording); final Recording[] finalRecordingArray = new Recording[1]; finalRecordingArray[0] = recording; try { this.recordingDownloader.downloadRecording(finalRecordingArray[0], null, () -> { String filesPath = this.openviduConfig.getOpenViduRecordingPath() + finalRecordingArray[0].getId() + "/"; File videoFile = new File(filesPath + finalRecordingArray[0].getName() + ".webm"); long finalSize = videoFile.length(); double finalDuration = (double) compositeWrapper.getDuration() / 1000; this.updateFilePermissions(filesPath); finalRecordingArray[0] = this.sealRecordingMetadataFileAsReady(finalRecordingArray[0], finalSize, finalDuration, filesPath + RecordingService.RECORDING_ENTITY_FILE + finalRecordingArray[0].getId()); // Decrement active recordings once it is downloaded. This method will also drop // the Media Node if no more sessions or recordings and status is // waiting-idle-to-terminate ((KurentoSession) session).getKms().decrementActiveRecordings(); // Upload if necessary this.uploadRecording(finalRecordingArray[0], reason); }); } catch (IOException e) { log.error("Error while downloading recording {}: {}", finalRecordingArray[0].getName(), e.getMessage()); } if (reason != null && session != null) { this.recordingManager.sessionHandler.sendRecordingStoppedNotification(session, finalRecordingArray[0], reason); } return finalRecordingArray[0]; } private void stopAndRemoveRecordingContainer(Recording recording, String containerId, int secondsOfWait) { // Gracefully stop ffmpeg process try { dockerManager.runCommandInContainerAsync(recording.getRecordingProperties().mediaNode(), containerId, "echo 'q' > stop"); } catch (IOException e1) { e1.printStackTrace(); } // Wait for the container to be gracefully self-stopped final int timeOfWait = 30; try { dockerManager.waitForContainerStopped(recording.getRecordingProperties().mediaNode(), containerId, timeOfWait); } catch (Exception e) { failRecordingCompletion(recording, containerId, true, new OpenViduException(Code.RECORDING_COMPLETION_ERROR_CODE, "The recording completion process couldn't finish in " + timeOfWait + " seconds")); } // Remove container dockerManager.removeContainer(recording.getRecordingProperties().mediaNode(), containerId, false); containers.remove(containerId); } protected void updateRecordingAttributes(Recording recording) { try { RecordingInfoUtils infoUtils = new RecordingInfoUtils(this.openviduConfig.getOpenViduRecordingPath() + recording.getId() + "/" + recording.getId() + RecordingService.COMPOSED_INFO_FILE_EXTENSION); if (!infoUtils.hasVideo()) { log.error("COMPOSED recording {} with hasVideo=true has not video track", recording.getId()); recording.setStatus(io.openvidu.java.client.Recording.Status.failed); } else { recording.setStatus(io.openvidu.java.client.Recording.Status.ready); recording.setDuration(infoUtils.getDurationInSeconds()); recording.setSize(infoUtils.getSizeInBytes()); recording.setResolution(infoUtils.videoWidth() + "x" + infoUtils.videoHeight()); recording.setHasAudio(infoUtils.hasAudio()); recording.setHasVideo(infoUtils.hasVideo()); } infoUtils.deleteFilePath(); } catch (IOException e) { recording.setStatus(io.openvidu.java.client.Recording.Status.failed); throw new OpenViduException(Code.RECORDING_REPORT_ERROR_CODE, "There was an error generating the metadata report file for the recording: " + e.getMessage()); } } protected void waitForVideoFileNotEmpty(Recording recording) throws Exception { final String VIDEO_FILE = this.openviduConfig.getOpenViduRecordingPath() + recording.getId() + "/" + recording.getName() + RecordingService.COMPOSED_RECORDING_EXTENSION; int SECONDS_MAX_WAIT = 20; this.fileManager.waitForFileToExistAndNotEmpty(recording.getRecordingProperties().mediaNode(), VIDEO_FILE, SECONDS_MAX_WAIT); } protected void failRecordingCompletion(Recording recording, String containerId, boolean removeContainer, OpenViduException e) throws OpenViduException { recording.setStatus(io.openvidu.java.client.Recording.Status.failed); if (removeContainer) { dockerManager.removeContainer(recording.getRecordingProperties().mediaNode(), containerId, true); containers.remove(containerId); } sealRecordingMetadataFileAsReady(recording, recording.getSize(), recording.getDuration(), getMetadataFilePath(recording)); cleanRecordingMaps(recording); throw e; } protected String getLayoutUrl(Recording recording) throws OpenViduException { String secret = openviduConfig.getOpenViduSecret(); // Check if "customLayout" property defines a final URL if (RecordingLayout.CUSTOM.equals(recording.getRecordingLayout())) { String layout = recording.getCustomLayout(); if (!layout.isEmpty()) { try { URL url = new URL(layout); log.info("\"customLayout\" property has a URL format ({}). Using it to connect to custom layout", url.toString()); return this.processCustomLayoutUrlFormat(url, recording.getSessionId()); } catch (MalformedURLException e) { String layoutPath = openviduConfig.getOpenviduRecordingCustomLayout() + layout; layoutPath = layoutPath.endsWith("/") ? layoutPath : (layoutPath + "/"); log.info( "\"customLayout\" property is defined as \"{}\". Using a different custom layout than the default one. Expected path: {}", layout, layoutPath + "index.html"); try { final File indexHtml = new File(layoutPath + "index.html"); if (!indexHtml.exists()) { throw new IOException(); } log.info("Custom layout path \"{}\" is valid. Found file {}", layout, indexHtml.getAbsolutePath()); } catch (IOException e1) { final String error = "Custom layout path " + layout + " is not valid. Expected file " + layoutPath + "index.html to exist and be readable"; log.error(error); throw new OpenViduException(Code.RECORDING_PATH_NOT_VALID, error); } } } } boolean recordingComposedUrlDefined = openviduConfig.getOpenViduRecordingComposedUrl() != null && !openviduConfig.getOpenViduRecordingComposedUrl().isEmpty(); String recordingUrl = recordingComposedUrlDefined ? openviduConfig.getOpenViduRecordingComposedUrl() : openviduConfig.getFinalUrl(); recordingUrl = recordingUrl.replaceFirst("https://", ""); boolean startsWithHttp = recordingUrl.startsWith("http://"); if (startsWithHttp) { recordingUrl = recordingUrl.replaceFirst("http://", ""); } if (recordingUrl.endsWith("/")) { recordingUrl = recordingUrl.substring(0, recordingUrl.length() - 1); } String layout, finalUrl; final String basicauth = openviduConfig.isOpenviduRecordingComposedBasicauth() ? ("OPENVIDUAPP:" + secret + "@") : ""; if (RecordingLayout.CUSTOM.equals(recording.getRecordingLayout())) { layout = recording.getCustomLayout(); if (!layout.isEmpty()) { layout = layout.startsWith("/") ? layout : ("/" + layout); layout = layout.endsWith("/") ? layout.substring(0, layout.length() - 1) : layout; } layout += "/index.html"; finalUrl = (startsWithHttp ? "http" : "https") + "://" + basicauth + recordingUrl + RequestMappings.CUSTOM_LAYOUTS + layout + "?sessionId=" + recording.getSessionId() + "&secret=" + secret; } else { layout = recording.getRecordingLayout().name().toLowerCase().replaceAll("_", "-"); int port = startsWithHttp ? 80 : 443; try { port = new URL(openviduConfig.getFinalUrl()).getPort(); } catch (MalformedURLException e) { log.error(e.getMessage()); } String defaultPathForDefaultLayout = recordingComposedUrlDefined ? "" : (openviduConfig.getOpenViduFrontendDefaultPath()); finalUrl = (startsWithHttp ? "http" : "https") + "://" + basicauth + recordingUrl + defaultPathForDefaultLayout + "/#/layout-" + layout + "/" + recording.getSessionId() + "/" + secret + "/" + port + "/" + !recording.hasAudio(); } return finalUrl; } private String processCustomLayoutUrlFormat(URL url, String shortSessionId) { String finalUrl = url.getProtocol() + "://" + url.getAuthority(); if (!url.getPath().isEmpty()) { finalUrl += url.getPath(); } finalUrl = finalUrl.endsWith("/") ? finalUrl.substring(0, finalUrl.length() - 1) : finalUrl; if (url.getQuery() != null) { URI uri; try { uri = url.toURI(); finalUrl += "?"; } catch (URISyntaxException e) { String error = "\"customLayout\" property has URL format and query params (" + url.toString() + "), but does not comply with RFC2396 URI format"; log.error(error); throw new OpenViduException(Code.RECORDING_PATH_NOT_VALID, error); } List<NameValuePair> params = URLEncodedUtils.parse(uri, Charset.forName("UTF-8")); Iterator<NameValuePair> it = params.iterator(); boolean hasSessionId = false; boolean hasSecret = false; while (it.hasNext()) { NameValuePair param = it.next(); finalUrl += param.getName() + "=" + param.getValue(); if (it.hasNext()) { finalUrl += "&"; } if (!hasSessionId) { hasSessionId = param.getName().equals("sessionId"); } if (!hasSecret) { hasSecret = param.getName().equals("secret"); } } if (!hasSessionId) { finalUrl += "&sessionId=" + shortSessionId; } if (!hasSecret) { finalUrl += "&secret=" + openviduConfig.getOpenViduSecret(); } } if (url.getRef() != null) { finalUrl += "#" + url.getRef(); } return finalUrl; } protected void downloadComposedRecording(final Session session, final Recording recording, final EndReason reason) { try { this.recordingDownloader.downloadRecording(recording, null, () -> { updateRecordingAttributes(recording); this.sealRecordingMetadataFileAsReady(recording, recording.getSize(), recording.getDuration(), getMetadataFilePath(recording)); cleanRecordingMaps(recording); // Decrement active recordings once it is downloaded. This method will also drop // the Media Node if no more sessions or recordings and status is // waiting-idle-to-terminate ((KurentoSession) session).getKms().decrementActiveRecordings(); // Upload if necessary this.uploadRecording(recording, reason); }); } catch (IOException e) { log.error("Error while downloading recording {}: {}", recording.getName(), e.getMessage()); } } }
openvidu-server: fix log message when recording with video only
openvidu-server/src/main/java/io/openvidu/server/recording/service/ComposedRecordingService.java
openvidu-server: fix log message when recording with video only
<ide><path>penvidu-server/src/main/java/io/openvidu/server/recording/service/ComposedRecordingService.java <ide> throws OpenViduException { <ide> <ide> log.info("Starting composed ({}) recording {} of session {}", <del> properties.hasAudio() ? "video + audio" : "audio-only", recording.getId(), recording.getSessionId()); <add> properties.hasAudio() ? "video + audio" : "video-only", recording.getId(), recording.getSessionId()); <ide> <ide> List<String> envs = new ArrayList<>(); <ide> <ide> protected Recording stopRecordingWithVideo(Session session, Recording recording, EndReason reason) { <ide> <ide> log.info("Stopping composed ({}) recording {} of session {}. Reason: {}", <del> recording.hasAudio() ? "video + audio" : "audio-only", recording.getId(), recording.getSessionId(), <add> recording.hasAudio() ? "video + audio" : "video-only", recording.getId(), recording.getSessionId(), <ide> RecordingManager.finalReason(reason)); <ide> <ide> String containerId = this.sessionsContainers.remove(recording.getSessionId());
Java
apache-2.0
e7491b24064d3b862024c622bc3f76e8b5cad637
0
vmarusic/springfox,yelhouti/springfox,ammmze/swagger-springmvc,zhiqinghuang/springfox,arshadalisoomro/springfox,qq291462491/springfox,namkee/springfox,thomsonreuters/springfox,zhiqinghuang/springfox,ammmze/swagger-springmvc,springfox/springfox,namkee/springfox,izeye/springfox,yelhouti/springfox,arshadalisoomro/springfox,jlstrater/springfox,jlstrater/springfox,ammmze/swagger-springmvc,namkee/springfox,thomsonreuters/springfox,wjc133/springfox,cbornet/springfox,jlstrater/springfox,thomasdarimont/springfox,maksimu/springfox,wjc133/springfox,acourtneybrown/springfox,kevinconaway/springfox,RobWin/springfox,arshadalisoomro/springfox,qq291462491/springfox,acourtneybrown/springfox,RobWin/springfox,vmarusic/springfox,acourtneybrown/springfox,choiapril6/springfox,springfox/springfox,thomsonreuters/springfox,kevinconaway/springfox,wjc133/springfox,erikthered/springfox,thomasdarimont/springfox,kevinconaway/springfox,yelhouti/springfox,erikthered/springfox,izeye/springfox,erikthered/springfox,qq291462491/springfox,cbornet/springfox,RobWin/springfox,maksimu/springfox,vmarusic/springfox,zorosteven/springfox,springfox/springfox,zhiqinghuang/springfox,choiapril6/springfox,cbornet/springfox,zorosteven/springfox,thomasdarimont/springfox,maksimu/springfox,zorosteven/springfox,choiapril6/springfox,springfox/springfox,izeye/springfox
package com.mangofactory.swagger.readers; import com.mangofactory.swagger.scanners.RequestMappingContext; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.converter.SwaggerSchemaConverter; import com.wordnik.swagger.model.Model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.method.HandlerMethod; import scala.Option; import java.util.Map; import static com.google.common.collect.Maps.newHashMap; import static com.mangofactory.swagger.ScalaUtils.fromOption; public class ApiModelReader implements Command<RequestMappingContext> { private static final Logger log = LoggerFactory.getLogger(ApiModelReader.class); @Override public void execute(RequestMappingContext context) { HandlerMethod handlerMethod = context.getHandlerMethod(); log.debug("Reading models for handlerMethod |{}|", handlerMethod.getMethod().getName()); SwaggerSchemaConverter parser = new SwaggerSchemaConverter(); Map<String, Model> modelMap = newHashMap(); Class<?> modelType = handlerMethod.getMethod().getReturnType(); ApiOperation apiOperationAnnotation = handlerMethod.getMethodAnnotation(ApiOperation.class); if(null != apiOperationAnnotation && Void.class != apiOperationAnnotation.response()){ modelType = apiOperationAnnotation.response(); } String schemaName = modelType.isArray() ? modelType.getComponentType().getSimpleName() : modelType.getSimpleName(); Option<Model> sModel = parser.read(modelType, new scala.collection.immutable.HashMap()); Model model = fromOption(sModel); if(null != model) { log.debug("Swagger generated model {} models", model.id()); modelMap.put(schemaName, model); } else{ log.debug("Swagger core did not find any models"); } Class<?>[] parameterTypes = handlerMethod.getMethod().getParameterTypes(); for (Class<?> parameterType : parameterTypes) { String parameterSchemaName = parameterType.isArray() ? parameterType.getComponentType().getSimpleName() : parameterType.getSimpleName(); Option<Model> spModel = parser.read(parameterType, new scala.collection.immutable.HashMap()); Model pModel = fromOption(spModel); if (null != pModel) { log.debug("Swagger generated parameter model {} models", pModel.id()); modelMap.put(parameterSchemaName, pModel); } else { log.debug("Swagger core did not find any parameter models for {}", parameterSchemaName); } } log.debug("Finished reading models for handlerMethod |{}|", handlerMethod.getMethod().getName()); context.put("models", modelMap); } }
src/main/java/com/mangofactory/swagger/readers/ApiModelReader.java
package com.mangofactory.swagger.readers; import com.mangofactory.swagger.scanners.RequestMappingContext; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.converter.SwaggerSchemaConverter; import com.wordnik.swagger.model.Model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.method.HandlerMethod; import scala.Option; import java.util.Map; import static com.google.common.collect.Maps.newHashMap; import static com.mangofactory.swagger.ScalaUtils.fromOption; public class ApiModelReader implements Command<RequestMappingContext> { private static final Logger log = LoggerFactory.getLogger(ApiModelReader.class); @Override public void execute(RequestMappingContext context) { HandlerMethod handlerMethod = context.getHandlerMethod(); log.debug("Reading models for handlerMethod |{}|", handlerMethod.getMethod().getName()); SwaggerSchemaConverter parser = new SwaggerSchemaConverter(); Map<String, Model> modelMap = newHashMap(); Class<?> modelType = handlerMethod.getMethod().getReturnType(); ApiOperation apiOperationAnnotation = handlerMethod.getMethodAnnotation(ApiOperation.class); if(null != apiOperationAnnotation && Void.class != apiOperationAnnotation.response()){ modelType = apiOperationAnnotation.response(); } String schemaName = modelType.isArray() ? modelType.getComponentType().getSimpleName() : modelType.getSimpleName(); Option<Model> sModel = parser.read(modelType, new scala.collection.immutable.HashMap()); Model model = fromOption(sModel); if(null != model) { log.debug("Swagger generated model {} models", model.id()); modelMap.put(schemaName, model); } else{ log.debug("Swagger core did not find any models"); } Class<?>[] parameterTypes = handlerMethod.getMethod().getParameterTypes(); for (Class<?> parameterType : parameterTypes) { String parameterSchemaName = parameterType.isArray() ? parameterType.getComponentType().getSimpleName() : parameterType.getSimpleName(); Option<Model> spModel = parser.read(parameterType, new scala.collection.immutable.HashMap()); Model pModel = fromOption(spModel); if (null != pModel) { log.debug("Swagger generated parameter model {} models", pModel.id()); modelMap.put(parameterSchemaName, pModel); } else { log.debug("Swagger core did not find any parameter models for {}", parameterSchemaName); } } log.debug("Finished reading models for handlerMethod |{}|", handlerMethod.getMethod().getName()); context.put("models", modelMap); } }
#214 fix parameter model generation
src/main/java/com/mangofactory/swagger/readers/ApiModelReader.java
#214 fix parameter model generation
<ide><path>rc/main/java/com/mangofactory/swagger/readers/ApiModelReader.java <ide> log.debug("Swagger core did not find any models"); <ide> } <ide> <del> Class<?>[] parameterTypes = handlerMethod.getMethod().getParameterTypes(); <del> for (Class<?> parameterType : parameterTypes) { <del> String parameterSchemaName = parameterType.isArray() ? parameterType.getComponentType().getSimpleName() : parameterType.getSimpleName(); <del> Option<Model> spModel = parser.read(parameterType, new scala.collection.immutable.HashMap()); <del> Model pModel = fromOption(spModel); <del> if (null != pModel) { <del> log.debug("Swagger generated parameter model {} models", pModel.id()); <del> modelMap.put(parameterSchemaName, pModel); <del> } else { <del> log.debug("Swagger core did not find any parameter models for {}", parameterSchemaName); <del> } <del> } <add> Class<?>[] parameterTypes = handlerMethod.getMethod().getParameterTypes(); <add> for (Class<?> parameterType : parameterTypes) { <add> String parameterSchemaName = parameterType.isArray() ? parameterType.getComponentType().getSimpleName() : parameterType.getSimpleName(); <add> Option<Model> spModel = parser.read(parameterType, new scala.collection.immutable.HashMap()); <add> Model pModel = fromOption(spModel); <add> if (null != pModel) { <add> log.debug("Swagger generated parameter model {} models", pModel.id()); <add> modelMap.put(parameterSchemaName, pModel); <add> } else { <add> log.debug("Swagger core did not find any parameter models for {}", parameterSchemaName); <add> } <add> } <ide> <ide> log.debug("Finished reading models for handlerMethod |{}|", handlerMethod.getMethod().getName()); <ide> context.put("models", modelMap);
Java
lgpl-2.1
e04e119bbdb689c29dc7d6e98f007765ccc0af91
0
armanbilge/BEAST_sandbox,svn2github/beast-mcmc,armanbilge/BEAST_sandbox,svn2github/beast-mcmc,svn2github/beast-mcmc,svn2github/beast-mcmc,armanbilge/BEAST_sandbox,armanbilge/BEAST_sandbox,svn2github/beast-mcmc,armanbilge/BEAST_sandbox
/* * HierarchicalTransmissionDemographicModel.java * * Copyright (c) 2002-2012 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.evomodel.transmission; import dr.evoxml.util.XMLUnits; import dr.inference.model.Parameter; import dr.xml.*; /** * A demographic model for within patient evolution in a transmission history with a hierarchical parameterization. * * @author Marc A. Suchard * @author Andrew Rambaut * @version $Id: TransmissionDemographicModel.java,v 1.7 2005/05/24 20:25:58 rambaut Exp $ */ public class HierarchicalTransmissionDemographicModel extends TransmissionDemographicModel { // // Public stuff // public static String HIERARCHICAL_TRANSMISSION_MODEL = "hierarchicalTransmissionModel"; public static String CONSTANT = TransmissionDemographicModel.CONSTANT; public static String EXPONENTIAL = TransmissionDemographicModel.EXPONENTIAL; public static String LOGISTIC = TransmissionDemographicModel.LOGISTIC; public static String POPULATION_SIZE = TransmissionDemographicModel.POPULATION_SIZE; public static String ANCESTRAL_PROPORTION = TransmissionDemographicModel.ANCESTRAL_PROPORTION; public static String GROWTH_RATE = TransmissionDemographicModel.GROWTH_RATE; public static String DOUBLING_TIME = TransmissionDemographicModel.DOUBLING_TIME; public static final String HOST_COUNT = "hostCount"; public HierarchicalTransmissionDemographicModel(int model, Parameter N0Parameter, Parameter N1Parameter, Parameter growthRateParameter, Parameter doublingTimeParameter, Type units) { this(HIERARCHICAL_TRANSMISSION_MODEL, model, N0Parameter, N1Parameter, growthRateParameter, doublingTimeParameter, units); } public HierarchicalTransmissionDemographicModel(String name, int model, Parameter N0Parameter, Parameter N1Parameter, Parameter growthRateParameter, Parameter doublingTimeParameter, Type units) { super(name, model, N0Parameter, N1Parameter, growthRateParameter, doublingTimeParameter, units); } public void resizeHierarchicalParameters(int hostCount) { if (N0Parameter != null) { N0Parameter.setDimension(hostCount); // N0Parameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); } if (N1Parameter != null) { N1Parameter.setDimension(hostCount); // N1Parameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); } if (growthRateParameter != null) { growthRateParameter.setDimension(hostCount); // growthRateParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); } if (doublingTimeParameter != null) { doublingTimeParameter.setDimension(hostCount); // doublingTimeParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); } } protected int getIndexFromHost(int host) { return host - 1; } /** * Parses an element from an DOM document into a ExponentialGrowth. */ public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return HIERARCHICAL_TRANSMISSION_MODEL; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { Type units = XMLUnits.Utils.getUnitsAttr(xo); int model = 0; Parameter N0Param = null; Parameter N1Param = null; Parameter rParam = null; Parameter dParam = null; if (xo.hasChildNamed(CONSTANT)) { XMLObject cxo = xo.getChild(CONSTANT); N0Param = (Parameter) cxo.getElementFirstChild(POPULATION_SIZE); model = 0; } else if (xo.hasChildNamed(EXPONENTIAL)) { XMLObject cxo = xo.getChild(EXPONENTIAL); N1Param = (Parameter) cxo.getElementFirstChild(ANCESTRAL_PROPORTION); if (cxo.hasChildNamed(GROWTH_RATE)) { rParam = (Parameter) cxo.getElementFirstChild(GROWTH_RATE); } else { dParam = (Parameter) cxo.getElementFirstChild(DOUBLING_TIME); } model = 1; } else if (xo.hasChildNamed(LOGISTIC)) { XMLObject cxo = xo.getChild(LOGISTIC); N0Param = (Parameter) cxo.getElementFirstChild(POPULATION_SIZE); N1Param = (Parameter) cxo.getElementFirstChild(ANCESTRAL_PROPORTION); if (cxo.hasChildNamed(GROWTH_RATE)) { rParam = (Parameter) cxo.getElementFirstChild(GROWTH_RATE); } else { dParam = (Parameter) cxo.getElementFirstChild(DOUBLING_TIME); } model = 2; } HierarchicalTransmissionDemographicModel demoModel = new HierarchicalTransmissionDemographicModel(model, N0Param, N1Param, rParam, dParam, units); demoModel.resizeHierarchicalParameters(xo.getAttribute(HOST_COUNT, 1)); return demoModel; } //************************************************************************ // AbstractXMLObjectParser implementation //************************************************************************ public String getParserDescription() { return "A SiteModel that has a gamma distributed rates across sites"; } public Class getReturnType() { return HierarchicalTransmissionDemographicModel.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ XMLUnits.UNITS_RULE, AttributeRule.newIntegerRule(HOST_COUNT, false), new XORRule( new ElementRule(CONSTANT, new XMLSyntaxRule[]{ new ElementRule(POPULATION_SIZE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter represents the carrying capacity (maximum population size). " + "If the shape is very large then the current day population size will be very close to the carrying capacity."), } ), new XORRule( new ElementRule(EXPONENTIAL, new XMLSyntaxRule[]{ new XORRule( new ElementRule(GROWTH_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the rate of growth during the exponential phase. See exponentialGrowth for details."), new ElementRule(DOUBLING_TIME, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the doubling time at peak growth rate.")), new ElementRule(ANCESTRAL_PROPORTION, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the populaation size at transmission.") } ), new ElementRule(LOGISTIC, new XMLSyntaxRule[]{ new ElementRule(POPULATION_SIZE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter represents the carrying capacity (maximum population size). " + "If the shape is very large then the current day population size will be very close to the carrying capacity."), new XORRule( new ElementRule(GROWTH_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the rate of growth during the exponential phase. See exponentialGrowth for details."), new ElementRule(DOUBLING_TIME, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the doubling time at peak growth rate.")), new ElementRule(ANCESTRAL_PROPORTION, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the populaation size at transmission.") } ) ) ) }; }; }
src/dr/evomodel/transmission/HierarchicalTransmissionDemographicModel.java
/* * HierarchicalTransmissionDemographicModel.java * * Copyright (c) 2002-2012 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.evomodel.transmission; import dr.evoxml.util.XMLUnits; import dr.inference.model.Parameter; import dr.xml.*; /** * A demographic model for within patient evolution in a transmission history with a hierarchical parameterization. * * @author Marc A. Suchard * @author Andrew Rambaut * @version $Id: TransmissionDemographicModel.java,v 1.7 2005/05/24 20:25:58 rambaut Exp $ */ public class HierarchicalTransmissionDemographicModel extends TransmissionDemographicModel { // // Public stuff // public static String HIERARCHICAL_TRANSMISSION_MODEL = "hierarchicalTransmissionModel"; public static String CONSTANT = TransmissionDemographicModel.CONSTANT; public static String EXPONENTIAL = TransmissionDemographicModel.EXPONENTIAL; public static String LOGISTIC = TransmissionDemographicModel.LOGISTIC; public static String POPULATION_SIZE = TransmissionDemographicModel.POPULATION_SIZE; public static String ANCESTRAL_PROPORTION = TransmissionDemographicModel.ANCESTRAL_PROPORTION; public static String GROWTH_RATE = TransmissionDemographicModel.GROWTH_RATE; public static String DOUBLING_TIME = TransmissionDemographicModel.DOUBLING_TIME; public static final String HOST_COUNT = "hostCount"; public HierarchicalTransmissionDemographicModel(int model, Parameter N0Parameter, Parameter N1Parameter, Parameter growthRateParameter, Parameter doublingTimeParameter, Type units) { this(HIERARCHICAL_TRANSMISSION_MODEL, model, N0Parameter, N1Parameter, growthRateParameter, doublingTimeParameter, units); } public HierarchicalTransmissionDemographicModel(String name, int model, Parameter N0Parameter, Parameter N1Parameter, Parameter growthRateParameter, Parameter doublingTimeParameter, Type units) { super(name, model, N0Parameter, N1Parameter, growthRateParameter, doublingTimeParameter, units); } public void resizeHierarchicalParameters(int hostCount) { if (N0Parameter != null) { N0Parameter.setDimension(hostCount); N0Parameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); } if (N1Parameter != null) { N1Parameter.setDimension(hostCount); N1Parameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); } if (growthRateParameter != null) { growthRateParameter.setDimension(hostCount); growthRateParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); } if (doublingTimeParameter != null) { doublingTimeParameter.setDimension(hostCount); doublingTimeParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); } } protected int getIndexFromHost(int host) { return host - 1; } /** * Parses an element from an DOM document into a ExponentialGrowth. */ public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return HIERARCHICAL_TRANSMISSION_MODEL; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { Type units = XMLUnits.Utils.getUnitsAttr(xo); int model = 0; Parameter N0Param = null; Parameter N1Param = null; Parameter rParam = null; Parameter dParam = null; if (xo.hasChildNamed(CONSTANT)) { XMLObject cxo = xo.getChild(CONSTANT); N0Param = (Parameter) cxo.getElementFirstChild(POPULATION_SIZE); model = 0; } else if (xo.hasChildNamed(EXPONENTIAL)) { XMLObject cxo = xo.getChild(EXPONENTIAL); N1Param = (Parameter) cxo.getElementFirstChild(ANCESTRAL_PROPORTION); if (cxo.hasChildNamed(GROWTH_RATE)) { rParam = (Parameter) cxo.getElementFirstChild(GROWTH_RATE); } else { dParam = (Parameter) cxo.getElementFirstChild(DOUBLING_TIME); } model = 1; } else if (xo.hasChildNamed(LOGISTIC)) { XMLObject cxo = xo.getChild(LOGISTIC); N0Param = (Parameter) cxo.getElementFirstChild(POPULATION_SIZE); N1Param = (Parameter) cxo.getElementFirstChild(ANCESTRAL_PROPORTION); if (cxo.hasChildNamed(GROWTH_RATE)) { rParam = (Parameter) cxo.getElementFirstChild(GROWTH_RATE); } else { dParam = (Parameter) cxo.getElementFirstChild(DOUBLING_TIME); } model = 2; } HierarchicalTransmissionDemographicModel demoModel = new HierarchicalTransmissionDemographicModel(model, N0Param, N1Param, rParam, dParam, units); demoModel.resizeHierarchicalParameters(xo.getAttribute(HOST_COUNT, 1)); return demoModel; } //************************************************************************ // AbstractXMLObjectParser implementation //************************************************************************ public String getParserDescription() { return "A SiteModel that has a gamma distributed rates across sites"; } public Class getReturnType() { return HierarchicalTransmissionDemographicModel.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ XMLUnits.UNITS_RULE, AttributeRule.newIntegerRule(HOST_COUNT, false), new XORRule( new ElementRule(CONSTANT, new XMLSyntaxRule[]{ new ElementRule(POPULATION_SIZE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter represents the carrying capacity (maximum population size). " + "If the shape is very large then the current day population size will be very close to the carrying capacity."), } ), new XORRule( new ElementRule(EXPONENTIAL, new XMLSyntaxRule[]{ new XORRule( new ElementRule(GROWTH_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the rate of growth during the exponential phase. See exponentialGrowth for details."), new ElementRule(DOUBLING_TIME, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the doubling time at peak growth rate.")), new ElementRule(ANCESTRAL_PROPORTION, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the populaation size at transmission.") } ), new ElementRule(LOGISTIC, new XMLSyntaxRule[]{ new ElementRule(POPULATION_SIZE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter represents the carrying capacity (maximum population size). " + "If the shape is very large then the current day population size will be very close to the carrying capacity."), new XORRule( new ElementRule(GROWTH_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the rate of growth during the exponential phase. See exponentialGrowth for details."), new ElementRule(DOUBLING_TIME, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the doubling time at peak growth rate.")), new ElementRule(ANCESTRAL_PROPORTION, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, "This parameter determines the populaation size at transmission.") } ) ) ) }; }; }
Tweaks to hierarchical transmission model git-svn-id: 67bc77c75b8364e4e9cdff0eb6560f5818674cd8@4972 ca793f91-a31e-0410-b540-2769d408b6a1
src/dr/evomodel/transmission/HierarchicalTransmissionDemographicModel.java
Tweaks to hierarchical transmission model
<ide><path>rc/dr/evomodel/transmission/HierarchicalTransmissionDemographicModel.java <ide> <ide> if (N0Parameter != null) { <ide> N0Parameter.setDimension(hostCount); <del> N0Parameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); <add>// N0Parameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); <ide> } <ide> <ide> if (N1Parameter != null) { <ide> N1Parameter.setDimension(hostCount); <del> N1Parameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); <add>// N1Parameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); <ide> } <ide> <ide> if (growthRateParameter != null) { <ide> growthRateParameter.setDimension(hostCount); <del> growthRateParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); <add>// growthRateParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); <ide> } <ide> <ide> if (doublingTimeParameter != null) { <ide> doublingTimeParameter.setDimension(hostCount); <del> doublingTimeParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); <add>// doublingTimeParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, hostCount)); <ide> } <ide> } <ide>
Java
mit
caccfa4f325396c866bb803d51ee0c3763e8d073
0
SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/SpongeCommon,SpongePowered/SpongeCommon
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.block; import net.minecraft.block.BlockDispenser; import net.minecraft.block.BlockDropper; import net.minecraft.block.BlockSourceImpl; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntityDispenser; import net.minecraft.tileentity.TileEntityHopper; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Surrogate; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.interfaces.IMixinInventory; @Mixin(BlockDropper.class) public abstract class MixinBlockDropper { @Inject(method = "dispense", cancellable = true, locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "INVOKE", target = "Lnet/minecraft/tileentity/TileEntityDispenser;setInventorySlotContents(ILnet/minecraft/item/ItemStack;)V")) private void afterDispense(World worldIn, BlockPos pos, CallbackInfo callbackInfo, BlockSourceImpl blocksourceimpl, TileEntityDispenser tileentitydispenser, int i, ItemStack itemstack, EnumFacing enumfacing, BlockPos blockpos, IInventory iinventory, ItemStack itemstack1) { // after setInventorySlotContents tileentitydispenser.setInventorySlotContents(i, itemstack1); // Transfer worked if remainder is one less than the original stack if (itemstack1.getCount() == itemstack.getCount() - 1) { IMixinInventory capture = forCapture(tileentitydispenser); Inventory sourceInv = toInventory(tileentitydispenser); SpongeCommonEventFactory.captureTransaction(capture, sourceInv, i, itemstack); SpongeCommonEventFactory.callTransferPost(capture, sourceInv, toInventory(iinventory)); } callbackInfo.cancel(); } @Surrogate private void afterDispense(World worldIn, BlockPos pos, CallbackInfo callbackInfo, BlockSourceImpl blocksourceimpl, TileEntityDispenser tileentitydispenser, int i, ItemStack itemstack, ItemStack itemstack1) { // after setInventorySlotContents tileentitydispenser.setInventorySlotContents(i, itemstack1); // Transfer worked if remainder is one less than the original stack if (itemstack1.getCount() == itemstack.getCount() - 1) { IMixinInventory capture = forCapture(tileentitydispenser); Inventory sourceInv = toInventory(tileentitydispenser); SpongeCommonEventFactory.captureTransaction(capture, sourceInv, i, itemstack); EnumFacing enumfacing = (EnumFacing)worldIn.getBlockState(pos).getValue(BlockDispenser.FACING); BlockPos blockpos = pos.offset(enumfacing); IInventory iinventory = TileEntityHopper.getInventoryAtPosition(worldIn, (double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ()); SpongeCommonEventFactory.callTransferPost(capture, sourceInv, toInventory(iinventory)); } callbackInfo.cancel(); } @Inject(method = "dispense", cancellable = true, locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "INVOKE", target = "Lnet/minecraft/tileentity/TileEntityHopper;putStackInInventoryAllSlots(Lnet/minecraft/inventory/IInventory;Lnet/minecraft/inventory/IInventory;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/EnumFacing;)Lnet/minecraft/item/ItemStack;")) private void onDispense(World world, BlockPos pos, CallbackInfo ci, BlockSourceImpl blocksourceimpl, TileEntityDispenser tileentitydispenser, int i, ItemStack itemstack, EnumFacing enumfacing, BlockPos blockpos, IInventory iinventory) { // Before putStackInInventoryAllSlots if (SpongeCommonEventFactory.callTransferPre(toInventory(tileentitydispenser), toInventory(iinventory)).isCancelled()) { ci.cancel(); } } private static Inventory toInventory(IInventory iinventory) { return ((Inventory) iinventory); } private static IMixinInventory forCapture(Object toCapture) { if (toCapture instanceof IMixinInventory) { return ((IMixinInventory) toCapture); } return null; } }
src/main/java/org/spongepowered/common/mixin/core/block/MixinBlockDropper.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.block; import net.minecraft.block.BlockDropper; import net.minecraft.block.BlockSourceImpl; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntityDispenser; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.interfaces.IMixinInventory; @Mixin(BlockDropper.class) public abstract class MixinBlockDropper { @Inject(method = "dispense", cancellable = true, locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "INVOKE", target = "Lnet/minecraft/tileentity/TileEntityDispenser;setInventorySlotContents(ILnet/minecraft/item/ItemStack;)V")) private void afterDispense(World worldIn, BlockPos pos, CallbackInfo callbackInfo, BlockSourceImpl blocksourceimpl, TileEntityDispenser tileentitydispenser, int i, ItemStack itemstack, EnumFacing enumfacing, BlockPos blockpos, IInventory iinventory, ItemStack itemstack1) { // after setInventorySlotContents tileentitydispenser.setInventorySlotContents(i, itemstack1); // Transfer worked if remainder is one less than the original stack if (itemstack1.getCount() == itemstack.getCount() - 1) { IMixinInventory capture = forCapture(tileentitydispenser); Inventory sourceInv = toInventory(tileentitydispenser); SpongeCommonEventFactory.captureTransaction(capture, sourceInv, i, itemstack); SpongeCommonEventFactory.callTransferPost(capture, sourceInv, toInventory(iinventory)); } callbackInfo.cancel(); } @Inject(method = "dispense", cancellable = true, locals = LocalCapture.CAPTURE_FAILEXCEPTION, at = @At(value = "INVOKE", target = "Lnet/minecraft/tileentity/TileEntityHopper;putStackInInventoryAllSlots(Lnet/minecraft/inventory/IInventory;Lnet/minecraft/inventory/IInventory;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/EnumFacing;)Lnet/minecraft/item/ItemStack;")) private void onDispense(World world, BlockPos pos, CallbackInfo ci, BlockSourceImpl blocksourceimpl, TileEntityDispenser tileentitydispenser, int i, ItemStack itemstack, EnumFacing enumfacing, BlockPos blockpos, IInventory iinventory) { // Before putStackInInventoryAllSlots if (SpongeCommonEventFactory.callTransferPre(toInventory(tileentitydispenser), toInventory(iinventory)).isCancelled()) { ci.cancel(); } } private static Inventory toInventory(IInventory iinventory) { return ((Inventory) iinventory); } private static IMixinInventory forCapture(Object toCapture) { if (toCapture instanceof IMixinInventory) { return ((IMixinInventory) toCapture); } return null; } }
add Surrogate for SpongeVanilla
src/main/java/org/spongepowered/common/mixin/core/block/MixinBlockDropper.java
add Surrogate for SpongeVanilla
<ide><path>rc/main/java/org/spongepowered/common/mixin/core/block/MixinBlockDropper.java <ide> */ <ide> package org.spongepowered.common.mixin.core.block; <ide> <add>import net.minecraft.block.BlockDispenser; <ide> import net.minecraft.block.BlockDropper; <ide> import net.minecraft.block.BlockSourceImpl; <ide> import net.minecraft.inventory.IInventory; <ide> import net.minecraft.item.ItemStack; <ide> import net.minecraft.tileentity.TileEntityDispenser; <add>import net.minecraft.tileentity.TileEntityHopper; <ide> import net.minecraft.util.EnumFacing; <ide> import net.minecraft.util.math.BlockPos; <ide> import net.minecraft.world.World; <ide> import org.spongepowered.asm.mixin.Mixin; <ide> import org.spongepowered.asm.mixin.injection.At; <ide> import org.spongepowered.asm.mixin.injection.Inject; <add>import org.spongepowered.asm.mixin.injection.Surrogate; <ide> import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; <ide> import org.spongepowered.asm.mixin.injection.callback.LocalCapture; <ide> import org.spongepowered.common.event.SpongeCommonEventFactory; <ide> IMixinInventory capture = forCapture(tileentitydispenser); <ide> Inventory sourceInv = toInventory(tileentitydispenser); <ide> SpongeCommonEventFactory.captureTransaction(capture, sourceInv, i, itemstack); <add> SpongeCommonEventFactory.callTransferPost(capture, sourceInv, toInventory(iinventory)); <add> } <add> callbackInfo.cancel(); <add> } <add> <add> @Surrogate <add> private void afterDispense(World worldIn, BlockPos pos, CallbackInfo callbackInfo, <add> BlockSourceImpl blocksourceimpl, TileEntityDispenser tileentitydispenser, int i, ItemStack itemstack, <add> ItemStack itemstack1) { <add> // after setInventorySlotContents <add> tileentitydispenser.setInventorySlotContents(i, itemstack1); <add> // Transfer worked if remainder is one less than the original stack <add> if (itemstack1.getCount() == itemstack.getCount() - 1) { <add> IMixinInventory capture = forCapture(tileentitydispenser); <add> Inventory sourceInv = toInventory(tileentitydispenser); <add> SpongeCommonEventFactory.captureTransaction(capture, sourceInv, i, itemstack); <add> EnumFacing enumfacing = (EnumFacing)worldIn.getBlockState(pos).getValue(BlockDispenser.FACING); <add> BlockPos blockpos = pos.offset(enumfacing); <add> IInventory iinventory = TileEntityHopper.getInventoryAtPosition(worldIn, (double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ()); <ide> SpongeCommonEventFactory.callTransferPost(capture, sourceInv, toInventory(iinventory)); <ide> } <ide> callbackInfo.cancel();
Java
apache-2.0
b508dd2357736e030bcf6666fd73527ebb61a10d
0
459below/jitsi,459below/jitsi,dkcreinoso/jitsi,damencho/jitsi,HelioGuilherme66/jitsi,mckayclarey/jitsi,tuijldert/jitsi,cobratbq/jitsi,pplatek/jitsi,cobratbq/jitsi,Metaswitch/jitsi,laborautonomo/jitsi,bhatvv/jitsi,iant-gmbh/jitsi,jitsi/jitsi,jitsi/jitsi,tuijldert/jitsi,pplatek/jitsi,bebo/jitsi,Metaswitch/jitsi,ibauersachs/jitsi,marclaporte/jitsi,martin7890/jitsi,Metaswitch/jitsi,laborautonomo/jitsi,jibaro/jitsi,459below/jitsi,ringdna/jitsi,gpolitis/jitsi,level7systems/jitsi,mckayclarey/jitsi,ringdna/jitsi,martin7890/jitsi,dkcreinoso/jitsi,tuijldert/jitsi,procandi/jitsi,iant-gmbh/jitsi,ringdna/jitsi,jibaro/jitsi,procandi/jitsi,marclaporte/jitsi,bebo/jitsi,iant-gmbh/jitsi,459below/jitsi,damencho/jitsi,laborautonomo/jitsi,martin7890/jitsi,jibaro/jitsi,laborautonomo/jitsi,gpolitis/jitsi,damencho/jitsi,jibaro/jitsi,level7systems/jitsi,procandi/jitsi,bhatvv/jitsi,martin7890/jitsi,bebo/jitsi,dkcreinoso/jitsi,459below/jitsi,dkcreinoso/jitsi,cobratbq/jitsi,bhatvv/jitsi,cobratbq/jitsi,mckayclarey/jitsi,tuijldert/jitsi,bhatvv/jitsi,pplatek/jitsi,ibauersachs/jitsi,HelioGuilherme66/jitsi,laborautonomo/jitsi,marclaporte/jitsi,level7systems/jitsi,damencho/jitsi,jitsi/jitsi,pplatek/jitsi,mckayclarey/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,jibaro/jitsi,ibauersachs/jitsi,pplatek/jitsi,level7systems/jitsi,cobratbq/jitsi,ibauersachs/jitsi,jitsi/jitsi,martin7890/jitsi,bebo/jitsi,ringdna/jitsi,ibauersachs/jitsi,marclaporte/jitsi,bebo/jitsi,gpolitis/jitsi,bhatvv/jitsi,gpolitis/jitsi,damencho/jitsi,tuijldert/jitsi,HelioGuilherme66/jitsi,ringdna/jitsi,gpolitis/jitsi,procandi/jitsi,HelioGuilherme66/jitsi,Metaswitch/jitsi,level7systems/jitsi,iant-gmbh/jitsi,procandi/jitsi,mckayclarey/jitsi,HelioGuilherme66/jitsi,dkcreinoso/jitsi,jitsi/jitsi
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.main; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.util.*; import java.util.List; import javax.swing.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.customcontrols.*; import net.java.sip.communicator.impl.gui.i18n.*; import net.java.sip.communicator.impl.gui.main.call.*; import net.java.sip.communicator.impl.gui.main.chat.*; import net.java.sip.communicator.impl.gui.main.chat.conference.*; import net.java.sip.communicator.impl.gui.main.chatroomslist.*; import net.java.sip.communicator.impl.gui.main.contactlist.*; import net.java.sip.communicator.impl.gui.main.contactlist.ContactListPanel.*; import net.java.sip.communicator.impl.gui.main.login.*; import net.java.sip.communicator.impl.gui.main.menus.*; import net.java.sip.communicator.impl.gui.main.presence.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.configuration.*; import net.java.sip.communicator.service.configuration.PropertyVetoException; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import org.osgi.framework.*; /** * The main application window. This class is the core of this ui * implementation. It stores all available protocol providers and their * operation sets, as well as all registered accounts, the * <tt>MetaContactListService</tt> and all sent messages that aren't * delivered yet. * * @author Yana Stamcheva */ public class MainFrame extends SIPCommFrame { private Logger logger = Logger.getLogger(MainFrame.class.getName()); private JPanel contactListPanel = new JPanel(new BorderLayout()); private JPanel mainPanel = new JPanel(new BorderLayout(0, 5)); private MainMenu menu; private CallManager callManager; private StatusPanel statusPanel; private MainTabbedPane tabbedPane; private QuickMenu quickMenu; private Map protocolSupportedOperationSets = new LinkedHashMap(); private Map protocolPresenceSets = new LinkedHashMap(); private Map protocolTelephonySets = new LinkedHashMap(); private LinkedHashMap protocolProviders = new LinkedHashMap(); private Map webContactInfoOperationSets = new LinkedHashMap(); private Map multiUserChatOperationSets = new LinkedHashMap(); private MetaContactListService contactList; private LoginManager loginManager; private ChatWindowManager chatWindowManager; private MultiUserChatManager multiChatManager; /** * Creates an instance of <tt>MainFrame</tt>. */ public MainFrame() { this.chatWindowManager = new ChatWindowManager(this); callManager = new CallManager(this); multiChatManager = new MultiUserChatManager(this); tabbedPane = new MainTabbedPane(this); quickMenu = new QuickMenu(this); statusPanel = new StatusPanel(this); menu = new MainMenu(this); this.addWindowListener(new MainFrameWindowAdapter()); //this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setInitialBounds(); this.setTitle(Messages.getI18NString("sipCommunicator").getText()); this.setIconImage( ImageLoader.getImage(ImageLoader.SIP_COMMUNICATOR_LOGO)); this.init(); } /** * Initiates the content of this frame. */ private void init() { this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), new RenameAction()); this.setJMenuBar(menu); this.contactListPanel.add(tabbedPane, BorderLayout.CENTER); this.contactListPanel.add(callManager, BorderLayout.SOUTH); this.mainPanel.add(quickMenu, BorderLayout.NORTH); this.mainPanel.add(contactListPanel, BorderLayout.CENTER); this.mainPanel.add(statusPanel, BorderLayout.SOUTH); this.mainPanel.getActionMap().put("runChat", new RunMessageWindowAction()); InputMap imap = mainPanel.getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "runChat"); this.getContentPane().add(mainPanel); } /** * Sets frame size and position. */ private void setInitialBounds() { this.setSize(200, 450); this.contactListPanel.setPreferredSize(new Dimension(300, 600)); this.contactListPanel.setMinimumSize(new Dimension(80, 200)); this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width - this.getWidth(), 50); } /** * Returns the <tt>MetaContactListService</tt>. * * @return <tt>MetaContactListService</tt> The current meta contact list. */ public MetaContactListService getContactList() { return this.contactList; } /** * Initializes the contact list panel. * * @param contactList The <tt>MetaContactListService</tt> containing * the contact list data. */ public void setContactList(MetaContactListService contactList) { this.contactList = contactList; ContactListPanel clistPanel = this.tabbedPane.getContactListPanel(); clistPanel.initList(contactList); CListKeySearchListener keyListener = new CListKeySearchListener(clistPanel.getContactList()); //add a key listener to the tabbed pane, when the contactlist is //initialized this.tabbedPane.addKeyListener(keyListener); clistPanel.addKeyListener(keyListener); clistPanel.getContactList().addKeyListener(keyListener); } /** * Returns a set of all operation sets supported by the given * protocol provider. * * @param protocolProvider The protocol provider. * @return a set of all operation sets supported by the given * protocol provider. */ public Map getSupportedOperationSets( ProtocolProviderService protocolProvider) { return (Map) this.protocolSupportedOperationSets.get(protocolProvider); } /** * Adds all protocol supported operation sets. * * @param protocolProvider The protocol provider. */ public void addProtocolSupportedOperationSets( ProtocolProviderService protocolProvider) { Map supportedOperationSets = protocolProvider.getSupportedOperationSets(); this.protocolSupportedOperationSets.put(protocolProvider, supportedOperationSets); String ppOpSetClassName = OperationSetPersistentPresence .class.getName(); String pOpSetClassName = OperationSetPresence.class.getName(); // Obtain the presence operation set. if (supportedOperationSets.containsKey(ppOpSetClassName) || supportedOperationSets.containsKey(pOpSetClassName)) { OperationSetPresence presence = (OperationSetPresence) supportedOperationSets.get(ppOpSetClassName); if(presence == null) { presence = (OperationSetPresence) supportedOperationSets.get(pOpSetClassName); } this.protocolPresenceSets.put(protocolProvider, presence); presence.addProviderPresenceStatusListener( new GUIProviderPresenceStatusListener()); presence.addContactPresenceStatusListener( new GUIContactPresenceStatusListener()); } // Obtain the basic instant messaging operation set. String imOpSetClassName = OperationSetBasicInstantMessaging .class.getName(); if (supportedOperationSets.containsKey(imOpSetClassName)) { OperationSetBasicInstantMessaging im = (OperationSetBasicInstantMessaging) supportedOperationSets.get(imOpSetClassName); //Add to all instant messaging operation sets the Message //listener implemented in the ContactListPanel, which handles //all received messages. im.addMessageListener(getContactListPanel()); } // Obtain the typing notifications operation set. String tnOpSetClassName = OperationSetTypingNotifications .class.getName(); if (supportedOperationSets.containsKey(tnOpSetClassName)) { OperationSetTypingNotifications tn = (OperationSetTypingNotifications) supportedOperationSets.get(tnOpSetClassName); //Add to all typing notification operation sets the Message //listener implemented in the ContactListPanel, which handles //all received messages. tn.addTypingNotificationsListener(this.getContactListPanel()); } // Obtain the web contact info operation set. String wciOpSetClassName = OperationSetWebContactInfo.class.getName(); if (supportedOperationSets.containsKey(wciOpSetClassName)) { OperationSetWebContactInfo wContactInfo = (OperationSetWebContactInfo) supportedOperationSets.get(wciOpSetClassName); this.webContactInfoOperationSets .put(protocolProvider, wContactInfo); } // Obtain the basic telephony operation set. String telOpSetClassName = OperationSetBasicTelephony.class.getName(); if (supportedOperationSets.containsKey(telOpSetClassName)) { OperationSetBasicTelephony telephony = (OperationSetBasicTelephony) supportedOperationSets.get(telOpSetClassName); telephony.addCallListener(callManager); this.getContactListPanel().getContactList() .addListSelectionListener(callManager); this.tabbedPane.addChangeListener(callManager); this.protocolTelephonySets.put(protocolProvider, telephony); } // Obtain the multi user chat operation set. String multiChatClassName = OperationSetMultiUserChat.class.getName(); if (supportedOperationSets.containsKey(multiChatClassName)) { OperationSetMultiUserChat multiUserChat = (OperationSetMultiUserChat) supportedOperationSets.get(multiChatClassName); multiUserChat.addInvitationListener(multiChatManager); multiUserChat.addInvitationRejectionListener(multiChatManager); this.getChatRoomsListPanel() .getChatRoomsList() .addChatServer(protocolProvider, multiUserChat); this.multiUserChatOperationSets.put(protocolProvider, multiUserChat); } } /** * Returns a set of all protocol providers. * * @return a set of all protocol providers. */ public Iterator getProtocolProviders() { return ((LinkedHashMap)protocolProviders.clone()).keySet().iterator(); } /** * Returns a set of all protocol providers supporting multi user chat. * * @return a set of all protocol providers supporting multi user chat. */ public Iterator getPProvidersSupportingMultiUserChat() { return this.multiUserChatOperationSets.keySet().iterator(); } /** * Returns the protocol provider associated to the account given * by the account user identifier. * * @param accountName The account user identifier. * @return The protocol provider associated to the given account. */ public ProtocolProviderService getProtocolProviderForAccount( String accountName) { Iterator i = this.protocolProviders.keySet().iterator(); while(i.hasNext()) { ProtocolProviderService pps = (ProtocolProviderService)i.next(); if (pps.getAccountID().getUserID().equals(accountName)) { return pps; } } return null; } /** * Adds a protocol provider. * @param protocolProvider The protocol provider to add. */ public void addProtocolProvider(ProtocolProviderService protocolProvider) { logger.trace("Add the following protocol provider to the gui: " + protocolProvider.getAccountID().getAccountAddress()); this.protocolProviders.put(protocolProvider, new Integer(initiateProviderIndex(protocolProvider))); this.addProtocolSupportedOperationSets(protocolProvider); this.addAccount(protocolProvider); } /** * Returns the index of the given protocol provider. * @param protocolProvider the protocol provider to search for * @return the index of the given protocol provider */ public int getProviderIndex(ProtocolProviderService protocolProvider) { Object o = protocolProviders.get(protocolProvider); if(o != null) { return ((Integer)o).intValue(); } return 0; } /** * Adds an account to the application. * * @param protocolProvider The protocol provider of the account. */ public void addAccount(ProtocolProviderService protocolProvider) { if (!getStatusPanel().containsAccount(protocolProvider)) { logger.trace("Add the following account to the status bar: " + protocolProvider.getAccountID().getAccountAddress()); this.getStatusPanel().addAccount(protocolProvider); //request the focus int the contact list panel, which //permits to search in the contact list this.tabbedPane.getContactListPanel().getContactList() .requestFocus(); } if(!callManager.containsCallAccount(protocolProvider) && getTelephonyOpSet(protocolProvider) != null) { callManager.addCallAccount(protocolProvider); } } /** * Adds an account to the application. * * @param protocolProvider The protocol provider of the account. */ public void removeProtocolProvider(ProtocolProviderService protocolProvider) { this.protocolProviders.remove(protocolProvider); this.updateProvidersIndexes(protocolProvider); if (getStatusPanel().containsAccount(protocolProvider)) { this.getStatusPanel().removeAccount(protocolProvider); } if(callManager.containsCallAccount(protocolProvider)) { callManager.removeCallAccount(protocolProvider); } } /** * Activates an account. Here we start the connecting process. * * @param protocolProvider The protocol provider of this account. */ public void activateAccount(ProtocolProviderService protocolProvider) { this.getStatusPanel().startConnecting(protocolProvider); } /** * Returns the account user id for the given protocol provider. * @return The account user id for the given protocol provider. */ public String getAccount(ProtocolProviderService protocolProvider) { return protocolProvider.getAccountID().getUserID(); } /** * Returns the presence operation set for the given protocol provider. * * @param protocolProvider The protocol provider for which the * presence operation set is searched. * @return the presence operation set for the given protocol provider. */ public OperationSetPresence getProtocolPresenceOpSet( ProtocolProviderService protocolProvider) { Object o = this.protocolPresenceSets.get(protocolProvider); if(o != null) return (OperationSetPresence) o; return null; } /** * Returns the Web Contact Info operation set for the given * protocol provider. * * @param protocolProvider The protocol provider for which the TN * is searched. * @return OperationSetWebContactInfo The Web Contact Info operation * set for the given protocol provider. */ public OperationSetWebContactInfo getWebContactInfoOpSet( ProtocolProviderService protocolProvider) { Object o = this.webContactInfoOperationSets.get(protocolProvider); if(o != null) return (OperationSetWebContactInfo) o; return null; } /** * Returns the telephony operation set for the given protocol provider. * * @param protocolProvider The protocol provider for which the telephony * operation set is about. * @return OperationSetBasicTelephony The telephony operation * set for the given protocol provider. */ public OperationSetBasicTelephony getTelephonyOpSet( ProtocolProviderService protocolProvider) { Object o = this.protocolTelephonySets.get(protocolProvider); if(o != null) return (OperationSetBasicTelephony) o; return null; } /** * Returns the multi user chat operation set for the given protocol provider. * * @param protocolProvider The protocol provider for which the multi user * chat operation set is about. * @return OperationSetMultiUserChat The telephony operation * set for the given protocol provider. */ public OperationSetMultiUserChat getMultiUserChatOpSet( ProtocolProviderService protocolProvider) { Object o = this.multiUserChatOperationSets.get(protocolProvider); if(o != null) return (OperationSetMultiUserChat) o; return null; } /** * Returns the call manager. * @return CallManager The call manager. */ public CallManager getCallManager() { return callManager; } /** * Returns the quick menu, placed above the main tabbed pane. * @return QuickMenu The quick menu, placed above the main tabbed pane. */ public QuickMenu getQuickMenu() { return quickMenu; } /** * Returns the status panel. * @return StatusPanel The status panel. */ public StatusPanel getStatusPanel() { return statusPanel; } /** * Listens for all contactPresenceStatusChanged events in order * to refresh tha contact list, when a status is changed. */ private class GUIContactPresenceStatusListener implements ContactPresenceStatusListener { public void contactPresenceStatusChanged( ContactPresenceStatusChangeEvent evt) { ContactListPanel clistPanel = tabbedPane.getContactListPanel(); Contact sourceContact = evt.getSourceContact(); MetaContact metaContact = contactList .findMetaContactByContact(sourceContact); if (metaContact != null && (evt.getOldStatus() != evt.getNewStatus())) { clistPanel.getContactList().modifyContact(metaContact); } } } /** * Listens for all providerStatusChanged and providerStatusMessageChanged * events in order to refresh the account status panel, when a status is * changed. */ private class GUIProviderPresenceStatusListener implements ProviderPresenceStatusListener { public void providerStatusChanged(ProviderPresenceStatusChangeEvent evt) { ProtocolProviderService pps = evt.getProvider(); getStatusPanel().updateStatus(pps, evt.getNewStatus()); if(callManager.containsCallAccount(pps)) { callManager.updateCallAccountStatus(pps); } } public void providerStatusMessageChanged(PropertyChangeEvent evt) { } } /** * Returns the list of all groups. * @return The list of all groups. */ public Iterator getAllGroups() { return getContactListPanel() .getContactList().getAllGroups(); } /** * Returns the Meta Contact Group corresponding to the given MetaUID. * * @param metaUID An identifier of a group. * @return The Meta Contact Group corresponding to the given MetaUID. */ public MetaContactGroup getGroupByID(String metaUID) { return getContactListPanel() .getContactList().getGroupByID(metaUID); } /** * Before closing the application window saves the current size and position * through the <tt>ConfigurationService</tt>. */ public class MainFrameWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { if(!GuiActivator.getUIService().getExitOnMainWindowClose()) { ConfigurationManager.setApplicationVisible(false); } } public void windowClosed(WindowEvent e) { if(GuiActivator.getUIService().getExitOnMainWindowClose()) { try { GuiActivator.bundleContext.getBundle(0).stop(); } catch (BundleException ex) { logger.error("Failed to gently shutdown Felix", ex); System.exit(0); } //stopping a bundle doesn't leave the time to the felix thread to //properly end all bundles and call their Activator.stop() methods. //if this causes problems don't uncomment the following line but //try and see why felix isn't exiting (suggesting: is it running //in embedded mode?) //System.exit(0); } } } /** * Saves the last status for all accounts. This information is used * on loging. Each time user logs in he's logged with the same status * as he was the last time before closing the application. */ public void saveStatusInformation(ProtocolProviderService protocolProvider, String statusName) { ConfigurationService configService = GuiActivator.getConfigurationService(); String prefix = "net.java.sip.communicator.impl.gui.accounts"; List accounts = configService .getPropertyNamesByPrefix(prefix, true); boolean savedAccount = false; Iterator accountsIter = accounts.iterator(); while(accountsIter.hasNext()) { String accountRootPropName = (String) accountsIter.next(); String accountUID = configService.getString(accountRootPropName); if(accountUID.equals(protocolProvider .getAccountID().getAccountUniqueID())) { configService.setProperty( accountRootPropName + ".lastAccountStatus", statusName); savedAccount = true; } } if(!savedAccount) { String accNodeName = "acc" + Long.toString(System.currentTimeMillis()); String accountPackage = "net.java.sip.communicator.impl.gui.accounts." + accNodeName; configService.setProperty(accountPackage, protocolProvider.getAccountID().getAccountUniqueID()); configService.setProperty( accountPackage+".lastAccountStatus", statusName); } } /** * Returns the class that manages user login. * @return the class that manages user login. */ public LoginManager getLoginManager() { return loginManager; } /** * Sets the class that manages user login. * @param loginManager The user login manager. */ public void setLoginManager(LoginManager loginManager) { this.loginManager = loginManager; } public CallListPanel getCallListManager() { return this.tabbedPane.getCallListPanel(); } /** * Returns the panel containing the ContactList. * @return ContactListPanel the panel containing the ContactList */ public ContactListPanel getContactListPanel() { return this.tabbedPane.getContactListPanel(); } /** * Returns the panel containing the chat rooms list. * @return the panel containing the chat rooms list */ public ChatRoomsListPanel getChatRoomsListPanel() { return this.tabbedPane.getChatRoomsListPanel(); } /** * Adds a tab in the main tabbed pane, where the given call panel * will be added. */ public void addCallPanel(CallPanel callPanel) { this.tabbedPane.addTab(callPanel.getTitle(), callPanel); this.tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1); this.tabbedPane.revalidate(); } /** * Removes the tab in the main tabbed pane, where the given call panel * is contained. */ public void removeCallPanel(CallPanel callPanel) { this.tabbedPane.remove(callPanel); Component c = getSelectedTab(); if(c == null || !(c instanceof CallPanel)) this.tabbedPane.setSelectedIndex(0); this.tabbedPane.revalidate(); } /** * Returns the component contained in the currently selected tab. * @return the selected CallPanel or null if there's no CallPanel selected */ public Component getSelectedTab() { Component c = this.tabbedPane.getSelectedComponent(); return c; } /** * Checks in the configuration xml if there is already stored index for * this provider and if yes, returns it, otherwise creates a new account * index and stores it. * * @param protocolProvider the protocol provider * @return the protocol provider index */ private int initiateProviderIndex( ProtocolProviderService protocolProvider) { ConfigurationService configService = GuiActivator.getConfigurationService(); String prefix = "net.java.sip.communicator.impl.gui.accounts"; List accounts = configService .getPropertyNamesByPrefix(prefix, true); Iterator accountsIter = accounts.iterator(); boolean savedAccount = false; while(accountsIter.hasNext()) { String accountRootPropName = (String) accountsIter.next(); String accountUID = configService.getString(accountRootPropName); if(accountUID.equals(protocolProvider .getAccountID().getAccountUniqueID())) { savedAccount = true; String index = configService.getString( accountRootPropName + ".accountIndex"); if(index != null) { //if we have found the accountIndex for this protocol provider //return this index return new Integer(index).intValue(); } else { //if there's no stored accountIndex for this protocol //provider, calculate the index, set it in the configuration //service and return it. int accountIndex = createAccountIndex(protocolProvider, accountRootPropName); return accountIndex; } } } if(!savedAccount) { String accNodeName = "acc" + Long.toString(System.currentTimeMillis()); String accountPackage = "net.java.sip.communicator.impl.gui.accounts." + accNodeName; configService.setProperty(accountPackage, protocolProvider.getAccountID().getAccountUniqueID()); int accountIndex = createAccountIndex(protocolProvider, accountPackage); return accountIndex; } return -1; } /** * Creates and calculates the account index for the given protocol * provider. * @param protocolProvider the protocol provider * @param accountRootPropName the path to where the index should be saved * in the configuration xml * @return the created index */ private int createAccountIndex(ProtocolProviderService protocolProvider, String accountRootPropName) { ConfigurationService configService = GuiActivator.getConfigurationService(); int accountIndex = -1; Iterator pproviders = protocolProviders.keySet().iterator(); ProtocolProviderService pps; while(pproviders.hasNext()) { pps = (ProtocolProviderService)pproviders.next(); if(pps.getProtocolName().equals( protocolProvider.getProtocolName()) && !pps.equals(protocolProvider)) { int index = ((Integer)protocolProviders.get(pps)) .intValue(); if(accountIndex < index) { accountIndex = index; } } } accountIndex++; configService.setProperty( accountRootPropName + ".accountIndex", new Integer(accountIndex)); return accountIndex; } /** * Updates the indexes in the configuration xml, when a provider has been * removed. * @param removedProvider the removed protocol provider */ private void updateProvidersIndexes(ProtocolProviderService removedProvider) { ConfigurationService configService = GuiActivator.getConfigurationService(); String prefix = "net.java.sip.communicator.impl.gui.accounts"; Iterator pproviders = protocolProviders.keySet().iterator(); ProtocolProviderService currentProvider = null; int sameProtocolProvidersCount = 0; while(pproviders.hasNext()) { ProtocolProviderService pps = (ProtocolProviderService)pproviders.next(); if(pps.getProtocolName().equals( removedProvider.getProtocolName())) { sameProtocolProvidersCount++; if(sameProtocolProvidersCount > 1) { break; } currentProvider = pps; } } if(sameProtocolProvidersCount < 2 && currentProvider != null) { protocolProviders.put(currentProvider, new Integer(0)); List accounts = configService .getPropertyNamesByPrefix(prefix, true); Iterator accountsIter = accounts.iterator(); while(accountsIter.hasNext()) { String rootPropName = (String) accountsIter.next(); String accountUID = configService.getString(rootPropName); if(accountUID.equals(currentProvider .getAccountID().getAccountUniqueID())) { configService.setProperty( rootPropName + ".accountIndex", new Integer(0)); } } this.getStatusPanel().updateAccount(currentProvider); } } /** * If the protocol provider supports presence operation set searches the * last status which was selected, otherwise returns null. * * @param protocolProvider the protocol provider we're interested in. * @return the last protocol provider presence status, or null if this * provider doesn't support presence operation set */ public Object getProtocolProviderLastStatus( ProtocolProviderService protocolProvider) { if(getProtocolPresenceOpSet(protocolProvider) != null) return this.statusPanel .getLastPresenceStatus(protocolProvider); else return this.statusPanel.getLastStatusString(protocolProvider); } /** * <tt>RenameAction</tt> is invoked when user presses the F2 key. Depending * on the selection opens the appropriate form for renaming. */ private class RenameAction extends AbstractAction { public void actionPerformed(ActionEvent e) { Object selectedObject = getContactListPanel().getContactList().getSelectedValue(); if(selectedObject instanceof MetaContact) { RenameContactDialog dialog = new RenameContactDialog( MainFrame.this, (MetaContact)selectedObject); dialog.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2 - 200, Toolkit.getDefaultToolkit().getScreenSize().height/2 - 50 ); dialog.setVisible(true); dialog.requestFocusInFiled(); } else if(selectedObject instanceof MetaContactGroup) { RenameGroupDialog dialog = new RenameGroupDialog( MainFrame.this, (MetaContactGroup)selectedObject); dialog.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2 - 200, Toolkit.getDefaultToolkit().getScreenSize().height/2 - 50 ); dialog.setVisible(true); dialog.requestFocusInFiled(); } } } /** * Overwrites the <tt>SIPCommFrame</tt> close method. This method is * invoked when user presses the Escape key. */ protected void close(boolean isEscaped) { ContactList contactList = getContactListPanel().getContactList(); ContactRightButtonMenu contactPopupMenu = contactList.getContactRightButtonMenu(); GroupRightButtonMenu groupPopupMenu = contactList.getGroupRightButtonMenu(); CommonRightButtonMenu commonPopupMenu = getContactListPanel().getCommonRightButtonMenu(); if(contactPopupMenu != null && contactPopupMenu.isVisible()) { contactPopupMenu.setVisible(false); } else if(groupPopupMenu != null && groupPopupMenu.isVisible()) { groupPopupMenu.setVisible(false); } else if(commonPopupMenu != null && commonPopupMenu.isVisible()) { commonPopupMenu.setVisible(false); } else if(statusPanel.hasSelectedMenus() || menu.hasSelectedMenus()) { MenuSelectionManager selectionManager = MenuSelectionManager.defaultManager(); selectionManager.clearSelectedPath(); } } /** * Returns the main menu in the application window. * @return the main menu in the application window */ public MainMenu getMainMenu() { return menu; } /** * Returns the <tt>ChatWindowManager</tt>. * @return the <tt>ChatWindowManager</tt> */ public ChatWindowManager getChatWindowManager() { return chatWindowManager; } /** * Opens chat window when the selected value is a MetaContact and opens a * group when the selected value is a MetaContactGroup. */ private class RunMessageWindowAction extends AbstractAction { public void actionPerformed(ActionEvent e) { ContactList clist = getContactListPanel().getContactList(); Object selectedValue = clist.getSelectedValue(); if (selectedValue instanceof MetaContact) { MetaContact contact = (MetaContact) selectedValue; SwingUtilities.invokeLater( getContactListPanel().new RunMessageWindow(contact)); } else if (selectedValue instanceof MetaContactGroup) { MetaContactGroup group = (MetaContactGroup) selectedValue; ContactListModel model = (ContactListModel) clist.getModel(); if (model.isGroupClosed(group)) { model.openGroup(group); } } } }; }
src/net/java/sip/communicator/impl/gui/main/MainFrame.java
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.main; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.util.*; import java.util.List; import javax.swing.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.customcontrols.*; import net.java.sip.communicator.impl.gui.i18n.*; import net.java.sip.communicator.impl.gui.main.call.*; import net.java.sip.communicator.impl.gui.main.chat.*; import net.java.sip.communicator.impl.gui.main.chat.conference.*; import net.java.sip.communicator.impl.gui.main.chatroomslist.*; import net.java.sip.communicator.impl.gui.main.contactlist.*; import net.java.sip.communicator.impl.gui.main.contactlist.ContactListPanel.*; import net.java.sip.communicator.impl.gui.main.login.*; import net.java.sip.communicator.impl.gui.main.menus.*; import net.java.sip.communicator.impl.gui.main.presence.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.configuration.*; import net.java.sip.communicator.service.configuration.PropertyVetoException; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import org.osgi.framework.*; /** * The main application window. This class is the core of this ui * implementation. It stores all available protocol providers and their * operation sets, as well as all registered accounts, the * <tt>MetaContactListService</tt> and all sent messages that aren't * delivered yet. * * @author Yana Stamcheva */ public class MainFrame extends SIPCommFrame { private Logger logger = Logger.getLogger(MainFrame.class.getName()); private JPanel contactListPanel = new JPanel(new BorderLayout()); private JPanel mainPanel = new JPanel(new BorderLayout(0, 5)); private MainMenu menu; private CallManager callManager; private StatusPanel statusPanel; private MainTabbedPane tabbedPane; private QuickMenu quickMenu; private Map protocolSupportedOperationSets = new LinkedHashMap(); private Map protocolPresenceSets = new LinkedHashMap(); private Map protocolTelephonySets = new LinkedHashMap(); private LinkedHashMap protocolProviders = new LinkedHashMap(); private Map webContactInfoOperationSets = new LinkedHashMap(); private Map multiUserChatOperationSets = new LinkedHashMap(); private MetaContactListService contactList; private LoginManager loginManager; private ChatWindowManager chatWindowManager; private MultiUserChatManager multiChatManager; /** * Creates an instance of <tt>MainFrame</tt>. */ public MainFrame() { this.chatWindowManager = new ChatWindowManager(this); callManager = new CallManager(this); multiChatManager = new MultiUserChatManager(this); tabbedPane = new MainTabbedPane(this); quickMenu = new QuickMenu(this); statusPanel = new StatusPanel(this); menu = new MainMenu(this); this.addWindowListener(new MainFrameWindowAdapter()); //this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setInitialBounds(); this.setTitle(Messages.getI18NString("sipCommunicator").getText()); this.setIconImage( ImageLoader.getImage(ImageLoader.SIP_COMMUNICATOR_LOGO)); this.init(); } /** * Initiates the content of this frame. */ private void init() { this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), new RenameAction()); this.setJMenuBar(menu); this.contactListPanel.add(tabbedPane, BorderLayout.CENTER); this.contactListPanel.add(callManager, BorderLayout.SOUTH); this.mainPanel.add(quickMenu, BorderLayout.NORTH); this.mainPanel.add(contactListPanel, BorderLayout.CENTER); this.mainPanel.add(statusPanel, BorderLayout.SOUTH); this.mainPanel.getActionMap().put("runChat", new RunMessageWindowAction()); InputMap imap = this.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "runChat"); this.getContentPane().add(mainPanel); } /** * Sets frame size and position. */ private void setInitialBounds() { this.setSize(200, 450); this.contactListPanel.setPreferredSize(new Dimension(300, 600)); this.contactListPanel.setMinimumSize(new Dimension(80, 200)); this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width - this.getWidth(), 50); } /** * Returns the <tt>MetaContactListService</tt>. * * @return <tt>MetaContactListService</tt> The current meta contact list. */ public MetaContactListService getContactList() { return this.contactList; } /** * Initializes the contact list panel. * * @param contactList The <tt>MetaContactListService</tt> containing * the contact list data. */ public void setContactList(MetaContactListService contactList) { this.contactList = contactList; ContactListPanel clistPanel = this.tabbedPane.getContactListPanel(); clistPanel.initList(contactList); CListKeySearchListener keyListener = new CListKeySearchListener(clistPanel.getContactList()); //add a key listener to the tabbed pane, when the contactlist is //initialized this.tabbedPane.addKeyListener(keyListener); clistPanel.addKeyListener(keyListener); clistPanel.getContactList().addKeyListener(keyListener); } /** * Returns a set of all operation sets supported by the given * protocol provider. * * @param protocolProvider The protocol provider. * @return a set of all operation sets supported by the given * protocol provider. */ public Map getSupportedOperationSets( ProtocolProviderService protocolProvider) { return (Map) this.protocolSupportedOperationSets.get(protocolProvider); } /** * Adds all protocol supported operation sets. * * @param protocolProvider The protocol provider. */ public void addProtocolSupportedOperationSets( ProtocolProviderService protocolProvider) { Map supportedOperationSets = protocolProvider.getSupportedOperationSets(); this.protocolSupportedOperationSets.put(protocolProvider, supportedOperationSets); String ppOpSetClassName = OperationSetPersistentPresence .class.getName(); String pOpSetClassName = OperationSetPresence.class.getName(); // Obtain the presence operation set. if (supportedOperationSets.containsKey(ppOpSetClassName) || supportedOperationSets.containsKey(pOpSetClassName)) { OperationSetPresence presence = (OperationSetPresence) supportedOperationSets.get(ppOpSetClassName); if(presence == null) { presence = (OperationSetPresence) supportedOperationSets.get(pOpSetClassName); } this.protocolPresenceSets.put(protocolProvider, presence); presence.addProviderPresenceStatusListener( new GUIProviderPresenceStatusListener()); presence.addContactPresenceStatusListener( new GUIContactPresenceStatusListener()); } // Obtain the basic instant messaging operation set. String imOpSetClassName = OperationSetBasicInstantMessaging .class.getName(); if (supportedOperationSets.containsKey(imOpSetClassName)) { OperationSetBasicInstantMessaging im = (OperationSetBasicInstantMessaging) supportedOperationSets.get(imOpSetClassName); //Add to all instant messaging operation sets the Message //listener implemented in the ContactListPanel, which handles //all received messages. im.addMessageListener(getContactListPanel()); } // Obtain the typing notifications operation set. String tnOpSetClassName = OperationSetTypingNotifications .class.getName(); if (supportedOperationSets.containsKey(tnOpSetClassName)) { OperationSetTypingNotifications tn = (OperationSetTypingNotifications) supportedOperationSets.get(tnOpSetClassName); //Add to all typing notification operation sets the Message //listener implemented in the ContactListPanel, which handles //all received messages. tn.addTypingNotificationsListener(this.getContactListPanel()); } // Obtain the web contact info operation set. String wciOpSetClassName = OperationSetWebContactInfo.class.getName(); if (supportedOperationSets.containsKey(wciOpSetClassName)) { OperationSetWebContactInfo wContactInfo = (OperationSetWebContactInfo) supportedOperationSets.get(wciOpSetClassName); this.webContactInfoOperationSets .put(protocolProvider, wContactInfo); } // Obtain the basic telephony operation set. String telOpSetClassName = OperationSetBasicTelephony.class.getName(); if (supportedOperationSets.containsKey(telOpSetClassName)) { OperationSetBasicTelephony telephony = (OperationSetBasicTelephony) supportedOperationSets.get(telOpSetClassName); telephony.addCallListener(callManager); this.getContactListPanel().getContactList() .addListSelectionListener(callManager); this.tabbedPane.addChangeListener(callManager); this.protocolTelephonySets.put(protocolProvider, telephony); } // Obtain the multi user chat operation set. String multiChatClassName = OperationSetMultiUserChat.class.getName(); if (supportedOperationSets.containsKey(multiChatClassName)) { OperationSetMultiUserChat multiUserChat = (OperationSetMultiUserChat) supportedOperationSets.get(multiChatClassName); multiUserChat.addInvitationListener(multiChatManager); multiUserChat.addInvitationRejectionListener(multiChatManager); this.getChatRoomsListPanel() .getChatRoomsList() .addChatServer(protocolProvider, multiUserChat); this.multiUserChatOperationSets.put(protocolProvider, multiUserChat); } } /** * Returns a set of all protocol providers. * * @return a set of all protocol providers. */ public Iterator getProtocolProviders() { return ((LinkedHashMap)protocolProviders.clone()).keySet().iterator(); } /** * Returns a set of all protocol providers supporting multi user chat. * * @return a set of all protocol providers supporting multi user chat. */ public Iterator getPProvidersSupportingMultiUserChat() { return this.multiUserChatOperationSets.keySet().iterator(); } /** * Returns the protocol provider associated to the account given * by the account user identifier. * * @param accountName The account user identifier. * @return The protocol provider associated to the given account. */ public ProtocolProviderService getProtocolProviderForAccount( String accountName) { Iterator i = this.protocolProviders.keySet().iterator(); while(i.hasNext()) { ProtocolProviderService pps = (ProtocolProviderService)i.next(); if (pps.getAccountID().getUserID().equals(accountName)) { return pps; } } return null; } /** * Adds a protocol provider. * @param protocolProvider The protocol provider to add. */ public void addProtocolProvider(ProtocolProviderService protocolProvider) { logger.trace("Add the following protocol provider to the gui: " + protocolProvider.getAccountID().getAccountAddress()); this.protocolProviders.put(protocolProvider, new Integer(initiateProviderIndex(protocolProvider))); this.addProtocolSupportedOperationSets(protocolProvider); this.addAccount(protocolProvider); } /** * Returns the index of the given protocol provider. * @param protocolProvider the protocol provider to search for * @return the index of the given protocol provider */ public int getProviderIndex(ProtocolProviderService protocolProvider) { Object o = protocolProviders.get(protocolProvider); if(o != null) { return ((Integer)o).intValue(); } return 0; } /** * Adds an account to the application. * * @param protocolProvider The protocol provider of the account. */ public void addAccount(ProtocolProviderService protocolProvider) { if (!getStatusPanel().containsAccount(protocolProvider)) { logger.trace("Add the following account to the status bar: " + protocolProvider.getAccountID().getAccountAddress()); this.getStatusPanel().addAccount(protocolProvider); //request the focus int the contact list panel, which //permits to search in the contact list this.tabbedPane.getContactListPanel().getContactList() .requestFocus(); } if(!callManager.containsCallAccount(protocolProvider) && getTelephonyOpSet(protocolProvider) != null) { callManager.addCallAccount(protocolProvider); } } /** * Adds an account to the application. * * @param protocolProvider The protocol provider of the account. */ public void removeProtocolProvider(ProtocolProviderService protocolProvider) { this.protocolProviders.remove(protocolProvider); this.updateProvidersIndexes(protocolProvider); if (getStatusPanel().containsAccount(protocolProvider)) { this.getStatusPanel().removeAccount(protocolProvider); } if(callManager.containsCallAccount(protocolProvider)) { callManager.removeCallAccount(protocolProvider); } } /** * Activates an account. Here we start the connecting process. * * @param protocolProvider The protocol provider of this account. */ public void activateAccount(ProtocolProviderService protocolProvider) { this.getStatusPanel().startConnecting(protocolProvider); } /** * Returns the account user id for the given protocol provider. * @return The account user id for the given protocol provider. */ public String getAccount(ProtocolProviderService protocolProvider) { return protocolProvider.getAccountID().getUserID(); } /** * Returns the presence operation set for the given protocol provider. * * @param protocolProvider The protocol provider for which the * presence operation set is searched. * @return the presence operation set for the given protocol provider. */ public OperationSetPresence getProtocolPresenceOpSet( ProtocolProviderService protocolProvider) { Object o = this.protocolPresenceSets.get(protocolProvider); if(o != null) return (OperationSetPresence) o; return null; } /** * Returns the Web Contact Info operation set for the given * protocol provider. * * @param protocolProvider The protocol provider for which the TN * is searched. * @return OperationSetWebContactInfo The Web Contact Info operation * set for the given protocol provider. */ public OperationSetWebContactInfo getWebContactInfoOpSet( ProtocolProviderService protocolProvider) { Object o = this.webContactInfoOperationSets.get(protocolProvider); if(o != null) return (OperationSetWebContactInfo) o; return null; } /** * Returns the telephony operation set for the given protocol provider. * * @param protocolProvider The protocol provider for which the telephony * operation set is about. * @return OperationSetBasicTelephony The telephony operation * set for the given protocol provider. */ public OperationSetBasicTelephony getTelephonyOpSet( ProtocolProviderService protocolProvider) { Object o = this.protocolTelephonySets.get(protocolProvider); if(o != null) return (OperationSetBasicTelephony) o; return null; } /** * Returns the multi user chat operation set for the given protocol provider. * * @param protocolProvider The protocol provider for which the multi user * chat operation set is about. * @return OperationSetMultiUserChat The telephony operation * set for the given protocol provider. */ public OperationSetMultiUserChat getMultiUserChatOpSet( ProtocolProviderService protocolProvider) { Object o = this.multiUserChatOperationSets.get(protocolProvider); if(o != null) return (OperationSetMultiUserChat) o; return null; } /** * Returns the call manager. * @return CallManager The call manager. */ public CallManager getCallManager() { return callManager; } /** * Returns the quick menu, placed above the main tabbed pane. * @return QuickMenu The quick menu, placed above the main tabbed pane. */ public QuickMenu getQuickMenu() { return quickMenu; } /** * Returns the status panel. * @return StatusPanel The status panel. */ public StatusPanel getStatusPanel() { return statusPanel; } /** * Listens for all contactPresenceStatusChanged events in order * to refresh tha contact list, when a status is changed. */ private class GUIContactPresenceStatusListener implements ContactPresenceStatusListener { public void contactPresenceStatusChanged( ContactPresenceStatusChangeEvent evt) { ContactListPanel clistPanel = tabbedPane.getContactListPanel(); Contact sourceContact = evt.getSourceContact(); MetaContact metaContact = contactList .findMetaContactByContact(sourceContact); if (metaContact != null && (evt.getOldStatus() != evt.getNewStatus())) { clistPanel.getContactList().modifyContact(metaContact); } } } /** * Listens for all providerStatusChanged and providerStatusMessageChanged * events in order to refresh the account status panel, when a status is * changed. */ private class GUIProviderPresenceStatusListener implements ProviderPresenceStatusListener { public void providerStatusChanged(ProviderPresenceStatusChangeEvent evt) { ProtocolProviderService pps = evt.getProvider(); getStatusPanel().updateStatus(pps, evt.getNewStatus()); if(callManager.containsCallAccount(pps)) { callManager.updateCallAccountStatus(pps); } } public void providerStatusMessageChanged(PropertyChangeEvent evt) { } } /** * Returns the list of all groups. * @return The list of all groups. */ public Iterator getAllGroups() { return getContactListPanel() .getContactList().getAllGroups(); } /** * Returns the Meta Contact Group corresponding to the given MetaUID. * * @param metaUID An identifier of a group. * @return The Meta Contact Group corresponding to the given MetaUID. */ public MetaContactGroup getGroupByID(String metaUID) { return getContactListPanel() .getContactList().getGroupByID(metaUID); } /** * Before closing the application window saves the current size and position * through the <tt>ConfigurationService</tt>. */ public class MainFrameWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { if(!GuiActivator.getUIService().getExitOnMainWindowClose()) { ConfigurationManager.setApplicationVisible(false); } } public void windowClosed(WindowEvent e) { if(GuiActivator.getUIService().getExitOnMainWindowClose()) { try { GuiActivator.bundleContext.getBundle(0).stop(); } catch (BundleException ex) { logger.error("Failed to gently shutdown Felix", ex); System.exit(0); } //stopping a bundle doesn't leave the time to the felix thread to //properly end all bundles and call their Activator.stop() methods. //if this causes problems don't uncomment the following line but //try and see why felix isn't exiting (suggesting: is it running //in embedded mode?) //System.exit(0); } } } /** * Saves the last status for all accounts. This information is used * on loging. Each time user logs in he's logged with the same status * as he was the last time before closing the application. */ public void saveStatusInformation(ProtocolProviderService protocolProvider, String statusName) { ConfigurationService configService = GuiActivator.getConfigurationService(); String prefix = "net.java.sip.communicator.impl.gui.accounts"; List accounts = configService .getPropertyNamesByPrefix(prefix, true); boolean savedAccount = false; Iterator accountsIter = accounts.iterator(); while(accountsIter.hasNext()) { String accountRootPropName = (String) accountsIter.next(); String accountUID = configService.getString(accountRootPropName); if(accountUID.equals(protocolProvider .getAccountID().getAccountUniqueID())) { configService.setProperty( accountRootPropName + ".lastAccountStatus", statusName); savedAccount = true; } } if(!savedAccount) { String accNodeName = "acc" + Long.toString(System.currentTimeMillis()); String accountPackage = "net.java.sip.communicator.impl.gui.accounts." + accNodeName; configService.setProperty(accountPackage, protocolProvider.getAccountID().getAccountUniqueID()); configService.setProperty( accountPackage+".lastAccountStatus", statusName); } } /** * Returns the class that manages user login. * @return the class that manages user login. */ public LoginManager getLoginManager() { return loginManager; } /** * Sets the class that manages user login. * @param loginManager The user login manager. */ public void setLoginManager(LoginManager loginManager) { this.loginManager = loginManager; } public CallListPanel getCallListManager() { return this.tabbedPane.getCallListPanel(); } /** * Returns the panel containing the ContactList. * @return ContactListPanel the panel containing the ContactList */ public ContactListPanel getContactListPanel() { return this.tabbedPane.getContactListPanel(); } /** * Returns the panel containing the chat rooms list. * @return the panel containing the chat rooms list */ public ChatRoomsListPanel getChatRoomsListPanel() { return this.tabbedPane.getChatRoomsListPanel(); } /** * Adds a tab in the main tabbed pane, where the given call panel * will be added. */ public void addCallPanel(CallPanel callPanel) { this.tabbedPane.addTab(callPanel.getTitle(), callPanel); this.tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1); this.tabbedPane.revalidate(); } /** * Removes the tab in the main tabbed pane, where the given call panel * is contained. */ public void removeCallPanel(CallPanel callPanel) { this.tabbedPane.remove(callPanel); Component c = getSelectedTab(); if(c == null || !(c instanceof CallPanel)) this.tabbedPane.setSelectedIndex(0); this.tabbedPane.revalidate(); } /** * Returns the component contained in the currently selected tab. * @return the selected CallPanel or null if there's no CallPanel selected */ public Component getSelectedTab() { Component c = this.tabbedPane.getSelectedComponent(); return c; } /** * Checks in the configuration xml if there is already stored index for * this provider and if yes, returns it, otherwise creates a new account * index and stores it. * * @param protocolProvider the protocol provider * @return the protocol provider index */ private int initiateProviderIndex( ProtocolProviderService protocolProvider) { ConfigurationService configService = GuiActivator.getConfigurationService(); String prefix = "net.java.sip.communicator.impl.gui.accounts"; List accounts = configService .getPropertyNamesByPrefix(prefix, true); Iterator accountsIter = accounts.iterator(); boolean savedAccount = false; while(accountsIter.hasNext()) { String accountRootPropName = (String) accountsIter.next(); String accountUID = configService.getString(accountRootPropName); if(accountUID.equals(protocolProvider .getAccountID().getAccountUniqueID())) { savedAccount = true; String index = configService.getString( accountRootPropName + ".accountIndex"); if(index != null) { //if we have found the accountIndex for this protocol provider //return this index return new Integer(index).intValue(); } else { //if there's no stored accountIndex for this protocol //provider, calculate the index, set it in the configuration //service and return it. int accountIndex = createAccountIndex(protocolProvider, accountRootPropName); return accountIndex; } } } if(!savedAccount) { String accNodeName = "acc" + Long.toString(System.currentTimeMillis()); String accountPackage = "net.java.sip.communicator.impl.gui.accounts." + accNodeName; configService.setProperty(accountPackage, protocolProvider.getAccountID().getAccountUniqueID()); int accountIndex = createAccountIndex(protocolProvider, accountPackage); return accountIndex; } return -1; } /** * Creates and calculates the account index for the given protocol * provider. * @param protocolProvider the protocol provider * @param accountRootPropName the path to where the index should be saved * in the configuration xml * @return the created index */ private int createAccountIndex(ProtocolProviderService protocolProvider, String accountRootPropName) { ConfigurationService configService = GuiActivator.getConfigurationService(); int accountIndex = -1; Iterator pproviders = protocolProviders.keySet().iterator(); ProtocolProviderService pps; while(pproviders.hasNext()) { pps = (ProtocolProviderService)pproviders.next(); if(pps.getProtocolName().equals( protocolProvider.getProtocolName()) && !pps.equals(protocolProvider)) { int index = ((Integer)protocolProviders.get(pps)) .intValue(); if(accountIndex < index) { accountIndex = index; } } } accountIndex++; configService.setProperty( accountRootPropName + ".accountIndex", new Integer(accountIndex)); return accountIndex; } /** * Updates the indexes in the configuration xml, when a provider has been * removed. * @param removedProvider the removed protocol provider */ private void updateProvidersIndexes(ProtocolProviderService removedProvider) { ConfigurationService configService = GuiActivator.getConfigurationService(); String prefix = "net.java.sip.communicator.impl.gui.accounts"; Iterator pproviders = protocolProviders.keySet().iterator(); ProtocolProviderService currentProvider = null; int sameProtocolProvidersCount = 0; while(pproviders.hasNext()) { ProtocolProviderService pps = (ProtocolProviderService)pproviders.next(); if(pps.getProtocolName().equals( removedProvider.getProtocolName())) { sameProtocolProvidersCount++; if(sameProtocolProvidersCount > 1) { break; } currentProvider = pps; } } if(sameProtocolProvidersCount < 2 && currentProvider != null) { protocolProviders.put(currentProvider, new Integer(0)); List accounts = configService .getPropertyNamesByPrefix(prefix, true); Iterator accountsIter = accounts.iterator(); while(accountsIter.hasNext()) { String rootPropName = (String) accountsIter.next(); String accountUID = configService.getString(rootPropName); if(accountUID.equals(currentProvider .getAccountID().getAccountUniqueID())) { configService.setProperty( rootPropName + ".accountIndex", new Integer(0)); } } this.getStatusPanel().updateAccount(currentProvider); } } /** * If the protocol provider supports presence operation set searches the * last status which was selected, otherwise returns null. * * @param protocolProvider the protocol provider we're interested in. * @return the last protocol provider presence status, or null if this * provider doesn't support presence operation set */ public Object getProtocolProviderLastStatus( ProtocolProviderService protocolProvider) { if(getProtocolPresenceOpSet(protocolProvider) != null) return this.statusPanel .getLastPresenceStatus(protocolProvider); else return this.statusPanel.getLastStatusString(protocolProvider); } /** * <tt>RenameAction</tt> is invoked when user presses the F2 key. Depending * on the selection opens the appropriate form for renaming. */ private class RenameAction extends AbstractAction { public void actionPerformed(ActionEvent e) { Object selectedObject = getContactListPanel().getContactList().getSelectedValue(); if(selectedObject instanceof MetaContact) { RenameContactDialog dialog = new RenameContactDialog( MainFrame.this, (MetaContact)selectedObject); dialog.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2 - 200, Toolkit.getDefaultToolkit().getScreenSize().height/2 - 50 ); dialog.setVisible(true); dialog.requestFocusInFiled(); } else if(selectedObject instanceof MetaContactGroup) { RenameGroupDialog dialog = new RenameGroupDialog( MainFrame.this, (MetaContactGroup)selectedObject); dialog.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2 - 200, Toolkit.getDefaultToolkit().getScreenSize().height/2 - 50 ); dialog.setVisible(true); dialog.requestFocusInFiled(); } } } /** * Overwrites the <tt>SIPCommFrame</tt> close method. This method is * invoked when user presses the Escape key. */ protected void close(boolean isEscaped) { ContactList contactList = getContactListPanel().getContactList(); ContactRightButtonMenu contactPopupMenu = contactList.getContactRightButtonMenu(); GroupRightButtonMenu groupPopupMenu = contactList.getGroupRightButtonMenu(); CommonRightButtonMenu commonPopupMenu = getContactListPanel().getCommonRightButtonMenu(); if(contactPopupMenu != null && contactPopupMenu.isVisible()) { contactPopupMenu.setVisible(false); } else if(groupPopupMenu != null && groupPopupMenu.isVisible()) { groupPopupMenu.setVisible(false); } else if(commonPopupMenu != null && commonPopupMenu.isVisible()) { commonPopupMenu.setVisible(false); } else if(statusPanel.hasSelectedMenus() || menu.hasSelectedMenus()) { MenuSelectionManager selectionManager = MenuSelectionManager.defaultManager(); selectionManager.clearSelectedPath(); } } /** * Returns the main menu in the application window. * @return the main menu in the application window */ public MainMenu getMainMenu() { return menu; } /** * Returns the <tt>ChatWindowManager</tt>. * @return the <tt>ChatWindowManager</tt> */ public ChatWindowManager getChatWindowManager() { return chatWindowManager; } /** * Opens chat window when the selected value is a MetaContact and opens a * group when the selected value is a MetaContactGroup. */ private class RunMessageWindowAction extends AbstractAction { public void actionPerformed(ActionEvent e) { ContactList clist = getContactListPanel().getContactList(); Object selectedValue = clist.getSelectedValue(); if (selectedValue instanceof MetaContact) { MetaContact contact = (MetaContact) selectedValue; SwingUtilities.invokeLater( getContactListPanel().new RunMessageWindow(contact)); } else if (selectedValue instanceof MetaContactGroup) { MetaContactGroup group = (MetaContactGroup) selectedValue; ContactListModel model = (ContactListModel) clist.getModel(); if (model.isGroupClosed(group)) { model.openGroup(group); } } } }; }
enter doesn't work on the contact list - fixed
src/net/java/sip/communicator/impl/gui/main/MainFrame.java
enter doesn't work on the contact list - fixed
<ide><path>rc/net/java/sip/communicator/impl/gui/main/MainFrame.java <ide> this.mainPanel.getActionMap().put("runChat", <ide> new RunMessageWindowAction()); <ide> <del> InputMap imap = this.getRootPane().getInputMap( <add> InputMap imap = mainPanel.getInputMap( <ide> JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); <ide> <ide> imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "runChat");
JavaScript
mit
c189c01b457581098b25b6f76f6c899693296b32
0
shamblesides/rpnow,shamblesides/rpnow
angular.module('rpnow', ['ngRoute', 'ngMaterial', 'angularCSS', 'luegg.directives', 'mp.colorPicker', 'LocalStorageModule']) .config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/', { title: 'RPNow', templateUrl: '/app/home.template.html', controller: 'NewRpController' }) .when('/rp/:rpCode', { title: 'Loading RP... | RPNow', templateUrl: '/app/rp.template.html', controller: 'RpController', css: [ '/app/rp.template.css', '/app/message.css', ] }) .when('/terms', { title: 'Terms of Use | RPNow', templateUrl: '/app/terms.template.html' }) .when('/about', { title: 'About | RPNow', templateUrl: '/app/about.template.html' }) .otherwise({ title: 'Not Found | RPNow', templateUrl: '/app/404.template.html', controller: ['$scope', '$location', function($scope, $location) { $scope.url = $location.url(); }] }); }]) .config(['$mdThemingProvider', function($mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('grey', { 'default': '50' }) .accentPalette('deep-purple'); $mdThemingProvider.theme('dark') .primaryPalette('grey', { 'default': '800' }) .accentPalette('amber') .dark(); $mdThemingProvider.alwaysWatchTheme(true); }]) .config(['localStorageServiceProvider', function(localStorageServiceProvider) { localStorageServiceProvider .setPrefix('rpnow') .setDefaultToCookie(false) }]) .run(['$rootScope', '$route', function($rootScope, $route) { // https://stackoverflow.com/questions/26308020/how-to-change-page-title-in-angular-using-routeprovider $rootScope.$on('$routeChangeSuccess', function() { document.title = $route.current.title; }); }]) .controller('NewRpController', ['$scope', '$timeout', '$location', '$mdMedia', 'RPRandom', 'socket', function($scope, $timeout, $location, $mdMedia, RPRandom, socket) { var spinTimer = null; function tick(millis) { RPRandom.roll('title', 25).then(function(title) { $scope.$apply(function() { $scope.title = title; }); if (millis < 200.0) spinTimer = $timeout(tick, millis, true, millis * 1.15); }) } $scope.spinTitle = function() { if (spinTimer) $timeout.cancel(spinTimer); tick(10.0); } $scope.submit = function() { $scope.submitted = true; socket.emit('create rp', {title: $scope.title, desc: $scope.desc}, function(err, data) { $scope.rpCode = data; $location.url('/rp/'+$scope.rpCode); }); }; $scope.$watch(function() { return $mdMedia('xs'); }, function(result) { $scope.isXs = result; }); }]) .controller('RpController', ['$scope', '$timeout', '$mdMedia', '$mdSidenav', '$mdDialog', 'pageAlerts', 'localStorageService', 'rpService', 'saveRpService', function($scope, $timeout, $mdMedia, $mdSidenav, $mdDialog, pageAlerts, localStorageService, rpService, saveRpService) { $scope.MAX_CHARA_NAME_LENGTH = 30; $scope.MAX_MSG_CONTENT_LENGTH = 10000; var RECENT_MSG_COUNT = 100; var MAX_RECENT_MSG_COUNT = 200; $scope.url = location.href.split('#')[0]; $scope.rp = rpService(); $scope.$watch('rp.loadError', function(loadError) { if (loadError) document.title = 'RP Not Found | RPNow'; }); $scope.$watch('rp.title', function(rpTitle) { if (rpTitle) document.title = rpTitle; }); $scope.isStoryGlued = true; // for SOME REASON this makes scrollglue work properly again // my best guess? view changes are happening AFTER scrollglue tries // to move the scrolling content, so it doesn't scroll the rest of // the way // this is a dumb workaround but what EVER $scope.$watch('showMessageDetails', checkScrollHeight); $scope.$watch('rp.loading', checkScrollHeight); $scope.$watchCollection('rp.msgs', checkScrollHeight); function checkScrollHeight() { $timeout(() => {},100); } $scope.numMsgsToShow = RECENT_MSG_COUNT; $scope.$watch('rp.msgs.length', function(newLength, oldLength) { if (!(newLength > oldLength)) return; var msg = $scope.rp.msgs[$scope.rp.msgs.length-1]; var alertText; if(msg.type === 'chara') alertText = '* ' + chara(msg).name + ' says...'; else if(msg.type === 'narrator') alertText = '* The narrator says...'; else if(msg.type === 'ooc') alertText = '* OOC message...'; else if(msg.type === 'image') alertText = '* Image posted...' pageAlerts.alert(alertText, $scope.notificationNoise); if ($scope.isStoryGlued) $scope.numMsgsToShow = RECENT_MSG_COUNT; else $scope.numMsgsToShow = Math.min($scope.numMsgsToShow+1, MAX_RECENT_MSG_COUNT); }); var id = $scope.id = function(item) { var index; if ((index = $scope.rp.charas && $scope.rp.charas.indexOf(item)) >= 0) return index; if ((index = $scope.rp.msgs && $scope.rp.msgs.indexOf(item)) >= 0) return index; return null; }; var chara = $scope.chara = function(x) { if (!$scope.rp.charas) return null; // voice if (x >= 0) return $scope.rp.charas[x]; // msg if (x.type === 'chara') return $scope.rp.charas[x.charaId]; // fail return null; }; $scope.color = function(voice) { if (voice === 'narrator') return $scope.nightMode? '#444444':'#ffffff'; if (voice === 'ooc') return $scope.nightMode? '#303030':'#fafafa'; if (voice >= 0) { if (!$scope.rp.charas) return ''; voice = $scope.rp.charas[voice]; } return voice.color; } $scope.msgBox = { content: '', voice: 'narrator', recentCharas: () => $scope.rp.charas ? $scope.msgBox.recentCharasString .split(',') .filter(x=>x>=0) .map(x=>$scope.rp.charas[+x]): [], recentCharasString: '', // stored in a string so it can be easily bound to localStorage isValid: function() { return $scope.msgBox.content.trim().length > 0; } }; $scope.$watch('msgBox.voice', function(newChara) { if (!(newChara >= 0)) return; if ($scope.msgBox.recentCharasString === undefined) return; if ($scope.rp.charas === undefined) return; var c = $scope.rp.charas[newChara]; var rc = $scope.msgBox.recentCharas(); // add to 'recent' list if it isn't already there if (rc.indexOf(c) === -1) rc.unshift(c); // or move it to the top else { rc.splice(rc.indexOf(c),1); rc.unshift(c); } if(rc.length > 5) { rc.splice(5, rc.length); } $scope.msgBox.recentCharasString = rc.map(c=>$scope.id(c)).join(','); }) $scope.sendMessage = function() { var msg = { content: $scope.msgBox.content.trim(), type: (+$scope.msgBox.voice >= 0) ? 'chara' : $scope.msgBox.voice } if (msg.type !== 'ooc') { [ /^\({2,}\s*(.*?[^\s])\s*\)*$/g, // (( stuff )) /^\{+\s*(.*?[^\s])\s*\}*$/g, // { stuff }, {{ stuff }}, ... /^\/\/\s*(.*[^\s])\s*$/g // //stuff ].forEach(function(oocRegex) { var match = oocRegex.exec(msg.content); if (match) { msg.content = match[1]; msg.type = 'ooc'; } }); } if (!msg.content) return; if (msg.type === 'chara') { msg.charaId = +$scope.msgBox.voice; } $scope.rp.addMessage(msg); $scope.msgBox.content = ''; }; $scope.addCharaBox = { name: '', color: '#ff0000', sending: false, isValid: function() { return $scope.addCharaBox.name.trim().length > 0 && /^#[0-9a-f]{6}$/g.test($scope.addCharaBox.color); } }; $scope.sendChara = function() { $scope.rp.addChara({ name: $scope.addCharaBox.name, color: $scope.addCharaBox.color }, function() { $timeout(function() { $mdSidenav('right').close(); },100); $mdDialog.hide(); $scope.msgBox.voice = $scope.rp.charas.length-1 }); $scope.addCharaBox.sending = true; $scope.addCharaBox.name = ''; }; $scope.imagePostBox = { url: '', sending: false, isValid: function() { var url = $scope.imagePostBox.url; var regexp = /^((ftp|https?):\/\/|(www\.)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]$/gi //https://github.com/angular/angular.js/blob/master/src/ngSanitize/filter/linky.js#L3 return url.match(regexp); } }; $scope.sendImage = function() { $scope.rp.addImage($scope.imagePostBox.url, function() { $scope.imagePostBox.sending = false; $mdDialog.hide(); }); $scope.imagePostBox.url = ''; $scope.imagePostBox.sending = true; } $scope.downloadOOC = true; $scope.downloadTxt = function() { saveRpService.saveTxt($scope.rp, $scope.downloadOOC); }; $scope.downloadDocx = function() { saveRpService.saveDocx($scope.rp, $scope.downloadOOC); }; $scope.beginEdit = function(msg) { msg.editing = true; msg.newContent = msg.content; }; $scope.cancelEdit = function(msg) { msg.editing = false; }; $scope.confirmEdit = function(msg) { var data = { id: id(msg), content: msg.newContent, secret: msg.secret }; $scope.rp.editMessage(data); msg.content = msg.newContent; msg.editing = false; msg.sending = true; }; $scope.allNoises = pageAlerts.allNoises; $scope.openNoiseSelector = function() { $timeout(function() { angular.element(document.getElementById('noiseSelector')).triggerHandler('click'); }) } $scope.pressEnterToSend = true; $scope.notificationNoise = 1; $scope.showMessageDetails = true; $scope.nightMode = false; $scope.toggleLeftDrawer = function() { $mdSidenav('left').toggle(); }; // all this complicated logic ends up creating intuitive behavior // for the right sidedrawer when resizing window, and opening/closing // sidedrawer within different window sizes. $scope.charaListDocked = false; $scope.toggleRightDrawer = function() { // if clicked from select menu, set it back to old chara $timeout(function(x){$scope.msgBox.voice=x;},0,true,$scope.msgBox.voice); // change behavior based on if we're on a large screen or not if ($mdMedia('gt-md')) { if ($scope.charaListDocked) { $mdSidenav('right').close(); $timeout(function() { $scope.charaListDocked = false; },100); } else { $scope.charaListDocked = true; } } else { $mdSidenav('right').toggle(); } } $scope.setVoice = function(voice) { $scope.msgBox.voice = voice; $mdSidenav('right').close(); } $scope.$watch(function() { return $scope.charaListDocked || $mdSidenav('right').isOpen(); }, function(isRightDrawerLockedOpen) { $scope.isRightDrawerLockedOpen = isRightDrawerLockedOpen; }); $scope.$watch(function() { return $mdMedia('gt-md') ? $scope.isRightDrawerLockedOpen : $mdSidenav('right').isOpen() }, function(isRightDrawerVisible) { $scope.isRightDrawerVisible = isRightDrawerVisible; }) $scope.hasManyCharacters = function() { return $scope.rp.charas && $scope.rp.charas.length > 10; }; $scope.showDialog = function(id, evt) { return $mdDialog.show({ contentElement: id, targetEvent: evt, clickOutsideToClose: true }); } $scope.hideDialog = function() { $mdDialog.cancel(); }; $scope.showCharacterDialog = function(evt) { $timeout(function(x){$scope.msgBox.voice=x;},0,true,$scope.msgBox.voice); $scope.showDialog('#characterCreatorDialog', evt) .then(function() { $scope.addCharaBox.sending = false; }) } $scope.viewMobileToolbarMenu = function($mdOpenMenu, evt) { $mdOpenMenu(evt); }; $scope.$watch(function() { return $mdMedia('gt-sm'); }, function(desktop) { $scope.isDesktopMode = desktop; }); // detect if the user is primarily using touch or a mouse, // guessing according to which the window notices first // used to decide whether to show tooltips or not $scope.hasMouse = undefined; window.addEventListener('touchstart', detectEvent); window.addEventListener('mousemove', detectEvent); function detectEvent(evt) { window.removeEventListener('touchstart', detectEvent); window.removeEventListener('mousemove', detectEvent); $scope.hasMouse = (evt.type === 'mousemove'); } // recall these values if they have been saved in localStorage // otherwise use the defaults defined earlier in the controller if (localStorageService.isSupported) { ['downloadOOC', 'pressEnterToSend', 'notificationNoise', 'showMessageDetails', 'nightMode', 'addCharaBox.color', 'charaListDocked'] .forEach(function(option) { var initVal = option.split('.').reduce(function(scope,key){return scope[key];},$scope); localStorageService.bind($scope, option, initVal); }); ['msgBox.content', 'msgBox.voice', 'msgBox.recentCharasString'] .forEach(function(option) { var initVal = option.split('.').reduce(function(scope,key){return scope[key];},$scope); localStorageService.bind($scope, option, initVal, $scope.rp.rpCode+'.'+option); }); } $scope.$on('$destroy', function() { $scope.rp.exit(); }); }]) .factory('rpService', ['socket', function(socket) { return function(rpCode) { return new RP(rpCode); }; function RP(rpCode) { var rp = this; rp.rpCode = rpCode || (location.href.split('#')[0]).split('/').pop(); rp.title = undefined; rp.desc = rp.loading = true; rp.loadError = null; var msgSendQueue = []; function enterRp() { socket.emit('enter rp', rp.rpCode, function(err, data) { rp.loading = false; if (err) { rp.loadError = err.code; return; } ['title', 'desc', 'msgs', 'charas', 'ipid', 'timestamp'] .forEach(function(prop) { if(data[prop] !== undefined) rp[prop] = JSON.parse(JSON.stringify(data[prop])); }); msgSendQueue.forEach(msg => rp.addMessage(msg)) }); } socket.on('reconnect', enterRp); enterRp(); rp.exit = function() { socket.emit('exit rp'); } socket.on('add message', function(msg) { rp.msgs.push(msg); }); socket.on('add character', function(chara) { rp.charas.push(chara); }); socket.on('edit message', function(data) { console.log(data); rp.msgs.splice(data.id,1, data.msg); }); rp.addMessage = function(msg, callback) { var placeholderMsg = JSON.parse(JSON.stringify(msg)); placeholderMsg.sending = true; rp.msgs.push(placeholderMsg); msgSendQueue.push(msg); socket.emit('add message', msg, function(err, receivedMsg) { if (err) return; msgSendQueue.splice(msgSendQueue.indexOf(msg),1); rp.msgs.splice(rp.msgs.indexOf(placeholderMsg),1); rp.msgs.push(receivedMsg); if (callback) callback(); }); }; rp.addChara = function(chara, callback) { socket.emit('add character', chara, function(err, receivedChara) { if (err) return; rp.charas.push(receivedChara); if (callback) callback(); }); }; rp.addImage = function(url, callback) { socket.emit('add image', url, function(err, receivedMsg) { if (err) return; rp.msgs.push(receivedMsg); if (callback) callback(); }); }; rp.editMessage = function(data, callback) { rp.msgs[data.id].sending = true; socket.emit('edit message', data, function(err, receivedMsg) { if (err) return; rp.msgs.splice(data.id,1, receivedMsg); if (callback) callback(); }); }; } }]) .factory('saveRpService', ['$http', function($http) { function saveTxt(rp, includeOOC) { var out = rp.msgs; if (!includeOOC) out = out.filter(function(msg) {return msg.type!=='ooc'}); out = out.map(function(msg) { if(msg.type === 'narrator') { return wordwrap(msg.content, 72); } else if(msg.type === 'ooc') { return wordwrap('(( OOC: '+msg.content+' ))', 72); } else if(msg.type === 'chara') { return rp.charas[msg.charaId].name.toUpperCase()+':\r\n' + wordwrap(msg.content, 70, ' '); } else if(msg.type === 'image') { return '--- IMAGE ---\r\n' + msg.url + '\r\n-------------'; } else { throw new Error('Unexpected message type: '+msg.type); } }); out.unshift(rp.title+'\r\n'+(rp.desc||'')+'\r\n----------'); var str = out.join('\r\n\r\n'); var blob = new Blob([str], {type: "text/plain;charset=utf-8"}); saveAs(blob, rp.title + ".txt"); } function wordwrap(str, width, indent) { return str.split('\n') .map(function(paragraph) { return (paragraph .match(/\S+\s*/g) || []) .reduce(function(lines,word) { if ((lines[lines.length-1]+word).trimRight().length>width) word.match(new RegExp("\\S{1,"+width+"}\\s*",'g')) .forEach(function(wordPiece){ lines.push(wordPiece); }) else lines[lines.length-1] += word; return lines; }, ['']) .map(function(str) { return (indent||'')+str.trimRight(); }) }) .reduce(function(lines, paragraph) { paragraph.forEach(function(line) { lines.push(line); }); return lines; }, []) .join('\r\n'); } var docxTemplateRequest; function saveDocx(rp, includeOOC) { var rpData = JSON.parse(JSON.stringify(rp)); rpData.hasDesc = !!rpData.desc; if (!includeOOC) rpData.msgs = rpData.msgs.filter(function(msg) {return msg.type!=='ooc'}); rpData.msgs.forEach(function(msg) { msg.isNarrator = msg.type === 'narrator'; msg.isOOC = msg.type === 'ooc'; msg.isChara = msg.type === 'chara'; msg.isImage = msg.type === 'image'; if (msg.isChara) msg.name = rpData.charas[msg.charaId].name.toUpperCase(); }); if (!docxTemplateRequest) { docxTemplateRequest = $http.get('/assets/template.docx', {responseType: 'arraybuffer'}); } docxTemplateRequest.then(function(res) { var doc = new Docxtemplater().loadZip(new JSZip(res.data)); doc.setData(rpData); doc.render(); var blob = doc.getZip().generate({ type: 'blob', mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }); saveAs(blob, rp.title + ".docx"); }) } return { saveTxt: saveTxt, saveDocx: saveDocx }; }]) .directive('onPressEnter', function() { return function(scope, element, attrs) { element.bind("keypress", function(evt) { if ((evt.keyCode || evt.which) !== 13) return; if (evt.shiftKey) return; var requireCtrlKey = scope.$eval(attrs.requireCtrlKey); if (requireCtrlKey && !evt.ctrlKey) return; evt.preventDefault(); scope.$apply(function() { scope.$eval(attrs.onPressEnter, {'event': evt}); }); }) } }) .directive('autoResize', function() { return function(scope, element, attrs) { var maxHeight = null; element.css('resize','none'); element.bind('input', resize); window.onresize = function() { maxHeight = null; resize(); } function resize() { if (attrs.maxHeight && !maxHeight) { element.css('overflow','hidden'); element.css('height', attrs.maxHeight); maxHeight = element[0].clientHeight; } element.css('height',''); var newHeight = element[0].scrollHeight; if (newHeight > maxHeight) newHeight = maxHeight; element.css('overflow', newHeight === maxHeight? 'auto':'hidden') element.css('height', newHeight + 'px'); } } }) .factory('RPRandom', ['$http', function($http) { var types = { 'title': ':Title' }; var dictPromises = { 'title': $http.get('/assets/titles.json') }; function resolve(str, dict) { do { var lastStr = str; str = str.replace(/:([a-zA-Z]+):?/, dictRep); } while(str !== lastStr); function dictRep(match, inner) { var x = dict[inner]; if(x) return x[Math.floor(Math.random()*x.length)]; else return inner.toUpperCase() + '?'; } return str.trim().replace(/\s+/g, ' '); } return { roll: function(template, maxLength) { return new Promise(function(success, fail) { dictPromises[template].then(function(res) { while (true) { var str = resolve(types[template], res.data); if (maxLength && str.length > maxLength) continue; return success(str); } }) }) } } }]) // https://stackoverflow.com/questions/14389049/ .factory('socket', ['$rootScope', function($rootScope) { var socket = io(); return { emit: function(type, data, callback) { socket.emit(type, data, function() { if (callback) callback.apply(socket, arguments); $rootScope.$apply(); }) }, on: function(type, callback) { socket.on(type, function() { callback.apply(socket, arguments); $rootScope.$apply(); }) } }; }]) // https://stackoverflow.com/questions/18006334/updating-time-ago-values-in-angularjs-and-momentjs .factory('timestampUpdateService', ['$rootScope', function($rootScope) { function timeAgoTick() { $rootScope.$broadcast('e:timeAgo'); } setInterval(function() { timeAgoTick(); $rootScope.$apply(); }, 1000*60); return { timeAgoTick: timeAgoTick, onTimeAgo: function($scope, handler) { $scope.$on('e:timeAgo', handler); } }; }]) .directive('momentAgoShort', ['timestampUpdateService', function(timestampUpdateService) { return { template: '<span>{{momentAgoShort}}</span>', replace: true, link: function(scope, el, attrs) { function updateTime() { var timestamp = scope.$eval(attrs.momentAgoShort); scope.momentAgoShort = moment(timestamp*1000).locale('en-short').fromNow(); } timestampUpdateService.onTimeAgo(scope, updateTime); updateTime(); } } }]) .filter('momentAgo', function() { return function(timestamp) { return moment(timestamp*1000).calendar(); } }) .filter('msgContent', ['$sce', '$filter', function($sce, $filter) { return function(str, color) { // escape characters var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; str = str.replace(/[&<>"']/g, function(m) { return escapeMap[m]; }); // urls // http://stackoverflow.com/a/3890175 str = str.replace( /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim, '<a href="$1" class="link" target="_blank">$1</a>' ); // actions if(color) { str = str.replace(/\*([^\r\n\*_]+)\*/g, '<span class="action" style="background-color:' + color + ';' + 'color:' + $filter('contrastColor')(color) + '">*$1*</span>'); } // bold str = str.replace(/(^|\s|(?:&quot;))__([^\r\n_]+)__([\s,\.\?!]|(?:&quot;)|$)/g, '$1<b>$2</b>$3'); // italix str = str.replace(/(^|\s|(?:&quot;))_([^\r\n_]+)_([\s,\.\?!]|(?:&quot;)|$)/g, '$1<i>$2</i>$3'); str = str.replace(/(^|\s|(?:&quot;))\/([^\r\n\/>]+)\/([\s,\.\?!]|(?:&quot;)|$)/g, '$1<i>$2</i>$3'); // both! str = str.replace(/(^|\s|(?:&quot;))___([^\r\n_]+)___([\s,\.\?!]|(?:&quot;)|$)/g, '$1<b><i>$2</i></b>$3'); // line breaks // http://stackoverflow.com/questions/2919337/jquery-convert-line-breaks-to-br-nl2br-equivalent str = str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2'); // mdash str = str.replace(/--/g, '&mdash;'); // done. return $sce.trustAsHtml(str); } }]) .filter('contrastColor', function() { return function(color, opacity) { //YIQ algorithm modified from: // http://24ways.org/2010/calculating-color-contrast/ var components = [1,3,5].map(i => parseInt(color.substr(i, 2), 16)); var yiq = components[0]*0.299 + components[1]*0.597 + components[2]*0.114; if (opacity) { var i = (yiq >= 128)? 0:255; return 'rgba('+i+','+i+','+i+','+opacity+')'; } return (yiq >= 128) ? 'black' : 'white'; }; }) .filter('needsContrastColor', function() { return function(color) { if (!color) return false; //YIQ algorithm modified from: // http://24ways.org/2010/calculating-color-contrast/ var components = [1,3,5].map(i => parseInt(color.substr(i, 2), 16)); var yiq = components[0]*0.299 + components[1]*0.597 + components[2]*0.114; return yiq > 200 || yiq < 60; }; }) .service('pageAlerts', function() { var pageAlerts = this; var alertText = null; var oldText = null; var flashesLeft = 0; var timer = null; var noiseDir = '/assets/sounds'; this.allNoises = [ {'name':'Off', 'audio':null}, {'name':'Typewriter', 'audio': new Audio(noiseDir+'/typewriter.mp3')}, {'name':'Page turn', 'audio': new Audio(noiseDir+'/pageturn.mp3')}, {'name':'Chimes', 'audio': new Audio(noiseDir+'/chimes.mp3')}, {'name':'Woosh', 'audio': new Audio(noiseDir+'/woosh.mp3')}, {'name':'Frog block', 'audio': new Audio(noiseDir+'/frogblock.mp3')}, {'name':'Classic alert', 'audio': new Audio(noiseDir+'/alert.mp3')}, ]; this.alert = function(text, noiseIdx) { if (document.visibilityState === 'visible') return; clearTimeout(timer); if (document.title === alertText) document.title = oldText; alertText = text; flashesLeft = 3; timerAction(); var noise = this.allNoises[noiseIdx]; if (noise.audio) noise.audio.play(); }; function timerAction() { if(document.title === alertText) { document.title = oldText; } else { oldText = document.title; document.title = alertText; if (flashesLeft <= 0) return; --flashesLeft; } timer = setTimeout(timerAction, 1000); } document.addEventListener('visibilitychange', function(evt) { if(document.visibilityState !== 'visible') return; if (document.title === alertText) document.title = oldText; clearTimeout(timer); }) }) moment.defineLocale('en-short', { parentLocale: 'en', relativeTime: { past: "%s", s: 'now', m: '%dmin', mm: '%dmin', h: '%dhr', hh: '%dhr', d: '%dday', dd: '%dday', M: '%dmo', MM: '%dmo', y: '%dyr', yy: '%dyrs' } });
client/app/app.js
angular.module('rpnow', ['ngRoute', 'ngMaterial', 'angularCSS', 'luegg.directives', 'mp.colorPicker', 'LocalStorageModule']) .config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/', { title: 'RPNow', templateUrl: '/app/home.template.html', controller: 'NewRpController' }) .when('/rp/:rpCode', { title: 'Loading RP... | RPNow', templateUrl: '/app/rp.template.html', controller: 'RpController', css: [ '/app/rp.template.css', '/app/message.css', ] }) .when('/terms', { title: 'Terms of Use | RPNow', templateUrl: '/app/terms.template.html' }) .when('/about', { title: 'About | RPNow', templateUrl: '/app/about.template.html' }) .otherwise({ title: 'Not Found | RPNow', templateUrl: '/app/404.template.html', controller: ['$scope', '$location', function($scope, $location) { $scope.url = $location.url(); }] }); }]) .config(['$mdThemingProvider', function($mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('grey', { 'default': '50' }) .accentPalette('deep-purple'); $mdThemingProvider.theme('dark') .primaryPalette('grey', { 'default': '800' }) .accentPalette('amber') .dark(); $mdThemingProvider.alwaysWatchTheme(true); }]) .config(['localStorageServiceProvider', function(localStorageServiceProvider) { localStorageServiceProvider .setPrefix('rpnow') .setDefaultToCookie(false) }]) .run(['$rootScope', '$route', function($rootScope, $route) { // https://stackoverflow.com/questions/26308020/how-to-change-page-title-in-angular-using-routeprovider $rootScope.$on('$routeChangeSuccess', function() { document.title = $route.current.title; }); }]) .controller('NewRpController', ['$scope', '$timeout', '$location', '$mdMedia', 'RPRandom', 'socket', function($scope, $timeout, $location, $mdMedia, RPRandom, socket) { var spinTimer = null; function tick(millis) { RPRandom.roll('title', 25).then(function(title) { $scope.$apply(function() { $scope.title = title; }); if (millis < 200.0) spinTimer = $timeout(tick, millis, true, millis * 1.15); }) } $scope.spinTitle = function() { if (spinTimer) $timeout.cancel(spinTimer); tick(10.0); } $scope.submit = function() { $scope.submitted = true; socket.emit('create rp', {title: $scope.title, desc: $scope.desc}, function(err, data) { $scope.rpCode = data; $location.url('/rp/'+$scope.rpCode); }); }; $scope.$watch(function() { return $mdMedia('xs'); }, function(result) { $scope.isXs = result; }); }]) .controller('RpController', ['$scope', '$timeout', '$mdMedia', '$mdSidenav', '$mdDialog', 'pageAlerts', 'localStorageService', 'rpService', 'saveRpService', function($scope, $timeout, $mdMedia, $mdSidenav, $mdDialog, pageAlerts, localStorageService, rpService, saveRpService) { $scope.MAX_CHARA_NAME_LENGTH = 30; $scope.MAX_MSG_CONTENT_LENGTH = 10000; var RECENT_MSG_COUNT = 100; var MAX_RECENT_MSG_COUNT = 200; $scope.url = location.href.split('#')[0]; $scope.rp = rpService(); $scope.$watch('rp.loadError', function(loadError) { if (loadError) document.title = 'RP Not Found | RPNow'; }); $scope.$watch('rp.title', function(rpTitle) { if (rpTitle) document.title = rpTitle; }); $scope.isStoryGlued = true; $scope.numMsgsToShow = RECENT_MSG_COUNT; $scope.$watch('rp.msgs.length', function(newLength, oldLength) { if (!(newLength > oldLength)) return; var msg = $scope.rp.msgs[$scope.rp.msgs.length-1]; var alertText; if(msg.type === 'chara') alertText = '* ' + chara(msg).name + ' says...'; else if(msg.type === 'narrator') alertText = '* The narrator says...'; else if(msg.type === 'ooc') alertText = '* OOC message...'; else if(msg.type === 'image') alertText = '* Image posted...' pageAlerts.alert(alertText, $scope.notificationNoise); if ($scope.isStoryGlued) $scope.numMsgsToShow = RECENT_MSG_COUNT; else $scope.numMsgsToShow = Math.min($scope.numMsgsToShow+1, MAX_RECENT_MSG_COUNT); }); var id = $scope.id = function(item) { var index; if ((index = $scope.rp.charas && $scope.rp.charas.indexOf(item)) >= 0) return index; if ((index = $scope.rp.msgs && $scope.rp.msgs.indexOf(item)) >= 0) return index; return null; }; var chara = $scope.chara = function(x) { if (!$scope.rp.charas) return null; // voice if (x >= 0) return $scope.rp.charas[x]; // msg if (x.type === 'chara') return $scope.rp.charas[x.charaId]; // fail return null; }; $scope.color = function(voice) { if (voice === 'narrator') return $scope.nightMode? '#444444':'#ffffff'; if (voice === 'ooc') return $scope.nightMode? '#303030':'#fafafa'; if (voice >= 0) { if (!$scope.rp.charas) return ''; voice = $scope.rp.charas[voice]; } return voice.color; } $scope.msgBox = { content: '', voice: 'narrator', recentCharas: () => $scope.rp.charas ? $scope.msgBox.recentCharasString .split(',') .filter(x=>x>=0) .map(x=>$scope.rp.charas[+x]): [], recentCharasString: '', // stored in a string so it can be easily bound to localStorage isValid: function() { return $scope.msgBox.content.trim().length > 0; } }; $scope.$watch('msgBox.voice', function(newChara) { if (!(newChara >= 0)) return; if ($scope.msgBox.recentCharasString === undefined) return; if ($scope.rp.charas === undefined) return; var c = $scope.rp.charas[newChara]; var rc = $scope.msgBox.recentCharas(); // add to 'recent' list if it isn't already there if (rc.indexOf(c) === -1) rc.unshift(c); // or move it to the top else { rc.splice(rc.indexOf(c),1); rc.unshift(c); } if(rc.length > 5) { rc.splice(5, rc.length); } $scope.msgBox.recentCharasString = rc.map(c=>$scope.id(c)).join(','); }) $scope.sendMessage = function() { var msg = { content: $scope.msgBox.content.trim(), type: (+$scope.msgBox.voice >= 0) ? 'chara' : $scope.msgBox.voice } if (msg.type !== 'ooc') { [ /^\({2,}\s*(.*?[^\s])\s*\)*$/g, // (( stuff )) /^\{+\s*(.*?[^\s])\s*\}*$/g, // { stuff }, {{ stuff }}, ... /^\/\/\s*(.*[^\s])\s*$/g // //stuff ].forEach(function(oocRegex) { var match = oocRegex.exec(msg.content); if (match) { msg.content = match[1]; msg.type = 'ooc'; } }); } if (!msg.content) return; if (msg.type === 'chara') { msg.charaId = +$scope.msgBox.voice; } $scope.rp.addMessage(msg); $scope.msgBox.content = ''; }; $scope.addCharaBox = { name: '', color: '#ff0000', sending: false, isValid: function() { return $scope.addCharaBox.name.trim().length > 0 && /^#[0-9a-f]{6}$/g.test($scope.addCharaBox.color); } }; $scope.sendChara = function() { $scope.rp.addChara({ name: $scope.addCharaBox.name, color: $scope.addCharaBox.color }, function() { $timeout(function() { $mdSidenav('right').close(); },100); $mdDialog.hide(); $scope.msgBox.voice = $scope.rp.charas.length-1 }); $scope.addCharaBox.sending = true; $scope.addCharaBox.name = ''; }; $scope.imagePostBox = { url: '', sending: false, isValid: function() { var url = $scope.imagePostBox.url; var regexp = /^((ftp|https?):\/\/|(www\.)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]$/gi //https://github.com/angular/angular.js/blob/master/src/ngSanitize/filter/linky.js#L3 return url.match(regexp); } }; $scope.sendImage = function() { $scope.rp.addImage($scope.imagePostBox.url, function() { $scope.imagePostBox.sending = false; $mdDialog.hide(); }); $scope.imagePostBox.url = ''; $scope.imagePostBox.sending = true; } $scope.downloadOOC = true; $scope.downloadTxt = function() { saveRpService.saveTxt($scope.rp, $scope.downloadOOC); }; $scope.downloadDocx = function() { saveRpService.saveDocx($scope.rp, $scope.downloadOOC); }; $scope.beginEdit = function(msg) { msg.editing = true; msg.newContent = msg.content; }; $scope.cancelEdit = function(msg) { msg.editing = false; }; $scope.confirmEdit = function(msg) { var data = { id: id(msg), content: msg.newContent, secret: msg.secret }; $scope.rp.editMessage(data); msg.content = msg.newContent; msg.editing = false; msg.sending = true; }; $scope.allNoises = pageAlerts.allNoises; $scope.openNoiseSelector = function() { $timeout(function() { angular.element(document.getElementById('noiseSelector')).triggerHandler('click'); }) } $scope.pressEnterToSend = true; $scope.notificationNoise = 1; $scope.showMessageDetails = true; $scope.nightMode = false; $scope.toggleLeftDrawer = function() { $mdSidenav('left').toggle(); }; // all this complicated logic ends up creating intuitive behavior // for the right sidedrawer when resizing window, and opening/closing // sidedrawer within different window sizes. $scope.charaListDocked = false; $scope.toggleRightDrawer = function() { // if clicked from select menu, set it back to old chara $timeout(function(x){$scope.msgBox.voice=x;},0,true,$scope.msgBox.voice); // change behavior based on if we're on a large screen or not if ($mdMedia('gt-md')) { if ($scope.charaListDocked) { $mdSidenav('right').close(); $timeout(function() { $scope.charaListDocked = false; },100); } else { $scope.charaListDocked = true; } } else { $mdSidenav('right').toggle(); } } $scope.setVoice = function(voice) { $scope.msgBox.voice = voice; $mdSidenav('right').close(); } $scope.$watch(function() { return $scope.charaListDocked || $mdSidenav('right').isOpen(); }, function(isRightDrawerLockedOpen) { $scope.isRightDrawerLockedOpen = isRightDrawerLockedOpen; }); $scope.$watch(function() { return $mdMedia('gt-md') ? $scope.isRightDrawerLockedOpen : $mdSidenav('right').isOpen() }, function(isRightDrawerVisible) { $scope.isRightDrawerVisible = isRightDrawerVisible; }) $scope.hasManyCharacters = function() { return $scope.rp.charas && $scope.rp.charas.length > 10; }; $scope.showDialog = function(id, evt) { return $mdDialog.show({ contentElement: id, targetEvent: evt, clickOutsideToClose: true }); } $scope.hideDialog = function() { $mdDialog.cancel(); }; $scope.showCharacterDialog = function(evt) { $timeout(function(x){$scope.msgBox.voice=x;},0,true,$scope.msgBox.voice); $scope.showDialog('#characterCreatorDialog', evt) .then(function() { $scope.addCharaBox.sending = false; }) } $scope.viewMobileToolbarMenu = function($mdOpenMenu, evt) { $mdOpenMenu(evt); }; $scope.$watch(function() { return $mdMedia('gt-sm'); }, function(desktop) { $scope.isDesktopMode = desktop; }); // detect if the user is primarily using touch or a mouse, // guessing according to which the window notices first // used to decide whether to show tooltips or not $scope.hasMouse = undefined; window.addEventListener('touchstart', detectEvent); window.addEventListener('mousemove', detectEvent); function detectEvent(evt) { window.removeEventListener('touchstart', detectEvent); window.removeEventListener('mousemove', detectEvent); $scope.hasMouse = (evt.type === 'mousemove'); } // recall these values if they have been saved in localStorage // otherwise use the defaults defined earlier in the controller if (localStorageService.isSupported) { ['downloadOOC', 'pressEnterToSend', 'notificationNoise', 'showMessageDetails', 'nightMode', 'addCharaBox.color', 'charaListDocked'] .forEach(function(option) { var initVal = option.split('.').reduce(function(scope,key){return scope[key];},$scope); localStorageService.bind($scope, option, initVal); }); ['msgBox.content', 'msgBox.voice', 'msgBox.recentCharasString'] .forEach(function(option) { var initVal = option.split('.').reduce(function(scope,key){return scope[key];},$scope); localStorageService.bind($scope, option, initVal, $scope.rp.rpCode+'.'+option); }); } $scope.$on('$destroy', function() { $scope.rp.exit(); }); }]) .factory('rpService', ['socket', function(socket) { return function(rpCode) { return new RP(rpCode); }; function RP(rpCode) { var rp = this; rp.rpCode = rpCode || (location.href.split('#')[0]).split('/').pop(); rp.loading = true; rp.loadError = null; var msgSendQueue = []; function enterRp() { socket.emit('enter rp', rp.rpCode, function(err, data) { rp.loading = false; if (err) { rp.loadError = err.code; return; } ['title', 'desc', 'msgs', 'charas', 'ipid', 'timestamp'] .forEach(function(prop) { if(data[prop] !== undefined) rp[prop] = JSON.parse(JSON.stringify(data[prop])); }); msgSendQueue.forEach(msg => rp.addMessage(msg)) }); } socket.on('reconnect', enterRp); enterRp(); rp.exit = function() { socket.emit('exit rp'); } socket.on('add message', function(msg) { rp.msgs.push(msg); }); socket.on('add character', function(chara) { rp.charas.push(chara); }); socket.on('edit message', function(data) { console.log(data); rp.msgs.splice(data.id,1, data.msg); }); rp.addMessage = function(msg, callback) { var placeholderMsg = JSON.parse(JSON.stringify(msg)); placeholderMsg.sending = true; rp.msgs.push(placeholderMsg); msgSendQueue.push(msg); socket.emit('add message', msg, function(err, receivedMsg) { if (err) return; msgSendQueue.splice(msgSendQueue.indexOf(msg),1); rp.msgs.splice(rp.msgs.indexOf(placeholderMsg),1); rp.msgs.push(receivedMsg); if (callback) callback(); }); }; rp.addChara = function(chara, callback) { socket.emit('add character', chara, function(err, receivedChara) { if (err) return; rp.charas.push(receivedChara); if (callback) callback(); }); }; rp.addImage = function(url, callback) { socket.emit('add image', url, function(err, receivedMsg) { if (err) return; rp.msgs.push(receivedMsg); if (callback) callback(); }); }; rp.editMessage = function(data, callback) { rp.msgs[data.id].sending = true; socket.emit('edit message', data, function(err, receivedMsg) { if (err) return; rp.msgs.splice(data.id,1, receivedMsg); if (callback) callback(); }); }; } }]) .factory('saveRpService', ['$http', function($http) { function saveTxt(rp, includeOOC) { var out = rp.msgs; if (!includeOOC) out = out.filter(function(msg) {return msg.type!=='ooc'}); out = out.map(function(msg) { if(msg.type === 'narrator') { return wordwrap(msg.content, 72); } else if(msg.type === 'ooc') { return wordwrap('(( OOC: '+msg.content+' ))', 72); } else if(msg.type === 'chara') { return rp.charas[msg.charaId].name.toUpperCase()+':\r\n' + wordwrap(msg.content, 70, ' '); } else if(msg.type === 'image') { return '--- IMAGE ---\r\n' + msg.url + '\r\n-------------'; } else { throw new Error('Unexpected message type: '+msg.type); } }); out.unshift(rp.title+'\r\n'+(rp.desc||'')+'\r\n----------'); var str = out.join('\r\n\r\n'); var blob = new Blob([str], {type: "text/plain;charset=utf-8"}); saveAs(blob, rp.title + ".txt"); } function wordwrap(str, width, indent) { return str.split('\n') .map(function(paragraph) { return (paragraph .match(/\S+\s*/g) || []) .reduce(function(lines,word) { if ((lines[lines.length-1]+word).trimRight().length>width) word.match(new RegExp("\\S{1,"+width+"}\\s*",'g')) .forEach(function(wordPiece){ lines.push(wordPiece); }) else lines[lines.length-1] += word; return lines; }, ['']) .map(function(str) { return (indent||'')+str.trimRight(); }) }) .reduce(function(lines, paragraph) { paragraph.forEach(function(line) { lines.push(line); }); return lines; }, []) .join('\r\n'); } var docxTemplateRequest; function saveDocx(rp, includeOOC) { var rpData = JSON.parse(JSON.stringify(rp)); rpData.hasDesc = !!rpData.desc; if (!includeOOC) rpData.msgs = rpData.msgs.filter(function(msg) {return msg.type!=='ooc'}); rpData.msgs.forEach(function(msg) { msg.isNarrator = msg.type === 'narrator'; msg.isOOC = msg.type === 'ooc'; msg.isChara = msg.type === 'chara'; msg.isImage = msg.type === 'image'; if (msg.isChara) msg.name = rpData.charas[msg.charaId].name.toUpperCase(); }); if (!docxTemplateRequest) { docxTemplateRequest = $http.get('/assets/template.docx', {responseType: 'arraybuffer'}); } docxTemplateRequest.then(function(res) { var doc = new Docxtemplater().loadZip(new JSZip(res.data)); doc.setData(rpData); doc.render(); var blob = doc.getZip().generate({ type: 'blob', mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }); saveAs(blob, rp.title + ".docx"); }) } return { saveTxt: saveTxt, saveDocx: saveDocx }; }]) .directive('onPressEnter', function() { return function(scope, element, attrs) { element.bind("keypress", function(evt) { if ((evt.keyCode || evt.which) !== 13) return; if (evt.shiftKey) return; var requireCtrlKey = scope.$eval(attrs.requireCtrlKey); if (requireCtrlKey && !evt.ctrlKey) return; evt.preventDefault(); scope.$apply(function() { scope.$eval(attrs.onPressEnter, {'event': evt}); }); }) } }) .directive('autoResize', function() { return function(scope, element, attrs) { var maxHeight = null; element.css('resize','none'); element.bind('input', resize); window.onresize = function() { maxHeight = null; resize(); } function resize() { if (attrs.maxHeight && !maxHeight) { element.css('overflow','hidden'); element.css('height', attrs.maxHeight); maxHeight = element[0].clientHeight; } element.css('height',''); var newHeight = element[0].scrollHeight; if (newHeight > maxHeight) newHeight = maxHeight; element.css('overflow', newHeight === maxHeight? 'auto':'hidden') element.css('height', newHeight + 'px'); } } }) .factory('RPRandom', ['$http', function($http) { var types = { 'title': ':Title' }; var dictPromises = { 'title': $http.get('/assets/titles.json') }; function resolve(str, dict) { do { var lastStr = str; str = str.replace(/:([a-zA-Z]+):?/, dictRep); } while(str !== lastStr); function dictRep(match, inner) { var x = dict[inner]; if(x) return x[Math.floor(Math.random()*x.length)]; else return inner.toUpperCase() + '?'; } return str.trim().replace(/\s+/g, ' '); } return { roll: function(template, maxLength) { return new Promise(function(success, fail) { dictPromises[template].then(function(res) { while (true) { var str = resolve(types[template], res.data); if (maxLength && str.length > maxLength) continue; return success(str); } }) }) } } }]) // https://stackoverflow.com/questions/14389049/ .factory('socket', ['$rootScope', function($rootScope) { var socket = io(); return { emit: function(type, data, callback) { socket.emit(type, data, function() { if (callback) callback.apply(socket, arguments); $rootScope.$apply(); }) }, on: function(type, callback) { socket.on(type, function() { callback.apply(socket, arguments); $rootScope.$apply(); }) } }; }]) // https://stackoverflow.com/questions/18006334/updating-time-ago-values-in-angularjs-and-momentjs .factory('timestampUpdateService', ['$rootScope', function($rootScope) { function timeAgoTick() { $rootScope.$broadcast('e:timeAgo'); } setInterval(function() { timeAgoTick(); $rootScope.$apply(); }, 1000*60); return { timeAgoTick: timeAgoTick, onTimeAgo: function($scope, handler) { $scope.$on('e:timeAgo', handler); } }; }]) .directive('momentAgoShort', ['timestampUpdateService', function(timestampUpdateService) { return { template: '<span>{{momentAgoShort}}</span>', replace: true, link: function(scope, el, attrs) { function updateTime() { var timestamp = scope.$eval(attrs.momentAgoShort); scope.momentAgoShort = moment(timestamp*1000).locale('en-short').fromNow(); } timestampUpdateService.onTimeAgo(scope, updateTime); updateTime(); } } }]) .filter('momentAgo', function() { return function(timestamp) { return moment(timestamp*1000).calendar(); } }) .filter('msgContent', ['$sce', '$filter', function($sce, $filter) { return function(str, color) { // escape characters var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; str = str.replace(/[&<>"']/g, function(m) { return escapeMap[m]; }); // urls // http://stackoverflow.com/a/3890175 str = str.replace( /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim, '<a href="$1" class="link" target="_blank">$1</a>' ); // actions if(color) { str = str.replace(/\*([^\r\n\*_]+)\*/g, '<span class="action" style="background-color:' + color + ';' + 'color:' + $filter('contrastColor')(color) + '">*$1*</span>'); } // bold str = str.replace(/(^|\s|(?:&quot;))__([^\r\n_]+)__([\s,\.\?!]|(?:&quot;)|$)/g, '$1<b>$2</b>$3'); // italix str = str.replace(/(^|\s|(?:&quot;))_([^\r\n_]+)_([\s,\.\?!]|(?:&quot;)|$)/g, '$1<i>$2</i>$3'); str = str.replace(/(^|\s|(?:&quot;))\/([^\r\n\/>]+)\/([\s,\.\?!]|(?:&quot;)|$)/g, '$1<i>$2</i>$3'); // both! str = str.replace(/(^|\s|(?:&quot;))___([^\r\n_]+)___([\s,\.\?!]|(?:&quot;)|$)/g, '$1<b><i>$2</i></b>$3'); // line breaks // http://stackoverflow.com/questions/2919337/jquery-convert-line-breaks-to-br-nl2br-equivalent str = str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2'); // mdash str = str.replace(/--/g, '&mdash;'); // done. return $sce.trustAsHtml(str); } }]) .filter('contrastColor', function() { return function(color, opacity) { //YIQ algorithm modified from: // http://24ways.org/2010/calculating-color-contrast/ var components = [1,3,5].map(i => parseInt(color.substr(i, 2), 16)); var yiq = components[0]*0.299 + components[1]*0.597 + components[2]*0.114; if (opacity) { var i = (yiq >= 128)? 0:255; return 'rgba('+i+','+i+','+i+','+opacity+')'; } return (yiq >= 128) ? 'black' : 'white'; }; }) .filter('needsContrastColor', function() { return function(color) { if (!color) return false; //YIQ algorithm modified from: // http://24ways.org/2010/calculating-color-contrast/ var components = [1,3,5].map(i => parseInt(color.substr(i, 2), 16)); var yiq = components[0]*0.299 + components[1]*0.597 + components[2]*0.114; return yiq > 200 || yiq < 60; }; }) .service('pageAlerts', function() { var pageAlerts = this; var alertText = null; var oldText = null; var flashesLeft = 0; var timer = null; var noiseDir = '/assets/sounds'; this.allNoises = [ {'name':'Off', 'audio':null}, {'name':'Typewriter', 'audio': new Audio(noiseDir+'/typewriter.mp3')}, {'name':'Page turn', 'audio': new Audio(noiseDir+'/pageturn.mp3')}, {'name':'Chimes', 'audio': new Audio(noiseDir+'/chimes.mp3')}, {'name':'Woosh', 'audio': new Audio(noiseDir+'/woosh.mp3')}, {'name':'Frog block', 'audio': new Audio(noiseDir+'/frogblock.mp3')}, {'name':'Classic alert', 'audio': new Audio(noiseDir+'/alert.mp3')}, ]; this.alert = function(text, noiseIdx) { if (document.visibilityState === 'visible') return; clearTimeout(timer); if (document.title === alertText) document.title = oldText; alertText = text; flashesLeft = 3; timerAction(); var noise = this.allNoises[noiseIdx]; if (noise.audio) noise.audio.play(); }; function timerAction() { if(document.title === alertText) { document.title = oldText; } else { oldText = document.title; document.title = alertText; if (flashesLeft <= 0) return; --flashesLeft; } timer = setTimeout(timerAction, 1000); } document.addEventListener('visibilitychange', function(evt) { if(document.visibilityState !== 'visible') return; if (document.title === alertText) document.title = oldText; clearTimeout(timer); }) }) moment.defineLocale('en-short', { parentLocale: 'en', relativeTime: { past: "%s", s: 'now', m: '%dmin', mm: '%dmin', h: '%dhr', hh: '%dhr', d: '%dday', dd: '%dday', M: '%dmo', MM: '%dmo', y: '%dyr', yy: '%dyrs' } });
Scrollglue problem workaround For some reason, these extra $watches make scrollglue be less spotty. I don't exactly understand why, but probably there are just view changes happening outside of angular that are causing problems. I don't want to figure them out right now
client/app/app.js
Scrollglue problem workaround
<ide><path>lient/app/app.js <ide> $scope.$watch('rp.title', function(rpTitle) { <ide> if (rpTitle) document.title = rpTitle; <ide> }); <del> <add> <ide> $scope.isStoryGlued = true; <add> // for SOME REASON this makes scrollglue work properly again <add> // my best guess? view changes are happening AFTER scrollglue tries <add> // to move the scrolling content, so it doesn't scroll the rest of <add> // the way <add> // this is a dumb workaround but what EVER <add> $scope.$watch('showMessageDetails', checkScrollHeight); <add> $scope.$watch('rp.loading', checkScrollHeight); <add> $scope.$watchCollection('rp.msgs', checkScrollHeight); <add> function checkScrollHeight() { $timeout(() => {},100); } <add> <ide> $scope.numMsgsToShow = RECENT_MSG_COUNT; <ide> $scope.$watch('rp.msgs.length', function(newLength, oldLength) { <ide> if (!(newLength > oldLength)) return; <ide> function RP(rpCode) { <ide> var rp = this; <ide> rp.rpCode = rpCode || (location.href.split('#')[0]).split('/').pop(); <add> rp.title = undefined; <add> rp.desc = <ide> rp.loading = true; <ide> rp.loadError = null; <ide>
Java
mit
3322fc977fae162e7fa6613eabf3e3f5bdd13919
0
mitdbg/modeldb,mitdbg/modeldb,mitdbg/modeldb,mitdbg/modeldb,mitdbg/modeldb
package ai.verta.modeldb.common.futures; import ai.verta.modeldb.common.CommonUtils; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.GeneratedMessageV3; import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.opentracing.util.GlobalTracer; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class FutureGrpc { // Converts a ListenableFuture, returned by a non-blocking call via grpc, to our custom // InternalFuture public static <T> InternalFuture<T> ClientRequest(ListenableFuture<T> f, Executor ex) { CompletableFuture<T> promise = new CompletableFuture<T>(); Futures.addCallback(f, new Callback<T>(promise), ex); return InternalFuture.from(promise); } // Injects the result of the Scala future into the grpc StreamObserver as the return of the server public static <T extends GeneratedMessageV3> void ServerResponse( StreamObserver<T> observer, InternalFuture<T> f, Executor ex) { f.whenComplete( (v, t) -> { if (t == null) { observer.onNext(v); observer.onCompleted(); } else { CommonUtils.observeError(observer, t); } }, ex); } // Wraps an Executor and make it compatible with grpc's context private static Executor makeCompatibleExecutor(Executor ex) { return new ExecutorWrapper(ex); } public static Executor initializeExecutor(Integer threadCount) { return FutureGrpc.makeCompatibleExecutor( Executors.newFixedThreadPool(threadCount, Executors.defaultThreadFactory())); } // Callback for a ListenableFuture to satisfy a promise private static class Callback<T> implements com.google.common.util.concurrent.FutureCallback<T> { final CompletableFuture<T> promise; private Callback(CompletableFuture<T> promise) { this.promise = promise; } @Override public void onSuccess(T t) { promise.complete(t); } @Override public void onFailure(Throwable t) { promise.completeExceptionally(t); } } private static class ExecutorWrapper implements Executor { final Executor other; ExecutorWrapper(Executor other) { this.other = other; } @Override public void execute(Runnable r) { if (GlobalTracer.isRegistered()) { final var tracer = GlobalTracer.get(); final var span = tracer.scopeManager().activeSpan(); other.execute(Context.current().wrap(() -> { tracer.scopeManager().activate(span); r.run(); })); } else { other.execute(Context.current().wrap(r)); } } } }
backend/common/src/main/java/ai/verta/modeldb/common/futures/FutureGrpc.java
package ai.verta.modeldb.common.futures; import ai.verta.modeldb.common.CommonUtils; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.GeneratedMessageV3; import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.opentracing.contrib.grpc.OpenTracingContextKey; import io.opentracing.util.GlobalTracer; import org.checkerframework.checker.nullness.compatqual.NullableDecl; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class FutureGrpc { // Converts a ListenableFuture, returned by a non-blocking call via grpc, to our custom // InternalFuture public static <T> InternalFuture<T> ClientRequest(ListenableFuture<T> f, Executor ex) { CompletableFuture<T> promise = new CompletableFuture<T>(); Futures.addCallback(f, new Callback<T>(promise), ex); return InternalFuture.from(promise); } // Injects the result of the Scala future into the grpc StreamObserver as the return of the server public static <T extends GeneratedMessageV3> void ServerResponse( StreamObserver<T> observer, InternalFuture<T> f, Executor ex) { f.whenComplete( (v, t) -> { if (t == null) { observer.onNext(v); observer.onCompleted(); } else { CommonUtils.observeError(observer, t); } }, ex); } // Wraps an Executor and make it compatible with grpc's context private static Executor makeCompatibleExecutor(Executor ex) { return new ExecutorWrapper(ex); } public static Executor initializeExecutor(Integer threadCount) { return FutureGrpc.makeCompatibleExecutor( Executors.newFixedThreadPool(threadCount, Executors.defaultThreadFactory())); } // Callback for a ListenableFuture to satisfy a promise private static class Callback<T> implements com.google.common.util.concurrent.FutureCallback<T> { final CompletableFuture<T> promise; private Callback(CompletableFuture<T> promise) { this.promise = promise; } @Override public void onSuccess(@NullableDecl T t) { promise.complete(t); } @Override public void onFailure(Throwable t) { promise.completeExceptionally(t); } } private static class ExecutorWrapper implements Executor { final Executor other; ExecutorWrapper(Executor other) { this.other = other; } @Override public void execute(Runnable r) { if (GlobalTracer.isRegistered()) { final var tracer = GlobalTracer.get(); final var span = tracer.scopeManager().activeSpan(); other.execute(Context.current().wrap(() -> { tracer.scopeManager().activate(span); r.run(); })); } else { other.execute(Context.current().wrap(r)); } } } }
Fix bad inport (#2543)
backend/common/src/main/java/ai/verta/modeldb/common/futures/FutureGrpc.java
Fix bad inport (#2543)
<ide><path>ackend/common/src/main/java/ai/verta/modeldb/common/futures/FutureGrpc.java <ide> import com.google.protobuf.GeneratedMessageV3; <ide> import io.grpc.Context; <ide> import io.grpc.stub.StreamObserver; <del>import io.opentracing.contrib.grpc.OpenTracingContextKey; <ide> import io.opentracing.util.GlobalTracer; <del>import org.checkerframework.checker.nullness.compatqual.NullableDecl; <ide> <ide> import java.util.Optional; <ide> import java.util.concurrent.CompletableFuture; <ide> } <ide> <ide> @Override <del> public void onSuccess(@NullableDecl T t) { <add> public void onSuccess(T t) { <ide> promise.complete(t); <ide> } <ide>
JavaScript
mit
dbb4157ce38854723b8763e5d11c93dd398ac259
0
nkohari/tutorial-navigator,nkohari/tutorial-navigator,nkohari/tutorial-navigator
import TutorialStore from './stores/tutorial-store'; import ArticleStore from './stores/article-store'; import loadSettingsAction from './action/load-settings-action'; import navigateAction from './action/navigate-action'; import loadArticleAction from './action/load-article-action'; import TutorialNavigator from './components/tutorial-navigator'; import Breadcrumbs from './components/breadcrumbs'; import Tutorial from './components/tutorial'; import { ServiceName } from './action/load-article-action'; import { loadArticle } from './util/tutorials'; import NavigatorAndTutorialView from './view/navigator-and-tutorial-view'; import createCustomContext from './util/create-custom-context'; import renderElement from './util/render-element'; module.exports = { TutorialNavigator : TutorialNavigator, Breadcrumbs: Breadcrumbs, Tutorial : Tutorial, TutorialStore : TutorialStore, ArticleStore : ArticleStore, articleService : { loadArticle : loadArticle }, loadSettingsAction : loadSettingsAction, loadArticleAction : loadArticleAction, renderElement: renderElement, createCustomContext: createCustomContext, navigateAction: navigateAction, Constants : { ArticleServiceName : ServiceName } }
src/app.js
import TutorialStore from './stores/tutorial-store'; import ArticleStore from './stores/article-store'; import loadSettingsAction from './action/load-settings-action'; import navigateAction from './action/navigate-action'; import loadArticleAction from './action/load-article-action'; import TutorialNavigator from './components/tutorial-navigator'; import Breadcrumbs from './components/breadcrumbs'; import Tutorial from './components/tutorial'; import { ServiceName } from './action/load-article-action'; import { loadArticle } from './util/tutorials'; import NavigatorAndTutorialView from './view/navigator-and-tutorial-view'; import createCustomContext from './util/create-custom-context'; import renderElement from './util/render-element'; module.exports = { TutorialNavigator : TutorialNavigator, Breadcrumbs: Breadcrumbs, Tutorial : Tutorial, TutorialStore : TutorialStore, ArticleStore : ArticleStore, articleService : loadArticle, loadSettingsAction : loadSettingsAction, loadArticleAction : loadArticleAction, renderElement: renderElement, createCustomContext: createCustomContext, navigateAction: navigateAction, Constants : { ArticleServiceName : ServiceName } }
Update article service
src/app.js
Update article service
<ide><path>rc/app.js <ide> Tutorial : Tutorial, <ide> TutorialStore : TutorialStore, <ide> ArticleStore : ArticleStore, <del> articleService : loadArticle, <add> articleService : { <add> loadArticle : loadArticle <add> }, <ide> loadSettingsAction : loadSettingsAction, <ide> loadArticleAction : loadArticleAction, <ide> renderElement: renderElement,
Java
apache-2.0
49b0ef9d16cc0acbf74c8560bed51c91062b9223
0
Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces
/******************************************************************************* * Copyright (c) 2012 GigaSpaces Technologies Ltd. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.openspaces.grid.gsm.strategy; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openspaces.admin.bean.BeanConfigurationException; import org.openspaces.admin.internal.pu.elastic.events.DefaultElasticAutoScalingProgressChangedEvent; import org.openspaces.admin.pu.elastic.config.AutomaticCapacityScaleConfig; import org.openspaces.admin.pu.elastic.config.AutomaticCapacityScaleRuleConfig; import org.openspaces.admin.pu.elastic.config.CapacityRequirementsConfig; import org.openspaces.admin.pu.elastic.config.CapacityRequirementsPerZonesConfig; import org.openspaces.admin.pu.elastic.config.ScaleStrategyConfig; import org.openspaces.admin.pu.statistics.ProcessingUnitStatisticsId; import org.openspaces.admin.pu.statistics.ProcessingUnitStatisticsIdConfigurer; import org.openspaces.admin.pu.statistics.TimeWindowStatisticsConfig; import org.openspaces.admin.zone.config.ZonesConfig; import org.openspaces.grid.gsm.autoscaling.AutoScalingSlaEnforcementEndpoint; import org.openspaces.grid.gsm.autoscaling.AutoScalingSlaEnforcementEndpointAware; import org.openspaces.grid.gsm.autoscaling.AutoScalingSlaPolicy; import org.openspaces.grid.gsm.autoscaling.AutoScalingSlaUtils; import org.openspaces.grid.gsm.autoscaling.AutomaticCapacityCooldownValidator; import org.openspaces.grid.gsm.autoscaling.exceptions.AutoScalingConfigConflictException; import org.openspaces.grid.gsm.autoscaling.exceptions.AutoScalingHighThresholdBreachedException; import org.openspaces.grid.gsm.autoscaling.exceptions.AutoScalingLowThresholdBreachedException; import org.openspaces.grid.gsm.autoscaling.exceptions.AutoScalingSlaEnforcementInProgressException; import org.openspaces.grid.gsm.autoscaling.exceptions.PerZoneAutoScalingSlaEnforcementInProgressException; import org.openspaces.grid.gsm.capacity.CapacityRequirements; import org.openspaces.grid.gsm.capacity.CapacityRequirementsPerZones; import org.openspaces.grid.gsm.containers.exceptions.ContainersSlaEnforcementInProgressException; import org.openspaces.grid.gsm.machines.exceptions.MachinesSlaEnforcementInProgressException; import org.openspaces.grid.gsm.machines.exceptions.MachinesSlaHasChangedException; import org.openspaces.grid.gsm.machines.exceptions.NeedToWaitUntilAllGridServiceAgentsDiscoveredException; import org.openspaces.grid.gsm.machines.exceptions.SomeProcessingUnitsHaveNotCompletedStateRecoveryException; import org.openspaces.grid.gsm.machines.exceptions.UndeployInProgressException; import org.openspaces.grid.gsm.rebalancing.exceptions.RebalancingSlaEnforcementInProgressException; import org.openspaces.grid.gsm.sla.exceptions.SlaEnforcementInProgressException; /** + * The business logic that scales an elastic processing unit based on the specified + * {@link AutomaticCapacityScaleConfig} + * + * @author itaif + * @since 9.0.0 + */ public class AutomaticCapacityScaleStrategyBean extends AbstractCapacityScaleStrategyBean implements AutoScalingSlaEnforcementEndpointAware { private AutoScalingSlaEnforcementEndpoint autoScalingEndpoint; // created by afterPropertiesSet() private AutomaticCapacityScaleConfig config; private AutomaticCapacityCooldownValidator cooldownValidator; // events state private ScaleStrategyProgressEventState autoScalingEventState; private CapacityRequirementsPerZones enforced; @Override public void setAutoScalingSlaEnforcementEndpoint(AutoScalingSlaEnforcementEndpoint endpoint) { this.autoScalingEndpoint = endpoint; } @Override public void afterPropertiesSet() { super.afterPropertiesSet(); this.config = new AutomaticCapacityScaleConfig(super.getProperties()); validateConfig(); this.cooldownValidator = new AutomaticCapacityCooldownValidator(); this.cooldownValidator.setCooldownAfterInstanceAdded(config.getCooldownAfterScaleOutSeconds(), TimeUnit.SECONDS); this.cooldownValidator.setCooldownAfterInstanceRemoved(config.getCooldownAfterScaleInSeconds(), TimeUnit.SECONDS); this.cooldownValidator.setProcessingUnit(getProcessingUnit()); CapacityRequirementsConfig initialCapacity = config.getInitialCapacity(); if (initialCapacity == null) { initialCapacity = config.getMinCapacity(); } autoScalingEventState = new ScaleStrategyProgressEventState( getEventsStore(), isUndeploying(), getProcessingUnit().getName(), DefaultElasticAutoScalingProgressChangedEvent.class); //inject initial manual scale capacity super.setPlannedCapacity(initialCapacity); super.setScaleStrategyConfig(config); getProcessingUnit().setStatisticsInterval(config.getStatisticsPollingIntervalSeconds(), TimeUnit.SECONDS); getProcessingUnit().startStatisticsMonitor(); if (getLogger().isDebugEnabled()) { getLogger().debug("isGridServiceAgentZonesAware="+isGridServiceAgentZonesAware()); } enablePuStatistics(); } private void validateConfig() { validateRulesConfig(); CapacityRequirements min = config.getMinCapacity().toCapacityRequirements(); if (min == null) { throw new BeanConfigurationException("Minimum capacity requirements is undefined"); } CapacityRequirements max = config.getMaxCapacity().toCapacityRequirements(); if (max == null) { throw new BeanConfigurationException("Maximum capacity requirements is undefined"); } if (min.greaterThan(max)) { throw new BeanConfigurationException("Maximum capacity (" + max + ") is less than minimum capacity (" + min + ")"); } CapacityRequirementsConfig initialConfig = config.getInitialCapacity(); if (initialConfig != null) { CapacityRequirements initial = initialConfig.toCapacityRequirements(); if (min.greaterThan(initial)) { throw new BeanConfigurationException("Initial capacity (" + initial + ") is less than minimum capacity (" + min + ")"); } if (initial.greaterThan(max)) { throw new BeanConfigurationException("Initial capacity (" + initial + ") is greater than maximum capacity (" + min + ")"); } } } @Override public void destroy() { disablePuStatistics(); super.destroy(); } @Override public ScaleStrategyConfig getConfig() { return config; } @Override protected void recoverStateOnEsmStart() throws SomeProcessingUnitsHaveNotCompletedStateRecoveryException, NeedToWaitUntilAllGridServiceAgentsDiscoveredException, MachinesSlaEnforcementInProgressException, UndeployInProgressException { super.recoverStateOnEsmStart(); CapacityRequirementsPerZones recoveredCapacity = super.getAllocatedCapacity(); if (!recoveredCapacity.equalsZero()) { // the ESM was restarted, as evident by the recovered capacity // in which case we need to overwrite the initial capacity with the recovered capacity setPlannedCapacity(recoveredCapacity); } } @Override protected boolean setPlannedCapacity(CapacityRequirementsPerZonesConfig config) { boolean planChanged = super.setPlannedCapacity(config); if (planChanged) { enablePuStatistics(); } return planChanged; } @Override protected void enforceSla() throws SlaEnforcementInProgressException { PerZoneAutoScalingSlaEnforcementInProgressException pendingAutoscaleInProgressExceptions = new PerZoneAutoScalingSlaEnforcementInProgressException(getProcessingUnit(), "Multiple Exceptions"); SlaEnforcementInProgressException pendingEnforcePlannedCapacityException = null; final CapacityRequirementsPerZones planned = super.getPlannedCapacity().toCapacityRequirementsPerZones(); try { super.enforcePlannedCapacity(); enforced = planned; if (getLogger().isDebugEnabled()) { getLogger().debug("enforcedCapacityRequirementsPerZones = " + planned); } // no exception means that manual scale is complete. } catch (RebalancingSlaEnforcementInProgressException e) { // do not run autoscaling algorithm if instances are changing throw e; } catch (ContainersSlaEnforcementInProgressException e) { // do not run autoscaling algorithm since GSM may already start deploying new instances throw e; } catch (MachinesSlaHasChangedException e) { //start over, since the plan has changed throw e; } catch (SlaEnforcementInProgressException e) { if (enforced == null) { // no prev capacityRequirements to work with throw e; } // no effect on instances yet... proceed with auto scaling rules // The reasoning is that it may take a long time for machines to start // and during that time the capacity requirements may need to change pendingEnforcePlannedCapacityException = e; } CapacityRequirementsPerZones newPlanned = new CapacityRequirementsPerZones(); // make sure that we are not in the cooldown period // Notice this check is performed after PU is INTACT, meaning the USM is already started // @see DefaultAdmin#degradeUniversalServiceManagerProcessingUnitStatus() cooldownValidator.validate(); Set<ZonesConfig> zoness = new HashSet<ZonesConfig>(); if (isGridServiceAgentZonesAware()) { zoness.addAll(enforced.getZones()); } else { zoness.add(getDefaultZones()); } // enforce SLA for each zone separately. for (ZonesConfig zones : zoness) { try { enforceAutoScalingSla(zones, enforced, newPlanned); } catch (AutoScalingHighThresholdBreachedException e) { if (getLogger().isDebugEnabled()) { getLogger().debug("High threshold breachned. Settings zones " + zones + " capacity to " + e.getNewCapacity()); } newPlanned = newPlanned.set(zones, e.getNewCapacity()); } catch (AutoScalingLowThresholdBreachedException e) { if (getLogger().isDebugEnabled()) { getLogger().debug("Low threshold breachned. Settings zones " + zones + " capacity to " + e.getNewCapacity()); } newPlanned = newPlanned.set(zones, e.getNewCapacity()); } catch (AutoScalingSlaEnforcementInProgressException e) { // do not change the plan if an exception was raised final CapacityRequirements plannedForZones = planned.getZonesCapacityOrZero(zones); if (getLogger().isDebugEnabled()) { getLogger().debug("Copying exising zones " + zones +" capacity " + plannedForZones); } newPlanned = newPlanned.set(zones, plannedForZones); // exception in one zone should not influence running autoscaling in another zone. // save exceptions for later handling pendingAutoscaleInProgressExceptions.addReason(zones, e); } } // no need to call AbstractCapacityScaleStrategyBean#enforePlannedCapacity if no capacity change is needed. boolean planChanged = setPlannedCapacity(new CapacityRequirementsPerZonesConfig(newPlanned)); if (pendingEnforcePlannedCapacityException != null) { // throw pending exception of previous manual scale capacity. // otherwise it could be lost when calling it again. throw pendingEnforcePlannedCapacityException; } if (pendingAutoscaleInProgressExceptions.hasReason()) { // exceptions during autoscaling sla enforcement per zone throw pendingAutoscaleInProgressExceptions; } if (planChanged) { // enforce new capacity requirements as soon as possible. // also exitting this method without an exception implies SLA is enforced super.enforcePlannedCapacity(); } } private void enforceAutoScalingSla(ZonesConfig zones, CapacityRequirementsPerZones enforced, CapacityRequirementsPerZones newPlanned) throws AutoScalingSlaEnforcementInProgressException { if (getLogger().isDebugEnabled()) { getLogger().debug("Enforcing automatic scaling SLA."); } final AutoScalingSlaPolicy sla = new AutoScalingSlaPolicy(); sla.setCapacityRequirements(enforced.getZonesCapacityOrZero(zones)); CapacityRequirements minimum = config.getMinCapacity().toCapacityRequirements(); CapacityRequirements maximum = config.getMaxCapacity().toCapacityRequirements(); if (isGridServiceAgentZonesAware()) { CapacityRequirements maximumPerZone = config.getMaxCapacityPerZone().toCapacityRequirements(); CapacityRequirements minimumPerZone = config.getMinCapacityPerZone().toCapacityRequirements(); maximum = AutoScalingSlaUtils.getMaximumCapacity(maximum, maximumPerZone, enforced, newPlanned, zones); minimum = AutoScalingSlaUtils.getMinimumCapacity(minimum, minimumPerZone, enforced, newPlanned, zones); } // for now we assume these values are already given as per zone. sla.setMaxCapacity(maximum); sla.setMinCapacity(minimum); sla.setRules(config.getRules()); sla.setZonesConfig(zones); sla.setContainerMemoryCapacityInMB(getGridServiceContainerConfig().getMaximumMemoryCapacityInMB()); if (getLogger().isDebugEnabled()) { getLogger().debug("Automatic Scaling SLA Policy: " + sla); } try { if (!maximum.greaterOrEquals(minimum)) { throw new AutoScalingConfigConflictException(getProcessingUnit(), minimum, maximum, zones.getZones(), enforced, newPlanned); } autoScalingEndpoint.enforceSla(sla); autoScalingCompletedEvent(); } catch (AutoScalingSlaEnforcementInProgressException e) { autoScalingInProgressEvent(e); throw e; } } private void validateRulesConfig() { for (AutomaticCapacityScaleRuleConfig rule : config.getRules()) { if (!rule.getLowThresholdBreachedDecrease().toCapacityRequirements().equalsZero() && !rule.getHighThresholdBreachedIncrease().toCapacityRequirements().equalsZero()) { try { if (AutoScalingSlaUtils.compare(rule.getLowThreshold(),rule.getHighThreshold()) > 0) { throw new BeanConfigurationException("Low threshold (" + rule.getLowThreshold() + ") cannot be higher than high threshold (" + rule.getHighThreshold() +")"); } } catch (NumberFormatException e) { throw new BeanConfigurationException("Failed to compare low threshold (" + rule.getLowThreshold() + ") and high threshold (" + rule.getHighThreshold() +")",e); } } } } private void enablePuStatistics() { int maxNumberOfSamples = 1; getLogger().info("enabling pu statistics for processing unit " + getProcessingUnit().getName()); // for each rule, add the statistics to calculate for (AutomaticCapacityScaleRuleConfig rule : config.getRules()) { ProcessingUnitStatisticsId statisticsId = rule.getStatistics(); TimeWindowStatisticsConfig timeWindowStatistics = statisticsId.getTimeWindowStatistics(); if (!isGridServiceAgentZonesAware()) { ProcessingUnitStatisticsId id = new ProcessingUnitStatisticsIdConfigurer() .agentZones(getDefaultZones()) .instancesStatistics(statisticsId.getInstancesStatistics()) .metric(statisticsId.getMetric()) .monitor(statisticsId.getMonitor()) .timeWindowStatistics(statisticsId.getTimeWindowStatistics()) .create(); maxNumberOfSamples = Math.max( maxNumberOfSamples, timeWindowStatistics.getMaxNumberOfSamples( config.getStatisticsPollingIntervalSeconds(), TimeUnit.SECONDS)); if (getLogger().isDebugEnabled()) { getLogger().debug("adding statistics calculation : " + id); } getProcessingUnit().addStatisticsCalculation(id); } else { Set<ZonesConfig> plannedZones = super.getPlannedZones(); getLogger().info("plannedZones = " + plannedZones); for (ZonesConfig zones : plannedZones) { zones.validate(); ProcessingUnitStatisticsId id = new ProcessingUnitStatisticsIdConfigurer() .agentZones(zones) .instancesStatistics(statisticsId.getInstancesStatistics()) .metric(statisticsId.getMetric()) .monitor(statisticsId.getMonitor()) .timeWindowStatistics(statisticsId.getTimeWindowStatistics()) .create(); getProcessingUnit().addStatisticsCalculation(id); // TODO eli - optimize : remove existing pu statistics in case the zones has changed(due to replacePlannedZones) maxNumberOfSamples = Math.max( maxNumberOfSamples, timeWindowStatistics.getMaxNumberOfSamples( config.getStatisticsPollingIntervalSeconds(), TimeUnit.SECONDS)); } } } getLogger().info("Start statistics polling for " + getProcessingUnit().getName() + " to " + config.getStatisticsPollingIntervalSeconds() + " seconds, history size is " + maxNumberOfSamples + " samples."); getProcessingUnit().setStatisticsHistorySize(maxNumberOfSamples); } private void disablePuStatistics() { getProcessingUnit().stopStatisticsMonitor(); } private void autoScalingCompletedEvent() { autoScalingEventState.enqueuProvisioningCompletedEvent(); } private void autoScalingInProgressEvent(AutoScalingSlaEnforcementInProgressException e) { autoScalingEventState.enqueuProvisioningInProgressEvent(e); } }
src/main/java/org/openspaces/grid/gsm/strategy/AutomaticCapacityScaleStrategyBean.java
/******************************************************************************* * Copyright (c) 2012 GigaSpaces Technologies Ltd. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.openspaces.grid.gsm.strategy; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openspaces.admin.bean.BeanConfigurationException; import org.openspaces.admin.internal.pu.elastic.events.DefaultElasticAutoScalingProgressChangedEvent; import org.openspaces.admin.pu.elastic.config.AutomaticCapacityScaleConfig; import org.openspaces.admin.pu.elastic.config.AutomaticCapacityScaleRuleConfig; import org.openspaces.admin.pu.elastic.config.CapacityRequirementsConfig; import org.openspaces.admin.pu.elastic.config.CapacityRequirementsPerZonesConfig; import org.openspaces.admin.pu.elastic.config.ScaleStrategyConfig; import org.openspaces.admin.pu.statistics.ProcessingUnitStatisticsId; import org.openspaces.admin.pu.statistics.ProcessingUnitStatisticsIdConfigurer; import org.openspaces.admin.pu.statistics.TimeWindowStatisticsConfig; import org.openspaces.admin.zone.config.ZonesConfig; import org.openspaces.grid.gsm.autoscaling.AutoScalingSlaEnforcementEndpoint; import org.openspaces.grid.gsm.autoscaling.AutoScalingSlaEnforcementEndpointAware; import org.openspaces.grid.gsm.autoscaling.AutoScalingSlaPolicy; import org.openspaces.grid.gsm.autoscaling.AutoScalingSlaUtils; import org.openspaces.grid.gsm.autoscaling.AutomaticCapacityCooldownValidator; import org.openspaces.grid.gsm.autoscaling.exceptions.AutoScalingConfigConflictException; import org.openspaces.grid.gsm.autoscaling.exceptions.AutoScalingHighThresholdBreachedException; import org.openspaces.grid.gsm.autoscaling.exceptions.AutoScalingLowThresholdBreachedException; import org.openspaces.grid.gsm.autoscaling.exceptions.AutoScalingSlaEnforcementInProgressException; import org.openspaces.grid.gsm.autoscaling.exceptions.PerZoneAutoScalingSlaEnforcementInProgressException; import org.openspaces.grid.gsm.capacity.CapacityRequirements; import org.openspaces.grid.gsm.capacity.CapacityRequirementsPerZones; import org.openspaces.grid.gsm.containers.exceptions.ContainersSlaEnforcementInProgressException; import org.openspaces.grid.gsm.machines.exceptions.MachinesSlaEnforcementInProgressException; import org.openspaces.grid.gsm.machines.exceptions.MachinesSlaHasChangedException; import org.openspaces.grid.gsm.machines.exceptions.NeedToWaitUntilAllGridServiceAgentsDiscoveredException; import org.openspaces.grid.gsm.machines.exceptions.SomeProcessingUnitsHaveNotCompletedStateRecoveryException; import org.openspaces.grid.gsm.machines.exceptions.UndeployInProgressException; import org.openspaces.grid.gsm.rebalancing.exceptions.RebalancingSlaEnforcementInProgressException; import org.openspaces.grid.gsm.sla.exceptions.SlaEnforcementInProgressException; /** + * The business logic that scales an elastic processing unit based on the specified + * {@link AutomaticCapacityScaleConfig} + * + * @author itaif + * @since 9.0.0 + */ public class AutomaticCapacityScaleStrategyBean extends AbstractCapacityScaleStrategyBean implements AutoScalingSlaEnforcementEndpointAware { private AutoScalingSlaEnforcementEndpoint autoScalingEndpoint; // created by afterPropertiesSet() private AutomaticCapacityScaleConfig config; private AutomaticCapacityCooldownValidator cooldownValidator; // events state private ScaleStrategyProgressEventState autoScalingEventState; private CapacityRequirementsPerZones enforced; @Override public void setAutoScalingSlaEnforcementEndpoint(AutoScalingSlaEnforcementEndpoint endpoint) { this.autoScalingEndpoint = endpoint; } @Override public void afterPropertiesSet() { super.afterPropertiesSet(); this.config = new AutomaticCapacityScaleConfig(super.getProperties()); validateConfig(); this.cooldownValidator = new AutomaticCapacityCooldownValidator(); this.cooldownValidator.setCooldownAfterInstanceAdded(config.getCooldownAfterScaleOutSeconds(), TimeUnit.SECONDS); this.cooldownValidator.setCooldownAfterInstanceRemoved(config.getCooldownAfterScaleInSeconds(), TimeUnit.SECONDS); this.cooldownValidator.setProcessingUnit(getProcessingUnit()); CapacityRequirementsConfig initialCapacity = config.getInitialCapacity(); if (initialCapacity == null) { initialCapacity = config.getMinCapacity(); } autoScalingEventState = new ScaleStrategyProgressEventState( getEventsStore(), isUndeploying(), getProcessingUnit().getName(), DefaultElasticAutoScalingProgressChangedEvent.class); //inject initial manual scale capacity super.setPlannedCapacity(initialCapacity); super.setScaleStrategyConfig(config); getProcessingUnit().setStatisticsInterval(config.getStatisticsPollingIntervalSeconds(), TimeUnit.SECONDS); getProcessingUnit().startStatisticsMonitor(); if (getLogger().isDebugEnabled()) { getLogger().debug("isGridServiceAgentZonesAware="+isGridServiceAgentZonesAware()); } enablePuStatistics(); } private void validateConfig() { validateRulesConfig(); CapacityRequirements min = config.getMinCapacity().toCapacityRequirements(); if (min == null) { throw new BeanConfigurationException("Minimum capacity requirements is undefined"); } CapacityRequirements max = config.getMaxCapacity().toCapacityRequirements(); if (max == null) { throw new BeanConfigurationException("Maximum capacity requirements is undefined"); } if (min.greaterThan(max)) { throw new BeanConfigurationException("Maximum capacity (" + max + ") is less than minimum capacity (" + min + ")"); } CapacityRequirementsConfig initialConfig = config.getInitialCapacity(); if (initialConfig != null) { CapacityRequirements initial = initialConfig.toCapacityRequirements(); if (min.greaterThan(initial)) { throw new BeanConfigurationException("Initial capacity (" + initial + ") is less than minimum capacity (" + min + ")"); } if (initial.greaterThan(max)) { throw new BeanConfigurationException("Initial capacity (" + initial + ") is greater than maximum capacity (" + min + ")"); } } } @Override public void destroy() { disablePuStatistics(); super.destroy(); } @Override public ScaleStrategyConfig getConfig() { return config; } @Override protected void recoverStateOnEsmStart() throws SomeProcessingUnitsHaveNotCompletedStateRecoveryException, NeedToWaitUntilAllGridServiceAgentsDiscoveredException, MachinesSlaEnforcementInProgressException, UndeployInProgressException { super.recoverStateOnEsmStart(); CapacityRequirementsPerZones recoveredCapacity = super.getAllocatedCapacity(); if (!recoveredCapacity.equalsZero()) { // the ESM was restarted, as evident by the recovered capacity // in which case we need to overwrite the initial capacity with the recovered capacity setPlannedCapacity(recoveredCapacity); } } @Override protected boolean setPlannedCapacity(CapacityRequirementsPerZonesConfig config) { boolean planChanged = super.setPlannedCapacity(config); if (planChanged) { enablePuStatistics(); } return planChanged; } @Override protected void enforceSla() throws SlaEnforcementInProgressException { PerZoneAutoScalingSlaEnforcementInProgressException pendingAutoscaleInProgressExceptions = new PerZoneAutoScalingSlaEnforcementInProgressException(getProcessingUnit(), "Multiple Exceptions"); SlaEnforcementInProgressException pendingEnforcePlannedCapacityException = null; final CapacityRequirementsPerZones planned = super.getPlannedCapacity().toCapacityRequirementsPerZones(); try { super.enforcePlannedCapacity(); enforced = planned; if (getLogger().isDebugEnabled()) { getLogger().debug("enforcedCapacityRequirementsPerZones = " + planned); } // no exception means that manual scale is complete. } catch (RebalancingSlaEnforcementInProgressException e) { // do not run autoscaling algorithm if instances are changing throw e; } catch (ContainersSlaEnforcementInProgressException e) { // do not run autoscaling algorithm since GSM may already start deploying new instances throw e; } catch (MachinesSlaHasChangedException e) { //start over, since the plan has changed throw e; } catch (SlaEnforcementInProgressException e) { if (enforced == null) { // no prev capacityRequirements to work with throw e; } // no effect on instances yet... proceed with auto scaling rules // The reasoning is that it may take a long time for machines to start // and during that time the capacity requirements may need to change pendingEnforcePlannedCapacityException = e; } CapacityRequirementsPerZones newPlanned = new CapacityRequirementsPerZones(); // make sure that we are not in the cooldown period // Notice this check is performed after PU is INTACT, meaning the USM is already started // @see DefaultAdmin#degradeUniversalServiceManagerProcessingUnitStatus() cooldownValidator.validate(); Set<ZonesConfig> zoness = new HashSet<ZonesConfig>(); if (isGridServiceAgentZonesAware()) { zoness.addAll(enforced.getZones()); } else { zoness.add(getDefaultZones()); } // enforce SLA for each zone separately. for (ZonesConfig zones : zoness) { try { enforceAutoScalingSla(zones, enforced, newPlanned); } catch (AutoScalingHighThresholdBreachedException e) { newPlanned = newPlanned.set(zones, e.getNewCapacity()); } catch (AutoScalingLowThresholdBreachedException e) { newPlanned = newPlanned.set(zones, e.getNewCapacity()); } catch (AutoScalingSlaEnforcementInProgressException e) { // do not change the plan if an exception was raised final CapacityRequirements plannedForZones = planned.getZonesCapacityOrZero(zones); newPlanned = newPlanned.set(zones, plannedForZones); // exception in one zone should not influence running autoscaling in another zone. // save exceptions for later handling pendingAutoscaleInProgressExceptions.addReason(zones, e); } } // no need to call AbstractCapacityScaleStrategyBean#enforePlannedCapacity if no capacity change is needed. boolean planChanged = setPlannedCapacity(new CapacityRequirementsPerZonesConfig(newPlanned)); if (pendingEnforcePlannedCapacityException != null) { // throw pending exception of previous manual scale capacity. // otherwise it could be lost when calling it again. throw pendingEnforcePlannedCapacityException; } if (pendingAutoscaleInProgressExceptions.hasReason()) { // exceptions during autoscaling sla enforcement per zone throw pendingAutoscaleInProgressExceptions; } if (planChanged) { // enforce new capacity requirements as soon as possible. // also exitting this method without an exception implies SLA is enforced super.enforcePlannedCapacity(); } } private void enforceAutoScalingSla(ZonesConfig zones, CapacityRequirementsPerZones enforced, CapacityRequirementsPerZones newPlanned) throws AutoScalingSlaEnforcementInProgressException { if (getLogger().isDebugEnabled()) { getLogger().debug("Enforcing automatic scaling SLA."); } final AutoScalingSlaPolicy sla = new AutoScalingSlaPolicy(); sla.setCapacityRequirements(enforced.getZonesCapacityOrZero(zones)); CapacityRequirements minimum = config.getMinCapacity().toCapacityRequirements(); CapacityRequirements maximum = config.getMaxCapacity().toCapacityRequirements(); if (isGridServiceAgentZonesAware()) { CapacityRequirements maximumPerZone = config.getMaxCapacityPerZone().toCapacityRequirements(); CapacityRequirements minimumPerZone = config.getMinCapacityPerZone().toCapacityRequirements(); maximum = AutoScalingSlaUtils.getMaximumCapacity(maximum, maximumPerZone, enforced, newPlanned, zones); minimum = AutoScalingSlaUtils.getMinimumCapacity(minimum, minimumPerZone, enforced, newPlanned, zones); } // for now we assume these values are already given as per zone. sla.setMaxCapacity(maximum); sla.setMinCapacity(minimum); sla.setRules(config.getRules()); sla.setZonesConfig(zones); sla.setContainerMemoryCapacityInMB(getGridServiceContainerConfig().getMaximumMemoryCapacityInMB()); if (getLogger().isDebugEnabled()) { getLogger().debug("Automatic Scaling SLA Policy: " + sla); } try { if (!maximum.greaterOrEquals(minimum)) { throw new AutoScalingConfigConflictException(getProcessingUnit(), minimum, maximum, zones.getZones(), enforced, newPlanned); } autoScalingEndpoint.enforceSla(sla); autoScalingCompletedEvent(); } catch (AutoScalingSlaEnforcementInProgressException e) { autoScalingInProgressEvent(e); throw e; } } private void validateRulesConfig() { for (AutomaticCapacityScaleRuleConfig rule : config.getRules()) { if (!rule.getLowThresholdBreachedDecrease().toCapacityRequirements().equalsZero() && !rule.getHighThresholdBreachedIncrease().toCapacityRequirements().equalsZero()) { try { if (AutoScalingSlaUtils.compare(rule.getLowThreshold(),rule.getHighThreshold()) > 0) { throw new BeanConfigurationException("Low threshold (" + rule.getLowThreshold() + ") cannot be higher than high threshold (" + rule.getHighThreshold() +")"); } } catch (NumberFormatException e) { throw new BeanConfigurationException("Failed to compare low threshold (" + rule.getLowThreshold() + ") and high threshold (" + rule.getHighThreshold() +")",e); } } } } private void enablePuStatistics() { int maxNumberOfSamples = 1; getLogger().info("enabling pu statistics for processing unit " + getProcessingUnit().getName()); // for each rule, add the statistics to calculate for (AutomaticCapacityScaleRuleConfig rule : config.getRules()) { ProcessingUnitStatisticsId statisticsId = rule.getStatistics(); TimeWindowStatisticsConfig timeWindowStatistics = statisticsId.getTimeWindowStatistics(); if (!isGridServiceAgentZonesAware()) { ProcessingUnitStatisticsId id = new ProcessingUnitStatisticsIdConfigurer() .agentZones(getDefaultZones()) .instancesStatistics(statisticsId.getInstancesStatistics()) .metric(statisticsId.getMetric()) .monitor(statisticsId.getMonitor()) .timeWindowStatistics(statisticsId.getTimeWindowStatistics()) .create(); maxNumberOfSamples = Math.max( maxNumberOfSamples, timeWindowStatistics.getMaxNumberOfSamples( config.getStatisticsPollingIntervalSeconds(), TimeUnit.SECONDS)); if (getLogger().isDebugEnabled()) { getLogger().debug("adding statistics calculation : " + id); } getProcessingUnit().addStatisticsCalculation(id); } else { Set<ZonesConfig> plannedZones = super.getPlannedZones(); getLogger().info("plannedZones = " + plannedZones); for (ZonesConfig zones : plannedZones) { zones.validate(); ProcessingUnitStatisticsId id = new ProcessingUnitStatisticsIdConfigurer() .agentZones(zones) .instancesStatistics(statisticsId.getInstancesStatistics()) .metric(statisticsId.getMetric()) .monitor(statisticsId.getMonitor()) .timeWindowStatistics(statisticsId.getTimeWindowStatistics()) .create(); getProcessingUnit().addStatisticsCalculation(id); // TODO eli - optimize : remove existing pu statistics in case the zones has changed(due to replacePlannedZones) maxNumberOfSamples = Math.max( maxNumberOfSamples, timeWindowStatistics.getMaxNumberOfSamples( config.getStatisticsPollingIntervalSeconds(), TimeUnit.SECONDS)); } } } getLogger().info("Start statistics polling for " + getProcessingUnit().getName() + " to " + config.getStatisticsPollingIntervalSeconds() + " seconds, history size is " + maxNumberOfSamples + " samples."); getProcessingUnit().setStatisticsHistorySize(maxNumberOfSamples); } private void disablePuStatistics() { getProcessingUnit().stopStatisticsMonitor(); } private void autoScalingCompletedEvent() { autoScalingEventState.enqueuProvisioningCompletedEvent(); } private void autoScalingInProgressEvent(AutoScalingSlaEnforcementInProgressException e) { autoScalingEventState.enqueuProvisioningInProgressEvent(e); } }
GS-10575 Added more debug level logging to investigate IllegalArgumentException svn path=/xap/trunk/openspaces/; revision=129239 Former-commit-id: cc6cee5906eab5b9f3e3a242358dc17a9ed8457f
src/main/java/org/openspaces/grid/gsm/strategy/AutomaticCapacityScaleStrategyBean.java
GS-10575 Added more debug level logging to investigate IllegalArgumentException
<ide><path>rc/main/java/org/openspaces/grid/gsm/strategy/AutomaticCapacityScaleStrategyBean.java <ide> enforceAutoScalingSla(zones, enforced, newPlanned); <ide> <ide> } catch (AutoScalingHighThresholdBreachedException e) { <add> if (getLogger().isDebugEnabled()) { <add> getLogger().debug("High threshold breachned. Settings zones " + zones + " capacity to " + e.getNewCapacity()); <add> } <ide> newPlanned = newPlanned.set(zones, e.getNewCapacity()); <ide> <ide> } catch (AutoScalingLowThresholdBreachedException e) { <add> if (getLogger().isDebugEnabled()) { <add> getLogger().debug("Low threshold breachned. Settings zones " + zones + " capacity to " + e.getNewCapacity()); <add> } <ide> newPlanned = newPlanned.set(zones, e.getNewCapacity()); <ide> <ide> } catch (AutoScalingSlaEnforcementInProgressException e) { <del> <ide> // do not change the plan if an exception was raised <ide> final CapacityRequirements plannedForZones = planned.getZonesCapacityOrZero(zones); <add> <add> if (getLogger().isDebugEnabled()) { <add> getLogger().debug("Copying exising zones " + zones +" capacity " + plannedForZones); <add> } <ide> newPlanned = newPlanned.set(zones, plannedForZones); <ide> <ide> // exception in one zone should not influence running autoscaling in another zone.
Java
lgpl-2.1
051fe2a163720bd7008ab6b9136f721f0100b97b
0
krichter722/swingx,trejkaz/swingx,tmyroadctfig/swingx,trejkaz/swingx,krichter722/swingx
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JRootPane; import org.jdesktop.swingx.util.WindowUtils; /** * A smarter JFrame specifically used for top level frames for Applications. * This frame uses a JXRootPane. */ public class JXFrame extends JFrame { public enum StartPosition {CenterInScreen, CenterInParent, Manual}; private Component waitPane = null; private Component glassPane = null; private boolean waitPaneVisible = false; private Cursor realCursor = null; private boolean waitCursorVisible = false; private boolean waiting = false; private StartPosition startPosition; private boolean hasBeenVisible = false; //startPosition is only used the first time the window is shown public JXFrame() { this(null, false); } public JXFrame(String title, boolean exitOnClose) { super(title); if (exitOnClose) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } public JXFrame(String title) { this(title, false); } // public void setCancelButton(JButton button) { // // } // // public JButton getCancelButton() { // // } // public void setDefaultButton(JButton button) { JButton old = getDefaultButton(); getRootPane().setDefaultButton(button); firePropertyChange("defaultButton", old, getDefaultButton()); } public JButton getDefaultButton() { return getRootPane().getDefaultButton(); } // public void setKeyPreview(boolean flag) { // // } // // public boolean getKeyPreview() { // // } public void setStartPosition(StartPosition position) { StartPosition old = getStartPosition(); this.startPosition = position; firePropertyChange("startPosition", old, getStartPosition()); } public StartPosition getStartPosition() { return startPosition == null ? StartPosition.Manual : startPosition; } public void setWaitCursorVisible(boolean flag) { boolean old = isWaitCursorVisible(); if (flag != old) { waitCursorVisible = flag; if (isWaitCursorVisible()) { realCursor = getCursor(); super.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } else { super.setCursor(realCursor); } firePropertyChange("waitCursorVisible", old, isWaitCursorVisible()); } } public boolean isWaitCursorVisible() { return waitCursorVisible; } @Override public void setCursor(Cursor c) { if (!isWaitCursorVisible()) { super.setCursor(c); } else { this.realCursor = c; } } public void setWaitPane(Component c) { Component old = getWaitPane(); this.waitPane = c; firePropertyChange("waitPane", old, getWaitPane()); } public Component getWaitPane() { return waitPane; } public void setWaitPaneVisible(boolean flag) { boolean old = isWaitPaneVisible(); if (flag != old) { this.waitPaneVisible = flag; Component wp = getWaitPane(); if (isWaitPaneVisible()) { glassPane = getRootPane().getGlassPane(); if (wp != null) { getRootPane().setGlassPane(wp); wp.setVisible(true); } } else { if (wp != null) { wp.setVisible(false); } getRootPane().setGlassPane(glassPane); } firePropertyChange("waitPaneVisible", old, isWaitPaneVisible()); } } public boolean isWaitPaneVisible() { return waitPaneVisible; } public void setWaiting(boolean waiting) { boolean old = isWaiting(); this.waiting = waiting; firePropertyChange("waiting", old, isWaiting()); setWaitPaneVisible(waiting); setWaitCursorVisible(waiting); } public boolean isWaiting() { return waiting; } @Override public void setVisible(boolean visible) { if (!hasBeenVisible && visible) { //move to the proper start position StartPosition pos = getStartPosition(); switch (pos) { case CenterInParent: setLocationRelativeTo(getParent()); break; case CenterInScreen: setLocation(WindowUtils.getPointForCentering(this)); break; case Manual: default: //nothing to do! } } super.setVisible(visible); } //---------------------------------------------------- Root Pane Methods /** * Overloaded to create a JXRootPane. */ protected JRootPane createRootPane() { return new JXRootPane(); } /** * Overloaded to make this public. */ public void setRootPane(JRootPane root) { super.setRootPane(root); } /** * Add a component to the Frame. */ public void addComponent(Component comp) { JXRootPane root = getRootPaneExt(); if (root != null) { root.addComponent(comp); } // XXX should probably fire some sort of container event. } /** * Removes a component from the frame. */ public void removeComponent(Component comp) { JXRootPane root = getRootPaneExt(); if (root != null) { root.removeComponent(comp); } // XXX should probably fire some sort of container event. } /** * Return the extended root pane. If this frame doesn't contain * an extended root pane the root pane should be accessed with * getRootPane(). * * @return the extended root pane or null. */ public JXRootPane getRootPaneExt() { if (rootPane instanceof JXRootPane) { return (JXRootPane)rootPane; } return null; } }
src/java/org/jdesktop/swingx/JXFrame.java
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JRootPane; /** * A smarter JFrame specifically used for top level frames for Applications. * This frame uses a JXRootPane. */ public class JXFrame extends JFrame { private Component waitPane = null; private Component glassPane = null; private boolean waitPaneVisible = false; private Cursor realCursor = null; private boolean waitCursorVisible = false; private boolean waiting = false; public JXFrame() { this(null, false); } public JXFrame(String title, boolean exitOnClose) { super(title); if (exitOnClose) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } public JXFrame(String title) { this(title, false); } // public void setCancelButton(JButton button) { // // } // // public JButton getCancelButton() { // // } // public void setDefaultButton(JButton button) { JButton old = getDefaultButton(); getRootPane().setDefaultButton(button); firePropertyChange("defaultButton", old, getDefaultButton()); } public JButton getDefaultButton() { return getRootPane().getDefaultButton(); } // public void setKeyPreview(boolean flag) { // // } // // public boolean getKeyPreview() { // // } // // public void setStartPosition(StartPosition position) { // // } // // public StartPosition getStartPosition() { // // } public void setWaitCursorVisible(boolean flag) { boolean old = isWaitCursorVisible(); if (flag != old) { waitCursorVisible = flag; if (isWaitCursorVisible()) { realCursor = getCursor(); super.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } else { super.setCursor(realCursor); } firePropertyChange("waitCursorVisible", old, isWaitCursorVisible()); } } public boolean isWaitCursorVisible() { return waitCursorVisible; } @Override public void setCursor(Cursor c) { if (!isWaitCursorVisible()) { super.setCursor(c); } else { this.realCursor = c; } } public void setWaitPane(Component c) { Component old = getWaitPane(); this.waitPane = c; firePropertyChange("waitPane", old, getWaitPane()); } public Component getWaitPane() { return waitPane; } public void setWaitPaneVisible(boolean flag) { boolean old = isWaitPaneVisible(); if (flag != old) { this.waitPaneVisible = flag; Component wp = getWaitPane(); if (isWaitPaneVisible()) { glassPane = getRootPane().getGlassPane(); if (wp != null) { getRootPane().setGlassPane(wp); wp.setVisible(true); } } else { if (wp != null) { wp.setVisible(false); } getRootPane().setGlassPane(glassPane); } firePropertyChange("waitPaneVisible", old, isWaitPaneVisible()); } } public boolean isWaitPaneVisible() { return waitPaneVisible; } public void setWaiting(boolean waiting) { boolean old = isWaiting(); this.waiting = waiting; firePropertyChange("waiting", old, isWaiting()); setWaitPaneVisible(waiting); setWaitCursorVisible(waiting); } public boolean isWaiting() { return waiting; } //---------------------------------------------------- Root Pane Methods /** * Overloaded to create a JXRootPane. */ protected JRootPane createRootPane() { return new JXRootPane(); } /** * Overloaded to make this public. */ public void setRootPane(JRootPane root) { super.setRootPane(root); } /** * Add a component to the Frame. */ public void addComponent(Component comp) { JXRootPane root = getRootPaneExt(); if (root != null) { root.addComponent(comp); } // XXX should probably fire some sort of container event. } /** * Removes a component from the frame. */ public void removeComponent(Component comp) { JXRootPane root = getRootPaneExt(); if (root != null) { root.removeComponent(comp); } // XXX should probably fire some sort of container event. } /** * Return the extended root pane. If this frame doesn't contain * an extended root pane the root pane should be accessed with * getRootPane(). * * @return the extended root pane or null. */ public JXRootPane getRootPaneExt() { if (rootPane instanceof JXRootPane) { return (JXRootPane)rootPane; } return null; } }
Added StartPosition enum and implementation (is this much different than setLocationRelativeTo?) git-svn-id: 9c6ef37dfd7eaa5a3748af7ba0f8d9e7b67c2a4c@1578 1312f61e-266d-0410-97fa-c3b71232c9ac
src/java/org/jdesktop/swingx/JXFrame.java
Added StartPosition enum and implementation (is this much different than setLocationRelativeTo?)
<ide><path>rc/java/org/jdesktop/swingx/JXFrame.java <ide> <ide> import javax.swing.JFrame; <ide> import javax.swing.JRootPane; <add>import org.jdesktop.swingx.util.WindowUtils; <ide> <ide> <ide> /** <ide> * This frame uses a JXRootPane. <ide> */ <ide> public class JXFrame extends JFrame { <add> public enum StartPosition {CenterInScreen, CenterInParent, Manual}; <add> <ide> private Component waitPane = null; <ide> private Component glassPane = null; <ide> private boolean waitPaneVisible = false; <ide> private Cursor realCursor = null; <ide> private boolean waitCursorVisible = false; <ide> private boolean waiting = false; <add> private StartPosition startPosition; <add> private boolean hasBeenVisible = false; //startPosition is only used the first time the window is shown <ide> <ide> public JXFrame() { <ide> this(null, false); <ide> // public boolean getKeyPreview() { <ide> // <ide> // } <del>// <del>// public void setStartPosition(StartPosition position) { <del>// <del>// } <del>// <del>// public StartPosition getStartPosition() { <del>// <del>// } <add> <add> public void setStartPosition(StartPosition position) { <add> StartPosition old = getStartPosition(); <add> this.startPosition = position; <add> firePropertyChange("startPosition", old, getStartPosition()); <add> } <add> <add> public StartPosition getStartPosition() { <add> return startPosition == null ? StartPosition.Manual : startPosition; <add> } <ide> <ide> public void setWaitCursorVisible(boolean flag) { <ide> boolean old = isWaitCursorVisible(); <ide> return waiting; <ide> } <ide> <add> @Override <add> public void setVisible(boolean visible) { <add> if (!hasBeenVisible && visible) { <add> //move to the proper start position <add> StartPosition pos = getStartPosition(); <add> switch (pos) { <add> case CenterInParent: <add> setLocationRelativeTo(getParent()); <add> break; <add> case CenterInScreen: <add> setLocation(WindowUtils.getPointForCentering(this)); <add> break; <add> case Manual: <add> default: <add> //nothing to do! <add> } <add> } <add> super.setVisible(visible); <add> } <add> <ide> //---------------------------------------------------- Root Pane Methods <ide> /** <ide> * Overloaded to create a JXRootPane.
Java
apache-2.0
e10f0fd0e7de751d8a9fb68401440b5cc4179f8c
0
blackducksoftware/hub-detect,blackducksoftware/hub-detect,blackducksoftware/hub-detect,blackducksoftware/hub-detect
/** * hub-detect * * Copyright (C) 2018 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.blackducksoftware.integration.hub.detect.help; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class DetectOption { final String key; final String fieldName; final Class<?> valueType; final String originalValue; final String defaultValue; final String resolvedValue; final boolean strictAcceptableValues; final boolean caseSensitiveAcceptableValues; final List<String> acceptableValues; final DetectOptionHelp detectOptionHelp; public List<String> warnings = new ArrayList<>(); public boolean requestedDeprecation = false; String interactiveValue = null; String finalValue = null; FinalValueType finalValueType = FinalValueType.DEFAULT; public DetectOption(final String key, final String fieldName, final String originalValue, final String resolvedValue, final Class<?> valueType, final String defaultValue, final boolean strictAcceptableValue, final boolean caseSensitiveAcceptableValues, final String[] acceptableValues, final DetectOptionHelp detectOptionHelp) { this.key = key; this.valueType = valueType; this.defaultValue = defaultValue; this.acceptableValues = Arrays.stream(acceptableValues).collect(Collectors.toList()); this.fieldName = fieldName; this.originalValue = originalValue; this.resolvedValue = resolvedValue; this.strictAcceptableValues = strictAcceptableValue; this.caseSensitiveAcceptableValues = caseSensitiveAcceptableValues; this.detectOptionHelp = detectOptionHelp; } public void requestDeprecation() { requestedDeprecation = true; } public void addWarning(final String description) { warnings.add(description); } public List<String> getWarnings() { return warnings.stream().collect(Collectors.toList()); } public boolean isRequestedDeprecation() { return requestedDeprecation; } public String getInteractiveValue() { return interactiveValue; } public void setInteractiveValue(final String interactiveValue) { this.interactiveValue = interactiveValue; } public String getFinalValue() { return finalValue; } public void setFinalValue(final String finalValue) { this.finalValue = finalValue; } public void setFinalValue(final String finalValue, final FinalValueType finalValueType) { setFinalValue(finalValue); setFinalValueType(finalValueType); } public FinalValueType getFinalValueType() { return finalValueType; } public void setFinalValueType(final FinalValueType finalValueType) { this.finalValueType = finalValueType; } public String getKey() { return key; } public String getFieldName() { return fieldName; } public Class<?> getValueType() { return valueType; } public String getOriginalValue() { return originalValue; } public String getDefaultValue() { return defaultValue; } public String getResolvedValue() { return resolvedValue; } public DetectOptionHelp getHelp() { return detectOptionHelp; } public List<String> getAcceptableValues() { return acceptableValues; } public boolean getCaseSensistiveAcceptableValues() { return caseSensitiveAcceptableValues; } public boolean isAcceptableValue(final String value) { //FIXME this is not working when the value is a comma separated list return acceptableValues.stream() .anyMatch(it -> { if (caseSensitiveAcceptableValues) { return it.equals(value); } else { return it.equalsIgnoreCase(value); } }); } public enum FinalValueType { DEFAULT, //the final value is the value in the default attribute INTERACTIVE, //the final value is from the interactive prompt LATEST, //the final value was resolved from latest CALCULATED, //the resolved value was not set and final value was set during init SUPPLIED, //the final value most likely came from spring OVERRIDE //the resolved value was set but during init a new value was set } }
src/main/groovy/com/blackducksoftware/integration/hub/detect/help/DetectOption.java
/** * hub-detect * * Copyright (C) 2018 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.blackducksoftware.integration.hub.detect.help; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class DetectOption { final String key; final String fieldName; final Class<?> valueType; final String originalValue; final String defaultValue; final String resolvedValue; final boolean strictAcceptableValues; final boolean caseSensitiveAcceptableValues; final List<String> acceptableValues; final DetectOptionHelp detectOptionHelp; public List<String> warnings = new ArrayList<>(); public boolean requestedDeprecation = false; String interactiveValue = null; String finalValue = null; FinalValueType finalValueType = FinalValueType.DEFAULT; public DetectOption(final String key, final String fieldName, final String originalValue, final String resolvedValue, final Class<?> valueType, final String defaultValue, final boolean strictAcceptableValue, final boolean caseSensitiveAcceptableValues, final String[] acceptableValues, final DetectOptionHelp detectOptionHelp) { this.key = key; this.valueType = valueType; this.defaultValue = defaultValue; this.acceptableValues = Arrays.stream(acceptableValues).collect(Collectors.toList()); this.fieldName = fieldName; this.originalValue = originalValue; this.resolvedValue = resolvedValue; this.strictAcceptableValues = strictAcceptableValue; this.caseSensitiveAcceptableValues = caseSensitiveAcceptableValues; this.detectOptionHelp = detectOptionHelp; } public void requestDeprecation() { requestedDeprecation = true; } public void addWarning(final String description) { warnings.add(description); } public List<String> getWarnings() { return warnings.stream().collect(Collectors.toList()); } public boolean isRequestedDeprecation() { return requestedDeprecation; } public String getInteractiveValue() { return interactiveValue; } public void setInteractiveValue(final String interactiveValue) { this.interactiveValue = interactiveValue; } public String getFinalValue() { return finalValue; } public void setFinalValue(final String finalValue) { this.finalValue = finalValue; } public void setFinalValue(final String finalValue, final FinalValueType finalValueType) { setFinalValue(finalValue); setFinalValueType(finalValueType); } public FinalValueType getFinalValueType() { return finalValueType; } public void setFinalValueType(final FinalValueType finalValueType) { this.finalValueType = finalValueType; } public String getKey() { return key; } public String getFieldName() { return fieldName; } public Class<?> getValueType() { return valueType; } public String getOriginalValue() { return originalValue; } public String getDefaultValue() { return defaultValue; } public String getResolvedValue() { return resolvedValue; } public DetectOptionHelp getHelp() { return detectOptionHelp; } public List<String> getAcceptableValues() { return acceptableValues; } public boolean getCaseSensistiveAcceptableValues() { return caseSensitiveAcceptableValues; } public boolean isAcceptableValue(final String value) { return acceptableValues.stream() .anyMatch(it -> { if (caseSensitiveAcceptableValues) { return it.equals(value); } else { return it.equalsIgnoreCase(value); } }); } public enum FinalValueType { DEFAULT, //the final value is the value in the default attribute INTERACTIVE, //the final value is from the interactive prompt LATEST, //the final value was resolved from latest CALCULATED, //the resolved value was not set and final value was set during init SUPPLIED, //the final value most likely came from spring OVERRIDE //the resolved value was set but during init a new value was set } }
Adding comment to fix the configuration printing
src/main/groovy/com/blackducksoftware/integration/hub/detect/help/DetectOption.java
Adding comment to fix the configuration printing
<ide><path>rc/main/groovy/com/blackducksoftware/integration/hub/detect/help/DetectOption.java <ide> } <ide> <ide> public boolean isAcceptableValue(final String value) { <add> //FIXME this is not working when the value is a comma separated list <ide> return acceptableValues.stream() <ide> .anyMatch(it -> { <ide> if (caseSensitiveAcceptableValues) {
Java
epl-1.0
83a47149d5afcfd56ca629ebc687fab9cec4b8cd
0
gnodet/wikitext
/******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ /* * Created on 14-Jan-2005 */ package org.eclipse.mylar.bugzilla.ui.tasklist; import java.io.IOException; import java.util.Date; import javax.security.auth.login.LoginException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.mylar.bugzilla.core.BugReport; import org.eclipse.mylar.bugzilla.core.BugzillaPlugin; import org.eclipse.mylar.bugzilla.core.BugzillaRepository; import org.eclipse.mylar.bugzilla.core.IBugzillaBug; import org.eclipse.mylar.bugzilla.core.internal.HtmlStreamTokenizer; import org.eclipse.mylar.bugzilla.ui.BugzillaImages; import org.eclipse.mylar.bugzilla.ui.BugzillaUiPlugin; import org.eclipse.mylar.bugzilla.ui.OfflineView; import org.eclipse.mylar.core.MylarPlugin; import org.eclipse.mylar.tasklist.MylarTasklistPlugin; import org.eclipse.mylar.tasklist.Task; import org.eclipse.mylar.tasklist.TaskListImages; import org.eclipse.mylar.tasklist.ui.views.TaskListView; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.Workbench; /** * @author Mik Kersten */ public class BugzillaTask extends Task { private static final String PROGRESS_LABEL_DOWNLOAD = "Downloading Bugzilla Reports..."; public enum BugReportSyncState { OUTGOING, OK, INCOMMING, CONFLICT } /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3257007648544469815L; public static final String FILE_EXTENSION = ".bug_reports"; public enum BugTaskState { FREE, WAITING, DOWNLOADING, COMPARING, OPENING } private transient BugTaskState state; /** * The bug report for this BugzillaTask. This is <code>null</code> if the * bug report with the specified ID was unable to download. */ protected transient BugReport bugReport = null; /** * Value is <code>true</code> if the bug report has saved changes that * need synchronizing with the Bugzilla server. */ private boolean isDirty; /** The last time this task's bug report was downloaded from the server. */ protected Date lastRefresh; /** * TODO: Move */ public static String getLastRefreshTime(Date lastRefresh) { String toolTip = "\n---------------\n" + "Last synchronized: "; Date timeNow = new Date(); if (lastRefresh == null) lastRefresh = new Date(); long timeDifference = (timeNow.getTime() - lastRefresh.getTime()) / 60000; long minutes = timeDifference % 60; timeDifference /= 60; long hours = timeDifference % 24; timeDifference /= 24; if (timeDifference > 0) { toolTip += timeDifference + ((timeDifference == 1) ? " day, " : " days, "); } if (hours > 0 || timeDifference > 0) { toolTip += hours + ((hours == 1) ? " hour, " : " hours, "); } toolTip += minutes + ((minutes == 1) ? " minute " : " minutes ") + "ago"; return toolTip; } public static final ISchedulingRule rule = new ISchedulingRule() { public boolean isConflicting(ISchedulingRule schedulingRule) { return schedulingRule == this; } public boolean contains(ISchedulingRule schedulingRule) { return schedulingRule == this; } }; public BugzillaTask(String handle, String label, boolean newTask) { super(handle, label, newTask); isDirty = false; scheduleDownloadReport(); setUrl(); } public BugzillaTask(String handle, String label, boolean noDownload, boolean newTask) { super(handle, label, newTask); isDirty = false; if (!noDownload) { scheduleDownloadReport(); } setUrl(); } public BugzillaTask(BugzillaHit hit, boolean newTask) { this(hit.getHandleIdentifier(), hit.getDescription(false), newTask); setPriority(hit.getPriority()); setUrl(); } private void setUrl() { int id = BugzillaTask.getBugId(getHandleIdentifier()); String url = BugzillaRepository.getBugUrlWithoutLogin(id); if (url != null) super.setIssueReportURL(url); } @Override public String getDescription(boolean truncate) { if (this.isBugDownloaded() || !super.getDescription(truncate).startsWith("<")) { return super.getDescription(truncate); } else { if (getState() == BugzillaTask.BugTaskState.FREE) { return BugzillaTask.getBugId(getHandleIdentifier()) + ": <Could not find bug>"; } else { return BugzillaTask.getBugId(getHandleIdentifier()) + ":"; } } // return BugzillaTasksTools.getBugzillaDescription(this); } /** * @return Returns the bugReport. */ public BugReport getBugReport() { return bugReport; } /** * @param bugReport The bugReport to set. */ public void setBugReport(BugReport bugReport) { this.bugReport = bugReport; } /** * @return Returns the serialVersionUID. */ public static long getSerialVersionUID() { return serialVersionUID; } /** * @return Returns the lastRefresh. */ public Date getLastRefresh() { return lastRefresh; } /** * @param lastRefresh The lastRefresh to set. */ public void setLastRefresh(Date lastRefresh) { this.lastRefresh = lastRefresh; } /** * @param state The state to set. */ public void setState(BugTaskState state) { this.state = state; } /** * @return Returns <code>true</code> if the bug report has saved changes * that need synchronizing with the Bugzilla server. */ public boolean isDirty() { return isDirty; } /** * @param isDirty The isDirty to set. */ public void setDirty(boolean isDirty) { this.isDirty = isDirty; notifyTaskDataChange(); } /** * @return Returns the state of the Bugzilla task. */ public BugTaskState getState() { return state; } /** * Try to download the bug from the server. * @param bugId The ID of the bug report to download. * * @return The bug report, or <code>null</code> if it was unsuccessfully * downloaded. */ public BugReport downloadReport() { try { // XXX make sure to send in the server name if there are multiple repositories if (BugzillaPlugin.getDefault() == null) { MylarPlugin.log("Bug Beport download failed for: " + getBugId(getHandleIdentifier()) + " due to bugzilla core not existing", this); return null; } return BugzillaRepository.getInstance().getBug(getBugId(getHandleIdentifier())); } catch (LoginException e) { Workbench.getInstance().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(Display.getDefault().getActiveShell(), "Report Download Failed", "The bugzilla report failed to be downloaded since your username or password is incorrect."); } }); } catch (IOException e) { Workbench.getInstance().getDisplay().asyncExec(new Runnable() { public void run() { ((ApplicationWindow) BugzillaPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow()).setStatus("Download of bug " + getBugId(getHandleIdentifier()) + " failed due to I/O exception"); } }); // MylarPlugin.log(e, "download failed due to I/O exception"); } return null; } @Override public void openTaskInEditor(boolean offline) { openTask(-1, offline); } /** * Opens this task's bug report in an editor revealing the selected comment. * @param commentNumber The comment number to reveal */ public void openTask(int commentNumber, boolean offline) { // if (state != BugTaskState.FREE) { // return; // } // // state = BugTaskState.OPENING; // notifyTaskDataChange(); OpenBugTaskJob job = new OpenBugTaskJob("Opening Bugzilla task in editor...", this, offline); job.schedule(); // job.addJobChangeListener(new IJobChangeListener(){ // // public void aboutToRun(IJobChangeEvent event) { // // don't care about this event // } // // public void awake(IJobChangeEvent event) { // // don't care about this event // } // public void done(IJobChangeEvent event) { // state = BugTaskState.FREE; // notifyTaskDataChange(); // } // // public void running(IJobChangeEvent event) { // // don't care about this event // } // // public void scheduled(IJobChangeEvent event) { // // don't care about this event // } // // public void sleeping(IJobChangeEvent event) { // // don't care about this event // } // }); } /** * @return <code>true</code> if the bug report for this BugzillaTask was * successfully downloaded. */ public boolean isBugDownloaded() { return bugReport != null; } @Override public String toString() { return "bugzilla report id: " + getHandleIdentifier(); } /** * We should be able to open the task at any point, meaning that if it isn't downloaded * attempt to get it from the server to open it */ protected void openTaskEditor(final BugzillaTaskEditorInput input, final boolean offline) { Workbench.getInstance().getDisplay().asyncExec(new Runnable() { public void run() { try { MylarTasklistPlugin.ReportOpenMode mode = MylarTasklistPlugin.getDefault().getReportMode(); if (mode == MylarTasklistPlugin.ReportOpenMode.EDITOR) { // if we can reach the server, get the latest for the bug if (!isBugDownloaded() && offline) { MessageDialog.openInformation(null, "Unable to open bug", "Unable to open the selected bugzilla task since you are currently offline"); return; } else if (!isBugDownloaded() && syncState != BugReportSyncState.OUTGOING && syncState != BugReportSyncState.CONFLICT) { input.getBugTask().downloadReport(); input.setOfflineBug(input.getBugTask().getBugReport()); } else if (syncState == BugReportSyncState.OUTGOING || syncState == BugReportSyncState.CONFLICT) { input.setOfflineBug(bugReport); } } // get the active workbench page IWorkbenchPage page = MylarTasklistPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage(); if (page == null) return; page.openEditor(input, "org.eclipse.mylar.bugzilla.ui.tasklist.bugzillaTaskEditor"); // else if (mode == MylarTasklistPlugin.ReportOpenMode.INTERNAL_BROWSER) { // String title = "Bug #" + BugzillaTask.getBugId(getHandle()); // BugzillaUITools.openUrl(title, title, getBugUrl()); // } if (syncState == BugReportSyncState.INCOMMING) { syncState = BugReportSyncState.OK; Display.getDefault().asyncExec(new Runnable() { public void run() { if (TaskListView.getDefault() != null && TaskListView.getDefault().getViewer() != null && !TaskListView.getDefault().getViewer().getControl().isDisposed()) { TaskListView.getDefault().getViewer().refresh(); } } }); } else if (syncState == BugReportSyncState.CONFLICT) { syncState = BugReportSyncState.OUTGOING; Display.getDefault().asyncExec(new Runnable() { public void run() { if (TaskListView.getDefault() != null && TaskListView.getDefault().getViewer() != null && !TaskListView.getDefault().getViewer().getControl().isDisposed()) { TaskListView.getDefault().getViewer().refresh(); } } }); } } catch (Exception ex) { MylarPlugin.log(ex, "couldn't open bugzilla task"); return; } } }); } /** * @return The number of seconds ago that this task's bug report was * downloaded from the server. */ public long getTimeSinceLastRefresh() { Date timeNow = new Date(); return (timeNow.getTime() - lastRefresh.getTime()) / 1000; } private class GetBugReportJob extends Job { public GetBugReportJob(String name) { super(name); setRule(rule); state = BugTaskState.WAITING; notifyTaskDataChange(); } @Override protected IStatus run(IProgressMonitor monitor) { try { state = BugTaskState.DOWNLOADING; notifyTaskDataChange(); // Update time this bugtask was last downloaded. lastRefresh = new Date(); bugReport = downloadReport(); state = BugTaskState.FREE; updateTaskDetails(); notifyTaskDataChange(); saveBugReport(true); } catch (Exception e) { MylarPlugin.fail(e, "Could not download report", false); } if (BugzillaUiPlugin.getDefault() != null) { BugzillaUiPlugin.getDefault().getBugzillaRefreshManager().removeRefreshingTask(BugzillaTask.this); } return new Status(IStatus.OK, MylarPlugin.IDENTIFIER, IStatus.OK, "", null); } } public void updateTaskDetails() { try { if (bugReport == null) bugReport = downloadReport(); if (bugReport == null) return; setPriority(bugReport.getAttribute("Priority").getValue()); String status = bugReport.getAttribute("Status").getValue(); if (status.equals("RESOLVED") || status.equals("CLOSED") || status.equals("VERIFIED")) { setCompleted(true); } else if (status.equals("REOPENED")) { setCompleted(false); } this.setDescription(HtmlStreamTokenizer.unescape(BugzillaTask.getBugId(getHandleIdentifier()) + ": " + bugReport.getSummary())); } catch (NullPointerException npe) { MylarPlugin.fail(npe, "Task details update failed", false); } } private class OpenBugTaskJob extends Job { protected BugzillaTask bugTask; private boolean offline; public OpenBugTaskJob(String name, BugzillaTask bugTask, boolean offline) { super(name); this.bugTask = bugTask; this.offline = offline; } @Override protected IStatus run(IProgressMonitor monitor) { try { boolean isLikeOffline = offline || syncState == BugReportSyncState.OUTGOING || syncState == BugReportSyncState.CONFLICT; final BugzillaTaskEditorInput input = new BugzillaTaskEditorInput(bugTask, isLikeOffline); // state = BugTaskState.OPENING; // notifyTaskDataChange(); openTaskEditor(input, offline); // state = BugTaskState.FREE; // notifyTaskDataChange(); return new Status(IStatus.OK, MylarPlugin.IDENTIFIER, IStatus.OK, "", null); } catch (Exception e) { // MessageDialog.openError(null, "Error Opening Bug", "Unable to open Bug report: " + BugzillaTask.getBugId(bugTask.getHandle())); MylarPlugin.fail(e, "Unable to open Bug report: " + BugzillaTask.getBugId(bugTask.getHandleIdentifier()), true); } return Status.CANCEL_STATUS; } } @Override public String getToolTipText() { if (lastRefresh == null) return ""; String toolTip = getDescription(true); toolTip += getLastRefreshTime(lastRefresh); return toolTip; } public boolean readBugReport() { // XXX server name needs to be with the bug report IBugzillaBug tempBug = OfflineView.find(getBugId(getHandleIdentifier())); if (tempBug == null) { bugReport = null; return true; } bugReport = (BugReport) tempBug; if (bugReport.hasChanges()) syncState = BugReportSyncState.OUTGOING; return true; } public void saveBugReport(boolean refresh) { if (bugReport == null) return; // XXX use the server name for multiple repositories // OfflineReportsFile offlineReports = BugzillaPlugin.getDefault().getOfflineReports(); // IBugzillaBug tempBug = OfflineView.find(getBugId(getHandle())); // OfflineView.re // if(location != -1){ // IBugzillaBug tmpBugReport = offlineReports.elements().get(location); // List<IBugzillaBug> l = new ArrayList<IBugzillaBug>(1); // l.add(tmpBugReport); // offlineReports.remove(l); // } // OfflineView.removeReport(tempBug); OfflineView.saveOffline(bugReport, false); final IWorkbench workbench = PlatformUI.getWorkbench(); if (refresh && !workbench.getDisplay().isDisposed()) { workbench.getDisplay().asyncExec(new Runnable() { public void run() { OfflineView.refresh(); } }); } } // public void removeReport() { // // XXX do we really want to do this??? // // XXX remove from registry too?? // IBugzillaBug tempBug = OfflineView.find(getBugId(getHandleIdentifier())); //// OfflineView.removeReport(tempBug); // // OfflineReportsFile offlineReports = BugzillaPlugin.getDefault().getOfflineReports(); // // int location = offlineReports.find(getBugId(getHandle())); // // if(location != -1){ // // IBugzillaBug tmpBugReport = offlineReports.elements().get(location); // // List<IBugzillaBug> l = new ArrayList<IBugzillaBug>(1); // // l.add(tmpBugReport); // // offlineReports.remove(l); // // } // } public static String getServerName(String handle) { int index = handle.lastIndexOf('-'); if (index != -1) { return handle.substring(0, index); } return null; } public static int getBugId(String handle) { int index = handle.lastIndexOf('-'); if (index != -1) { String id = handle.substring(index + 1); return Integer.parseInt(id); } return -1; } @Override public Image getIcon() { if (syncState == BugReportSyncState.OK) { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA); } else if (syncState == BugReportSyncState.OUTGOING) { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA_OUTGOING); } else if (syncState == BugReportSyncState.INCOMMING) { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA_INCOMMING); } else if (syncState == BugReportSyncState.CONFLICT) { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA_CONFLICT); } else { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA); } } public String getBugUrl() { // fix for bug 103537 - should login automatically, but dont want to show the login info in the query string return BugzillaRepository.getBugUrlWithoutLogin(getBugId(handle)); } @Override public boolean canEditDescription() { return false; } @Override public String getDeleteConfirmationMessage() { return "Remove this report from the task list, and discard any task context or local notes?"; } @Override public boolean isLocal() { return false; } @Override public boolean participatesInTaskHandles() { return false; } @Override public Font getFont() { Font f = super.getFont(); if (f != null) return f; if (getState() != BugzillaTask.BugTaskState.FREE || bugReport == null) { return ITALIC; } return null; } public void scheduleDownloadReport() { GetBugReportJob job = new GetBugReportJob(PROGRESS_LABEL_DOWNLOAD); job.schedule(); } public Job getRefreshJob() { if (isDirty() || (state != BugTaskState.FREE)) { return null; } GetBugReportJob job = new GetBugReportJob("Refreshing Bugzilla Reports..."); return job; } public String getStringForSortingDescription() { return getBugId(getHandleIdentifier()) + ""; } public static long getLastRefreshTimeInMinutes(Date lastRefresh) { Date timeNow = new Date(); if (lastRefresh == null) lastRefresh = new Date(); long timeDifference = (timeNow.getTime() - lastRefresh.getTime()) / 60000; return timeDifference; } private BugReportSyncState syncState = BugReportSyncState.OK; public void setSyncState(BugReportSyncState syncState) { if ((this.syncState == BugReportSyncState.INCOMMING && syncState == BugReportSyncState.OK)) { // do nothing } else { this.syncState = syncState; } } public static String getHandle(IBugzillaBug bug) { return "Bugzilla-" + bug.getId(); } public BugReportSyncState getSyncState() { return syncState; } }
org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/tasklist/BugzillaTask.java
/******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ /* * Created on 14-Jan-2005 */ package org.eclipse.mylar.bugzilla.ui.tasklist; import java.io.IOException; import java.util.Date; import javax.security.auth.login.LoginException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.mylar.bugzilla.core.BugReport; import org.eclipse.mylar.bugzilla.core.BugzillaPlugin; import org.eclipse.mylar.bugzilla.core.BugzillaRepository; import org.eclipse.mylar.bugzilla.core.IBugzillaBug; import org.eclipse.mylar.bugzilla.core.internal.HtmlStreamTokenizer; import org.eclipse.mylar.bugzilla.ui.BugzillaImages; import org.eclipse.mylar.bugzilla.ui.BugzillaUiPlugin; import org.eclipse.mylar.bugzilla.ui.OfflineView; import org.eclipse.mylar.core.MylarPlugin; import org.eclipse.mylar.tasklist.MylarTasklistPlugin; import org.eclipse.mylar.tasklist.Task; import org.eclipse.mylar.tasklist.TaskListImages; import org.eclipse.mylar.tasklist.ui.views.TaskListView; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.Workbench; /** * @author Mik Kersten */ public class BugzillaTask extends Task { private static final String PROGRESS_LABEL_DOWNLOAD = "Downloading Bugzilla Reports..."; public enum BugReportSyncState { OUTGOING, OK, INCOMMING, CONFLICT } /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3257007648544469815L; public static final String FILE_EXTENSION = ".bug_reports"; public enum BugTaskState { FREE, WAITING, DOWNLOADING, COMPARING, OPENING } private transient BugTaskState state; /** * The bug report for this BugzillaTask. This is <code>null</code> if the * bug report with the specified ID was unable to download. */ protected transient BugReport bugReport = null; /** * Value is <code>true</code> if the bug report has saved changes that * need synchronizing with the Bugzilla server. */ private boolean isDirty; /** The last time this task's bug report was downloaded from the server. */ protected Date lastRefresh; /** * TODO: Move */ public static String getLastRefreshTime(Date lastRefresh) { String toolTip = "\n---------------\n" + "Last synchronized: "; Date timeNow = new Date(); if (lastRefresh == null) lastRefresh = new Date(); long timeDifference = (timeNow.getTime() - lastRefresh.getTime()) / 60000; long minutes = timeDifference % 60; timeDifference /= 60; long hours = timeDifference % 24; timeDifference /= 24; if (timeDifference > 0) { toolTip += timeDifference + ((timeDifference == 1) ? " day, " : " days, "); } if (hours > 0 || timeDifference > 0) { toolTip += hours + ((hours == 1) ? " hour, " : " hours, "); } toolTip += minutes + ((minutes == 1) ? " minute " : " minutes ") + "ago"; return toolTip; } public static final ISchedulingRule rule = new ISchedulingRule() { public boolean isConflicting(ISchedulingRule schedulingRule) { return schedulingRule == this; } public boolean contains(ISchedulingRule schedulingRule) { return schedulingRule == this; } }; public BugzillaTask(String handle, String label, boolean newTask) { super(handle, label, newTask); isDirty = false; scheduleDownloadReport(); setUrl(); } public BugzillaTask(String handle, String label, boolean noDownload, boolean newTask) { super(handle, label, newTask); isDirty = false; if (!noDownload) { scheduleDownloadReport(); } setUrl(); } public BugzillaTask(BugzillaHit hit, boolean newTask) { this(hit.getHandleIdentifier(), hit.getDescription(false), newTask); setPriority(hit.getPriority()); setUrl(); } private void setUrl() { int id = BugzillaTask.getBugId(getHandleIdentifier()); String url = BugzillaRepository.getBugUrlWithoutLogin(id); if (url != null) super.setIssueReportURL(url); } @Override public String getDescription(boolean truncate) { if (this.isBugDownloaded() || !super.getDescription(truncate).startsWith("<")) { return super.getDescription(truncate); } else { if (getState() == BugzillaTask.BugTaskState.FREE) { return BugzillaTask.getBugId(getHandleIdentifier()) + ": <Could not find bug>"; } else { return BugzillaTask.getBugId(getHandleIdentifier()) + ":"; } } // return BugzillaTasksTools.getBugzillaDescription(this); } /** * @return Returns the bugReport. */ public BugReport getBugReport() { return bugReport; } /** * @param bugReport The bugReport to set. */ public void setBugReport(BugReport bugReport) { this.bugReport = bugReport; } /** * @return Returns the serialVersionUID. */ public static long getSerialVersionUID() { return serialVersionUID; } /** * @return Returns the lastRefresh. */ public Date getLastRefresh() { return lastRefresh; } /** * @param lastRefresh The lastRefresh to set. */ public void setLastRefresh(Date lastRefresh) { this.lastRefresh = lastRefresh; } /** * @param state The state to set. */ public void setState(BugTaskState state) { this.state = state; } /** * @return Returns <code>true</code> if the bug report has saved changes * that need synchronizing with the Bugzilla server. */ public boolean isDirty() { return isDirty; } /** * @param isDirty The isDirty to set. */ public void setDirty(boolean isDirty) { this.isDirty = isDirty; notifyTaskDataChange(); } /** * @return Returns the state of the Bugzilla task. */ public BugTaskState getState() { return state; } /** * Try to download the bug from the server. * @param bugId The ID of the bug report to download. * * @return The bug report, or <code>null</code> if it was unsuccessfully * downloaded. */ public BugReport downloadReport() { try { // XXX make sure to send in the server name if there are multiple repositories if (BugzillaPlugin.getDefault() == null) { MylarPlugin.log("Bug Beport download failed for: " + getBugId(getHandleIdentifier()) + " due to bugzilla core not existing", this); return null; } return BugzillaRepository.getInstance().getBug(getBugId(getHandleIdentifier())); } catch (LoginException e) { Workbench.getInstance().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(Display.getDefault().getActiveShell(), "Report Download Failed", "The bugzilla report failed to be downloaded since your username or password is incorrect."); } }); } catch (IOException e) { Workbench.getInstance().getDisplay().asyncExec(new Runnable() { public void run() { ((ApplicationWindow) BugzillaPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow()).setStatus("Download of bug " + getBugId(getHandleIdentifier()) + " failed due to I/O exception"); } }); // MylarPlugin.log(e, "download failed due to I/O exception"); } return null; } @Override public void openTaskInEditor(boolean offline) { openTask(-1, offline); } /** * Opens this task's bug report in an editor revealing the selected comment. * @param commentNumber The comment number to reveal */ public void openTask(int commentNumber, boolean offline) { // if (state != BugTaskState.FREE) { // return; // } // // state = BugTaskState.OPENING; // notifyTaskDataChange(); OpenBugTaskJob job = new OpenBugTaskJob("Opening Bugzilla task in editor...", this, offline); job.schedule(); // job.addJobChangeListener(new IJobChangeListener(){ // // public void aboutToRun(IJobChangeEvent event) { // // don't care about this event // } // // public void awake(IJobChangeEvent event) { // // don't care about this event // } // public void done(IJobChangeEvent event) { // state = BugTaskState.FREE; // notifyTaskDataChange(); // } // // public void running(IJobChangeEvent event) { // // don't care about this event // } // // public void scheduled(IJobChangeEvent event) { // // don't care about this event // } // // public void sleeping(IJobChangeEvent event) { // // don't care about this event // } // }); } /** * @return <code>true</code> if the bug report for this BugzillaTask was * successfully downloaded. */ public boolean isBugDownloaded() { return bugReport != null; } @Override public String toString() { return "bugzilla report id: " + getHandleIdentifier(); } /** * We should be able to open the task at any point, meaning that if it isn't downloaded * attempt to get it from the server to open it */ protected void openTaskEditor(final BugzillaTaskEditorInput input, final boolean offline) { Workbench.getInstance().getDisplay().asyncExec(new Runnable() { public void run() { try { MylarTasklistPlugin.ReportOpenMode mode = MylarTasklistPlugin.getDefault().getReportMode(); if (mode == MylarTasklistPlugin.ReportOpenMode.EDITOR) { // if we can reach the server, get the latest for the bug if (!isBugDownloaded() && offline) { MessageDialog.openInformation(null, "Unable to open bug", "Unable to open the selected bugzilla task since you are currently offline"); return; } else if (!isBugDownloaded() && syncState != BugReportSyncState.OUTGOING && syncState != BugReportSyncState.CONFLICT) { input.getBugTask().downloadReport(); input.setOfflineBug(input.getBugTask().getBugReport()); } else if (syncState == BugReportSyncState.OUTGOING || syncState == BugReportSyncState.CONFLICT) { input.setOfflineBug(bugReport); } } // get the active workbench page IWorkbenchPage page = MylarTasklistPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage(); if (page == null) return; page.openEditor(input, "org.eclipse.mylar.bugzilla.ui.tasklist.bugzillaTaskEditor"); // else if (mode == MylarTasklistPlugin.ReportOpenMode.INTERNAL_BROWSER) { // String title = "Bug #" + BugzillaTask.getBugId(getHandle()); // BugzillaUITools.openUrl(title, title, getBugUrl()); // } if (syncState == BugReportSyncState.INCOMMING) { syncState = BugReportSyncState.OK; Display.getDefault().asyncExec(new Runnable() { public void run() { if (TaskListView.getDefault() != null && TaskListView.getDefault().getViewer() != null && !TaskListView.getDefault().getViewer().getControl().isDisposed()) { TaskListView.getDefault().getViewer().refresh(); } } }); } else if (syncState == BugReportSyncState.CONFLICT) { syncState = BugReportSyncState.OUTGOING; Display.getDefault().asyncExec(new Runnable() { public void run() { if (TaskListView.getDefault() != null && TaskListView.getDefault().getViewer() != null && !TaskListView.getDefault().getViewer().getControl().isDisposed()) { TaskListView.getDefault().getViewer().refresh(); } } }); } } catch (Exception ex) { MylarPlugin.log(ex, "couldn't open bugzilla task"); return; } } }); } /** * @return The number of seconds ago that this task's bug report was * downloaded from the server. */ public long getTimeSinceLastRefresh() { Date timeNow = new Date(); return (timeNow.getTime() - lastRefresh.getTime()) / 1000; } private class GetBugReportJob extends Job { public GetBugReportJob(String name) { super(name); setRule(rule); state = BugTaskState.WAITING; notifyTaskDataChange(); } @Override protected IStatus run(IProgressMonitor monitor) { try { state = BugTaskState.DOWNLOADING; notifyTaskDataChange(); // Update time this bugtask was last downloaded. lastRefresh = new Date(); bugReport = downloadReport(); state = BugTaskState.FREE; updateTaskDetails(); notifyTaskDataChange(); saveBugReport(true); } catch (Exception e) { MylarPlugin.fail(e, "Could not download report", false); } if (BugzillaUiPlugin.getDefault() != null) { BugzillaUiPlugin.getDefault().getBugzillaRefreshManager().removeRefreshingTask(BugzillaTask.this); } return new Status(IStatus.OK, MylarPlugin.IDENTIFIER, IStatus.OK, "", null); } } public void updateTaskDetails() { try { if (bugReport == null) bugReport = downloadReport(); if (bugReport == null) return; setPriority(bugReport.getAttribute("Priority").getValue()); String status = bugReport.getAttribute("Status").getValue(); if (status.equals("RESOLVED") || status.equals("CLOSED") || status.equals("VERIFIED")) { setCompleted(true); } this.setDescription(HtmlStreamTokenizer.unescape(BugzillaTask.getBugId(getHandleIdentifier()) + ": " + bugReport.getSummary())); } catch (NullPointerException npe) { MylarPlugin.fail(npe, "Task details update failed", false); } } private class OpenBugTaskJob extends Job { protected BugzillaTask bugTask; private boolean offline; public OpenBugTaskJob(String name, BugzillaTask bugTask, boolean offline) { super(name); this.bugTask = bugTask; this.offline = offline; } @Override protected IStatus run(IProgressMonitor monitor) { try { boolean isLikeOffline = offline || syncState == BugReportSyncState.OUTGOING || syncState == BugReportSyncState.CONFLICT; final BugzillaTaskEditorInput input = new BugzillaTaskEditorInput(bugTask, isLikeOffline); // state = BugTaskState.OPENING; // notifyTaskDataChange(); openTaskEditor(input, offline); // state = BugTaskState.FREE; // notifyTaskDataChange(); return new Status(IStatus.OK, MylarPlugin.IDENTIFIER, IStatus.OK, "", null); } catch (Exception e) { // MessageDialog.openError(null, "Error Opening Bug", "Unable to open Bug report: " + BugzillaTask.getBugId(bugTask.getHandle())); MylarPlugin.fail(e, "Unable to open Bug report: " + BugzillaTask.getBugId(bugTask.getHandleIdentifier()), true); } return Status.CANCEL_STATUS; } } @Override public String getToolTipText() { if (lastRefresh == null) return ""; String toolTip = getDescription(true); toolTip += getLastRefreshTime(lastRefresh); return toolTip; } public boolean readBugReport() { // XXX server name needs to be with the bug report IBugzillaBug tempBug = OfflineView.find(getBugId(getHandleIdentifier())); if (tempBug == null) { bugReport = null; return true; } bugReport = (BugReport) tempBug; if (bugReport.hasChanges()) syncState = BugReportSyncState.OUTGOING; return true; } public void saveBugReport(boolean refresh) { if (bugReport == null) return; // XXX use the server name for multiple repositories // OfflineReportsFile offlineReports = BugzillaPlugin.getDefault().getOfflineReports(); // IBugzillaBug tempBug = OfflineView.find(getBugId(getHandle())); // OfflineView.re // if(location != -1){ // IBugzillaBug tmpBugReport = offlineReports.elements().get(location); // List<IBugzillaBug> l = new ArrayList<IBugzillaBug>(1); // l.add(tmpBugReport); // offlineReports.remove(l); // } // OfflineView.removeReport(tempBug); OfflineView.saveOffline(bugReport, false); final IWorkbench workbench = PlatformUI.getWorkbench(); if (refresh && !workbench.getDisplay().isDisposed()) { workbench.getDisplay().asyncExec(new Runnable() { public void run() { OfflineView.refresh(); } }); } } // public void removeReport() { // // XXX do we really want to do this??? // // XXX remove from registry too?? // IBugzillaBug tempBug = OfflineView.find(getBugId(getHandleIdentifier())); //// OfflineView.removeReport(tempBug); // // OfflineReportsFile offlineReports = BugzillaPlugin.getDefault().getOfflineReports(); // // int location = offlineReports.find(getBugId(getHandle())); // // if(location != -1){ // // IBugzillaBug tmpBugReport = offlineReports.elements().get(location); // // List<IBugzillaBug> l = new ArrayList<IBugzillaBug>(1); // // l.add(tmpBugReport); // // offlineReports.remove(l); // // } // } public static String getServerName(String handle) { int index = handle.lastIndexOf('-'); if (index != -1) { return handle.substring(0, index); } return null; } public static int getBugId(String handle) { int index = handle.lastIndexOf('-'); if (index != -1) { String id = handle.substring(index + 1); return Integer.parseInt(id); } return -1; } @Override public Image getIcon() { if (syncState == BugReportSyncState.OK) { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA); } else if (syncState == BugReportSyncState.OUTGOING) { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA_OUTGOING); } else if (syncState == BugReportSyncState.INCOMMING) { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA_INCOMMING); } else if (syncState == BugReportSyncState.CONFLICT) { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA_CONFLICT); } else { return TaskListImages.getImage(BugzillaImages.TASK_BUGZILLA); } } public String getBugUrl() { // fix for bug 103537 - should login automatically, but dont want to show the login info in the query string return BugzillaRepository.getBugUrlWithoutLogin(getBugId(handle)); } @Override public boolean canEditDescription() { return false; } @Override public String getDeleteConfirmationMessage() { return "Remove this report from the task list, and discard any task context or local notes?"; } @Override public boolean isLocal() { return false; } @Override public boolean participatesInTaskHandles() { return false; } @Override public Font getFont() { Font f = super.getFont(); if (f != null) return f; if (getState() != BugzillaTask.BugTaskState.FREE || bugReport == null) { return ITALIC; } return null; } public void scheduleDownloadReport() { GetBugReportJob job = new GetBugReportJob(PROGRESS_LABEL_DOWNLOAD); job.schedule(); } public Job getRefreshJob() { if (isDirty() || (state != BugTaskState.FREE)) { return null; } GetBugReportJob job = new GetBugReportJob("Refreshing Bugzilla Reports..."); return job; } public String getStringForSortingDescription() { return getBugId(getHandleIdentifier()) + ""; } public static long getLastRefreshTimeInMinutes(Date lastRefresh) { Date timeNow = new Date(); if (lastRefresh == null) lastRefresh = new Date(); long timeDifference = (timeNow.getTime() - lastRefresh.getTime()) / 60000; return timeDifference; } private BugReportSyncState syncState = BugReportSyncState.OK; public void setSyncState(BugReportSyncState syncState) { if ((this.syncState == BugReportSyncState.INCOMMING && syncState == BugReportSyncState.OK)) { // do nothing } else { this.syncState = syncState; } } public static String getHandle(IBugzillaBug bug) { return "Bugzilla-" + bug.getId(); } public BugReportSyncState getSyncState() { return syncState; } }
fix for reopen bug completion
org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/tasklist/BugzillaTask.java
fix for reopen bug completion
<ide><path>rg.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/tasklist/BugzillaTask.java <ide> String status = bugReport.getAttribute("Status").getValue(); <ide> if (status.equals("RESOLVED") || status.equals("CLOSED") || status.equals("VERIFIED")) { <ide> setCompleted(true); <del> } <add> } else if (status.equals("REOPENED")) { <add> setCompleted(false); <add> } <ide> this.setDescription(HtmlStreamTokenizer.unescape(BugzillaTask.getBugId(getHandleIdentifier()) + ": " + bugReport.getSummary())); <ide> } catch (NullPointerException npe) { <ide> MylarPlugin.fail(npe, "Task details update failed", false);
Java
apache-2.0
3535eb380abc4e81434ea556a6f5bcdac45b6b0f
0
lanceleverich/drools,292388900/drools,TonnyFeng/drools,yurloc/drools,TonnyFeng/drools,iambic69/drools,manstis/drools,jiripetrlik/drools,sotty/drools,kevinpeterson/drools,droolsjbpm/drools,lanceleverich/drools,jomarko/drools,romartin/drools,sotty/drools,pperboires/PocDrools,sutaakar/drools,mrrodriguez/drools,liupugong/drools,iambic69/drools,Buble1981/MyDroolsFork,sotty/drools,vinodkiran/drools,reynoldsm88/drools,pperboires/PocDrools,iambic69/drools,ThomasLau/drools,ChallenHB/drools,manstis/drools,ngs-mtech/drools,jomarko/drools,ThomasLau/drools,ngs-mtech/drools,sutaakar/drools,kevinpeterson/drools,liupugong/drools,OnePaaS/drools,romartin/drools,Buble1981/MyDroolsFork,OnePaaS/drools,prabasn/drools,prabasn/drools,mswiderski/drools,sutaakar/drools,ThomasLau/drools,mrrodriguez/drools,amckee23/drools,winklerm/drools,psiroky/drools,ChallenHB/drools,yurloc/drools,kedzie/drools-android,mrrodriguez/drools,romartin/drools,HHzzhz/drools,kedzie/drools-android,292388900/drools,reynoldsm88/drools,reynoldsm88/drools,ngs-mtech/drools,vinodkiran/drools,pwachira/droolsexamples,mrietveld/drools,ngs-mtech/drools,prabasn/drools,amckee23/drools,kevinpeterson/drools,romartin/drools,vinodkiran/drools,vinodkiran/drools,OnePaaS/drools,jiripetrlik/drools,yurloc/drools,rajashekharmunthakewill/drools,mswiderski/drools,liupugong/drools,292388900/drools,manstis/drools,TonnyFeng/drools,OnePaaS/drools,292388900/drools,droolsjbpm/drools,HHzzhz/drools,sutaakar/drools,droolsjbpm/drools,iambic69/drools,OnePaaS/drools,liupugong/drools,mswiderski/drools,rajashekharmunthakewill/drools,jiripetrlik/drools,manstis/drools,droolsjbpm/drools,mswiderski/drools,kedzie/drools-android,ThiagoGarciaAlves/drools,lanceleverich/drools,kedzie/drools-android,jomarko/drools,winklerm/drools,psiroky/drools,kedzie/drools-android,iambic69/drools,amckee23/drools,droolsjbpm/drools,Buble1981/MyDroolsFork,mrietveld/drools,rajashekharmunthakewill/drools,mrietveld/drools,kevinpeterson/drools,pperboires/PocDrools,HHzzhz/drools,ChallenHB/drools,ThiagoGarciaAlves/drools,jiripetrlik/drools,liupugong/drools,jomarko/drools,winklerm/drools,ThomasLau/drools,sotty/drools,Buble1981/MyDroolsFork,amckee23/drools,lanceleverich/drools,prabasn/drools,HHzzhz/drools,romartin/drools,jiripetrlik/drools,kevinpeterson/drools,TonnyFeng/drools,mrrodriguez/drools,ThiagoGarciaAlves/drools,sutaakar/drools,mrrodriguez/drools,ChallenHB/drools,reynoldsm88/drools,ChallenHB/drools,ThomasLau/drools,lanceleverich/drools,winklerm/drools,jomarko/drools,psiroky/drools,ThiagoGarciaAlves/drools,HHzzhz/drools,ThiagoGarciaAlves/drools,TonnyFeng/drools,mrietveld/drools,292388900/drools,winklerm/drools,amckee23/drools,psiroky/drools,mrietveld/drools,pperboires/PocDrools,manstis/drools,rajashekharmunthakewill/drools,rajashekharmunthakewill/drools,ngs-mtech/drools,sotty/drools,prabasn/drools,reynoldsm88/drools,vinodkiran/drools,yurloc/drools
/** * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.rule; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import org.drools.base.ClassObjectType; import org.drools.definition.KnowledgeDefinition; import org.drools.factmodel.ClassDefinition; import org.drools.facttemplates.FactTemplate; import org.drools.facttemplates.FactTemplateObjectType; import org.drools.io.Resource; import org.drools.spi.AcceptsReadAccessor; import org.drools.spi.InternalReadAccessor; import org.drools.spi.ObjectType; /** * The type declaration class stores all type's metadata * declared in source files. * * @author etirelli */ public class TypeDeclaration implements KnowledgeDefinition, Externalizable { public static final String ATTR_CLASS = "class"; public static final String ATTR_TEMPLATE = "template"; public static final String ATTR_DURATION = "duration"; public static final String ATTR_TIMESTAMP = "timestamp"; public static final String ATTR_EXPIRE = "expires"; public static final String ATTR_FIELD_POSITION = "position"; public static final String ATTR_PROP_CHANGE_SUPPORT = "propertyChangeSupport"; public static enum Role { FACT, EVENT; public static final String ID = "role"; public static Role parseRole(String role) { if ( "event".equalsIgnoreCase( role ) ) { return EVENT; } else if ( "fact".equalsIgnoreCase( role ) ) { return FACT; } return null; } } public static enum Format { POJO, TEMPLATE; public static final String ID = "format"; public static Format parseFormat(String format) { if ( "pojo".equalsIgnoreCase( format ) ) { return POJO; } else if ( "template".equalsIgnoreCase( format ) ) { return TEMPLATE; } return null; } } private String typeName; private Role role; private Format format; private String timestampAttribute; private String durationAttribute; private InternalReadAccessor durationExtractor; private InternalReadAccessor timestampExtractor; private transient Class< ? > typeClass; private String typeClassName; private FactTemplate typeTemplate; private ClassDefinition typeClassDef; private Resource resource; private boolean dynamic; private transient ObjectType objectType; private long expirationOffset = -1; public TypeDeclaration() { } public TypeDeclaration(String typeName) { this.typeName = typeName; this.role = Role.FACT; this.format = Format.POJO; this.durationAttribute = null; this.timestampAttribute = null; this.typeTemplate = null; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.typeName = (String) in.readObject(); this.role = (Role) in.readObject(); this.format = (Format) in.readObject(); this.durationAttribute = (String) in.readObject(); this.timestampAttribute = (String) in.readObject(); this.typeClassName = (String) in.readObject(); this.typeTemplate = (FactTemplate) in.readObject(); this.typeClassDef = (ClassDefinition) in.readObject(); this.durationExtractor = (InternalReadAccessor) in.readObject(); this.timestampExtractor = (InternalReadAccessor) in.readObject(); this.resource = (Resource) in.readObject(); this.expirationOffset = in.readLong(); this.dynamic = in.readBoolean(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( typeName ); out.writeObject( role ); out.writeObject( format ); out.writeObject( durationAttribute ); out.writeObject( timestampAttribute ); out.writeObject( typeClassName ); out.writeObject( typeTemplate ); out.writeObject( typeClassDef ); out.writeObject( durationExtractor ); out.writeObject( timestampExtractor ); out.writeObject( this.resource ); out.writeLong( expirationOffset ); out.writeBoolean( dynamic ); } /** * @return the type */ public String getTypeName() { return typeName; } /** * @return the category */ public Role getRole() { return role; } /** * @param role the category to set */ public void setRole(Role role) { this.role = role; } /** * @return the format */ public Format getFormat() { return format; } /** * @param format the format to set */ public void setFormat(Format format) { this.format = format; } /** * @return the timestampAttribute */ public String getTimestampAttribute() { return timestampAttribute; } /** * @param timestampAttribute the timestampAttribute to set */ public void setTimestampAttribute(String timestampAttribute) { this.timestampAttribute = timestampAttribute; } /** * @return the durationAttribute */ public String getDurationAttribute() { return durationAttribute; } /** * @param durationAttribute the durationAttribute to set */ public void setDurationAttribute(String durationAttribute) { this.durationAttribute = durationAttribute; } /** * @return the typeClass */ public Class< ? > getTypeClass() { return typeClass; } /** * @param typeClass the typeClass to set */ public void setTypeClass(Class< ? > typeClass) { this.typeClass = typeClass; if ( this.typeClassDef != null ) { this.typeClassDef.setDefinedClass( this.typeClass ); } if ( this.typeClass != null ) { this.typeClassName = this.typeClass.getName(); } } /** * @return the typeTemplate */ public FactTemplate getTypeTemplate() { return typeTemplate; } /** * @param typeTemplate the typeTemplate to set */ public void setTypeTemplate(FactTemplate typeTemplate) { this.typeTemplate = typeTemplate; } /** * Returns true if the given parameter matches this type declaration * * @param clazz * @return */ public boolean matches(Object clazz) { boolean matches = false; if ( clazz instanceof FactTemplate ) { matches = this.typeTemplate.equals( clazz ); } else { matches = this.typeClass.isAssignableFrom( (Class< ? >) clazz ); } return matches; } public boolean equals(Object obj) { if ( obj == this ) { return true; } else if ( obj instanceof TypeDeclaration ) { TypeDeclaration that = (TypeDeclaration) obj; return isObjectEqual( typeName, that.typeName ) && role == that.role && format == that.format && isObjectEqual( timestampAttribute, that.timestampAttribute ) && isObjectEqual( durationAttribute, that.durationAttribute ) && typeClass == that.typeClass && isObjectEqual( typeTemplate, that.typeTemplate ); } return false; } private static boolean isObjectEqual(Object a, Object b) { return a == b || a != null && a.equals( b ); } public InternalReadAccessor getDurationExtractor() { return durationExtractor; } public void setDurationExtractor(InternalReadAccessor durationExtractor) { this.durationExtractor = durationExtractor; } /** * @return the typeClassDef */ public ClassDefinition getTypeClassDef() { return typeClassDef; } /** * @param typeClassDef the typeClassDef to set */ public void setTypeClassDef(ClassDefinition typeClassDef) { this.typeClassDef = typeClassDef; } public InternalReadAccessor getTimestampExtractor() { return timestampExtractor; } public void setTimestampExtractor(InternalReadAccessor timestampExtractor) { this.timestampExtractor = timestampExtractor; } public class DurationAccessorSetter implements AcceptsReadAccessor, Serializable { private static final long serialVersionUID = 510l; public void setReadAccessor(InternalReadAccessor readAccessor) { setDurationExtractor( readAccessor ); } } public class TimestampAccessorSetter implements AcceptsReadAccessor, Serializable { private static final long serialVersionUID = 510l; public void setReadAccessor(InternalReadAccessor readAccessor) { setTimestampExtractor( readAccessor ); } } public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; } public ObjectType getObjectType() { if ( this.objectType == null ) { if ( this.getFormat() == Format.POJO ) { this.objectType = new ClassObjectType( this.getTypeClass() ); } else { this.objectType = new FactTemplateObjectType( this.getTypeTemplate() ); } } return this.objectType; } public long getExpirationOffset() { return this.expirationOffset; } public void setExpirationOffset(final long expirationOffset) { this.expirationOffset = expirationOffset; } public String getTypeClassName() { return typeClassName; } public void setTypeClassName(String typeClassName) { this.typeClassName = typeClassName; } public boolean isDynamic() { return dynamic; } public void setDynamic(boolean dynamic) { this.dynamic = dynamic; } }
drools-core/src/main/java/org/drools/rule/TypeDeclaration.java
/** * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.rule; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import org.drools.base.ClassObjectType; import org.drools.definition.KnowledgeDefinition; import org.drools.factmodel.ClassDefinition; import org.drools.facttemplates.FactTemplate; import org.drools.facttemplates.FactTemplateObjectType; import org.drools.io.Resource; import org.drools.spi.AcceptsReadAccessor; import org.drools.spi.InternalReadAccessor; import org.drools.spi.ObjectType; /** * The type declaration class stores all type's metadata * declared in source files. * * @author etirelli */ public class TypeDeclaration implements KnowledgeDefinition, Externalizable { public static final String ATTR_CLASS = "class"; public static final String ATTR_TEMPLATE = "template"; public static final String ATTR_DURATION = "duration"; public static final String ATTR_TIMESTAMP = "timestamp"; public static final String ATTR_EXPIRE = "expires"; public static final String ATTR_PROP_CHANGE_SUPPORT = "propertyChangeSupport"; public static enum Role { FACT, EVENT; public static final String ID = "role"; public static Role parseRole(String role) { if ( "event".equalsIgnoreCase( role ) ) { return EVENT; } else if ( "fact".equalsIgnoreCase( role ) ) { return FACT; } return null; } } public static enum Format { POJO, TEMPLATE; public static final String ID = "format"; public static Format parseFormat(String format) { if ( "pojo".equalsIgnoreCase( format ) ) { return POJO; } else if ( "template".equalsIgnoreCase( format ) ) { return TEMPLATE; } return null; } } private String typeName; private Role role; private Format format; private String timestampAttribute; private String durationAttribute; private InternalReadAccessor durationExtractor; private InternalReadAccessor timestampExtractor; private transient Class< ? > typeClass; private String typeClassName; private FactTemplate typeTemplate; private ClassDefinition typeClassDef; private Resource resource; private boolean dynamic; private transient ObjectType objectType; private long expirationOffset = -1; public TypeDeclaration() { } public TypeDeclaration(String typeName) { this.typeName = typeName; this.role = Role.FACT; this.format = Format.POJO; this.durationAttribute = null; this.timestampAttribute = null; this.typeTemplate = null; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.typeName = (String) in.readObject(); this.role = (Role) in.readObject(); this.format = (Format) in.readObject(); this.durationAttribute = (String) in.readObject(); this.timestampAttribute = (String) in.readObject(); this.typeClassName = (String) in.readObject(); this.typeTemplate = (FactTemplate) in.readObject(); this.typeClassDef = (ClassDefinition) in.readObject(); this.durationExtractor = (InternalReadAccessor) in.readObject(); this.timestampExtractor = (InternalReadAccessor) in.readObject(); this.resource = (Resource) in.readObject(); this.expirationOffset = in.readLong(); this.dynamic = in.readBoolean(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( typeName ); out.writeObject( role ); out.writeObject( format ); out.writeObject( durationAttribute ); out.writeObject( timestampAttribute ); out.writeObject( typeClassName ); out.writeObject( typeTemplate ); out.writeObject( typeClassDef ); out.writeObject( durationExtractor ); out.writeObject( timestampExtractor ); out.writeObject( this.resource ); out.writeLong( expirationOffset ); out.writeBoolean( dynamic ); } /** * @return the type */ public String getTypeName() { return typeName; } /** * @return the category */ public Role getRole() { return role; } /** * @param role the category to set */ public void setRole(Role role) { this.role = role; } /** * @return the format */ public Format getFormat() { return format; } /** * @param format the format to set */ public void setFormat(Format format) { this.format = format; } /** * @return the timestampAttribute */ public String getTimestampAttribute() { return timestampAttribute; } /** * @param timestampAttribute the timestampAttribute to set */ public void setTimestampAttribute(String timestampAttribute) { this.timestampAttribute = timestampAttribute; } /** * @return the durationAttribute */ public String getDurationAttribute() { return durationAttribute; } /** * @param durationAttribute the durationAttribute to set */ public void setDurationAttribute(String durationAttribute) { this.durationAttribute = durationAttribute; } /** * @return the typeClass */ public Class< ? > getTypeClass() { return typeClass; } /** * @param typeClass the typeClass to set */ public void setTypeClass(Class< ? > typeClass) { this.typeClass = typeClass; if ( this.typeClassDef != null ) { this.typeClassDef.setDefinedClass( this.typeClass ); } if ( this.typeClass != null ) { this.typeClassName = this.typeClass.getName(); } } /** * @return the typeTemplate */ public FactTemplate getTypeTemplate() { return typeTemplate; } /** * @param typeTemplate the typeTemplate to set */ public void setTypeTemplate(FactTemplate typeTemplate) { this.typeTemplate = typeTemplate; } /** * Returns true if the given parameter matches this type declaration * * @param clazz * @return */ public boolean matches(Object clazz) { boolean matches = false; if ( clazz instanceof FactTemplate ) { matches = this.typeTemplate.equals( clazz ); } else { matches = this.typeClass.isAssignableFrom( (Class< ? >) clazz ); } return matches; } public boolean equals(Object obj) { if ( obj == this ) { return true; } else if ( obj instanceof TypeDeclaration ) { TypeDeclaration that = (TypeDeclaration) obj; return isObjectEqual( typeName, that.typeName ) && role == that.role && format == that.format && isObjectEqual( timestampAttribute, that.timestampAttribute ) && isObjectEqual( durationAttribute, that.durationAttribute ) && typeClass == that.typeClass && isObjectEqual( typeTemplate, that.typeTemplate ); } return false; } private static boolean isObjectEqual(Object a, Object b) { return a == b || a != null && a.equals( b ); } public InternalReadAccessor getDurationExtractor() { return durationExtractor; } public void setDurationExtractor(InternalReadAccessor durationExtractor) { this.durationExtractor = durationExtractor; } /** * @return the typeClassDef */ public ClassDefinition getTypeClassDef() { return typeClassDef; } /** * @param typeClassDef the typeClassDef to set */ public void setTypeClassDef(ClassDefinition typeClassDef) { this.typeClassDef = typeClassDef; } public InternalReadAccessor getTimestampExtractor() { return timestampExtractor; } public void setTimestampExtractor(InternalReadAccessor timestampExtractor) { this.timestampExtractor = timestampExtractor; } public class DurationAccessorSetter implements AcceptsReadAccessor, Serializable { private static final long serialVersionUID = 510l; public void setReadAccessor(InternalReadAccessor readAccessor) { setDurationExtractor( readAccessor ); } } public class TimestampAccessorSetter implements AcceptsReadAccessor, Serializable { private static final long serialVersionUID = 510l; public void setReadAccessor(InternalReadAccessor readAccessor) { setTimestampExtractor( readAccessor ); } } public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; } public ObjectType getObjectType() { if ( this.objectType == null ) { if ( this.getFormat() == Format.POJO ) { this.objectType = new ClassObjectType( this.getTypeClass() ); } else { this.objectType = new FactTemplateObjectType( this.getTypeTemplate() ); } } return this.objectType; } public long getExpirationOffset() { return this.expirationOffset; } public void setExpirationOffset(final long expirationOffset) { this.expirationOffset = expirationOffset; } public String getTypeClassName() { return typeClassName; } public void setTypeClassName(String typeClassName) { this.typeClassName = typeClassName; } public boolean isDynamic() { return dynamic; } public void setDynamic(boolean dynamic) { this.dynamic = dynamic; } }
Parser fixes, related to 35927. git-svn-id: a243bed356d289ca0d1b6d299a0597bdc4ecaa09@35929 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70
drools-core/src/main/java/org/drools/rule/TypeDeclaration.java
Parser fixes, related to 35927.
<ide><path>rools-core/src/main/java/org/drools/rule/TypeDeclaration.java <ide> public static final String ATTR_DURATION = "duration"; <ide> public static final String ATTR_TIMESTAMP = "timestamp"; <ide> public static final String ATTR_EXPIRE = "expires"; <add> public static final String ATTR_FIELD_POSITION = "position"; <ide> public static final String ATTR_PROP_CHANGE_SUPPORT = "propertyChangeSupport"; <ide> <ide> public static enum Role {
Java
bsd-3-clause
19ddd8cf21fe7159b8b4decdcc148ec224bb689a
0
Polidea/android-flip3d
package pl.polidea.androidflip3d; import java.util.Arrays; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation.AnimationListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; /** * Views that can be swapped on click in 3D animation mode. * */ public class Flip3DView extends FrameLayout { private static final String TAG = Flip3DView.class.getSimpleName(); private static final int DEFAULT_ANIMATION_LENGTH = 500; private static final int DEFAULT_INTERNAL_PADDING = 0; private static final int DEFAULT_INTERNAL_MARGIN = 0; private static final int DEFAULT_FRONT_TO_BACK = RotationDirection.ROTATE_LEFT; private static final int DEFAULT_BACK_TO_FRONT = RotationDirection.ROTATE_RIGHT; private final FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); private final View.OnClickListener clickHidingListener = new View.OnClickListener() { @Override public void onClick(final View view) { Log.d(TAG, "Click ignored: " + ViewIndex.getViewType(view.getId())); } }; private AnimationListener finishFlippingListener; private final FrameLayout[] views = new FrameLayout[ViewIndex.VIEW_NUMBER]; private int internalPadding = DEFAULT_INTERNAL_PADDING; private long animationLength = DEFAULT_ANIMATION_LENGTH; private int frontToBack = DEFAULT_FRONT_TO_BACK; private int backToFront = DEFAULT_BACK_TO_FRONT; private int internalMargin = DEFAULT_INTERNAL_MARGIN; private final OnClickListener listenerDelegate = new OnClickListener() { @Override public void onClick(final View v) { Log.v(TAG, "Delegate clicked on view " + v.getId() + ", view:" + v); if (listener != null) { Log.v(TAG, "Finding the listener."); listener.onClick(v); } } }; private OnClickListener listener; /** * Sets amount of internal padding. * * @param internalPadding * internal padding in pixels */ public void setInternalPadding(final int internalPadding) { this.internalPadding = internalPadding; } /** * Sets amount of internal margin. * * @param internalMargin * internal padding in pixels */ public void setInternalMargin(final int internalMargin) { this.internalMargin = internalMargin; } /** * Sets length of animation flippingx. * * @param animationLength * length of animation in milliseconds */ public synchronized void setAnimationLength(final long animationLength) { this.animationLength = animationLength; } public Flip3DView(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); setId(-1); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Flip3DView); try { parsePaddingAttributes(a); initializeViews(); parseImageAttributes(a); parseOtherAttributes(a); } finally { a.recycle(); } } public Flip3DView(final Context context, final AttributeSet attrs) { this(context, attrs, 0); } public Flip3DView(final Context context) { super(context); setId(-1); initializeViews(); } private void parsePaddingAttributes(final TypedArray a) { internalPadding = a.getDimensionPixelSize(R.styleable.Flip3DView_internal_padding, DEFAULT_INTERNAL_PADDING); internalMargin = a.getDimensionPixelSize(R.styleable.Flip3DView_internal_margin, DEFAULT_INTERNAL_MARGIN); layoutParams.setMargins(internalMargin, internalMargin, internalMargin, internalMargin); } private void parseImageAttributes(final TypedArray a) { final Drawable front = a.getDrawable(R.styleable.Flip3DView_src_front); if (front != null) { setImageFrontDrawable(front); } final Drawable back = a.getDrawable(R.styleable.Flip3DView_src_back); if (back != null) { setImageBackDrawable(back); } } private synchronized void parseOtherAttributes(final TypedArray a) { animationLength = a.getInt(R.styleable.Flip3DView_animation_length_millis, DEFAULT_ANIMATION_LENGTH); frontToBack = a.getInt(R.styleable.Flip3DView_front_to_back_flip_direction, DEFAULT_FRONT_TO_BACK); backToFront = a.getInt(R.styleable.Flip3DView_back_to_front_flip_direction, DEFAULT_BACK_TO_FRONT); } /** * Sets rotation mode for front to back change. * * <pre> * Accepted values are: * 0 - LEFT * 1 - RIGHT * </pre> * * @param direction * rotation direction */ public synchronized void setFrontToBack(final int direction) { this.frontToBack = direction; } /** * Sets rotation mode for back to front change. * * <pre> * Accepted values are: * 0 - LEFT * 1 - RIGHT * </pre> * * @param direction * rotation direction */ public synchronized void setBackToFront(final int direction) { this.backToFront = direction; } /** * Sets layout parameters of the image view depending on the type of the * Drawable. * * @param view * the image view */ private void setViewParameters(final View view) { view.setLayoutParams(layoutParams); } /** * Sets layout parameters of the image view depending on the type of the * Drawable. * * @param imageView * the image view * @param drawable * drawable to set */ private void setImageParameters(final ImageView imageView, final Drawable drawable) { imageView.setImageDrawable(drawable); } /** * Sets view to the given side. * * @param viewSide * side of the view * @param view * view to set */ private void setView(final int viewSide, final FrameLayout view) { if (this.views[viewSide] != null) { this.removeView(this.views[viewSide]); } this.views[viewSide] = view; view.setId(viewSide); setViewParameters(view); this.addView(view); } /** * Sets front view on the control. * * @param viewFront * front view */ public final void setViewFront(final View viewFront) { setInternalView(ViewIndex.FRONT_VIEW, viewFront); } /** * Sets back view on the control. * * @param viewBack * back view */ public final void setViewBack(final View viewBack) { setInternalView(ViewIndex.BACK_VIEW, viewBack); } private void setInternalView(final int viewSide, final View view) { final FrameLayout frame = (FrameLayout) inflate(getContext(), R.layout.view_layout_with_padding, null); frame.setPadding(internalPadding, internalPadding, internalPadding, internalPadding); frame.addView(view); setView(viewSide, frame); } private void setImageDrawable(final int viewSide, final Drawable drawable) { final FrameLayout frame = (FrameLayout) inflate(getContext(), R.layout.image_layout_with_padding, null); frame.setPadding(internalPadding, internalPadding, internalPadding, internalPadding); final ImageView imageView = (ImageView) frame.findViewById(R.id.padded_view); imageView.setScaleType(ScaleType.FIT_CENTER); setImageParameters(imageView, drawable); setView(viewSide, frame); } /** * Sets image drawable for front. * * @param drawable * drawable for front. */ public final void setImageFrontDrawable(final Drawable drawable) { setImageDrawable(ViewIndex.FRONT_VIEW, drawable); } /** * Sets image drawable for back. * * @param drawable * drawable for back. */ public final void setImageBackDrawable(final Drawable drawable) { setImageDrawable(ViewIndex.BACK_VIEW, drawable); } /** * Sets image drawable for foreground (not add it to the main view). * * @param drawable * drawable for foreground. */ private void setImageForegroundDrawable(final Drawable drawable) { setImageDrawable(ViewIndex.FOREGROUND_VIEW, drawable); } private void initializeViews() { setImageFrontDrawable(new ColorDrawable(Color.BLUE)); setImageBackDrawable(new ColorDrawable(Color.RED)); setImageForegroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } protected synchronized void initializeViewState(final int currentViewIndex) { views[ViewIndex.FOREGROUND_VIEW].setVisibility(View.INVISIBLE); setViewClickability(ViewIndex.FOREGROUND_VIEW, false); views[ViewIndex.BACK_VIEW].setVisibility(currentViewIndex == ViewIndex.BACK_VIEW ? View.VISIBLE : View.INVISIBLE); setViewClickability(ViewIndex.BACK_VIEW, currentViewIndex == ViewIndex.BACK_VIEW); views[ViewIndex.FRONT_VIEW].setVisibility(currentViewIndex == ViewIndex.FRONT_VIEW ? View.VISIBLE : View.INVISIBLE); setViewClickability(ViewIndex.FRONT_VIEW, currentViewIndex == ViewIndex.FRONT_VIEW); } public void setViewClickability(final int viewIndex, final boolean enable) { Log.v(TAG, "Setting view clickability for view " + getId() + " " + ViewIndex.getViewType(viewIndex) + " to " + enable); final View view = views[viewIndex]; view.setClickable(true); if (enable) { if (viewIndex == ViewIndex.FOREGROUND_VIEW) { // always ignore clicks on foreground view view.setOnClickListener(clickHidingListener); } else { view.setOnClickListener(listenerDelegate); } view.bringToFront(); view.requestFocus(); } else { view.setOnClickListener(clickHidingListener); } } public void requestViewIndexFocus(final int viewIndex) { views[viewIndex].requestFocus(); } /** * Starts rotation according to direction. * * @param currentViewIndex * starting index of view which to animate */ public synchronized void startRotation(final int currentViewIndex) { Log.v(TAG, "Starting rotation from " + ViewIndex.getViewType(currentViewIndex)); final int direction = currentViewIndex == ViewIndex.FRONT_VIEW ? frontToBack : backToFront; setFlipping(true); final float centerX = getWidth() / 2.0f; final float centerY = getHeight() / 2.0f; final Flip3DAnimation rotation = new Flip3DAnimation(0, RotationDirection.getMultiplier(direction) * 90, centerX, centerY); rotation.setDuration(animationLength); rotation.setFillAfter(true); rotation.setInterpolator(new AccelerateInterpolator()); rotation.setAnimationListener(new GetToTheMiddleOfFlipping(currentViewIndex, views, animationLength, direction, finishFlippingListener)); views[currentViewIndex].startAnimation(rotation); Log.v(TAG, " View: " + views[currentViewIndex] + ",Parent: " + views[currentViewIndex].getParent() + " View grandParent " + views[currentViewIndex].getParent().getParent()); Log.v(TAG, "Animation started in " + currentViewIndex + " on view " + views[currentViewIndex]); } public void setFlipping(final boolean flipping) { final View foregroundView = views[ViewIndex.FOREGROUND_VIEW]; if (flipping) { // make sure the view is taking over all the clicks setViewClickability(ViewIndex.FOREGROUND_VIEW, true); foregroundView.setVisibility(VISIBLE); foregroundView.bringToFront(); } else { setViewClickability(ViewIndex.FOREGROUND_VIEW, false); foregroundView.setVisibility(GONE); } } @Override public void setOnClickListener(final OnClickListener l) { Log.v(TAG, "Setting the listener to " + l + " on view " + getId()); super.setOnClickListener(l); this.listener = l; } /** * Listener to listen for flipping finished. * * @param finishFlippingListener * listener to listen to finish flipping */ public void setFinishFlippingListener(final AnimationListener finishFlippingListener) { this.finishFlippingListener = finishFlippingListener; } @Override public String toString() { return "Flip3DView [layoutParams=" + layoutParams + ", clickHidingListener=" + clickHidingListener + ", finishFlippingListener=" + finishFlippingListener + ", views=" + Arrays.toString(views) + ", internalPadding=" + internalPadding + ", animationLength=" + animationLength + ", frontToBack=" + frontToBack + ", backToFront=" + backToFront + ", listenerDelegate=" + listenerDelegate + ", listener=" + listener + "]"; } /** * Cancels all animations running for the view. */ public void clearAllAnimations() { for (int i = 0; i < ViewIndex.VIEW_NUMBER; i++) { if (views[i] != null) { views[i].clearAnimation(); } } } /** * Returns view of a given index; * * @param viewIndex * index of a view. * @return the view. */ public FrameLayout getView(final int viewIndex) { return views[viewIndex]; } }
src/pl/polidea/androidflip3d/Flip3DView.java
package pl.polidea.androidflip3d; import java.util.Arrays; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation.AnimationListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; /** * Views that can be swapped on click in 3D animation mode. * */ public class Flip3DView extends FrameLayout { private static final String TAG = Flip3DView.class.getSimpleName(); private static final int DEFAULT_ANIMATION_LENGTH = 500; private static final int DEFAULT_INTERNAL_PADDING = 0; private static final int DEFAULT_INTERNAL_MARGIN = 0; private static final int DEFAULT_FRONT_TO_BACK = RotationDirection.ROTATE_LEFT; private static final int DEFAULT_BACK_TO_FRONT = RotationDirection.ROTATE_RIGHT; private final FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); private final View.OnClickListener clickHidingListener = new View.OnClickListener() { @Override public void onClick(final View view) { Log.d(TAG, "Click ignored: " + ViewIndex.getViewType(view.getId())); } }; private AnimationListener finishFlippingListener; private final View[] views = new View[ViewIndex.VIEW_NUMBER]; private int internalPadding = DEFAULT_INTERNAL_PADDING; private long animationLength = DEFAULT_ANIMATION_LENGTH; private int frontToBack = DEFAULT_FRONT_TO_BACK; private int backToFront = DEFAULT_BACK_TO_FRONT; private int internalMargin = DEFAULT_INTERNAL_MARGIN; private final OnClickListener listenerDelegate = new OnClickListener() { @Override public void onClick(final View v) { Log.v(TAG, "Delegate clicked on view " + v.getId() + ", view:" + v); if (listener != null) { Log.v(TAG, "Finding the listener."); listener.onClick(v); } } }; private OnClickListener listener; /** * Sets amount of internal padding. * * @param internalPadding * internal padding in pixels */ public void setInternalPadding(final int internalPadding) { this.internalPadding = internalPadding; } /** * Sets amount of internal margin. * * @param internalMargin * internal padding in pixels */ public void setInternalMargin(final int internalMargin) { this.internalMargin = internalMargin; } /** * Sets length of animation flippingx. * * @param animationLength * length of animation in milliseconds */ public synchronized void setAnimationLength(final long animationLength) { this.animationLength = animationLength; } public Flip3DView(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); setId(-1); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Flip3DView); try { parsePaddingAttributes(a); initializeViews(); parseImageAttributes(a); parseOtherAttributes(a); } finally { a.recycle(); } } public Flip3DView(final Context context, final AttributeSet attrs) { this(context, attrs, 0); } public Flip3DView(final Context context) { super(context); setId(-1); initializeViews(); } private void parsePaddingAttributes(final TypedArray a) { internalPadding = a.getDimensionPixelSize( R.styleable.Flip3DView_internal_padding, DEFAULT_INTERNAL_PADDING); internalMargin = a .getDimensionPixelSize(R.styleable.Flip3DView_internal_margin, DEFAULT_INTERNAL_MARGIN); layoutParams.setMargins(internalMargin, internalMargin, internalMargin, internalMargin); } private void parseImageAttributes(final TypedArray a) { final Drawable front = a.getDrawable(R.styleable.Flip3DView_src_front); if (front != null) { setImageFrontDrawable(front); } final Drawable back = a.getDrawable(R.styleable.Flip3DView_src_back); if (back != null) { setImageBackDrawable(back); } } private synchronized void parseOtherAttributes(final TypedArray a) { animationLength = a.getInt( R.styleable.Flip3DView_animation_length_millis, DEFAULT_ANIMATION_LENGTH); frontToBack = a.getInt( R.styleable.Flip3DView_front_to_back_flip_direction, DEFAULT_FRONT_TO_BACK); backToFront = a.getInt( R.styleable.Flip3DView_back_to_front_flip_direction, DEFAULT_BACK_TO_FRONT); } /** * Sets rotation mode for front to back change. * * <pre> * Accepted values are: * 0 - LEFT * 1 - RIGHT * </pre> * * @param direction * rotation direction */ public synchronized void setFrontToBack(final int direction) { this.frontToBack = direction; } /** * Sets rotation mode for back to front change. * * <pre> * Accepted values are: * 0 - LEFT * 1 - RIGHT * </pre> * * @param direction * rotation direction */ public synchronized void setBackToFront(final int direction) { this.backToFront = direction; } /** * Sets layout parameters of the image view depending on the type of the * Drawable. * * @param view * the image view */ private void setViewParameters(final View view) { view.setLayoutParams(layoutParams); } /** * Sets layout parameters of the image view depending on the type of the * Drawable. * * @param imageView * the image view * @param drawable * drawable to set */ private void setImageParameters(final ImageView imageView, final Drawable drawable) { imageView.setImageDrawable(drawable); } /** * Sets view to the given side. * * @param viewSide * side of the view * @param view * view to set */ private void setView(final int viewSide, final FrameLayout view) { if (this.views[viewSide] != null) { this.removeView(this.views[viewSide]); } this.views[viewSide] = view; view.setId(viewSide); setViewParameters(view); this.addView(view); } /** * Sets front view on the control. * * @param viewFront * front view */ public final void setViewFront(final View viewFront) { setInternalView(ViewIndex.FRONT_VIEW, viewFront); } /** * Sets back view on the control. * * @param viewBack * back view */ public final void setViewBack(final View viewBack) { setInternalView(ViewIndex.BACK_VIEW, viewBack); } private void setInternalView(final int viewSide, final View view) { final FrameLayout frame = (FrameLayout) inflate(getContext(), R.layout.view_layout_with_padding, null); frame.setPadding(internalPadding, internalPadding, internalPadding, internalPadding); frame.addView(view); setView(viewSide, frame); } private void setImageDrawable(final int viewSide, final Drawable drawable) { final FrameLayout frame = (FrameLayout) inflate(getContext(), R.layout.image_layout_with_padding, null); frame.setPadding(internalPadding, internalPadding, internalPadding, internalPadding); final ImageView imageView = (ImageView) frame .findViewById(R.id.padded_view); imageView.setScaleType(ScaleType.FIT_CENTER); setImageParameters(imageView, drawable); setView(viewSide, frame); } /** * Sets image drawable for front. * * @param drawable * drawable for front. */ public final void setImageFrontDrawable(final Drawable drawable) { setImageDrawable(ViewIndex.FRONT_VIEW, drawable); } /** * Sets image drawable for back. * * @param drawable * drawable for back. */ public final void setImageBackDrawable(final Drawable drawable) { setImageDrawable(ViewIndex.BACK_VIEW, drawable); } /** * Sets image drawable for foreground (not add it to the main view). * * @param drawable * drawable for foreground. */ private void setImageForegroundDrawable(final Drawable drawable) { setImageDrawable(ViewIndex.FOREGROUND_VIEW, drawable); } private void initializeViews() { setImageFrontDrawable(new ColorDrawable(Color.BLUE)); setImageBackDrawable(new ColorDrawable(Color.RED)); setImageForegroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } protected synchronized void initializeViewState(final int currentViewIndex) { views[ViewIndex.FOREGROUND_VIEW].setVisibility(View.INVISIBLE); setViewClickability(ViewIndex.FOREGROUND_VIEW, false); views[ViewIndex.BACK_VIEW] .setVisibility(currentViewIndex == ViewIndex.BACK_VIEW ? View.VISIBLE : View.INVISIBLE); setViewClickability(ViewIndex.BACK_VIEW, currentViewIndex == ViewIndex.BACK_VIEW); views[ViewIndex.FRONT_VIEW] .setVisibility(currentViewIndex == ViewIndex.FRONT_VIEW ? View.VISIBLE : View.INVISIBLE); setViewClickability(ViewIndex.FRONT_VIEW, currentViewIndex == ViewIndex.FRONT_VIEW); } public void setViewClickability(final int viewIndex, final boolean enable) { Log.v(TAG, "Setting view clickability for view " + getId() + " " + ViewIndex.getViewType(viewIndex) + " to " + enable); final View view = views[viewIndex]; view.setClickable(true); if (enable) { if (viewIndex == ViewIndex.FOREGROUND_VIEW) { // always ignore clicks on foreground view view.setOnClickListener(clickHidingListener); } else { view.setOnClickListener(listenerDelegate); } view.bringToFront(); view.requestFocus(); } else { view.setOnClickListener(clickHidingListener); } } public void requestViewIndexFocus(final int viewIndex) { views[viewIndex].requestFocus(); } /** * Starts rotation according to direction. * * @param currentViewIndex * starting index of view which to animate */ public synchronized void startRotation(final int currentViewIndex) { Log.v(TAG, "Starting rotation from " + ViewIndex.getViewType(currentViewIndex)); final int direction = currentViewIndex == ViewIndex.FRONT_VIEW ? frontToBack : backToFront; setFlipping(true); final float centerX = getWidth() / 2.0f; final float centerY = getHeight() / 2.0f; final Flip3DAnimation rotation = new Flip3DAnimation(0, RotationDirection.getMultiplier(direction) * 90, centerX, centerY); rotation.setDuration(animationLength); rotation.setFillAfter(true); rotation.setInterpolator(new AccelerateInterpolator()); rotation.setAnimationListener(new GetToTheMiddleOfFlipping( currentViewIndex, views, animationLength, direction, finishFlippingListener)); views[currentViewIndex].startAnimation(rotation); Log.v(TAG, " View: " + views[currentViewIndex] + ",Parent: " + views[currentViewIndex].getParent() + " View grandParent " + views[currentViewIndex].getParent().getParent()); Log.v(TAG, "Animation started in " + currentViewIndex + " on view " + views[currentViewIndex]); } public void setFlipping(final boolean flipping) { final View foregroundView = views[ViewIndex.FOREGROUND_VIEW]; if (flipping) { // make sure the view is taking over all the clicks setViewClickability(ViewIndex.FOREGROUND_VIEW, true); foregroundView.setVisibility(VISIBLE); foregroundView.bringToFront(); } else { setViewClickability(ViewIndex.FOREGROUND_VIEW, false); foregroundView.setVisibility(GONE); } } @Override public void setOnClickListener(final OnClickListener l) { Log.v(TAG, "Setting the listener to " + l + " on view " + getId()); super.setOnClickListener(l); this.listener = l; } /** * Listener to listen for flipping finished. * * @param finishFlippingListener * listener to listen to finish flipping */ public void setFinishFlippingListener( final AnimationListener finishFlippingListener) { this.finishFlippingListener = finishFlippingListener; } @Override public String toString() { return "Flip3DView [layoutParams=" + layoutParams + ", clickHidingListener=" + clickHidingListener + ", finishFlippingListener=" + finishFlippingListener + ", views=" + Arrays.toString(views) + ", internalPadding=" + internalPadding + ", animationLength=" + animationLength + ", frontToBack=" + frontToBack + ", backToFront=" + backToFront + ", listenerDelegate=" + listenerDelegate + ", listener=" + listener + "]"; } /** * Cancels all animations running for the view. */ public void clearAllAnimations() { for (int i = 0; i < ViewIndex.VIEW_NUMBER; i++) { if (views[i] != null) { views[i].clearAnimation(); } } } }
Added possibility of retrieving views.
src/pl/polidea/androidflip3d/Flip3DView.java
Added possibility of retrieving views.
<ide><path>rc/pl/polidea/androidflip3d/Flip3DView.java <ide> private static final int DEFAULT_FRONT_TO_BACK = RotationDirection.ROTATE_LEFT; <ide> private static final int DEFAULT_BACK_TO_FRONT = RotationDirection.ROTATE_RIGHT; <ide> <del> private final FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( <del> LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); <add> private final FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, <add> LayoutParams.FILL_PARENT); <ide> <ide> private final View.OnClickListener clickHidingListener = new View.OnClickListener() { <ide> @Override <ide> <ide> private AnimationListener finishFlippingListener; <ide> <del> private final View[] views = new View[ViewIndex.VIEW_NUMBER]; <add> private final FrameLayout[] views = new FrameLayout[ViewIndex.VIEW_NUMBER]; <ide> private int internalPadding = DEFAULT_INTERNAL_PADDING; <ide> private long animationLength = DEFAULT_ANIMATION_LENGTH; <ide> private int frontToBack = DEFAULT_FRONT_TO_BACK; <ide> this.animationLength = animationLength; <ide> } <ide> <del> public Flip3DView(final Context context, final AttributeSet attrs, <del> final int defStyle) { <add> public Flip3DView(final Context context, final AttributeSet attrs, final int defStyle) { <ide> super(context, attrs, defStyle); <ide> setId(-1); <del> final TypedArray a = context.obtainStyledAttributes(attrs, <del> R.styleable.Flip3DView); <add> final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Flip3DView); <ide> try { <ide> parsePaddingAttributes(a); <ide> initializeViews(); <ide> } <ide> <ide> private void parsePaddingAttributes(final TypedArray a) { <del> internalPadding = a.getDimensionPixelSize( <del> R.styleable.Flip3DView_internal_padding, <del> DEFAULT_INTERNAL_PADDING); <del> internalMargin = a <del> .getDimensionPixelSize(R.styleable.Flip3DView_internal_margin, <del> DEFAULT_INTERNAL_MARGIN); <del> layoutParams.setMargins(internalMargin, internalMargin, internalMargin, <del> internalMargin); <add> internalPadding = a.getDimensionPixelSize(R.styleable.Flip3DView_internal_padding, DEFAULT_INTERNAL_PADDING); <add> internalMargin = a.getDimensionPixelSize(R.styleable.Flip3DView_internal_margin, DEFAULT_INTERNAL_MARGIN); <add> layoutParams.setMargins(internalMargin, internalMargin, internalMargin, internalMargin); <ide> } <ide> <ide> private void parseImageAttributes(final TypedArray a) { <ide> } <ide> <ide> private synchronized void parseOtherAttributes(final TypedArray a) { <del> animationLength = a.getInt( <del> R.styleable.Flip3DView_animation_length_millis, <del> DEFAULT_ANIMATION_LENGTH); <del> frontToBack = a.getInt( <del> R.styleable.Flip3DView_front_to_back_flip_direction, <del> DEFAULT_FRONT_TO_BACK); <del> backToFront = a.getInt( <del> R.styleable.Flip3DView_back_to_front_flip_direction, <del> DEFAULT_BACK_TO_FRONT); <add> animationLength = a.getInt(R.styleable.Flip3DView_animation_length_millis, DEFAULT_ANIMATION_LENGTH); <add> frontToBack = a.getInt(R.styleable.Flip3DView_front_to_back_flip_direction, DEFAULT_FRONT_TO_BACK); <add> backToFront = a.getInt(R.styleable.Flip3DView_back_to_front_flip_direction, DEFAULT_BACK_TO_FRONT); <ide> } <ide> <ide> /** <ide> * @param drawable <ide> * drawable to set <ide> */ <del> private void setImageParameters(final ImageView imageView, <del> final Drawable drawable) { <add> private void setImageParameters(final ImageView imageView, final Drawable drawable) { <ide> imageView.setImageDrawable(drawable); <ide> } <ide> <ide> } <ide> <ide> private void setInternalView(final int viewSide, final View view) { <del> final FrameLayout frame = (FrameLayout) inflate(getContext(), <del> R.layout.view_layout_with_padding, null); <del> frame.setPadding(internalPadding, internalPadding, internalPadding, <del> internalPadding); <add> final FrameLayout frame = (FrameLayout) inflate(getContext(), R.layout.view_layout_with_padding, null); <add> frame.setPadding(internalPadding, internalPadding, internalPadding, internalPadding); <ide> frame.addView(view); <ide> setView(viewSide, frame); <ide> } <ide> <ide> private void setImageDrawable(final int viewSide, final Drawable drawable) { <del> final FrameLayout frame = (FrameLayout) inflate(getContext(), <del> R.layout.image_layout_with_padding, null); <del> frame.setPadding(internalPadding, internalPadding, internalPadding, <del> internalPadding); <del> final ImageView imageView = (ImageView) frame <del> .findViewById(R.id.padded_view); <add> final FrameLayout frame = (FrameLayout) inflate(getContext(), R.layout.image_layout_with_padding, null); <add> frame.setPadding(internalPadding, internalPadding, internalPadding, internalPadding); <add> final ImageView imageView = (ImageView) frame.findViewById(R.id.padded_view); <ide> imageView.setScaleType(ScaleType.FIT_CENTER); <ide> setImageParameters(imageView, drawable); <ide> setView(viewSide, frame); <ide> protected synchronized void initializeViewState(final int currentViewIndex) { <ide> views[ViewIndex.FOREGROUND_VIEW].setVisibility(View.INVISIBLE); <ide> setViewClickability(ViewIndex.FOREGROUND_VIEW, false); <del> views[ViewIndex.BACK_VIEW] <del> .setVisibility(currentViewIndex == ViewIndex.BACK_VIEW ? View.VISIBLE <del> : View.INVISIBLE); <del> setViewClickability(ViewIndex.BACK_VIEW, <del> currentViewIndex == ViewIndex.BACK_VIEW); <del> views[ViewIndex.FRONT_VIEW] <del> .setVisibility(currentViewIndex == ViewIndex.FRONT_VIEW ? View.VISIBLE <del> : View.INVISIBLE); <del> setViewClickability(ViewIndex.FRONT_VIEW, <del> currentViewIndex == ViewIndex.FRONT_VIEW); <add> views[ViewIndex.BACK_VIEW].setVisibility(currentViewIndex == ViewIndex.BACK_VIEW ? View.VISIBLE <add> : View.INVISIBLE); <add> setViewClickability(ViewIndex.BACK_VIEW, currentViewIndex == ViewIndex.BACK_VIEW); <add> views[ViewIndex.FRONT_VIEW].setVisibility(currentViewIndex == ViewIndex.FRONT_VIEW ? View.VISIBLE <add> : View.INVISIBLE); <add> setViewClickability(ViewIndex.FRONT_VIEW, currentViewIndex == ViewIndex.FRONT_VIEW); <ide> <ide> } <ide> <ide> public void setViewClickability(final int viewIndex, final boolean enable) { <del> Log.v(TAG, "Setting view clickability for view " + getId() + " " <del> + ViewIndex.getViewType(viewIndex) + " to " + enable); <add> Log.v(TAG, "Setting view clickability for view " + getId() + " " + ViewIndex.getViewType(viewIndex) + " to " <add> + enable); <ide> final View view = views[viewIndex]; <ide> view.setClickable(true); <ide> if (enable) { <ide> * starting index of view which to animate <ide> */ <ide> public synchronized void startRotation(final int currentViewIndex) { <del> Log.v(TAG, <del> "Starting rotation from " <del> + ViewIndex.getViewType(currentViewIndex)); <del> final int direction = currentViewIndex == ViewIndex.FRONT_VIEW ? frontToBack <del> : backToFront; <add> Log.v(TAG, "Starting rotation from " + ViewIndex.getViewType(currentViewIndex)); <add> final int direction = currentViewIndex == ViewIndex.FRONT_VIEW ? frontToBack : backToFront; <ide> setFlipping(true); <ide> final float centerX = getWidth() / 2.0f; <ide> final float centerY = getHeight() / 2.0f; <del> final Flip3DAnimation rotation = new Flip3DAnimation(0, <del> RotationDirection.getMultiplier(direction) * 90, centerX, <del> centerY); <add> final Flip3DAnimation rotation = new Flip3DAnimation(0, RotationDirection.getMultiplier(direction) * 90, <add> centerX, centerY); <ide> rotation.setDuration(animationLength); <ide> rotation.setFillAfter(true); <ide> rotation.setInterpolator(new AccelerateInterpolator()); <del> rotation.setAnimationListener(new GetToTheMiddleOfFlipping( <del> currentViewIndex, views, animationLength, direction, <add> rotation.setAnimationListener(new GetToTheMiddleOfFlipping(currentViewIndex, views, animationLength, direction, <ide> finishFlippingListener)); <ide> views[currentViewIndex].startAnimation(rotation); <del> Log.v(TAG, " View: " + views[currentViewIndex] + ",Parent: " <del> + views[currentViewIndex].getParent() + " View grandParent " <del> + views[currentViewIndex].getParent().getParent()); <del> Log.v(TAG, "Animation started in " + currentViewIndex + " on view " <del> + views[currentViewIndex]); <add> Log.v(TAG, " View: " + views[currentViewIndex] + ",Parent: " + views[currentViewIndex].getParent() <add> + " View grandParent " + views[currentViewIndex].getParent().getParent()); <add> Log.v(TAG, "Animation started in " + currentViewIndex + " on view " + views[currentViewIndex]); <ide> } <ide> <ide> public void setFlipping(final boolean flipping) { <ide> * @param finishFlippingListener <ide> * listener to listen to finish flipping <ide> */ <del> public void setFinishFlippingListener( <del> final AnimationListener finishFlippingListener) { <add> public void setFinishFlippingListener(final AnimationListener finishFlippingListener) { <ide> this.finishFlippingListener = finishFlippingListener; <ide> } <ide> <ide> @Override <ide> public String toString() { <del> return "Flip3DView [layoutParams=" + layoutParams <del> + ", clickHidingListener=" + clickHidingListener <del> + ", finishFlippingListener=" + finishFlippingListener <del> + ", views=" + Arrays.toString(views) + ", internalPadding=" <del> + internalPadding + ", animationLength=" + animationLength <del> + ", frontToBack=" + frontToBack + ", backToFront=" <del> + backToFront + ", listenerDelegate=" + listenerDelegate <add> return "Flip3DView [layoutParams=" + layoutParams + ", clickHidingListener=" + clickHidingListener <add> + ", finishFlippingListener=" + finishFlippingListener + ", views=" + Arrays.toString(views) <add> + ", internalPadding=" + internalPadding + ", animationLength=" + animationLength + ", frontToBack=" <add> + frontToBack + ", backToFront=" + backToFront + ", listenerDelegate=" + listenerDelegate <ide> + ", listener=" + listener + "]"; <ide> } <ide> <ide> } <ide> } <ide> } <add> <add> /** <add> * Returns view of a given index; <add> * <add> * @param viewIndex <add> * index of a view. <add> * @return the view. <add> */ <add> public FrameLayout getView(final int viewIndex) { <add> return views[viewIndex]; <add> } <ide> }
Java
apache-2.0
0f7fc4c148ac3419d9c76736badf69ff1d27e569
0
Shockah/Godwit
package pl.shockah.godwit; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import lombok.Getter; import pl.shockah.godwit.fx.Animatable; import pl.shockah.godwit.fx.Animatables; import pl.shockah.godwit.geom.IVec2; import pl.shockah.godwit.geom.MutableVec2; import pl.shockah.godwit.geom.Vec2; import pl.shockah.godwit.gl.Gfx; import pl.shockah.godwit.gl.Renderable; import pl.shockah.unicorn.SafeList; public class Entity implements Renderable, Animatable<Entity> { @Nonnull public final SafeList<Entity> children = new SafeList<>(new ArrayList<>()); @Nonnull public MutableVec2 position = new MutableVec2(); @Getter private Entity parent; @Getter private float depth = 0f; @Nullable private Animatables.Properties<Entity> animatableProperties; public final void setDepth(float depth) { Entity parent = this.parent; if (parent != null) parent.children.remove(this); this.depth = depth; if (parent != null) parent.children.add(this); } public final boolean hasParent() { return parent != null; } public final boolean hasRenderGroup() { Entity entity = this; while (entity != null) { if (entity instanceof RenderGroup && entity != this) return true; entity = entity.parent; } return false; } @Nonnull public final RenderGroup getRenderGroup() { Entity entity = this; while (entity != null) { if (entity instanceof RenderGroup && entity != this) return (RenderGroup)entity; entity = entity.parent; } throw new IllegalStateException(String.format("Entity %s doesn't have a RenderGroup.", this)); } public final boolean hasCameraGroup() { Entity entity = this; while (entity != null) { if (entity instanceof RenderGroup && entity != this) return true; entity = entity.parent; } return false; } @Nonnull public final CameraGroup getCameraGroup() { Entity entity = this; while (entity != null) { if (entity instanceof CameraGroup && entity != this) return (CameraGroup)entity; entity = entity.parent; } throw new IllegalStateException(String.format("Entity %s doesn't have a CameraGroup.", this)); } public void addChild(@Nonnull Entity entity) { if (entity.parent != null) throw new IllegalStateException(String.format("Entity %s already has a parent %s.", entity, entity.parent)); entity.parent = this; children.add(entity); callDownAddedToHierarchy(this, entity); callAddedToHierarchy(entity); entity.onAddedToParent(); } public void removeFromParent() { if (parent == null) throw new IllegalStateException(String.format("Entity %s doesn't have a parent.", this)); onRemovedFromParent(); callRemovedFromHierarchy(this); callDownRemovedFromHierarchy(parent, this); parent.children.remove(this); parent = null; } private static void callAddedToHierarchy(@Nonnull Entity entity) { entity.onAddedToHierarchy(); for (Entity child : entity.children.get()) { callAddedToHierarchy(child); } } private static void callDownAddedToHierarchy(@Nonnull Entity context, @Nonnull Entity entity) { context.onAddedToHierarchy(entity); Entity parent = context.getParent(); if (parent != null) callDownAddedToHierarchy(parent, entity); } private static void callRemovedFromHierarchy(@Nonnull Entity entity) { for (Entity child : entity.children.get()) { callRemovedFromHierarchy(child); } entity.onRemovedFromHierarchy(); } private static void callDownRemovedFromHierarchy(@Nonnull Entity context, @Nonnull Entity entity) { context.onRemovedFromHierarchy(entity); Entity parent = context.getParent(); if (parent != null) callDownRemovedFromHierarchy(parent, entity); } public void update() { children.update(); updateSelf(); updateFx(); updateChildren(); } public void updateSelf() { } public void updateChildren() { for (Entity entity : children.get()) { entity.update(); } } @Override public void render(@Nonnull Gfx gfx, @Nonnull IVec2 v) { } @Override public final void render(@Nonnull Gfx gfx, float x, float y) { render(gfx, new Vec2(x, y)); } @Override public final void render(@Nonnull Gfx gfx) { render(gfx, Vec2.zero); } public void onAddedToParent() { children.update(); } public void onRemovedFromParent() { } private void handleAddToRenderGroupHierarchy() { try { if (getClass() != Entity.class) { RenderGroup renderGroup = getRenderGroup(); if (!renderGroup.renderOrder.contains(this)) getRenderGroup().renderOrder.add(this); } for (Entity entity : children.get()) { entity.handleAddToRenderGroupHierarchy(); } for (Entity entity : children.getWaitingToAdd()) { entity.handleAddToRenderGroupHierarchy(); } } catch (IllegalStateException ignored) { } } private void handleRemoveFromRenderGroupHierarchy() { try { if (getClass() != Entity.class) getRenderGroup().renderOrder.remove(this); for (Entity entity : children.get()) { entity.handleRemoveFromRenderGroupHierarchy(); } for (Entity entity : children.getWaitingToAdd()) { entity.handleRemoveFromRenderGroupHierarchy(); } } catch (IllegalStateException ignored) { } } public void onAddedToHierarchy() { handleAddToRenderGroupHierarchy(); } public void onRemovedFromHierarchy() { handleRemoveFromRenderGroupHierarchy(); } public void onAddedToHierarchy(@Nonnull Entity indirectChild) { } public void onRemovedFromHierarchy(@Nonnull Entity indirectChild) { } @Nonnull public final Vec2 getAbsolutePoint() { return getAbsolutePoint(Vec2.zero); } @Nonnull public final Vec2 getAbsolutePoint(@Nonnull IVec2 point) { Vec2 currentPoint = point.asImmutable(); Entity entity = this; while (entity != null) { currentPoint = entity.getTranslatedPoint(currentPoint); entity = entity.parent; } return currentPoint; } @Nonnull public final MutableVec2 getPointInEntity(@Nonnull Entity entity) { MutableVec2 mutable = new MutableVec2(); calculatePointInEntity(entity, mutable); return mutable; } @Nonnull public final MutableVec2 getPointInEntity(@Nonnull Entity entity, @Nonnull IVec2 point) { MutableVec2 mutable = point.mutableCopy(); calculatePointInEntity(entity, mutable); return mutable; } public final void calculatePointInEntity(@Nonnull Entity entity, @Nonnull MutableVec2 point) { Entity current = this; while (current != null) { if (current == entity) return; current.calculateTranslatedPoint(point); current = current.parent; } throw new IllegalStateException(String.format("Entity %s is not in the tree of %s.", entity, this)); } @Nonnull public final Entity[] getParentTree() { List<Entity> tree = new LinkedList<>(); Entity entity = this; while (entity != null) { if (tree.isEmpty()) tree.add(entity); else tree.add(0, entity); entity = entity.parent; } return tree.toArray(new Entity[tree.size()]); } @Nullable public static Entity getCommonParent(@Nonnull Entity[] parentTree1, @Nonnull Entity[] parentTree2, @Nonnull Entity entity1, @Nonnull Entity entity2) { if (parentTree1[0] != parentTree2[0]) return null; for (int i = 1; i < Math.min(parentTree1.length, parentTree2.length); i++) { if (parentTree1[i] != parentTree2[i]) return parentTree1[i - 1]; } return parentTree1[Math.min(parentTree1.length, parentTree2.length) - 1]; } @Nullable public final Entity getCommonParent(@Nonnull Entity entity) { return getCommonParent(getParentTree(), entity.getParentTree(), this, entity); } protected void calculateTranslatedPoint(@Nonnull MutableVec2 point) { point.x += position.x; point.y += position.y; } @Nonnull protected Vec2 getTranslatedPoint(@Nonnull IVec2 point) { return point.add(position); } @SuppressWarnings("unchecked") @Override @Nonnull public Animatables.Properties<Entity> getAnimatableProperties() { if (animatableProperties == null) animatableProperties = Animatables.getAnimatableProperties(this); return animatableProperties; } }
core/src/pl/shockah/godwit/Entity.java
package pl.shockah.godwit; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import lombok.Getter; import pl.shockah.godwit.fx.Animatable; import pl.shockah.godwit.fx.Animatables; import pl.shockah.godwit.geom.IVec2; import pl.shockah.godwit.geom.MutableVec2; import pl.shockah.godwit.geom.Vec2; import pl.shockah.godwit.gl.Gfx; import pl.shockah.godwit.gl.Renderable; import pl.shockah.unicorn.SafeList; public class Entity implements Renderable, Animatable<Entity> { @Nonnull public final SafeList<Entity> children = new SafeList<>(new ArrayList<>()); @Nonnull public MutableVec2 position = new MutableVec2(); @Getter private Entity parent; @Getter private float depth = 0f; @Nullable private Animatables.Properties<Entity> animatableProperties; public final void setDepth(float depth) { Entity parent = this.parent; if (parent != null) parent.children.remove(this); this.depth = depth; if (parent != null) parent.children.add(this); } public final boolean hasParent() { return parent != null; } public final boolean hasRenderGroup() { Entity entity = this; while (entity != null) { if (entity instanceof RenderGroup && entity != this) return true; entity = entity.parent; } return false; } @Nonnull public final RenderGroup getRenderGroup() { Entity entity = this; while (entity != null) { if (entity instanceof RenderGroup && entity != this) return (RenderGroup)entity; entity = entity.parent; } throw new IllegalStateException(String.format("Entity %s doesn't have a RenderGroup.", this)); } public final boolean hasCameraGroup() { Entity entity = this; while (entity != null) { if (entity instanceof RenderGroup && entity != this) return true; entity = entity.parent; } return false; } @Nonnull public final CameraGroup getCameraGroup() { Entity entity = this; while (entity != null) { if (entity instanceof CameraGroup && entity != this) return (CameraGroup)entity; entity = entity.parent; } throw new IllegalStateException(String.format("Entity %s doesn't have a CameraGroup.", this)); } public void addChild(@Nonnull Entity entity) { if (entity.parent != null) throw new IllegalStateException(String.format("Entity %s already has a parent %s.", entity, entity.parent)); entity.parent = this; children.add(entity); callAddedToHierarchy(entity); entity.onAddedToParent(); } public void removeFromParent() { if (parent == null) throw new IllegalStateException(String.format("Entity %s doesn't have a parent.", this)); onRemovedFromParent(); callRemovedFromHierarchy(this); parent.children.remove(this); parent = null; } private static void callAddedToHierarchy(@Nonnull Entity entity) { entity.onAddedToHierarchy(); for (Entity child : entity.children.get()) { callAddedToHierarchy(child); } } private static void callRemovedFromHierarchy(@Nonnull Entity entity) { for (Entity child : entity.children.get()) { callRemovedFromHierarchy(child); } entity.onRemovedFromHierarchy(); } public void update() { children.update(); updateSelf(); updateFx(); updateChildren(); } public void updateSelf() { } public void updateChildren() { for (Entity entity : children.get()) { entity.update(); } } @Override public void render(@Nonnull Gfx gfx, @Nonnull IVec2 v) { } @Override public final void render(@Nonnull Gfx gfx, float x, float y) { render(gfx, new Vec2(x, y)); } @Override public final void render(@Nonnull Gfx gfx) { render(gfx, Vec2.zero); } public void onAddedToParent() { children.update(); } public void onRemovedFromParent() { } private void handleAddToRenderGroupHierarchy() { try { if (getClass() != Entity.class) { RenderGroup renderGroup = getRenderGroup(); if (!renderGroup.renderOrder.contains(this)) getRenderGroup().renderOrder.add(this); } for (Entity entity : children.get()) { entity.handleAddToRenderGroupHierarchy(); } for (Entity entity : children.getWaitingToAdd()) { entity.handleAddToRenderGroupHierarchy(); } } catch (IllegalStateException ignored) { } } private void handleRemoveFromRenderGroupHierarchy() { try { if (getClass() != Entity.class) getRenderGroup().renderOrder.remove(this); for (Entity entity : children.get()) { entity.handleRemoveFromRenderGroupHierarchy(); } for (Entity entity : children.getWaitingToAdd()) { entity.handleRemoveFromRenderGroupHierarchy(); } } catch (IllegalStateException ignored) { } } public void onAddedToHierarchy() { handleAddToRenderGroupHierarchy(); } public void onRemovedFromHierarchy() { handleRemoveFromRenderGroupHierarchy(); } @Nonnull public final Vec2 getAbsolutePoint() { return getAbsolutePoint(Vec2.zero); } @Nonnull public final Vec2 getAbsolutePoint(@Nonnull IVec2 point) { Vec2 currentPoint = point.asImmutable(); Entity entity = this; while (entity != null) { currentPoint = entity.getTranslatedPoint(currentPoint); entity = entity.parent; } return currentPoint; } @Nonnull public final MutableVec2 getPointInEntity(@Nonnull Entity entity) { MutableVec2 mutable = new MutableVec2(); calculatePointInEntity(entity, mutable); return mutable; } @Nonnull public final MutableVec2 getPointInEntity(@Nonnull Entity entity, @Nonnull IVec2 point) { MutableVec2 mutable = point.mutableCopy(); calculatePointInEntity(entity, mutable); return mutable; } public final void calculatePointInEntity(@Nonnull Entity entity, @Nonnull MutableVec2 point) { Entity current = this; while (current != null) { if (current == entity) return; current.calculateTranslatedPoint(point); current = current.parent; } throw new IllegalStateException(String.format("Entity %s is not in the tree of %s.", entity, this)); } @Nonnull public final Entity[] getParentTree() { List<Entity> tree = new LinkedList<>(); Entity entity = this; while (entity != null) { if (tree.isEmpty()) tree.add(entity); else tree.add(0, entity); entity = entity.parent; } return tree.toArray(new Entity[tree.size()]); } @Nullable public static Entity getCommonParent(@Nonnull Entity[] parentTree1, @Nonnull Entity[] parentTree2, @Nonnull Entity entity1, @Nonnull Entity entity2) { if (parentTree1[0] != parentTree2[0]) return null; for (int i = 1; i < Math.min(parentTree1.length, parentTree2.length); i++) { if (parentTree1[i] != parentTree2[i]) return parentTree1[i - 1]; } return parentTree1[Math.min(parentTree1.length, parentTree2.length) - 1]; } @Nullable public final Entity getCommonParent(@Nonnull Entity entity) { return getCommonParent(getParentTree(), entity.getParentTree(), this, entity); } protected void calculateTranslatedPoint(@Nonnull MutableVec2 point) { point.x += position.x; point.y += position.y; } @Nonnull protected Vec2 getTranslatedPoint(@Nonnull IVec2 point) { return point.add(position); } @SuppressWarnings("unchecked") @Override @Nonnull public Animatables.Properties<Entity> getAnimatableProperties() { if (animatableProperties == null) animatableProperties = Animatables.getAnimatableProperties(this); return animatableProperties; } }
Entity.on(AddedTo/RemovedFrom)Hierarchy(Entity indirectChild)
core/src/pl/shockah/godwit/Entity.java
Entity.on(AddedTo/RemovedFrom)Hierarchy(Entity indirectChild)
<ide><path>ore/src/pl/shockah/godwit/Entity.java <ide> throw new IllegalStateException(String.format("Entity %s already has a parent %s.", entity, entity.parent)); <ide> entity.parent = this; <ide> children.add(entity); <add> callDownAddedToHierarchy(this, entity); <ide> callAddedToHierarchy(entity); <ide> entity.onAddedToParent(); <ide> } <ide> throw new IllegalStateException(String.format("Entity %s doesn't have a parent.", this)); <ide> onRemovedFromParent(); <ide> callRemovedFromHierarchy(this); <add> callDownRemovedFromHierarchy(parent, this); <ide> parent.children.remove(this); <ide> parent = null; <ide> } <ide> } <ide> } <ide> <add> private static void callDownAddedToHierarchy(@Nonnull Entity context, @Nonnull Entity entity) { <add> context.onAddedToHierarchy(entity); <add> Entity parent = context.getParent(); <add> if (parent != null) <add> callDownAddedToHierarchy(parent, entity); <add> } <add> <ide> private static void callRemovedFromHierarchy(@Nonnull Entity entity) { <ide> for (Entity child : entity.children.get()) { <ide> callRemovedFromHierarchy(child); <ide> } <ide> entity.onRemovedFromHierarchy(); <add> } <add> <add> private static void callDownRemovedFromHierarchy(@Nonnull Entity context, @Nonnull Entity entity) { <add> context.onRemovedFromHierarchy(entity); <add> Entity parent = context.getParent(); <add> if (parent != null) <add> callDownRemovedFromHierarchy(parent, entity); <ide> } <ide> <ide> public void update() { <ide> <ide> public void onRemovedFromHierarchy() { <ide> handleRemoveFromRenderGroupHierarchy(); <add> } <add> <add> public void onAddedToHierarchy(@Nonnull Entity indirectChild) { <add> } <add> <add> public void onRemovedFromHierarchy(@Nonnull Entity indirectChild) { <ide> } <ide> <ide> @Nonnull public final Vec2 getAbsolutePoint() {
Java
apache-2.0
49f916abb89dd4ded38cc0d322d6cf28960f8731
0
chanakaudaya/carbon-transports,wggihan/carbon-transports,wso2/carbon-transports,shafreenAnfar/carbon-transports,bsenduran/carbon-transports,thusithathilina/carbon-transports
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package org.wso2.carbon.transport.http.netty.listener; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.LastHttpContent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wso2.carbon.messaging.CarbonCallback; import org.wso2.carbon.messaging.CarbonMessage; import org.wso2.carbon.messaging.DefaultCarbonMessage; import org.wso2.carbon.messaging.MessageDataSource; import org.wso2.carbon.transport.http.netty.common.Constants; import org.wso2.carbon.transport.http.netty.common.Util; import org.wso2.carbon.transport.http.netty.internal.HTTPTransportContextHolder; import org.wso2.carbon.transport.http.netty.message.HTTPCarbonMessage; import java.nio.ByteBuffer; /** * A Class responsible for handling the response. */ public class ResponseCallback implements CarbonCallback { private ChannelHandlerContext ctx; private static final Logger logger = LoggerFactory.getLogger(ResponseCallback.class); private static final String HTTP_CONNECTION_CLOSE = "close"; public ResponseCallback(ChannelHandlerContext channelHandlerContext) { this.ctx = channelHandlerContext; } public void done(CarbonMessage cMsg) { handleResponsesWithoutContentLength(cMsg); if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor().executeAtSourceResponseReceiving(cMsg); } final HttpResponse response = Util.createHttpResponse(cMsg); ctx.write(response); if (!cMsg.isBufferContent()) { cMsg.setWriter(new ResponseContentWriter(ctx)); } else { if (cMsg instanceof HTTPCarbonMessage) { HTTPCarbonMessage nettyCMsg = (HTTPCarbonMessage) cMsg; while (true) { if (nettyCMsg.isEndOfMsgAdded() && nettyCMsg.isEmpty()) { ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); break; } HttpContent httpContent = nettyCMsg.getHttpContent(); if (httpContent instanceof LastHttpContent) { ctx.writeAndFlush(httpContent); if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor(). executeAtSourceResponseSending(cMsg); } break; } ctx.write(httpContent); } } else if (cMsg instanceof DefaultCarbonMessage) { DefaultCarbonMessage defaultCMsg = (DefaultCarbonMessage) cMsg; while (true) { ByteBuffer byteBuffer = defaultCMsg.getMessageBody(); ByteBuf bbuf = Unpooled.wrappedBuffer(byteBuffer); DefaultHttpContent httpContent = new DefaultHttpContent(bbuf); ctx.write(httpContent); if (defaultCMsg.isEndOfMsgAdded() && defaultCMsg.isEmpty()) { ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor(). executeAtSourceResponseSending(cMsg); } String connection = cMsg.getHeader(Constants.HTTP_CONNECTION); if (connection != null && HTTP_CONNECTION_CLOSE.equalsIgnoreCase(connection)) { future.addListener(ChannelFutureListener.CLOSE); } break; } } } } } private void handleResponsesWithoutContentLength(CarbonMessage cMsg) { if (cMsg.isAlreadyRead()) { MessageDataSource messageDataSource = cMsg.getMessageDataSource(); if (messageDataSource != null) { messageDataSource.serializeData(); cMsg.setEndOfMsgAdded(true); cMsg.getHeaders().remove(Constants.HTTP_CONTENT_LENGTH); } else { logger.error("Message is already built but cannot find the MessageDataSource"); } } if (cMsg.getHeader(Constants.HTTP_TRANSFER_ENCODING) == null && cMsg.getHeader(Constants.HTTP_CONTENT_LENGTH) == null) { cMsg.setHeader(Constants.HTTP_CONTENT_LENGTH, String.valueOf(cMsg.getFullMessageLength())); } } }
http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/listener/ResponseCallback.java
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package org.wso2.carbon.transport.http.netty.listener; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.LastHttpContent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wso2.carbon.messaging.CarbonCallback; import org.wso2.carbon.messaging.CarbonMessage; import org.wso2.carbon.messaging.DefaultCarbonMessage; import org.wso2.carbon.transport.http.netty.common.Constants; import org.wso2.carbon.transport.http.netty.common.Util; import org.wso2.carbon.transport.http.netty.internal.HTTPTransportContextHolder; import org.wso2.carbon.transport.http.netty.message.HTTPCarbonMessage; import java.nio.ByteBuffer; /** * A Class responsible for handling the response. */ public class ResponseCallback implements CarbonCallback { private ChannelHandlerContext ctx; private static final Logger LOG = LoggerFactory.getLogger(ResponseCallback.class); private static final String HTTP_CONNECTION_CLOSE = "close"; public ResponseCallback(ChannelHandlerContext channelHandlerContext) { this.ctx = channelHandlerContext; } public void done(CarbonMessage cMsg) { handleResponsesWithoutContentLength(cMsg); if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor().executeAtSourceResponseReceiving(cMsg); } final HttpResponse response = Util.createHttpResponse(cMsg); ctx.write(response); if (!cMsg.isBufferContent()) { cMsg.setWriter(new ResponseContentWriter(ctx)); } else { if (cMsg instanceof HTTPCarbonMessage) { HTTPCarbonMessage nettyCMsg = (HTTPCarbonMessage) cMsg; while (true) { if (nettyCMsg.isEndOfMsgAdded() && nettyCMsg.isEmpty()) { ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); break; } HttpContent httpContent = nettyCMsg.getHttpContent(); if (httpContent instanceof LastHttpContent) { ctx.writeAndFlush(httpContent); if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor(). executeAtSourceResponseSending(cMsg); } break; } ctx.write(httpContent); } } else if (cMsg instanceof DefaultCarbonMessage) { DefaultCarbonMessage defaultCMsg = (DefaultCarbonMessage) cMsg; while (true) { ByteBuffer byteBuffer = defaultCMsg.getMessageBody(); ByteBuf bbuf = Unpooled.wrappedBuffer(byteBuffer); DefaultHttpContent httpContent = new DefaultHttpContent(bbuf); ctx.write(httpContent); if (defaultCMsg.isEndOfMsgAdded() && defaultCMsg.isEmpty()) { ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor(). executeAtSourceResponseSending(cMsg); } String connection = cMsg.getHeader(Constants.HTTP_CONNECTION); if (connection != null && HTTP_CONNECTION_CLOSE.equalsIgnoreCase(connection)) { future.addListener(ChannelFutureListener.CLOSE); } break; } } } } } private void handleResponsesWithoutContentLength(CarbonMessage cMsg) { if (cMsg.getHeader(Constants.HTTP_TRANSFER_ENCODING) == null && cMsg.getHeader(Constants.HTTP_CONTENT_LENGTH) == null) { cMsg.setHeader(Constants.HTTP_CONTENT_LENGTH, String.valueOf(cMsg.getFullMessageLength())); } } }
Response path, handling already built messages (#129) * Response path, handling already built messages * Changed Variable name of the log instance
http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/listener/ResponseCallback.java
Response path, handling already built messages (#129)
<ide><path>ttp/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/listener/ResponseCallback.java <ide> import org.wso2.carbon.messaging.CarbonCallback; <ide> import org.wso2.carbon.messaging.CarbonMessage; <ide> import org.wso2.carbon.messaging.DefaultCarbonMessage; <add>import org.wso2.carbon.messaging.MessageDataSource; <ide> import org.wso2.carbon.transport.http.netty.common.Constants; <ide> import org.wso2.carbon.transport.http.netty.common.Util; <ide> import org.wso2.carbon.transport.http.netty.internal.HTTPTransportContextHolder; <ide> <ide> private ChannelHandlerContext ctx; <ide> <del> private static final Logger LOG = LoggerFactory.getLogger(ResponseCallback.class); <add> private static final Logger logger = LoggerFactory.getLogger(ResponseCallback.class); <ide> private static final String HTTP_CONNECTION_CLOSE = "close"; <ide> <ide> public ResponseCallback(ChannelHandlerContext channelHandlerContext) { <ide> } <ide> <ide> private void handleResponsesWithoutContentLength(CarbonMessage cMsg) { <add> if (cMsg.isAlreadyRead()) { <add> MessageDataSource messageDataSource = cMsg.getMessageDataSource(); <add> if (messageDataSource != null) { <add> messageDataSource.serializeData(); <add> cMsg.setEndOfMsgAdded(true); <add> cMsg.getHeaders().remove(Constants.HTTP_CONTENT_LENGTH); <add> } else { <add> logger.error("Message is already built but cannot find the MessageDataSource"); <add> } <add> } <ide> if (cMsg.getHeader(Constants.HTTP_TRANSFER_ENCODING) == null <ide> && cMsg.getHeader(Constants.HTTP_CONTENT_LENGTH) == null) { <ide> cMsg.setHeader(Constants.HTTP_CONTENT_LENGTH, String.valueOf(cMsg.getFullMessageLength()));
Java
apache-2.0
6b85770e9de6961eccbe96c7f0f132cba69215a0
0
UniTime/unitime,maciej-zygmunt/unitime,nikeshmhr/unitime,rafati/unitime,sktoo/timetabling-system-,rafati/unitime,zuzanamullerova/unitime,sktoo/timetabling-system-,rafati/unitime,UniTime/unitime,nikeshmhr/unitime,sktoo/timetabling-system-,maciej-zygmunt/unitime,zuzanamullerova/unitime,UniTime/unitime,maciej-zygmunt/unitime,nikeshmhr/unitime,zuzanamullerova/unitime
/* * UniTime 3.2 (University Timetabling Application) * Copyright (C) 2008 - 2010, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.unitime.timetable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import org.unitime.commons.Debug; import org.unitime.timetable.model.ApplicationConfig; import org.unitime.timetable.model.dao._RootDAO; import org.unitime.timetable.util.Constants; /** * Sets the system properties for any application. * The properties in this file is adapted for each application * @author Heston Fernandes */ public class ApplicationProperties { public static SimpleDateFormat sDF_file = new SimpleDateFormat("dd-MMM-yy_HHmmssSSS"); private static Properties props = new Properties(); private static long appPropertiesLastModified = -1, custPropertiesLastModified = -1; private static PropertyFileChangeListener pfc=null; private static Properties configProps = null; /** * Sets the properties */ static { load(); // Spawn thread to dynamically reload // by design once this thread is set up it cannot be destroyed even if the reloaded property is set to false String dynamicReload = props.getProperty("tmtbl.properties.dynamic_reload", null); if ((appPropertiesLastModified>0 || custPropertiesLastModified>0) && dynamicReload!=null && dynamicReload.equalsIgnoreCase("true")) { pfc = new PropertyFileChangeListener(); pfc.start(); } } /** * Load properties */ public static void load() { try { // Load properties set in application.properties URL appPropertiesUrl = ApplicationProperties.class.getClassLoader().getResource("application.properties"); if (appPropertiesUrl!=null) { Debug.info("Reading " + URLDecoder.decode(appPropertiesUrl.getPath(), "UTF-8") + " ..."); props.load(appPropertiesUrl.openStream()); } try { try { appPropertiesLastModified = new File(appPropertiesUrl.toURI()).lastModified(); } catch (URISyntaxException e) { appPropertiesLastModified = new File(appPropertiesUrl.getPath()).lastModified(); } } catch (Exception e) {} // Load properties set in custom properties String customProperties = System.getProperty("tmtbl.custom.properties"); if (customProperties==null) customProperties = props.getProperty("tmtbl.custom.properties", "custom.properties"); URL custPropertiesUrl = ApplicationProperties.class.getClassLoader().getResource(customProperties); if (custPropertiesUrl!=null) { Debug.info("Reading " + URLDecoder.decode(custPropertiesUrl.getPath(), "UTF-8") + " ..."); props.load(custPropertiesUrl.openStream()); try { try { custPropertiesLastModified = new File(custPropertiesUrl.toURI()).lastModified(); } catch (URISyntaxException e) { custPropertiesLastModified = new File(custPropertiesUrl.getPath()).lastModified(); } } catch (Exception e) {} } else if (new File(customProperties).exists()) { Debug.info("Reading " + customProperties + " ..."); FileInputStream fis = null; try { fis = new FileInputStream(customProperties); props.load(fis); custPropertiesLastModified = new File(customProperties).lastModified(); } finally { if (fis!=null) fis.close(); } } // Load system properties props.putAll(System.getProperties()); } catch (Exception e) { Debug.error(e); } } /** * Reload properties from file application.properties */ public static void reloadIfNeeded() { if (appPropertiesLastModified>=0) { URL appPropertiesUrl = ApplicationProperties.class.getClassLoader().getResource("application.properties"); long appPropTS = -1; try { try { appPropTS = new File(appPropertiesUrl.toURI()).lastModified(); } catch (URISyntaxException e) { appPropTS = new File(appPropertiesUrl.getPath()).lastModified(); } } catch (Exception e) {} String customProperties = System.getProperty("tmtbl.custom.properties"); if (customProperties==null) customProperties = props.getProperty("tmtbl.custom.properties", "custom.properties"); URL custPropertiesUrl = ApplicationProperties.class.getClassLoader().getResource(customProperties); long custPropTS = -1; try { if (custPropertiesUrl!=null) { try { custPropTS = new File(custPropertiesUrl.toURI()).lastModified(); } catch (URISyntaxException e) { custPropTS = new File(custPropertiesUrl.getPath()).lastModified(); } } else if (new File(customProperties).exists()) { custPropTS = new File(customProperties).lastModified(); } } catch (Exception e) {} if (appPropTS>appPropertiesLastModified || custPropTS>custPropertiesLastModified) load(); } } public static Properties getConfigProperties() { if (configProps==null && _RootDAO.getConfiguration()!=null) configProps = ApplicationConfig.toProperties(); return (configProps==null?new Properties():configProps); } public static void clearConfigProperties() { configProps = null; } /** * Retrieves value for the property key * @param key * @return null if invalid key / key does not exist */ public static String getProperty(String key) { return getProperty(key, null); } /** * Retrieves value for the property key * @param defaultValue * @param key * @return default value if invalid key / key does not exist */ public static String getProperty(String key, String defaultValue) { if(key==null || key.trim().length()==0) return defaultValue; String value = getConfigProperties().getProperty(key); if (value!=null) return value; return props.getProperty(key, defaultValue); } /** * Gets the properties used to configure the application * @return Properties object */ public static Properties getProperties() { Properties ret = (Properties)props.clone(); ret.putAll(getConfigProperties()); return ret; } /** * Most resources are located in /WEB-INF folder * This function constructs the absolute path to /WEB-INF * @return Absolute file path */ public static String getBasePath() { //Get the URL of the class location (usually in /WEB-INF/classes/...) URL url = ApplicationProperties.class. getProtectionDomain().getCodeSource().getLocation(); if (url==null) return null; //Get file and parent File file = null; try { // Try to use URI to avoid bug 4466485 on Windows (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4466485) file = new File(new URI(url.toString()).getPath()); } catch (URISyntaxException e) { file = new File(url.getFile()); } File parent = file.getParentFile(); // Iterate up the folder structure till WEB-INF is encountered while (parent!=null && !parent.getName().equals("WEB-INF")) parent = parent.getParentFile(); return (parent==null?null:parent.getAbsolutePath()); } public static File getDataFolder() { if (getProperty("unitime.data.dir") != null) { File dir = new File(getProperty("unitime.data.dir")); dir.mkdirs(); return dir; } File dir = new File(getBasePath()); if (!dir.getName().equals("webapps")) dir = dir.getParentFile(); dir = dir.getParentFile().getParentFile(); dir = new File(dir, "data"); dir = new File(dir,"unitime"); dir.mkdirs(); return dir; } public static File getBlobFolder() { File dir = new File(getDataFolder(),"blob"); dir.mkdir(); return dir; } public static File getRestoreFolder() { File dir = new File(getDataFolder(),"restore"); dir.mkdir(); return dir; } public static File getPassivationFolder() { File dir = new File(getDataFolder(),"passivate"); dir.mkdir(); return dir; } public static File getTempFolder() { File dir = new File(new File(getBasePath()).getParentFile(), "temp"); dir.mkdir(); return dir; } public static boolean isLocalSolverEnabled() { return "true".equalsIgnoreCase(getProperty("tmtbl.solver.local.enabled","true")); } public static File getTempFile(String prefix, String ext) { File file = null; try { file = File.createTempFile(prefix+"_"+sDF_file.format(new Date()),"."+ext,getTempFolder()); } catch (IOException e) { Debug.error(e); file = new File(getTempFolder(), prefix+"_"+sDF_file.format(new Date())+"."+ext); } file.deleteOnExit(); return file; } /** * Stop Property File Change Listener Thread */ public static void stopListener() { if (pfc!=null && pfc.isAlive() && !pfc.isInterrupted()) { Debug.info("Stopping Property File Change Listener Thread ..."); pfc.interrupt(); } } /** * Thread to check if property file has changed * and reload the properties on the fly. Interval = 1 minute */ static class PropertyFileChangeListener extends Thread { public PropertyFileChangeListener() { setName("Property File Change Listener Thread"); setDaemon(true); } public void run() { try { Debug.info("Starting Property File Change Listener Thread ..."); long threadInterval = Constants.getPositiveInteger( ApplicationProperties.getProperty("tmtbl.properties.dynamic_reload_interval"), 15000 ); while (true) { try { sleep(threadInterval); reloadIfNeeded(); } catch (InterruptedException e) { Debug.info("Property File Change Listener Thread interrupted ..."); break; } } } catch (Exception e) { Debug.warning("Property File Change Listener Thread failed, reason: "+e.getMessage()); } } } }
JavaSource/org/unitime/timetable/ApplicationProperties.java
/* * UniTime 3.2 (University Timetabling Application) * Copyright (C) 2008 - 2010, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.unitime.timetable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import org.unitime.commons.Debug; import org.unitime.timetable.model.ApplicationConfig; import org.unitime.timetable.model.dao._RootDAO; import org.unitime.timetable.util.Constants; /** * Sets the system properties for any application. * The properties in this file is adapted for each application * @author Heston Fernandes */ public class ApplicationProperties { public static SimpleDateFormat sDF_file = new SimpleDateFormat("dd-MMM-yy_HHmmssSSS"); private static Properties props = new Properties(); private static long appPropertiesLastModified = -1, custPropertiesLastModified = -1; private static PropertyFileChangeListener pfc=null; private static Properties configProps = null; /** * Sets the properties */ static { load(); // Spawn thread to dynamically reload // by design once this thread is set up it cannot be destroyed even if the reloaded property is set to false String dynamicReload = props.getProperty("tmtbl.properties.dynamic_reload", null); if ((appPropertiesLastModified>0 || custPropertiesLastModified>0) && dynamicReload!=null && dynamicReload.equalsIgnoreCase("true")) { pfc = new PropertyFileChangeListener(); pfc.start(); } } /** * Load properties */ public static void load() { try { // Load properties set in application.properties URL appPropertiesUrl = ApplicationProperties.class.getClassLoader().getResource("application.properties"); if (appPropertiesUrl!=null) { Debug.info("Reading " + URLDecoder.decode(appPropertiesUrl.getPath(), "UTF-8") + " ..."); props.load(appPropertiesUrl.openStream()); } try { try { appPropertiesLastModified = new File(appPropertiesUrl.toURI()).lastModified(); } catch (URISyntaxException e) { appPropertiesLastModified = new File(appPropertiesUrl.getPath()).lastModified(); } } catch (Exception e) {} // Load properties set in custom properties String customProperties = System.getProperty("tmtbl.custom.properties"); if (customProperties==null) customProperties = props.getProperty("tmtbl.custom.properties", "custom.properties"); URL custPropertiesUrl = ApplicationProperties.class.getClassLoader().getResource(customProperties); if (custPropertiesUrl!=null) { Debug.info("Reading " + URLDecoder.decode(custPropertiesUrl.getPath(), "UTF-8") + " ..."); props.load(custPropertiesUrl.openStream()); try { try { custPropertiesLastModified = new File(custPropertiesUrl.toURI()).lastModified(); } catch (URISyntaxException e) { custPropertiesLastModified = new File(custPropertiesUrl.getPath()).lastModified(); } } catch (Exception e) {} } else if (new File(customProperties).exists()) { Debug.info("Reading " + customProperties + " ..."); FileInputStream fis = null; try { fis = new FileInputStream(customProperties); props.load(fis); custPropertiesLastModified = new File(customProperties).lastModified(); } finally { if (fis!=null) fis.close(); } } // Load system properties props.putAll(System.getProperties()); } catch (Exception e) { Debug.error(e); } } /** * Reload properties from file application.properties */ public static void reloadIfNeeded() { if (appPropertiesLastModified>=0) { URL appPropertiesUrl = ApplicationProperties.class.getClassLoader().getResource("application.properties"); long appPropTS = -1; try { try { appPropTS = new File(appPropertiesUrl.toURI()).lastModified(); } catch (URISyntaxException e) { appPropTS = new File(appPropertiesUrl.getPath()).lastModified(); } } catch (Exception e) {} String customProperties = System.getProperty("tmtbl.custom.properties"); if (customProperties==null) customProperties = props.getProperty("tmtbl.custom.properties", "custom.properties"); URL custPropertiesUrl = ApplicationProperties.class.getClassLoader().getResource(customProperties); long custPropTS = -1; try { if (custPropertiesUrl!=null) { try { custPropTS = new File(custPropertiesUrl.toURI()).lastModified(); } catch (URISyntaxException e) { custPropTS = new File(custPropertiesUrl.getPath()).lastModified(); } } else if (new File(customProperties).exists()) { custPropTS = new File(customProperties).lastModified(); } } catch (Exception e) {} if (appPropTS>appPropertiesLastModified || custPropTS>custPropertiesLastModified) load(); } } public static Properties getConfigProperties() { if (configProps==null && _RootDAO.getConfiguration()!=null) configProps = ApplicationConfig.toProperties(); return (configProps==null?new Properties():configProps); } public static void clearConfigProperties() { configProps = null; } /** * Retrieves value for the property key * @param key * @return null if invalid key / key does not exist */ public static String getProperty(String key) { return getProperty(key, null); } /** * Retrieves value for the property key * @param defaultValue * @param key * @return default value if invalid key / key does not exist */ public static String getProperty(String key, String defaultValue) { if(key==null || key.trim().length()==0) return defaultValue; String value = getConfigProperties().getProperty(key); if (value!=null) return value; return props.getProperty(key, defaultValue); } /** * Gets the properties used to configure the application * @return Properties object */ public static Properties getProperties() { Properties ret = (Properties)props.clone(); ret.putAll(getConfigProperties()); return ret; } /** * Most resources are located in /WEB-INF folder * This function constructs the absolute path to /WEB-INF * @return Absolute file path */ public static String getBasePath() { //Get the URL of the class location (usually in /WEB-INF/classes/...) URL url = ApplicationProperties.class. getProtectionDomain().getCodeSource().getLocation(); if (url==null) return null; //Get file and parent File file = null; try { // Try to use URI to avoid bug 4466485 on Windows (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4466485) file = new File(new URI(url.toString()).getPath()); } catch (URISyntaxException e) { file = new File(url.getFile()); } File parent = file.getParentFile(); // Iterate up the folder structure till WEB-INF is encountered while (parent!=null && !parent.getName().equals("WEB-INF")) parent = parent.getParentFile(); return (parent==null?null:parent.getAbsolutePath()); } public static File getDataFolder() { File dir = new File(getBasePath()); if (!dir.getName().equals("webapps")) dir = dir.getParentFile(); dir = dir.getParentFile().getParentFile(); dir = new File(dir, "data"); dir = new File(dir,"unitime"); dir.mkdirs(); return dir; } public static File getBlobFolder() { File dir = new File(getDataFolder(),"blob"); dir.mkdir(); return dir; } public static File getRestoreFolder() { File dir = new File(getDataFolder(),"restore"); dir.mkdir(); return dir; } public static File getPassivationFolder() { File dir = new File(getDataFolder(),"passivate"); dir.mkdir(); return dir; } public static File getTempFolder() { File dir = new File(new File(getBasePath()).getParentFile(), "temp"); dir.mkdir(); return dir; } public static boolean isLocalSolverEnabled() { return "true".equalsIgnoreCase(getProperty("tmtbl.solver.local.enabled","true")); } public static File getTempFile(String prefix, String ext) { File file = null; try { file = File.createTempFile(prefix+"_"+sDF_file.format(new Date()),"."+ext,getTempFolder()); } catch (IOException e) { Debug.error(e); file = new File(getTempFolder(), prefix+"_"+sDF_file.format(new Date())+"."+ext); } file.deleteOnExit(); return file; } /** * Stop Property File Change Listener Thread */ public static void stopListener() { if (pfc!=null && pfc.isAlive() && !pfc.isInterrupted()) { Debug.info("Stopping Property File Change Listener Thread ..."); pfc.interrupt(); } } /** * Thread to check if property file has changed * and reload the properties on the fly. Interval = 1 minute */ static class PropertyFileChangeListener extends Thread { public PropertyFileChangeListener() { setName("Property File Change Listener Thread"); setDaemon(true); } public void run() { try { Debug.info("Starting Property File Change Listener Thread ..."); long threadInterval = Constants.getPositiveInteger( ApplicationProperties.getProperty("tmtbl.properties.dynamic_reload_interval"), 15000 ); while (true) { try { sleep(threadInterval); reloadIfNeeded(); } catch (InterruptedException e) { Debug.info("Property File Change Listener Thread interrupted ..."); break; } } } catch (Exception e) { Debug.warning("Property File Change Listener Thread failed, reason: "+e.getMessage()); } } } }
Application properties - allow to override the default data folder using the unitime.data.dir property (this allows two UniTime instances to co-exist on the same Tomcat server)
JavaSource/org/unitime/timetable/ApplicationProperties.java
Application properties - allow to override the default data folder using the unitime.data.dir property (this allows two UniTime instances to co-exist on the same Tomcat server)
<ide><path>avaSource/org/unitime/timetable/ApplicationProperties.java <ide> } <ide> <ide> public static File getDataFolder() { <add> if (getProperty("unitime.data.dir") != null) { <add> File dir = new File(getProperty("unitime.data.dir")); <add> dir.mkdirs(); <add> return dir; <add> } <ide> File dir = new File(getBasePath()); <ide> if (!dir.getName().equals("webapps")) dir = dir.getParentFile(); <ide> dir = dir.getParentFile().getParentFile();
Java
apache-2.0
f0071287dcfb518e884da29db5f0a5965adbfa66
0
xfournet/intellij-community,apixandru/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,joewalnes/idea-community,semonte/intellij-community,diorcety/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,slisson/intellij-community,allotria/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,signed/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,consulo/consulo,jagguli/intellij-community,ibinti/intellij-community,signed/intellij-community,jagguli/intellij-community,kdwink/intellij-community,dslomov/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ernestp/consulo,fengbaicanhe/intellij-community,kdwink/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,idea4bsd/idea4bsd,vvv1559/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,caot/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,allotria/intellij-community,samthor/intellij-community,supersven/intellij-community,FHannes/intellij-community,allotria/intellij-community,gnuhub/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,da1z/intellij-community,clumsy/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,signed/intellij-community,suncycheng/intellij-community,ernestp/consulo,samthor/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,caot/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,amith01994/intellij-community,adedayo/intellij-community,holmes/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,jexp/idea2,ernestp/consulo,kool79/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,kool79/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,da1z/intellij-community,semonte/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,allotria/intellij-community,asedunov/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,da1z/intellij-community,izonder/intellij-community,signed/intellij-community,jexp/idea2,TangHao1987/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,da1z/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,da1z/intellij-community,fnouama/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,diorcety/intellij-community,izonder/intellij-community,kdwink/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,jexp/idea2,ol-loginov/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,caot/intellij-community,ibinti/intellij-community,blademainer/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,holmes/intellij-community,apixandru/intellij-community,fnouama/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,slisson/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,retomerz/intellij-community,allotria/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,jexp/idea2,Distrotech/intellij-community,nicolargo/intellij-community,samthor/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,slisson/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,caot/intellij-community,joewalnes/idea-community,retomerz/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,vladmm/intellij-community,ernestp/consulo,michaelgallacher/intellij-community,blademainer/intellij-community,izonder/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,allotria/intellij-community,orekyuu/intellij-community,allotria/intellij-community,consulo/consulo,youdonghai/intellij-community,diorcety/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,caot/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,samthor/intellij-community,consulo/consulo,caot/intellij-community,apixandru/intellij-community,da1z/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ibinti/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,petteyg/intellij-community,allotria/intellij-community,akosyakov/intellij-community,izonder/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,holmes/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,kool79/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,fitermay/intellij-community,jagguli/intellij-community,samthor/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,caot/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,jexp/idea2,orekyuu/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,kool79/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,amith01994/intellij-community,ernestp/consulo,gnuhub/intellij-community,retomerz/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,holmes/intellij-community,supersven/intellij-community,robovm/robovm-studio,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,vladmm/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,xfournet/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,jexp/idea2,semonte/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,samthor/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,jagguli/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,ibinti/intellij-community,fnouama/intellij-community,fitermay/intellij-community,izonder/intellij-community,adedayo/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,slisson/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,kool79/intellij-community,caot/intellij-community,semonte/intellij-community,jexp/idea2,kdwink/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,blademainer/intellij-community,adedayo/intellij-community,ernestp/consulo,akosyakov/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,holmes/intellij-community,izonder/intellij-community,dslomov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,blademainer/intellij-community,semonte/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,da1z/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,signed/intellij-community,xfournet/intellij-community,adedayo/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,semonte/intellij-community,blademainer/intellij-community,supersven/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,retomerz/intellij-community,kdwink/intellij-community,slisson/intellij-community,amith01994/intellij-community,signed/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,apixandru/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,samthor/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,alphafoobar/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,kool79/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,samthor/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,caot/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,supersven/intellij-community,dslomov/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,caot/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,kool79/intellij-community,clumsy/intellij-community,diorcety/intellij-community,FHannes/intellij-community,joewalnes/idea-community,amith01994/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,consulo/consulo,samthor/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,asedunov/intellij-community,ibinti/intellij-community,slisson/intellij-community,robovm/robovm-studio,supersven/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,slisson/intellij-community,joewalnes/idea-community,kool79/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,jexp/idea2,consulo/consulo,vvv1559/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,dslomov/intellij-community,xfournet/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,kdwink/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,izonder/intellij-community,jagguli/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,adedayo/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,retomerz/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,clumsy/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,robovm/robovm-studio,izonder/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,caot/intellij-community,signed/intellij-community
/* * Copyright 2000-2007 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.codeStyle; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ClassMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import java.util.*; public class CodeStyleSettings implements Cloneable, JDOMExternalizable { private ClassMap<CustomCodeStyleSettings> myCustomSettings = new ClassMap<CustomCodeStyleSettings>(); @NonNls private static final String ADDITIONAL_INDENT_OPTIONS = "ADDITIONAL_INDENT_OPTIONS"; @NonNls private static final String FILETYPE = "fileType"; public CodeStyleSettings() { this(true); } public CodeStyleSettings(boolean loadExtensions) { initTypeToName(); initImports(); if (loadExtensions) { final CodeStyleSettingsProvider[] codeStyleSettingsProviders = Extensions.getExtensions(CodeStyleSettingsProvider.EXTENSION_POINT_NAME); for (final CodeStyleSettingsProvider provider : codeStyleSettingsProviders) { addCustomSettings(provider.createCustomSettings(this)); } } } private void initImports() { PACKAGES_TO_USE_IMPORT_ON_DEMAND.insertEntryAt(new PackageTable.Entry("java.awt", false), 0); PACKAGES_TO_USE_IMPORT_ON_DEMAND.insertEntryAt(new PackageTable.Entry("javax.swing", false), 1); IMPORT_LAYOUT_TABLE.insertEntryAt(new ImportLayoutTable.PackageEntry("", true), 0); IMPORT_LAYOUT_TABLE.insertEntryAt(new ImportLayoutTable.EmptyLineEntry(), 1); IMPORT_LAYOUT_TABLE.insertEntryAt(new ImportLayoutTable.PackageEntry("javax", true), 2); IMPORT_LAYOUT_TABLE.insertEntryAt(new ImportLayoutTable.PackageEntry("java", true), 3); } private void initTypeToName() { initGeneralLocalVariable(PARAMETER_TYPE_TO_NAME); initGeneralLocalVariable(LOCAL_VARIABLE_TYPE_TO_NAME); PARAMETER_TYPE_TO_NAME.addPair("*Exception", "e"); } private static void initGeneralLocalVariable(@NonNls TypeToNameMap map) { map.addPair("int", "i"); map.addPair("byte", "b"); map.addPair("char", "c"); map.addPair("long", "l"); map.addPair("short", "i"); map.addPair("boolean", "b"); map.addPair("double", "v"); map.addPair("float", "v"); map.addPair("java.lang.Object", "o"); map.addPair("java.lang.String", "s"); map.addPair("*Event", "event"); } public void setParentSettings(CodeStyleSettings parent) { myParentSettings = parent; } public CodeStyleSettings getParentSettings() { return myParentSettings; } private void addCustomSettings(CustomCodeStyleSettings settings) { if (settings != null) { myCustomSettings.put(settings.getClass(), settings); } } public <T extends CustomCodeStyleSettings> T getCustomSettings(Class<T> aClass) { return (T)myCustomSettings.get(aClass); } public CodeStyleSettings clone() { try { CodeStyleSettings clon = (CodeStyleSettings)super.clone(); clon.myCustomSettings = new ClassMap<CustomCodeStyleSettings>(); for (final CustomCodeStyleSettings settings : myCustomSettings.values()) { clon.addCustomSettings((CustomCodeStyleSettings) settings.clone()); } clon.FIELD_TYPE_TO_NAME = (TypeToNameMap)FIELD_TYPE_TO_NAME.clone(); clon.STATIC_FIELD_TYPE_TO_NAME = (TypeToNameMap)STATIC_FIELD_TYPE_TO_NAME.clone(); clon.PARAMETER_TYPE_TO_NAME = (TypeToNameMap)PARAMETER_TYPE_TO_NAME.clone(); clon.LOCAL_VARIABLE_TYPE_TO_NAME = (TypeToNameMap)LOCAL_VARIABLE_TYPE_TO_NAME.clone(); clon.PACKAGES_TO_USE_IMPORT_ON_DEMAND = (PackageTable)PACKAGES_TO_USE_IMPORT_ON_DEMAND.clone(); clon.IMPORT_LAYOUT_TABLE = (ImportLayoutTable)IMPORT_LAYOUT_TABLE.clone(); clon.OTHER_INDENT_OPTIONS = (IndentOptions)OTHER_INDENT_OPTIONS.clone(); clon.ourAdditionalIndentOptions = new LinkedHashMap<FileType, IndentOptions>(); for(Map.Entry<FileType,IndentOptions> optionEntry:ourAdditionalIndentOptions.entrySet()) { clon.ourAdditionalIndentOptions.put(optionEntry.getKey(),(IndentOptions)optionEntry.getValue().clone()); } return clon; } catch (CloneNotSupportedException e) { return null; } } //----------------- GENERAL -------------------- public boolean LINE_COMMENT_AT_FIRST_COLUMN = true; public boolean BLOCK_COMMENT_AT_FIRST_COLUMN = true; public boolean KEEP_LINE_BREAKS = true; /** * Controls END_OF_LINE_COMMENT's and C_STYLE_COMMENT's */ public boolean KEEP_FIRST_COLUMN_COMMENT = true; public boolean INSERT_FIRST_SPACE_IN_LINE = true; public boolean USE_SAME_INDENTS = true; public static class IndentOptions implements JDOMExternalizable, Cloneable { public int INDENT_SIZE = 4; public int CONTINUATION_INDENT_SIZE = 8; public int TAB_SIZE = 4; public boolean USE_TAB_CHARACTER = false; public boolean SMART_TABS = false; public int LABEL_INDENT_SIZE = 0; public boolean LABEL_INDENT_ABSOLUTE = false; public void readExternal(Element element) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, element); } public void writeExternal(Element element) throws WriteExternalException { DefaultJDOMExternalizer.writeExternal(this, element); } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { // Cannot happen return null; } } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof IndentOptions)) return false; final IndentOptions indentOptions = (IndentOptions)o; if (CONTINUATION_INDENT_SIZE != indentOptions.CONTINUATION_INDENT_SIZE) return false; if (INDENT_SIZE != indentOptions.INDENT_SIZE) return false; if (SMART_TABS != indentOptions.SMART_TABS) return false; if (TAB_SIZE != indentOptions.TAB_SIZE) return false; if (USE_TAB_CHARACTER != indentOptions.USE_TAB_CHARACTER) return false; return true; } } @Deprecated public IndentOptions JAVA_INDENT_OPTIONS = new IndentOptions(); @Deprecated public IndentOptions JSP_INDENT_OPTIONS = new IndentOptions(); @Deprecated public IndentOptions XML_INDENT_OPTIONS = new IndentOptions(); public IndentOptions OTHER_INDENT_OPTIONS = new IndentOptions(); private Map<FileType,IndentOptions> ourAdditionalIndentOptions = new LinkedHashMap<FileType, IndentOptions>(); private static final String ourSystemLineSeparator = SystemProperties.getLineSeparator(); /** * Line separator. It can be null if choosen line separator is "System-dependent"! */ public String LINE_SEPARATOR; /** * @return line separator. If choosen line separator is "System-dependent" method returns default separator for this OS. */ public String getLineSeparator() { return LINE_SEPARATOR != null ? LINE_SEPARATOR : ourSystemLineSeparator; } /** * Keep "if (..) ...;" (also while, for) * Does not control "if (..) { .. }" */ public boolean KEEP_CONTROL_STATEMENT_IN_ONE_LINE = true; //----------------- BRACES & INDENTS -------------------- /** * <PRE> * 1. * if (..) { * body; * } * 2. * if (..) * { * body; * } * 3. * if (..) * { * body; * } * 4. * if (..) * { * body; * } * 5. * if (long-condition-1 && * long-condition-2) * { * body; * } * if (short-condition) { * body; * } * </PRE> */ public static final int END_OF_LINE = 1; public static final int NEXT_LINE = 2; public static final int NEXT_LINE_SHIFTED = 3; public static final int NEXT_LINE_SHIFTED2 = 4; public static final int NEXT_LINE_IF_WRAPPED = 5; public int BRACE_STYLE = 1; public int CLASS_BRACE_STYLE = 1; public int METHOD_BRACE_STYLE = 1; public boolean DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS = false; /** * <PRE> * "} * else" * or * "} else" * </PRE> */ public boolean ELSE_ON_NEW_LINE = false; /** * <PRE> * "} * while" * or * "} while" * </PRE> */ public boolean WHILE_ON_NEW_LINE = false; /** * <PRE> * "} * catch" * or * "} catch" * </PRE> */ public boolean CATCH_ON_NEW_LINE = false; /** * <PRE> * "} * finally" * or * "} finally" * </PRE> */ public boolean FINALLY_ON_NEW_LINE = false; public boolean INDENT_CASE_FROM_SWITCH = true; public boolean SPECIAL_ELSE_IF_TREATMENT = true; public boolean ALIGN_MULTILINE_PARAMETERS = true; public boolean ALIGN_MULTILINE_PARAMETERS_IN_CALLS = false; public boolean ALIGN_MULTILINE_FOR = true; public boolean ALIGN_MULTILINE_BINARY_OPERATION = false; public boolean ALIGN_MULTILINE_ASSIGNMENT = false; public boolean ALIGN_MULTILINE_TERNARY_OPERATION = false; public boolean ALIGN_MULTILINE_THROWS_LIST = false; public boolean ALIGN_MULTILINE_EXTENDS_LIST = false; public boolean ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION = false; public boolean ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION = false; //----------------- Group alignments --------------- public boolean ALIGN_GROUP_FIELD_DECLARATIONS = false; //----------------- BLANK LINES -------------------- /** * Keep up to this amount of blank lines between declarations */ public int KEEP_BLANK_LINES_IN_DECLARATIONS = 2; /** * Keep up to this amount of blank lines in code */ public int KEEP_BLANK_LINES_IN_CODE = 2; public int KEEP_BLANK_LINES_BEFORE_RBRACE = 2; public int BLANK_LINES_BEFORE_PACKAGE = 0; public int BLANK_LINES_AFTER_PACKAGE = 1; public int BLANK_LINES_BEFORE_IMPORTS = 1; public int BLANK_LINES_AFTER_IMPORTS = 1; public int BLANK_LINES_AROUND_CLASS = 1; public int BLANK_LINES_AROUND_FIELD = 0; public int BLANK_LINES_AROUND_METHOD = 1; public int BLANK_LINES_AFTER_CLASS_HEADER = 0; //public int BLANK_LINES_BETWEEN_CASE_BLOCKS; //----------------- SPACES -------------------- /** * Controls =, +=, -=, etc */ public boolean SPACE_AROUND_ASSIGNMENT_OPERATORS = true; /** * Controls &&, || */ public boolean SPACE_AROUND_LOGICAL_OPERATORS = true; /** * Controls ==, != */ public boolean SPACE_AROUND_EQUALITY_OPERATORS = true; /** * Controls <, >, <=, >= */ public boolean SPACE_AROUND_RELATIONAL_OPERATORS = true; /** * Controls &, |, ^ */ public boolean SPACE_AROUND_BITWISE_OPERATORS = true; /** * Controls +, - */ public boolean SPACE_AROUND_ADDITIVE_OPERATORS = true; /** * Controls *, /, % */ public boolean SPACE_AROUND_MULTIPLICATIVE_OPERATORS = true; /** * Controls <<. >>, >>> */ public boolean SPACE_AROUND_SHIFT_OPERATORS = true; public boolean SPACE_AFTER_COMMA = true; public boolean SPACE_BEFORE_COMMA = false; public boolean SPACE_AFTER_SEMICOLON = true; // in for-statement public boolean SPACE_BEFORE_SEMICOLON = false; // in for-statement /** * "( expr )" * or * "(expr)" */ public boolean SPACE_WITHIN_PARENTHESES = false; /** * "f( expr )" * or * "f(expr)" */ public boolean SPACE_WITHIN_METHOD_CALL_PARENTHESES = false; /** * "void f( int param )" * or * "void f(int param)" */ public boolean SPACE_WITHIN_METHOD_PARENTHESES = false; /** * "if( expr )" * or * "if(expr)" */ public boolean SPACE_WITHIN_IF_PARENTHESES = false; /** * "while( expr )" * or * "while(expr)" */ public boolean SPACE_WITHIN_WHILE_PARENTHESES = false; /** * "for( int i = 0; i < 10; i++ )" * or * "for(int i = 0; i < 10; i++)" */ public boolean SPACE_WITHIN_FOR_PARENTHESES = false; /** * "catch( Exception e )" * or * "catch(Exception e)" */ public boolean SPACE_WITHIN_CATCH_PARENTHESES = false; /** * "switch( expr )" * or * "switch(expr)" */ public boolean SPACE_WITHIN_SWITCH_PARENTHESES = false; /** * "synchronized( expr )" * or * "synchronized(expr)" */ public boolean SPACE_WITHIN_SYNCHRONIZED_PARENTHESES = false; /** * "( Type )expr" * or * "(Type)expr" */ public boolean SPACE_WITHIN_CAST_PARENTHESES = false; /** * "[ expr ]" * or * "[expr]" */ public boolean SPACE_WITHIN_BRACKETS = false; /** * "int X[] { 1, 3, 5 }" * or * "int X[] {1, 3, 5}" */ public boolean SPACE_WITHIN_ARRAY_INITIALIZER_BRACES = false; public boolean SPACE_AFTER_TYPE_CAST = true; /** * "f (x)" * or * "f(x)" */ public boolean SPACE_BEFORE_METHOD_CALL_PARENTHESES = false; /** * "void f (int param)" * or * "void f(int param)" */ public boolean SPACE_BEFORE_METHOD_PARENTHESES = false; /** * "if (...)" * or * "if(...)" */ public boolean SPACE_BEFORE_IF_PARENTHESES = true; /** * "while (...)" * or * "while(...)" */ public boolean SPACE_BEFORE_WHILE_PARENTHESES = true; /** * "for (...)" * or * "for(...)" */ public boolean SPACE_BEFORE_FOR_PARENTHESES = true; /** * "catch (...)" * or * "catch(...)" */ public boolean SPACE_BEFORE_CATCH_PARENTHESES = true; /** * "switch (...)" * or * "switch(...)" */ public boolean SPACE_BEFORE_SWITCH_PARENTHESES = true; /** * "synchronized (...)" * or * "synchronized(...)" */ public boolean SPACE_BEFORE_SYNCHRONIZED_PARENTHESES = true; /** * "class A {" * or * "class A{" */ public boolean SPACE_BEFORE_CLASS_LBRACE = true; /** * "void f() {" * or * "void f(){" */ public boolean SPACE_BEFORE_METHOD_LBRACE = true; /** * "if (...) {" * or * "if (...){" */ public boolean SPACE_BEFORE_IF_LBRACE = true; /** * "else {" * or * "else{" */ public boolean SPACE_BEFORE_ELSE_LBRACE = true; /** * "while (...) {" * or * "while (...){" */ public boolean SPACE_BEFORE_WHILE_LBRACE = true; /** * "for (...) {" * or * "for (...){" */ public boolean SPACE_BEFORE_FOR_LBRACE = true; /** * "do {" * or * "do{" */ public boolean SPACE_BEFORE_DO_LBRACE = true; /** * "switch (...) {" * or * "switch (...){" */ public boolean SPACE_BEFORE_SWITCH_LBRACE = true; /** * "try {" * or * "try{" */ public boolean SPACE_BEFORE_TRY_LBRACE = true; /** * "catch (...) {" * or * "catch (...){" */ public boolean SPACE_BEFORE_CATCH_LBRACE = true; /** * "finally {" * or * "finally{" */ public boolean SPACE_BEFORE_FINALLY_LBRACE = true; /** * "synchronized (...) {" * or * "synchronized (...){" */ public boolean SPACE_BEFORE_SYNCHRONIZED_LBRACE = true; /** * "new int[] {" * or * "new int[]{" */ public boolean SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE = false; public boolean SPACE_BEFORE_QUEST = true; public boolean SPACE_AFTER_QUEST = true; public boolean SPACE_BEFORE_COLON = true; public boolean SPACE_AFTER_COLON = true; public boolean SPACE_BEFORE_TYPE_PARAMETER_LIST = false; //----------------- NAMING CONVENTIONS -------------------- public String FIELD_NAME_PREFIX = ""; public String STATIC_FIELD_NAME_PREFIX = ""; public String PARAMETER_NAME_PREFIX = ""; public String LOCAL_VARIABLE_NAME_PREFIX = ""; public String FIELD_NAME_SUFFIX = ""; public String STATIC_FIELD_NAME_SUFFIX = ""; public String PARAMETER_NAME_SUFFIX = ""; public String LOCAL_VARIABLE_NAME_SUFFIX = ""; public boolean PREFER_LONGER_NAMES = true; public TypeToNameMap FIELD_TYPE_TO_NAME = new TypeToNameMap(); public TypeToNameMap STATIC_FIELD_TYPE_TO_NAME = new TypeToNameMap(); @NonNls public TypeToNameMap PARAMETER_TYPE_TO_NAME = new TypeToNameMap(); public TypeToNameMap LOCAL_VARIABLE_TYPE_TO_NAME = new TypeToNameMap(); //----------------- 'final' modifier settings ------- public boolean GENERATE_FINAL_LOCALS = false; public boolean GENERATE_FINAL_PARAMETERS = false; //----------------- annotations ---------------- public boolean USE_EXTERNAL_ANNOTATIONS = false; public boolean INSERT_OVERRIDE_ANNOTATION = true; //----------------- IMPORTS -------------------- public boolean USE_FQ_CLASS_NAMES = false; public boolean USE_FQ_CLASS_NAMES_IN_JAVADOC = true; public boolean USE_SINGLE_CLASS_IMPORTS = true; public boolean INSERT_INNER_CLASS_IMPORTS = false; public int CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = 5; public int NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND = 3; public PackageTable PACKAGES_TO_USE_IMPORT_ON_DEMAND = new PackageTable(); public ImportLayoutTable IMPORT_LAYOUT_TABLE = new ImportLayoutTable(); public boolean OPTIMIZE_IMPORTS_ON_THE_FLY = false; public boolean ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false; //----------------- ORDER OF MEMBERS ------------------ public int FIELDS_ORDER_WEIGHT = 1; public int CONSTRUCTORS_ORDER_WEIGHT = 2; public int METHODS_ORDER_WEIGHT = 3; public int INNER_CLASSES_ORDER_WEIGHT = 4; //----------------- WRAPPING --------------------------- public int RIGHT_MARGIN = 120; public static final int DO_NOT_WRAP = 0x00; public static final int WRAP_AS_NEEDED = 0x01; public static final int WRAP_ALWAYS = 0x02; public static final int WRAP_ON_EVERY_ITEM = 0x04; public int CALL_PARAMETERS_WRAP = DO_NOT_WRAP; public boolean PREFER_PARAMETERS_WRAP = false; public boolean CALL_PARAMETERS_LPAREN_ON_NEXT_LINE = false; public boolean CALL_PARAMETERS_RPAREN_ON_NEXT_LINE = false; public int METHOD_PARAMETERS_WRAP = DO_NOT_WRAP; public boolean METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE = false; public boolean METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE = false; public int EXTENDS_LIST_WRAP = DO_NOT_WRAP; public int THROWS_LIST_WRAP = DO_NOT_WRAP; public int EXTENDS_KEYWORD_WRAP = DO_NOT_WRAP; public int THROWS_KEYWORD_WRAP = DO_NOT_WRAP; public int METHOD_CALL_CHAIN_WRAP = DO_NOT_WRAP; public boolean PARENTHESES_EXPRESSION_LPAREN_WRAP = false; public boolean PARENTHESES_EXPRESSION_RPAREN_WRAP = false; public int BINARY_OPERATION_WRAP = DO_NOT_WRAP; public boolean BINARY_OPERATION_SIGN_ON_NEXT_LINE = false; public int TERNARY_OPERATION_WRAP = DO_NOT_WRAP; public boolean TERNARY_OPERATION_SIGNS_ON_NEXT_LINE = false; public boolean MODIFIER_LIST_WRAP = false; public boolean KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false; public boolean KEEP_SIMPLE_METHODS_IN_ONE_LINE = false; public int FOR_STATEMENT_WRAP = DO_NOT_WRAP; public boolean FOR_STATEMENT_LPAREN_ON_NEXT_LINE = false; public boolean FOR_STATEMENT_RPAREN_ON_NEXT_LINE = false; public int ARRAY_INITIALIZER_WRAP = DO_NOT_WRAP; public boolean ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE = false; public boolean ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE = false; public int ASSIGNMENT_WRAP = DO_NOT_WRAP; public boolean PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE = false; public int LABELED_STATEMENT_WRAP = WRAP_ALWAYS; public boolean WRAP_COMMENTS = false; public int ASSERT_STATEMENT_WRAP = DO_NOT_WRAP; public boolean ASSERT_STATEMENT_COLON_ON_NEXT_LINE = false; // BRACE FORCING public static final int DO_NOT_FORCE = 0x00; public static final int FORCE_BRACES_IF_MULTILINE = 0x01; public static final int FORCE_BRACES_ALWAYS = 0x03; public int IF_BRACE_FORCE = DO_NOT_FORCE; public int DOWHILE_BRACE_FORCE = DO_NOT_FORCE; public int WHILE_BRACE_FORCE = DO_NOT_FORCE; public int FOR_BRACE_FORCE = DO_NOT_FORCE; //----------------- EJB NAMING CONVENTIONS ------------- /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_EB_PREFIX = ""; //EntityBean EJB Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_EB_SUFFIX = "Bean"; //EntityBean EJB Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_HI_PREFIX = ""; //EntityBean Home interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_HI_SUFFIX = "Home"; //EntityBean Home interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_RI_PREFIX = ""; //EntityBean Remote interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_RI_SUFFIX = ""; //EntityBean Remote interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_LHI_PREFIX = "Local"; //EntityBean local Home interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_LHI_SUFFIX = "Home"; //EntityBean local Home interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_LI_PREFIX = "Local"; //EntityBean local interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_LI_SUFFIX = ""; //EntityBean local interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_DD_PREFIX = ""; //EntityBean deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_DD_SUFFIX = "EJB"; //EntityBean deployment descriptor name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_VO_PREFIX = ""; /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_VO_SUFFIX = "VO"; /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_PK_CLASS = "java.lang.String"; /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_EB_PREFIX = ""; //SessionBean EJB Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_EB_SUFFIX = "Bean"; //SessionBean EJB Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_HI_PREFIX = ""; //SessionBean Home interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_HI_SUFFIX = "Home"; //SessionBean Home interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_RI_PREFIX = ""; //SessionBean Remote interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_RI_SUFFIX = ""; //SessionBean Remote interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_LHI_PREFIX = "Local"; //SessionBean local Home interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_LHI_SUFFIX = "Home"; //SessionBean local Home interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_LI_PREFIX = "Local"; //SessionBean local interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_LI_SUFFIX = ""; //SessionBean local interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_SI_PREFIX = ""; //SessionBean service endpoint interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_SI_SUFFIX = "Service"; //SessionBean service endpoint interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_DD_PREFIX = ""; //SessionBean deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_DD_SUFFIX = "EJB"; //SessionBean deployment descriptor name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String MESSAGE_EB_PREFIX = ""; //MessageBean EJB Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String MESSAGE_EB_SUFFIX = "Bean"; //MessageBean EJB Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String MESSAGE_DD_PREFIX = ""; //MessageBean deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String MESSAGE_DD_SUFFIX = "EJB"; //MessageBean deployment descriptor name suffix //----------------- Servlet NAMING CONVENTIONS ------------- /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SERVLET_CLASS_PREFIX = ""; //SERVLET Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SERVLET_CLASS_SUFFIX = ""; //SERVLET Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SERVLET_DD_PREFIX = ""; //SERVLET deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SERVLET_DD_SUFFIX = ""; //SERVLET deployment descriptor name suffix //----------------- Web Filter NAMING CONVENTIONS ------------- /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String FILTER_CLASS_PREFIX = ""; //Filter Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String FILTER_CLASS_SUFFIX = ""; //Filter Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String FILTER_DD_PREFIX = ""; //Filter deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String FILTER_DD_SUFFIX = ""; //Filter deployment descriptor name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String LISTENER_CLASS_PREFIX = ""; //Listener Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String LISTENER_CLASS_SUFFIX = ""; //Listener Class name suffix //------------------------------------------------------------------------ // ---------------------------------- Javadoc formatting options ------------------------- public boolean ENABLE_JAVADOC_FORMATTING = true; /** * Align parameter comments to longest parameter name */ public boolean JD_ALIGN_PARAM_COMMENTS = true; public int JD_MIN_PARM_NAME_LENGTH = 0; public int JD_MAX_PARM_NAME_LENGTH = 30; /** * Align exception comments to longest exception name */ public boolean JD_ALIGN_EXCEPTION_COMMENTS = true; public int JD_MIN_EXCEPTION_NAME_LENGTH = 0; public int JD_MAX_EXCEPTION_NAME_LENGTH = 30; public boolean JD_ADD_BLANK_AFTER_PARM_COMMENTS = false; public boolean JD_ADD_BLANK_AFTER_RETURN = false; public boolean JD_ADD_BLANK_AFTER_DESCRIPTION = true; public boolean JD_P_AT_EMPTY_LINES = true; public boolean JD_KEEP_INVALID_TAGS = true; public boolean JD_KEEP_EMPTY_LINES = true; public boolean JD_DO_NOT_WRAP_ONE_LINE_COMMENTS = false; public boolean JD_USE_THROWS_NOT_EXCEPTION = true; public boolean JD_KEEP_EMPTY_PARAMETER = true; public boolean JD_KEEP_EMPTY_EXCEPTION = true; public boolean JD_KEEP_EMPTY_RETURN = true; public boolean JD_LEADING_ASTERISKS_ARE_ENABLED = true; // --------------------------------------------------------------------------------------- // ---------------------------------- XML formatting options ------------------------- public boolean XML_KEEP_WHITESPACES = false; public int XML_ATTRIBUTE_WRAP = WRAP_AS_NEEDED; public int XML_TEXT_WRAP = WRAP_AS_NEEDED; public boolean XML_KEEP_LINE_BREAKS = true; public boolean XML_KEEP_LINE_BREAKS_IN_TEXT = true; public int XML_KEEP_BLANK_LINES = 2; public boolean XML_ALIGN_ATTRIBUTES = true; public boolean XML_ALIGN_TEXT = false; public boolean XML_SPACE_AROUND_EQUALITY_IN_ATTRIBUTE = false; public boolean XML_SPACE_AFTER_TAG_NAME = false; public boolean XML_SPACE_INSIDE_EMPTY_TAG = false; // --------------------------------------------------------------------------------------- // ---------------------------------- HTML formatting options ------------------------- public boolean HTML_KEEP_WHITESPACES = false; public int HTML_ATTRIBUTE_WRAP = WRAP_AS_NEEDED; public int HTML_TEXT_WRAP = WRAP_AS_NEEDED; public boolean HTML_KEEP_LINE_BREAKS = true; public boolean HTML_KEEP_LINE_BREAKS_IN_TEXT = true; public int HTML_KEEP_BLANK_LINES = 2; public boolean HTML_ALIGN_ATTRIBUTES = true; public boolean HTML_ALIGN_TEXT = false; public boolean HTML_SPACE_AROUND_EQUALITY_IN_ATTRINUTE = false; public boolean HTML_SPACE_AFTER_TAG_NAME = false; public boolean HTML_SPACE_INSIDE_EMPTY_TAG = false; @NonNls public String HTML_ELEMENTS_TO_INSERT_NEW_LINE_BEFORE = "body,div,p,form,h1,h2,h3"; @NonNls public String HTML_ELEMENTS_TO_REMOVE_NEW_LINE_BEFORE = "br"; @NonNls public String HTML_DO_NOT_INDENT_CHILDREN_OF = "html,body"; public int HTML_DO_NOT_ALIGN_CHILDREN_OF_MIN_LINES = 100; @NonNls public String HTML_KEEP_WHITESPACES_INSIDE = "span,pre"; @NonNls public String HTML_INLINE_ELEMENTS = "a,abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,input,kbd,label,q,s,samp,select,span,strike,strong,sub,sup,textarea,tt,u,var"; @NonNls public String HTML_DONT_ADD_BREAKS_IF_INLINE_CONTENT = "title,h1,h2,h3,h4,h5,h6,p"; // --------------------------------------------------------------------------------------- // true if <%page import="x.y.z, x.y.t"%> // false if <%page import="x.y.z"%> // <%page import="x.y.t"%> public boolean JSP_PREFER_COMMA_SEPARATED_IMPORT_LIST = false; //---------------------------------------------------------------------------------------- //-------------- Annotation formatting settings------------------------------------------- public int METHOD_ANNOTATION_WRAP = WRAP_ALWAYS; public int CLASS_ANNOTATION_WRAP = WRAP_ALWAYS; public int FIELD_ANNOTATION_WRAP = WRAP_ALWAYS; public int PARAMETER_ANNOTATION_WRAP = DO_NOT_WRAP; public int VARIABLE_ANNOTATION_WRAP = DO_NOT_WRAP; public boolean SPACE_BEFORE_ANOTATION_PARAMETER_LIST = false; public boolean SPACE_WITHIN_ANNOTATION_PARENTHESES = false; //---------------------------------------------------------------------------------------- //-------------------------Enums---------------------------------------------------------- public int ENUM_CONSTANTS_WRAP = DO_NOT_WRAP; //---------------------------------------------------------------------------------------- private CodeStyleSettings myParentSettings; public void readExternal(Element element) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, element); importOldIndentOptions(element); for (final CustomCodeStyleSettings settings : myCustomSettings.values()) { settings.readExternal(element); } final List list = element.getChildren(ADDITIONAL_INDENT_OPTIONS); if (list != null) { for(Object o:list) { if (o instanceof Element) { final Element additionalIndentElement = (Element)o; final String fileTypeId = additionalIndentElement.getAttributeValue(FILETYPE); if (fileTypeId != null) { FileType target = FileTypeManager.getInstance().getFileTypeByExtension(fileTypeId); final IndentOptions options = new IndentOptions(); options.readExternal(additionalIndentElement); registerAdditionalIndentOptions(target, options); } } } } copyOldIndentOptions("java", JAVA_INDENT_OPTIONS); copyOldIndentOptions("jsp", JSP_INDENT_OPTIONS); copyOldIndentOptions("xml", XML_INDENT_OPTIONS); } private void copyOldIndentOptions(@NonNls final String extension, final IndentOptions options) { final FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(extension); if (fileType != FileTypes.UNKNOWN && !ourAdditionalIndentOptions.containsKey(fileType)) { registerAdditionalIndentOptions(fileType, options); } } private void importOldIndentOptions(@NonNls Element element) { final List options = element.getChildren("option"); for (Object option1 : options) { @NonNls Element option = (Element)option1; @NonNls final String name = option.getAttributeValue("name"); if ("TAB_SIZE".equals(name)) { final int value = Integer.valueOf(option.getAttributeValue("value")).intValue(); JAVA_INDENT_OPTIONS.TAB_SIZE = value; JSP_INDENT_OPTIONS.TAB_SIZE = value; XML_INDENT_OPTIONS.TAB_SIZE = value; OTHER_INDENT_OPTIONS.TAB_SIZE = value; } else if ("INDENT_SIZE".equals(name)) { final int value = Integer.valueOf(option.getAttributeValue("value")).intValue(); JAVA_INDENT_OPTIONS.INDENT_SIZE = value; JSP_INDENT_OPTIONS.INDENT_SIZE = value; XML_INDENT_OPTIONS.INDENT_SIZE = value; OTHER_INDENT_OPTIONS.INDENT_SIZE = value; } else if ("CONTINUATION_INDENT_SIZE".equals(name)) { final int value = Integer.valueOf(option.getAttributeValue("value")).intValue(); JAVA_INDENT_OPTIONS.CONTINUATION_INDENT_SIZE = value; JSP_INDENT_OPTIONS.CONTINUATION_INDENT_SIZE = value; XML_INDENT_OPTIONS.CONTINUATION_INDENT_SIZE = value; OTHER_INDENT_OPTIONS.CONTINUATION_INDENT_SIZE = value; } else if ("USE_TAB_CHARACTER".equals(name)) { final boolean value = Boolean.valueOf(option.getAttributeValue("value")).booleanValue(); JAVA_INDENT_OPTIONS.USE_TAB_CHARACTER = value; JSP_INDENT_OPTIONS.USE_TAB_CHARACTER = value; XML_INDENT_OPTIONS.USE_TAB_CHARACTER = value; OTHER_INDENT_OPTIONS.USE_TAB_CHARACTER = value; } else if ("SMART_TABS".equals(name)) { final boolean value = Boolean.valueOf(option.getAttributeValue("value")).booleanValue(); JAVA_INDENT_OPTIONS.SMART_TABS = value; JSP_INDENT_OPTIONS.SMART_TABS = value; XML_INDENT_OPTIONS.SMART_TABS = value; OTHER_INDENT_OPTIONS.SMART_TABS = value; } } } public void writeExternal(Element element) throws WriteExternalException { final CodeStyleSettings parentSettings = new CodeStyleSettings(); DefaultJDOMExternalizer.writeExternal(this, element, new DifferenceFilter<CodeStyleSettings>(this, parentSettings)); List<CustomCodeStyleSettings> customSettings = new ArrayList<CustomCodeStyleSettings>(myCustomSettings.values()); Collections.sort(customSettings, new Comparator<CustomCodeStyleSettings>(){ public int compare(final CustomCodeStyleSettings o1, final CustomCodeStyleSettings o2) { return o1.getTagName().compareTo(o2.getTagName()); } }); for (final CustomCodeStyleSettings settings : customSettings) { final CustomCodeStyleSettings parentCustomSettings = parentSettings.getCustomSettings(settings.getClass()); assert parentCustomSettings != null; settings.writeExternal(element, parentCustomSettings); } final FileType[] fileTypes = ourAdditionalIndentOptions.keySet().toArray(new FileType[ourAdditionalIndentOptions.keySet().size()]); Arrays.sort(fileTypes, new Comparator<FileType>() { public int compare(final FileType o1, final FileType o2) { return o1.getDefaultExtension().compareTo(o2.getDefaultExtension()); } }); for (FileType fileType : fileTypes) { final IndentOptions indentOptions = ourAdditionalIndentOptions.get(fileType); Element additionalIndentOptions = new Element(ADDITIONAL_INDENT_OPTIONS); indentOptions.writeExternal(additionalIndentOptions); additionalIndentOptions.setAttribute(FILETYPE,fileType.getDefaultExtension()); element.addContent(additionalIndentOptions); } } public IndentOptions getIndentOptions(FileType fileType) { if (USE_SAME_INDENTS || fileType == null) return OTHER_INDENT_OPTIONS; final IndentOptions indentOptions = ourAdditionalIndentOptions.get(fileType); if (indentOptions != null) return indentOptions; return OTHER_INDENT_OPTIONS; } public boolean isSmartTabs(FileType fileType) { return getIndentOptions(fileType).SMART_TABS; } public int getIndentSize(FileType fileType) { return getIndentOptions(fileType).INDENT_SIZE; } public int getContinuationIndentSize(FileType fileType) { return getIndentOptions(fileType).CONTINUATION_INDENT_SIZE; } public int getLabelIndentSize(FileType fileType) { return getIndentOptions(fileType).LABEL_INDENT_SIZE; } public boolean getLabelIndentAbsolute(FileType fileType) { return getIndentOptions(fileType).LABEL_INDENT_ABSOLUTE; } public int getTabSize(FileType fileType) { return getIndentOptions(fileType).TAB_SIZE; } public boolean useTabCharacter(FileType fileType) { return getIndentOptions(fileType).USE_TAB_CHARACTER; } public static class TypeToNameMap implements JDOMExternalizable, Cloneable { private ArrayList<String> myPatterns = new ArrayList<String>(); private ArrayList<String> myNames = new ArrayList<String>(); public void addPair(String pattern, String name) { myPatterns.add(pattern); myNames.add(name); } public String nameByType(String type) { for (int i = 0; i < myPatterns.size(); i++) { String pattern = myPatterns.get(i); if (StringUtil.startsWithChar(pattern, '*')) { if (type.endsWith(pattern.substring(1))) { return myNames.get(i); } } else { if (type.equals(pattern)) { return myNames.get(i); } } } return null; } public void readExternal(@NonNls Element element) throws InvalidDataException { myPatterns.clear(); myNames.clear(); for (final Object o : element.getChildren("pair")) { @NonNls Element e = (Element)o; String pattern = e.getAttributeValue("type"); String name = e.getAttributeValue("name"); if (pattern == null || name == null) { throw new InvalidDataException(); } myPatterns.add(pattern); myNames.add(name); } } public void writeExternal(Element parentNode) throws WriteExternalException { for (int i = 0; i < myPatterns.size(); i++) { String pattern = myPatterns.get(i); String name = myNames.get(i); @NonNls Element element = new Element("pair"); parentNode.addContent(element); element.setAttribute("type", pattern); element.setAttribute("name", name); } } public Object clone() throws CloneNotSupportedException { TypeToNameMap clon = (TypeToNameMap)TypeToNameMap.super.clone(); clon.myPatterns = (ArrayList<String>)myPatterns.clone(); clon.myNames = (ArrayList<String>)myNames.clone(); return clon; } public boolean equals(Object other) { if (other instanceof TypeToNameMap) { TypeToNameMap otherMap = (TypeToNameMap)other; if (myPatterns.size() != otherMap.myPatterns.size()) { return false; } if (myNames.size() != otherMap.myNames.size()) { return false; } for (int i = 0; i < myPatterns.size(); i++) { String s1 = myPatterns.get(i); String s2 = otherMap.myPatterns.get(i); if (!Comparing.equal(s1, s2)) { return false; } } for (int i = 0; i < myNames.size(); i++) { String s1 = myNames.get(i); String s2 = otherMap.myNames.get(i); if (!Comparing.equal(s1, s2)) { return false; } } return true; } return false; } public int hashCode() { int code = 0; for (String myPattern : myPatterns) { code += myPattern.hashCode(); } for (String myName : myNames) { code += myName.hashCode(); } return code; } } public static class PackageTable implements JDOMExternalizable, Cloneable { public static class Entry implements Cloneable { final String packageName; final boolean withSubpackages; public Entry(@NonNls String packageName, boolean withSubpackages) { this.packageName = packageName; this.withSubpackages = withSubpackages; } public String getPackageName() { return packageName; } public boolean isWithSubpackages() { return withSubpackages; } public boolean equals(Object obj) { if (!(obj instanceof Entry)) { return false; } Entry entry = (Entry)obj; return entry.withSubpackages == withSubpackages && Comparing.equal(entry.packageName, packageName); } public int hashCode() { if (packageName == null) { return 0; } return packageName.hashCode(); } } private ArrayList<Entry> myEntries = new ArrayList<Entry>(); public boolean equals(Object obj) { if (!(obj instanceof PackageTable)) { return false; } PackageTable other = (PackageTable)obj; if (other.myEntries.size() != myEntries.size()) { return false; } for (int i = 0; i < myEntries.size(); i++) { Entry entry = myEntries.get(i); Entry otherentry = other.myEntries.get(i); if (!Comparing.equal(entry, otherentry)) { return false; } } return true; } public int hashCode() { if (!myEntries.isEmpty() && myEntries.get(0) != null) { return myEntries.get(0).hashCode(); } return 0; } public Object clone() throws CloneNotSupportedException { PackageTable clon = (PackageTable)PackageTable.super.clone(); clon.myEntries = (ArrayList<Entry>)myEntries.clone(); return clon; } public void copyFrom(PackageTable packageTable) { myEntries = (ArrayList<Entry>)packageTable.myEntries.clone(); } public Entry[] getEntries() { return myEntries.toArray(new Entry[myEntries.size()]); } public void insertEntryAt(Entry entry, int i) { myEntries.add(i, entry); } public void removeEntryAt(int i) { myEntries.remove(i); } public Entry getEntryAt(int i) { return myEntries.get(i); } public int getEntryCount() { return myEntries.size(); } public void setEntryAt(Entry entry, int i) { myEntries.set(i, entry); } public boolean contains(String packageName) { for (Entry entry : myEntries) { if (packageName.startsWith(entry.packageName)) { if (packageName.length() == entry.packageName.length()) return true; if (entry.withSubpackages) { if (packageName.charAt(entry.packageName.length()) == '.') return true; } } } return false; } public void readExternal(@NonNls Element element) throws InvalidDataException { myEntries.clear(); for (final Object o : element.getChildren("package")) { @NonNls Element e = (Element)o; String packageName = e.getAttributeValue("name"); boolean withSubpackages = Boolean.parseBoolean(e.getAttributeValue("withSubpackages")); if (packageName == null) { throw new InvalidDataException(); } myEntries.add(new Entry(packageName, withSubpackages)); } } public void writeExternal(Element parentNode) throws WriteExternalException { for (Entry entry : myEntries) { @NonNls Element element = new Element("package"); parentNode.addContent(element); element.setAttribute("name", entry.packageName); element.setAttribute("withSubpackages", Boolean.toString(entry.withSubpackages)); } } } public static class ImportLayoutTable implements JDOMExternalizable, Cloneable { private ArrayList<Entry> myEntries = new ArrayList<Entry>(); public interface Entry { } public static class PackageEntry implements Entry { private final String myPackageName; private final boolean myWithSubpackages; public PackageEntry(@NonNls String packageName, boolean withSubpackages) { myPackageName = packageName; myWithSubpackages = withSubpackages; } public String getPackageName() { return myPackageName; } public boolean isWithSubpackages() { return myWithSubpackages; } public boolean matchesPackageName(String packageName) { if (myPackageName.length() == 0 && myWithSubpackages) return true; if (packageName.startsWith(myPackageName)) { if (packageName.length() == myPackageName.length()) return true; if (myWithSubpackages) { if (packageName.charAt(myPackageName.length()) == '.') return true; } } return false; } public boolean matchesClassName(String className) { int dotIndex = className.lastIndexOf('.'); String packageName = dotIndex < 0 ? "" : className.substring(0, dotIndex); return matchesPackageName(packageName); } public boolean equals(Object obj) { if (!(obj instanceof PackageEntry)) { return false; } PackageEntry entry = (PackageEntry)obj; return entry.myWithSubpackages == myWithSubpackages && Comparing.equal(entry.myPackageName, myPackageName); } public int hashCode() { if (myPackageName == null) { return 0; } return myPackageName.hashCode(); } } public static class EmptyLineEntry implements Entry { public boolean equals(Object obj) { return obj instanceof EmptyLineEntry; } public int hashCode() { return 100; } } public void copyFrom(ImportLayoutTable importLayoutTable) { myEntries = (ArrayList<Entry>)importLayoutTable.myEntries.clone(); } public Entry[] getEntries() { return myEntries.toArray(new Entry[myEntries.size()]); } public void insertEntryAt(Entry entry, int i) { myEntries.add(i, entry); } public void removeEntryAt(int i) { myEntries.remove(i); } public Entry getEntryAt(int i) { return myEntries.get(i); } public int getEntryCount() { return myEntries.size(); } public void setEntryAt(Entry entry, int i) { myEntries.set(i, entry); } public void readExternal(Element element) throws InvalidDataException { myEntries.clear(); List children = element.getChildren(); for (final Object aChildren : children) { @NonNls Element e = (Element)aChildren; @NonNls String name = e.getName(); if ("package".equals(name)) { String packageName = e.getAttributeValue("name"); boolean withSubpackages = Boolean.parseBoolean(e.getAttributeValue("withSubpackages")); if (packageName == null) { throw new InvalidDataException(); } myEntries.add(new PackageEntry(packageName, withSubpackages)); } else { if ("emptyLine".equals(name)) { myEntries.add(new EmptyLineEntry()); } } } } public void writeExternal(Element parentNode) throws WriteExternalException { for (Entry myEntry : myEntries) { if (myEntry instanceof PackageEntry) { PackageEntry entry = (PackageEntry)myEntry; @NonNls Element element = new Element("package"); parentNode.addContent(element); element.setAttribute("name", entry.getPackageName()); element.setAttribute("withSubpackages", entry.isWithSubpackages() ? "true" : "false"); } else { if (myEntry instanceof EmptyLineEntry) { @NonNls Element element = new Element("emptyLine"); parentNode.addContent(element); } } } } public boolean equals(Object obj) { if (!(obj instanceof ImportLayoutTable)) { return false; } ImportLayoutTable other = (ImportLayoutTable)obj; if (other.myEntries.size() != myEntries.size()) { return false; } for (int i = 0; i < myEntries.size(); i++) { Entry entry = myEntries.get(i); Entry otherentry = other.myEntries.get(i); if (!Comparing.equal(entry, otherentry)) { return false; } } return true; } public int hashCode() { if (!myEntries.isEmpty() && myEntries.get(0) != null) { return myEntries.get(0).hashCode(); } return 0; } public Object clone() throws CloneNotSupportedException { ImportLayoutTable clon = (ImportLayoutTable)ImportLayoutTable.super.clone(); clon.myEntries = (ArrayList<Entry>)myEntries.clone(); return clon; } } private void registerAdditionalIndentOptions(FileType fileType, IndentOptions options) { ourAdditionalIndentOptions.put(fileType, options); } public IndentOptions getAdditionalIndentOptions(FileType fileType) { IndentOptions result = ourAdditionalIndentOptions.get(fileType); if (result == null) { final FileTypeIndentOptionsProvider[] fileTypeIndentOptionsProviders = Extensions.getExtensions(FileTypeIndentOptionsProvider.EP_NAME); for (final FileTypeIndentOptionsProvider provider : fileTypeIndentOptionsProviders) { if (fileType == provider.getFileType()) { result = provider.createIndentOptions(); registerAdditionalIndentOptions(provider.getFileType(), result); } } } return result; } }
lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettings.java
/* * Copyright 2000-2007 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.codeStyle; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ClassMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import java.util.*; public class CodeStyleSettings implements Cloneable, JDOMExternalizable { private ClassMap<CustomCodeStyleSettings> myCustomSettings = new ClassMap<CustomCodeStyleSettings>(); @NonNls private static final String ADDITIONAL_INDENT_OPTIONS = "ADDITIONAL_INDENT_OPTIONS"; @NonNls private static final String FILETYPE = "fileType"; public CodeStyleSettings() { this(true); } public CodeStyleSettings(boolean loadExtensions) { initTypeToName(); initImports(); if (loadExtensions) { final CodeStyleSettingsProvider[] codeStyleSettingsProviders = Extensions.getExtensions(CodeStyleSettingsProvider.EXTENSION_POINT_NAME); for (final CodeStyleSettingsProvider provider : codeStyleSettingsProviders) { addCustomSettings(provider.createCustomSettings(this)); } } } private void initImports() { PACKAGES_TO_USE_IMPORT_ON_DEMAND.insertEntryAt(new PackageTable.Entry("java.awt", false), 0); PACKAGES_TO_USE_IMPORT_ON_DEMAND.insertEntryAt(new PackageTable.Entry("javax.swing", false), 1); IMPORT_LAYOUT_TABLE.insertEntryAt(new ImportLayoutTable.PackageEntry("", true), 0); IMPORT_LAYOUT_TABLE.insertEntryAt(new ImportLayoutTable.EmptyLineEntry(), 1); IMPORT_LAYOUT_TABLE.insertEntryAt(new ImportLayoutTable.PackageEntry("javax", true), 2); IMPORT_LAYOUT_TABLE.insertEntryAt(new ImportLayoutTable.PackageEntry("java", true), 3); } private void initTypeToName() { initGeneralLocalVariable(PARAMETER_TYPE_TO_NAME); initGeneralLocalVariable(LOCAL_VARIABLE_TYPE_TO_NAME); PARAMETER_TYPE_TO_NAME.addPair("*Exception", "e"); } private static void initGeneralLocalVariable(@NonNls TypeToNameMap map) { map.addPair("int", "i"); map.addPair("byte", "b"); map.addPair("char", "c"); map.addPair("long", "l"); map.addPair("short", "i"); map.addPair("boolean", "b"); map.addPair("double", "v"); map.addPair("float", "v"); map.addPair("java.lang.Object", "o"); map.addPair("java.lang.String", "s"); map.addPair("*Event", "event"); } public void setParentSettings(CodeStyleSettings parent) { myParentSettings = parent; } public CodeStyleSettings getParentSettings() { return myParentSettings; } private void addCustomSettings(CustomCodeStyleSettings settings) { if (settings != null) { myCustomSettings.put(settings.getClass(), settings); } } public <T extends CustomCodeStyleSettings> T getCustomSettings(Class<T> aClass) { return (T)myCustomSettings.get(aClass); } public CodeStyleSettings clone() { try { CodeStyleSettings clon = (CodeStyleSettings)super.clone(); clon.myCustomSettings = new ClassMap<CustomCodeStyleSettings>(); for (final CustomCodeStyleSettings settings : myCustomSettings.values()) { clon.addCustomSettings((CustomCodeStyleSettings) settings.clone()); } clon.FIELD_TYPE_TO_NAME = (TypeToNameMap)FIELD_TYPE_TO_NAME.clone(); clon.STATIC_FIELD_TYPE_TO_NAME = (TypeToNameMap)STATIC_FIELD_TYPE_TO_NAME.clone(); clon.PARAMETER_TYPE_TO_NAME = (TypeToNameMap)PARAMETER_TYPE_TO_NAME.clone(); clon.LOCAL_VARIABLE_TYPE_TO_NAME = (TypeToNameMap)LOCAL_VARIABLE_TYPE_TO_NAME.clone(); clon.PACKAGES_TO_USE_IMPORT_ON_DEMAND = (PackageTable)PACKAGES_TO_USE_IMPORT_ON_DEMAND.clone(); clon.IMPORT_LAYOUT_TABLE = (ImportLayoutTable)IMPORT_LAYOUT_TABLE.clone(); clon.OTHER_INDENT_OPTIONS = (IndentOptions)OTHER_INDENT_OPTIONS.clone(); clon.ourAdditionalIndentOptions = new LinkedHashMap<FileType, IndentOptions>(); for(Map.Entry<FileType,IndentOptions> optionEntry:ourAdditionalIndentOptions.entrySet()) { clon.ourAdditionalIndentOptions.put(optionEntry.getKey(),(IndentOptions)optionEntry.getValue().clone()); } return clon; } catch (CloneNotSupportedException e) { return null; } } //----------------- GENERAL -------------------- public boolean LINE_COMMENT_AT_FIRST_COLUMN = true; public boolean BLOCK_COMMENT_AT_FIRST_COLUMN = true; public boolean KEEP_LINE_BREAKS = true; /** * Controls END_OF_LINE_COMMENT's and C_STYLE_COMMENT's */ public boolean KEEP_FIRST_COLUMN_COMMENT = true; public boolean INSERT_FIRST_SPACE_IN_LINE = true; public boolean USE_SAME_INDENTS = true; public static class IndentOptions implements JDOMExternalizable, Cloneable { public int INDENT_SIZE = 4; public int CONTINUATION_INDENT_SIZE = 8; public int TAB_SIZE = 4; public boolean USE_TAB_CHARACTER = false; public boolean SMART_TABS = false; public int LABEL_INDENT_SIZE = 0; public boolean LABEL_INDENT_ABSOLUTE = false; public void readExternal(Element element) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, element); } public void writeExternal(Element element) throws WriteExternalException { DefaultJDOMExternalizer.writeExternal(this, element); } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { // Cannot happen return null; } } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof IndentOptions)) return false; final IndentOptions indentOptions = (IndentOptions)o; if (CONTINUATION_INDENT_SIZE != indentOptions.CONTINUATION_INDENT_SIZE) return false; if (INDENT_SIZE != indentOptions.INDENT_SIZE) return false; if (SMART_TABS != indentOptions.SMART_TABS) return false; if (TAB_SIZE != indentOptions.TAB_SIZE) return false; if (USE_TAB_CHARACTER != indentOptions.USE_TAB_CHARACTER) return false; return true; } } @Deprecated public IndentOptions JAVA_INDENT_OPTIONS = new IndentOptions(); @Deprecated public IndentOptions JSP_INDENT_OPTIONS = new IndentOptions(); @Deprecated public IndentOptions XML_INDENT_OPTIONS = new IndentOptions(); public IndentOptions OTHER_INDENT_OPTIONS = new IndentOptions(); private Map<FileType,IndentOptions> ourAdditionalIndentOptions = new LinkedHashMap<FileType, IndentOptions>(); private static final String ourSystemLineSeparator = SystemProperties.getLineSeparator(); /** * Line separator. It can be null if choosen line separator is "System-dependent"! */ public String LINE_SEPARATOR; /** * @return line separator. If choosen line separator is "System-dependent" method returns default separator for this OS. */ public String getLineSeparator() { return LINE_SEPARATOR != null ? LINE_SEPARATOR : ourSystemLineSeparator; } /** * Keep "if (..) ...;" (also while, for) * Does not control "if (..) { .. }" */ public boolean KEEP_CONTROL_STATEMENT_IN_ONE_LINE = true; //----------------- BRACES & INDENTS -------------------- /** * <PRE> * 1. * if (..) { * body; * } * 2. * if (..) * { * body; * } * 3. * if (..) * { * body; * } * 4. * if (..) * { * body; * } * 5. * if (long-condition-1 && * long-condition-2) * { * body; * } * if (short-condition) { * body; * } * </PRE> */ public static final int END_OF_LINE = 1; public static final int NEXT_LINE = 2; public static final int NEXT_LINE_SHIFTED = 3; public static final int NEXT_LINE_SHIFTED2 = 4; public static final int NEXT_LINE_IF_WRAPPED = 5; public int BRACE_STYLE = 1; public int CLASS_BRACE_STYLE = 1; public int METHOD_BRACE_STYLE = 1; public boolean DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS = false; /** * <PRE> * "} * else" * or * "} else" * </PRE> */ public boolean ELSE_ON_NEW_LINE = false; /** * <PRE> * "} * while" * or * "} while" * </PRE> */ public boolean WHILE_ON_NEW_LINE = false; /** * <PRE> * "} * catch" * or * "} catch" * </PRE> */ public boolean CATCH_ON_NEW_LINE = false; /** * <PRE> * "} * finally" * or * "} finally" * </PRE> */ public boolean FINALLY_ON_NEW_LINE = false; public boolean INDENT_CASE_FROM_SWITCH = true; public boolean SPECIAL_ELSE_IF_TREATMENT = true; public boolean ALIGN_MULTILINE_PARAMETERS = true; public boolean ALIGN_MULTILINE_PARAMETERS_IN_CALLS = false; public boolean ALIGN_MULTILINE_FOR = true; public boolean ALIGN_MULTILINE_BINARY_OPERATION = false; public boolean ALIGN_MULTILINE_ASSIGNMENT = false; public boolean ALIGN_MULTILINE_TERNARY_OPERATION = false; public boolean ALIGN_MULTILINE_THROWS_LIST = false; public boolean ALIGN_MULTILINE_EXTENDS_LIST = false; public boolean ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION = false; public boolean ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION = false; //----------------- Group alignments --------------- public boolean ALIGN_GROUP_FIELD_DECLARATIONS = false; //----------------- BLANK LINES -------------------- /** * Keep up to this amount of blank lines between declarations */ public int KEEP_BLANK_LINES_IN_DECLARATIONS = 2; /** * Keep up to this amount of blank lines in code */ public int KEEP_BLANK_LINES_IN_CODE = 2; public int KEEP_BLANK_LINES_BEFORE_RBRACE = 2; public int BLANK_LINES_BEFORE_PACKAGE = 0; public int BLANK_LINES_AFTER_PACKAGE = 1; public int BLANK_LINES_BEFORE_IMPORTS = 1; public int BLANK_LINES_AFTER_IMPORTS = 1; public int BLANK_LINES_AROUND_CLASS = 1; public int BLANK_LINES_AROUND_FIELD = 0; public int BLANK_LINES_AROUND_METHOD = 1; public int BLANK_LINES_AFTER_CLASS_HEADER = 0; //public int BLANK_LINES_BETWEEN_CASE_BLOCKS; //----------------- SPACES -------------------- /** * Controls =, +=, -=, etc */ public boolean SPACE_AROUND_ASSIGNMENT_OPERATORS = true; /** * Controls &&, || */ public boolean SPACE_AROUND_LOGICAL_OPERATORS = true; /** * Controls ==, != */ public boolean SPACE_AROUND_EQUALITY_OPERATORS = true; /** * Controls <, >, <=, >= */ public boolean SPACE_AROUND_RELATIONAL_OPERATORS = true; /** * Controls &, |, ^ */ public boolean SPACE_AROUND_BITWISE_OPERATORS = true; /** * Controls +, - */ public boolean SPACE_AROUND_ADDITIVE_OPERATORS = true; /** * Controls *, /, % */ public boolean SPACE_AROUND_MULTIPLICATIVE_OPERATORS = true; /** * Controls <<. >>, >>> */ public boolean SPACE_AROUND_SHIFT_OPERATORS = true; public boolean SPACE_AFTER_COMMA = true; public boolean SPACE_BEFORE_COMMA = false; public boolean SPACE_AFTER_SEMICOLON = true; // in for-statement public boolean SPACE_BEFORE_SEMICOLON = false; // in for-statement /** * "( expr )" * or * "(expr)" */ public boolean SPACE_WITHIN_PARENTHESES = false; /** * "f( expr )" * or * "f(expr)" */ public boolean SPACE_WITHIN_METHOD_CALL_PARENTHESES = false; /** * "void f( int param )" * or * "void f(int param)" */ public boolean SPACE_WITHIN_METHOD_PARENTHESES = false; /** * "if( expr )" * or * "if(expr)" */ public boolean SPACE_WITHIN_IF_PARENTHESES = false; /** * "while( expr )" * or * "while(expr)" */ public boolean SPACE_WITHIN_WHILE_PARENTHESES = false; /** * "for( int i = 0; i < 10; i++ )" * or * "for(int i = 0; i < 10; i++)" */ public boolean SPACE_WITHIN_FOR_PARENTHESES = false; /** * "catch( Exception e )" * or * "catch(Exception e)" */ public boolean SPACE_WITHIN_CATCH_PARENTHESES = false; /** * "switch( expr )" * or * "switch(expr)" */ public boolean SPACE_WITHIN_SWITCH_PARENTHESES = false; /** * "synchronized( expr )" * or * "synchronized(expr)" */ public boolean SPACE_WITHIN_SYNCHRONIZED_PARENTHESES = false; /** * "( Type )expr" * or * "(Type)expr" */ public boolean SPACE_WITHIN_CAST_PARENTHESES = false; /** * "[ expr ]" * or * "[expr]" */ public boolean SPACE_WITHIN_BRACKETS = false; /** * "int X[] { 1, 3, 5 }" * or * "int X[] {1, 3, 5}" */ public boolean SPACE_WITHIN_ARRAY_INITIALIZER_BRACES = false; public boolean SPACE_AFTER_TYPE_CAST = true; /** * "f (x)" * or * "f(x)" */ public boolean SPACE_BEFORE_METHOD_CALL_PARENTHESES = false; /** * "void f (int param)" * or * "void f(int param)" */ public boolean SPACE_BEFORE_METHOD_PARENTHESES = false; /** * "if (...)" * or * "if(...)" */ public boolean SPACE_BEFORE_IF_PARENTHESES = true; /** * "while (...)" * or * "while(...)" */ public boolean SPACE_BEFORE_WHILE_PARENTHESES = true; /** * "for (...)" * or * "for(...)" */ public boolean SPACE_BEFORE_FOR_PARENTHESES = true; /** * "catch (...)" * or * "catch(...)" */ public boolean SPACE_BEFORE_CATCH_PARENTHESES = true; /** * "switch (...)" * or * "switch(...)" */ public boolean SPACE_BEFORE_SWITCH_PARENTHESES = true; /** * "synchronized (...)" * or * "synchronized(...)" */ public boolean SPACE_BEFORE_SYNCHRONIZED_PARENTHESES = true; /** * "class A {" * or * "class A{" */ public boolean SPACE_BEFORE_CLASS_LBRACE = true; /** * "void f() {" * or * "void f(){" */ public boolean SPACE_BEFORE_METHOD_LBRACE = true; /** * "if (...) {" * or * "if (...){" */ public boolean SPACE_BEFORE_IF_LBRACE = true; /** * "else {" * or * "else{" */ public boolean SPACE_BEFORE_ELSE_LBRACE = true; /** * "while (...) {" * or * "while (...){" */ public boolean SPACE_BEFORE_WHILE_LBRACE = true; /** * "for (...) {" * or * "for (...){" */ public boolean SPACE_BEFORE_FOR_LBRACE = true; /** * "do {" * or * "do{" */ public boolean SPACE_BEFORE_DO_LBRACE = true; /** * "switch (...) {" * or * "switch (...){" */ public boolean SPACE_BEFORE_SWITCH_LBRACE = true; /** * "try {" * or * "try{" */ public boolean SPACE_BEFORE_TRY_LBRACE = true; /** * "catch (...) {" * or * "catch (...){" */ public boolean SPACE_BEFORE_CATCH_LBRACE = true; /** * "finally {" * or * "finally{" */ public boolean SPACE_BEFORE_FINALLY_LBRACE = true; /** * "synchronized (...) {" * or * "synchronized (...){" */ public boolean SPACE_BEFORE_SYNCHRONIZED_LBRACE = true; /** * "new int[] {" * or * "new int[]{" */ public boolean SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE = false; public boolean SPACE_BEFORE_QUEST = true; public boolean SPACE_AFTER_QUEST = true; public boolean SPACE_BEFORE_COLON = true; public boolean SPACE_AFTER_COLON = true; public boolean SPACE_BEFORE_TYPE_PARAMETER_LIST = false; //----------------- NAMING CONVENTIONS -------------------- public String FIELD_NAME_PREFIX = ""; public String STATIC_FIELD_NAME_PREFIX = ""; public String PARAMETER_NAME_PREFIX = ""; public String LOCAL_VARIABLE_NAME_PREFIX = ""; public String FIELD_NAME_SUFFIX = ""; public String STATIC_FIELD_NAME_SUFFIX = ""; public String PARAMETER_NAME_SUFFIX = ""; public String LOCAL_VARIABLE_NAME_SUFFIX = ""; public boolean PREFER_LONGER_NAMES = true; public TypeToNameMap FIELD_TYPE_TO_NAME = new TypeToNameMap(); public TypeToNameMap STATIC_FIELD_TYPE_TO_NAME = new TypeToNameMap(); @NonNls public TypeToNameMap PARAMETER_TYPE_TO_NAME = new TypeToNameMap(); public TypeToNameMap LOCAL_VARIABLE_TYPE_TO_NAME = new TypeToNameMap(); //----------------- 'final' modifier settings ------- public boolean GENERATE_FINAL_LOCALS = false; public boolean GENERATE_FINAL_PARAMETERS = false; //----------------- annotations ---------------- public boolean USE_EXTERNAL_ANNOTATIONS = false; public boolean INSERT_OVERRIDE_ANNOTATION = true; //----------------- IMPORTS -------------------- public boolean USE_FQ_CLASS_NAMES = false; public boolean USE_FQ_CLASS_NAMES_IN_JAVADOC = true; public boolean USE_SINGLE_CLASS_IMPORTS = true; public boolean INSERT_INNER_CLASS_IMPORTS = false; public int CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = 5; public int NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND = 3; public PackageTable PACKAGES_TO_USE_IMPORT_ON_DEMAND = new PackageTable(); public ImportLayoutTable IMPORT_LAYOUT_TABLE = new ImportLayoutTable(); public boolean OPTIMIZE_IMPORTS_ON_THE_FLY = false; public boolean ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false; //----------------- ORDER OF MEMBERS ------------------ public int FIELDS_ORDER_WEIGHT = 1; public int CONSTRUCTORS_ORDER_WEIGHT = 2; public int METHODS_ORDER_WEIGHT = 3; public int INNER_CLASSES_ORDER_WEIGHT = 4; //----------------- WRAPPING --------------------------- public int RIGHT_MARGIN = 120; public static final int DO_NOT_WRAP = 0x00; public static final int WRAP_AS_NEEDED = 0x01; public static final int WRAP_ALWAYS = 0x02; public static final int WRAP_ON_EVERY_ITEM = 0x04; public int CALL_PARAMETERS_WRAP = DO_NOT_WRAP; public boolean PREFER_PARAMETERS_WRAP = false; public boolean CALL_PARAMETERS_LPAREN_ON_NEXT_LINE = false; public boolean CALL_PARAMETERS_RPAREN_ON_NEXT_LINE = false; public int METHOD_PARAMETERS_WRAP = DO_NOT_WRAP; public boolean METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE = false; public boolean METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE = false; public int EXTENDS_LIST_WRAP = DO_NOT_WRAP; public int THROWS_LIST_WRAP = DO_NOT_WRAP; public int EXTENDS_KEYWORD_WRAP = DO_NOT_WRAP; public int THROWS_KEYWORD_WRAP = DO_NOT_WRAP; public int METHOD_CALL_CHAIN_WRAP = DO_NOT_WRAP; public boolean PARENTHESES_EXPRESSION_LPAREN_WRAP = false; public boolean PARENTHESES_EXPRESSION_RPAREN_WRAP = false; public int BINARY_OPERATION_WRAP = DO_NOT_WRAP; public boolean BINARY_OPERATION_SIGN_ON_NEXT_LINE = false; public int TERNARY_OPERATION_WRAP = DO_NOT_WRAP; public boolean TERNARY_OPERATION_SIGNS_ON_NEXT_LINE = false; public boolean MODIFIER_LIST_WRAP = false; public boolean KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false; public boolean KEEP_SIMPLE_METHODS_IN_ONE_LINE = false; public int FOR_STATEMENT_WRAP = DO_NOT_WRAP; public boolean FOR_STATEMENT_LPAREN_ON_NEXT_LINE = false; public boolean FOR_STATEMENT_RPAREN_ON_NEXT_LINE = false; public int ARRAY_INITIALIZER_WRAP = DO_NOT_WRAP; public boolean ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE = false; public boolean ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE = false; public int ASSIGNMENT_WRAP = DO_NOT_WRAP; public boolean PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE = false; public int LABELED_STATEMENT_WRAP = WRAP_ALWAYS; public boolean WRAP_COMMENTS = false; public int ASSERT_STATEMENT_WRAP = DO_NOT_WRAP; public boolean ASSERT_STATEMENT_COLON_ON_NEXT_LINE = false; // BRACE FORCING public static final int DO_NOT_FORCE = 0x00; public static final int FORCE_BRACES_IF_MULTILINE = 0x01; public static final int FORCE_BRACES_ALWAYS = 0x03; public int IF_BRACE_FORCE = DO_NOT_FORCE; public int DOWHILE_BRACE_FORCE = DO_NOT_FORCE; public int WHILE_BRACE_FORCE = DO_NOT_FORCE; public int FOR_BRACE_FORCE = DO_NOT_FORCE; //----------------- EJB NAMING CONVENTIONS ------------- /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_EB_PREFIX = ""; //EntityBean EJB Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_EB_SUFFIX = "Bean"; //EntityBean EJB Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_HI_PREFIX = ""; //EntityBean Home interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_HI_SUFFIX = "Home"; //EntityBean Home interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_RI_PREFIX = ""; //EntityBean Remote interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_RI_SUFFIX = ""; //EntityBean Remote interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_LHI_PREFIX = "Local"; //EntityBean local Home interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_LHI_SUFFIX = "Home"; //EntityBean local Home interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_LI_PREFIX = "Local"; //EntityBean local interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_LI_SUFFIX = ""; //EntityBean local interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_DD_PREFIX = ""; //EntityBean deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_DD_SUFFIX = "EJB"; //EntityBean deployment descriptor name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_VO_PREFIX = ""; /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_VO_SUFFIX = "VO"; /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String ENTITY_PK_CLASS = "java.lang.String"; /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_EB_PREFIX = ""; //SessionBean EJB Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_EB_SUFFIX = "Bean"; //SessionBean EJB Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_HI_PREFIX = ""; //SessionBean Home interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_HI_SUFFIX = "Home"; //SessionBean Home interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_RI_PREFIX = ""; //SessionBean Remote interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_RI_SUFFIX = ""; //SessionBean Remote interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_LHI_PREFIX = "Local"; //SessionBean local Home interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_LHI_SUFFIX = "Home"; //SessionBean local Home interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_LI_PREFIX = "Local"; //SessionBean local interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_LI_SUFFIX = ""; //SessionBean local interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_SI_PREFIX = ""; //SessionBean service endpoint interface name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_SI_SUFFIX = "Service"; //SessionBean service endpoint interface name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_DD_PREFIX = ""; //SessionBean deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SESSION_DD_SUFFIX = "EJB"; //SessionBean deployment descriptor name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String MESSAGE_EB_PREFIX = ""; //MessageBean EJB Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String MESSAGE_EB_SUFFIX = "Bean"; //MessageBean EJB Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String MESSAGE_DD_PREFIX = ""; //MessageBean deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String MESSAGE_DD_SUFFIX = "EJB"; //MessageBean deployment descriptor name suffix //----------------- Servlet NAMING CONVENTIONS ------------- /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SERVLET_CLASS_PREFIX = ""; //SERVLET Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SERVLET_CLASS_SUFFIX = ""; //SERVLET Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SERVLET_DD_PREFIX = ""; //SERVLET deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String SERVLET_DD_SUFFIX = ""; //SERVLET deployment descriptor name suffix //----------------- Web Filter NAMING CONVENTIONS ------------- /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String FILTER_CLASS_PREFIX = ""; //Filter Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String FILTER_CLASS_SUFFIX = ""; //Filter Class name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String FILTER_DD_PREFIX = ""; //Filter deployment descriptor name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String FILTER_DD_SUFFIX = ""; //Filter deployment descriptor name suffix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String LISTENER_CLASS_PREFIX = ""; //Listener Class name prefix /** * @deprecated use com.intellij.javaee.JavaeeCodeStyleSettings class */ @NonNls public String LISTENER_CLASS_SUFFIX = ""; //Listener Class name suffix //------------------------------------------------------------------------ // ---------------------------------- Javadoc formatting options ------------------------- public boolean ENABLE_JAVADOC_FORMATTING = true; /** * Align parameter comments to longest parameter name */ public boolean JD_ALIGN_PARAM_COMMENTS = true; public int JD_MIN_PARM_NAME_LENGTH = 0; public int JD_MAX_PARM_NAME_LENGTH = 30; /** * Align exception comments to longest exception name */ public boolean JD_ALIGN_EXCEPTION_COMMENTS = true; public int JD_MIN_EXCEPTION_NAME_LENGTH = 0; public int JD_MAX_EXCEPTION_NAME_LENGTH = 30; public boolean JD_ADD_BLANK_AFTER_PARM_COMMENTS = false; public boolean JD_ADD_BLANK_AFTER_RETURN = false; public boolean JD_ADD_BLANK_AFTER_DESCRIPTION = true; public boolean JD_P_AT_EMPTY_LINES = true; public boolean JD_KEEP_INVALID_TAGS = true; public boolean JD_KEEP_EMPTY_LINES = true; public boolean JD_DO_NOT_WRAP_ONE_LINE_COMMENTS = false; public boolean JD_USE_THROWS_NOT_EXCEPTION = true; public boolean JD_KEEP_EMPTY_PARAMETER = true; public boolean JD_KEEP_EMPTY_EXCEPTION = true; public boolean JD_KEEP_EMPTY_RETURN = true; public boolean JD_LEADING_ASTERISKS_ARE_ENABLED = true; // --------------------------------------------------------------------------------------- // ---------------------------------- XML formatting options ------------------------- public boolean XML_KEEP_WHITESPACES = false; public int XML_ATTRIBUTE_WRAP = WRAP_AS_NEEDED; public int XML_TEXT_WRAP = WRAP_AS_NEEDED; public boolean XML_KEEP_LINE_BREAKS = true; public boolean XML_KEEP_LINE_BREAKS_IN_TEXT = true; public int XML_KEEP_BLANK_LINES = 2; public boolean XML_ALIGN_ATTRIBUTES = true; public boolean XML_ALIGN_TEXT = false; public boolean XML_SPACE_AROUND_EQUALITY_IN_ATTRIBUTE = false; public boolean XML_SPACE_AFTER_TAG_NAME = false; public boolean XML_SPACE_INSIDE_EMPTY_TAG = false; // --------------------------------------------------------------------------------------- // ---------------------------------- HTML formatting options ------------------------- public boolean HTML_KEEP_WHITESPACES = false; public int HTML_ATTRIBUTE_WRAP = WRAP_AS_NEEDED; public int HTML_TEXT_WRAP = WRAP_AS_NEEDED; public boolean HTML_KEEP_LINE_BREAKS = true; public boolean HTML_KEEP_LINE_BREAKS_IN_TEXT = true; public int HTML_KEEP_BLANK_LINES = 2; public boolean HTML_ALIGN_ATTRIBUTES = true; public boolean HTML_ALIGN_TEXT = false; public boolean HTML_SPACE_AROUND_EQUALITY_IN_ATTRINUTE = false; public boolean HTML_SPACE_AFTER_TAG_NAME = false; public boolean HTML_SPACE_INSIDE_EMPTY_TAG = false; @NonNls public String HTML_ELEMENTS_TO_INSERT_NEW_LINE_BEFORE = "body,div,p,form,h1,h2,h3"; @NonNls public String HTML_ELEMENTS_TO_REMOVE_NEW_LINE_BEFORE = "br"; @NonNls public String HTML_DO_NOT_INDENT_CHILDREN_OF = "html,body"; public int HTML_DO_NOT_ALIGN_CHILDREN_OF_MIN_LINES = 100; @NonNls public String HTML_KEEP_WHITESPACES_INSIDE = "span,pre"; @NonNls public String HTML_INLINE_ELEMENTS = "a,abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,input,kbd,label,q,s,samp,select,span,strike,strong,sub,sup,textarea,tt,u,var"; @NonNls public String HTML_DONT_ADD_BREAKS_IF_INLINE_CONTENT = "title,h1,h2,h3,h4,h5,h6,p"; // --------------------------------------------------------------------------------------- // true if <%page import="x.y.z, x.y.t"%> // false if <%page import="x.y.z"%> // <%page import="x.y.t"%> public boolean JSP_PREFER_COMMA_SEPARATED_IMPORT_LIST = false; //---------------------------------------------------------------------------------------- //-------------- Annotation formatting settings------------------------------------------- public int METHOD_ANNOTATION_WRAP = WRAP_ALWAYS; public int CLASS_ANNOTATION_WRAP = WRAP_ALWAYS; public int FIELD_ANNOTATION_WRAP = WRAP_ALWAYS; public int PARAMETER_ANNOTATION_WRAP = DO_NOT_WRAP; public int VARIABLE_ANNOTATION_WRAP = DO_NOT_WRAP; public boolean SPACE_BEFORE_ANOTATION_PARAMETER_LIST = false; public boolean SPACE_WITHIN_ANNOTATION_PARENTHESES = false; //---------------------------------------------------------------------------------------- //-------------------------Enums---------------------------------------------------------- public int ENUM_CONSTANTS_WRAP = DO_NOT_WRAP; //---------------------------------------------------------------------------------------- private CodeStyleSettings myParentSettings; public void readExternal(Element element) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, element); importOldIndentOptions(element); for (final CustomCodeStyleSettings settings : myCustomSettings.values()) { settings.readExternal(element); } final List list = element.getChildren(ADDITIONAL_INDENT_OPTIONS); if (list != null) { for(Object o:list) { if (o instanceof Element) { final Element additionalIndentElement = (Element)o; final String fileTypeId = additionalIndentElement.getAttributeValue(FILETYPE); if (fileTypeId != null) { FileType target = FileTypeManager.getInstance().getFileTypeByExtension(fileTypeId); final IndentOptions options = new IndentOptions(); options.readExternal(additionalIndentElement); registerAdditionalIndentOptions(target, options); } } } } copyOldIndentOptions("java", JAVA_INDENT_OPTIONS); copyOldIndentOptions("jsp", JSP_INDENT_OPTIONS); copyOldIndentOptions("xml", XML_INDENT_OPTIONS); } private void copyOldIndentOptions(@NonNls final String extension, final IndentOptions options) { final FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(extension); if (fileType != FileTypes.UNKNOWN && !ourAdditionalIndentOptions.containsKey(fileType)) { registerAdditionalIndentOptions(fileType, options); } } private void importOldIndentOptions(@NonNls Element element) { final List options = element.getChildren("option"); for (Object option1 : options) { @NonNls Element option = (Element)option1; @NonNls final String name = option.getAttributeValue("name"); if ("TAB_SIZE".equals(name)) { final int value = Integer.valueOf(option.getAttributeValue("value")).intValue(); JAVA_INDENT_OPTIONS.TAB_SIZE = value; JSP_INDENT_OPTIONS.TAB_SIZE = value; XML_INDENT_OPTIONS.TAB_SIZE = value; OTHER_INDENT_OPTIONS.TAB_SIZE = value; } else if ("INDENT_SIZE".equals(name)) { final int value = Integer.valueOf(option.getAttributeValue("value")).intValue(); JAVA_INDENT_OPTIONS.INDENT_SIZE = value; JSP_INDENT_OPTIONS.INDENT_SIZE = value; XML_INDENT_OPTIONS.INDENT_SIZE = value; OTHER_INDENT_OPTIONS.INDENT_SIZE = value; } else if ("CONTINUATION_INDENT_SIZE".equals(name)) { final int value = Integer.valueOf(option.getAttributeValue("value")).intValue(); JAVA_INDENT_OPTIONS.CONTINUATION_INDENT_SIZE = value; JSP_INDENT_OPTIONS.CONTINUATION_INDENT_SIZE = value; XML_INDENT_OPTIONS.CONTINUATION_INDENT_SIZE = value; OTHER_INDENT_OPTIONS.CONTINUATION_INDENT_SIZE = value; } else if ("USE_TAB_CHARACTER".equals(name)) { final boolean value = Boolean.valueOf(option.getAttributeValue("value")).booleanValue(); JAVA_INDENT_OPTIONS.USE_TAB_CHARACTER = value; JSP_INDENT_OPTIONS.USE_TAB_CHARACTER = value; XML_INDENT_OPTIONS.USE_TAB_CHARACTER = value; OTHER_INDENT_OPTIONS.USE_TAB_CHARACTER = value; } else if ("SMART_TABS".equals(name)) { final boolean value = Boolean.valueOf(option.getAttributeValue("value")).booleanValue(); JAVA_INDENT_OPTIONS.SMART_TABS = value; JSP_INDENT_OPTIONS.SMART_TABS = value; XML_INDENT_OPTIONS.SMART_TABS = value; OTHER_INDENT_OPTIONS.SMART_TABS = value; } } } public void writeExternal(Element element) throws WriteExternalException { final CodeStyleSettings parentSettings = new CodeStyleSettings(); DefaultJDOMExternalizer.writeExternal(this, element, new DifferenceFilter<CodeStyleSettings>(this, parentSettings)); for (final CustomCodeStyleSettings settings : myCustomSettings.values()) { final CustomCodeStyleSettings parentCustomSettings = parentSettings.getCustomSettings(settings.getClass()); assert parentCustomSettings != null; settings.writeExternal(element, parentCustomSettings); } final FileType[] fileTypes = ourAdditionalIndentOptions.keySet().toArray(new FileType[ourAdditionalIndentOptions.keySet().size()]); Arrays.sort(fileTypes, new Comparator<FileType>() { public int compare(final FileType o1, final FileType o2) { return o1.getDefaultExtension().compareTo(o2.getDefaultExtension()); } }); for (FileType fileType : fileTypes) { final IndentOptions indentOptions = ourAdditionalIndentOptions.get(fileType); Element additionalIndentOptions = new Element(ADDITIONAL_INDENT_OPTIONS); indentOptions.writeExternal(additionalIndentOptions); additionalIndentOptions.setAttribute(FILETYPE,fileType.getDefaultExtension()); element.addContent(additionalIndentOptions); } } public IndentOptions getIndentOptions(FileType fileType) { if (USE_SAME_INDENTS || fileType == null) return OTHER_INDENT_OPTIONS; final IndentOptions indentOptions = ourAdditionalIndentOptions.get(fileType); if (indentOptions != null) return indentOptions; return OTHER_INDENT_OPTIONS; } public boolean isSmartTabs(FileType fileType) { return getIndentOptions(fileType).SMART_TABS; } public int getIndentSize(FileType fileType) { return getIndentOptions(fileType).INDENT_SIZE; } public int getContinuationIndentSize(FileType fileType) { return getIndentOptions(fileType).CONTINUATION_INDENT_SIZE; } public int getLabelIndentSize(FileType fileType) { return getIndentOptions(fileType).LABEL_INDENT_SIZE; } public boolean getLabelIndentAbsolute(FileType fileType) { return getIndentOptions(fileType).LABEL_INDENT_ABSOLUTE; } public int getTabSize(FileType fileType) { return getIndentOptions(fileType).TAB_SIZE; } public boolean useTabCharacter(FileType fileType) { return getIndentOptions(fileType).USE_TAB_CHARACTER; } public static class TypeToNameMap implements JDOMExternalizable, Cloneable { private ArrayList<String> myPatterns = new ArrayList<String>(); private ArrayList<String> myNames = new ArrayList<String>(); public void addPair(String pattern, String name) { myPatterns.add(pattern); myNames.add(name); } public String nameByType(String type) { for (int i = 0; i < myPatterns.size(); i++) { String pattern = myPatterns.get(i); if (StringUtil.startsWithChar(pattern, '*')) { if (type.endsWith(pattern.substring(1))) { return myNames.get(i); } } else { if (type.equals(pattern)) { return myNames.get(i); } } } return null; } public void readExternal(@NonNls Element element) throws InvalidDataException { myPatterns.clear(); myNames.clear(); for (final Object o : element.getChildren("pair")) { @NonNls Element e = (Element)o; String pattern = e.getAttributeValue("type"); String name = e.getAttributeValue("name"); if (pattern == null || name == null) { throw new InvalidDataException(); } myPatterns.add(pattern); myNames.add(name); } } public void writeExternal(Element parentNode) throws WriteExternalException { for (int i = 0; i < myPatterns.size(); i++) { String pattern = myPatterns.get(i); String name = myNames.get(i); @NonNls Element element = new Element("pair"); parentNode.addContent(element); element.setAttribute("type", pattern); element.setAttribute("name", name); } } public Object clone() throws CloneNotSupportedException { TypeToNameMap clon = (TypeToNameMap)TypeToNameMap.super.clone(); clon.myPatterns = (ArrayList<String>)myPatterns.clone(); clon.myNames = (ArrayList<String>)myNames.clone(); return clon; } public boolean equals(Object other) { if (other instanceof TypeToNameMap) { TypeToNameMap otherMap = (TypeToNameMap)other; if (myPatterns.size() != otherMap.myPatterns.size()) { return false; } if (myNames.size() != otherMap.myNames.size()) { return false; } for (int i = 0; i < myPatterns.size(); i++) { String s1 = myPatterns.get(i); String s2 = otherMap.myPatterns.get(i); if (!Comparing.equal(s1, s2)) { return false; } } for (int i = 0; i < myNames.size(); i++) { String s1 = myNames.get(i); String s2 = otherMap.myNames.get(i); if (!Comparing.equal(s1, s2)) { return false; } } return true; } return false; } public int hashCode() { int code = 0; for (String myPattern : myPatterns) { code += myPattern.hashCode(); } for (String myName : myNames) { code += myName.hashCode(); } return code; } } public static class PackageTable implements JDOMExternalizable, Cloneable { public static class Entry implements Cloneable { final String packageName; final boolean withSubpackages; public Entry(@NonNls String packageName, boolean withSubpackages) { this.packageName = packageName; this.withSubpackages = withSubpackages; } public String getPackageName() { return packageName; } public boolean isWithSubpackages() { return withSubpackages; } public boolean equals(Object obj) { if (!(obj instanceof Entry)) { return false; } Entry entry = (Entry)obj; return entry.withSubpackages == withSubpackages && Comparing.equal(entry.packageName, packageName); } public int hashCode() { if (packageName == null) { return 0; } return packageName.hashCode(); } } private ArrayList<Entry> myEntries = new ArrayList<Entry>(); public boolean equals(Object obj) { if (!(obj instanceof PackageTable)) { return false; } PackageTable other = (PackageTable)obj; if (other.myEntries.size() != myEntries.size()) { return false; } for (int i = 0; i < myEntries.size(); i++) { Entry entry = myEntries.get(i); Entry otherentry = other.myEntries.get(i); if (!Comparing.equal(entry, otherentry)) { return false; } } return true; } public int hashCode() { if (!myEntries.isEmpty() && myEntries.get(0) != null) { return myEntries.get(0).hashCode(); } return 0; } public Object clone() throws CloneNotSupportedException { PackageTable clon = (PackageTable)PackageTable.super.clone(); clon.myEntries = (ArrayList<Entry>)myEntries.clone(); return clon; } public void copyFrom(PackageTable packageTable) { myEntries = (ArrayList<Entry>)packageTable.myEntries.clone(); } public Entry[] getEntries() { return myEntries.toArray(new Entry[myEntries.size()]); } public void insertEntryAt(Entry entry, int i) { myEntries.add(i, entry); } public void removeEntryAt(int i) { myEntries.remove(i); } public Entry getEntryAt(int i) { return myEntries.get(i); } public int getEntryCount() { return myEntries.size(); } public void setEntryAt(Entry entry, int i) { myEntries.set(i, entry); } public boolean contains(String packageName) { for (Entry entry : myEntries) { if (packageName.startsWith(entry.packageName)) { if (packageName.length() == entry.packageName.length()) return true; if (entry.withSubpackages) { if (packageName.charAt(entry.packageName.length()) == '.') return true; } } } return false; } public void readExternal(@NonNls Element element) throws InvalidDataException { myEntries.clear(); for (final Object o : element.getChildren("package")) { @NonNls Element e = (Element)o; String packageName = e.getAttributeValue("name"); boolean withSubpackages = Boolean.parseBoolean(e.getAttributeValue("withSubpackages")); if (packageName == null) { throw new InvalidDataException(); } myEntries.add(new Entry(packageName, withSubpackages)); } } public void writeExternal(Element parentNode) throws WriteExternalException { for (Entry entry : myEntries) { @NonNls Element element = new Element("package"); parentNode.addContent(element); element.setAttribute("name", entry.packageName); element.setAttribute("withSubpackages", Boolean.toString(entry.withSubpackages)); } } } public static class ImportLayoutTable implements JDOMExternalizable, Cloneable { private ArrayList<Entry> myEntries = new ArrayList<Entry>(); public interface Entry { } public static class PackageEntry implements Entry { private final String myPackageName; private final boolean myWithSubpackages; public PackageEntry(@NonNls String packageName, boolean withSubpackages) { myPackageName = packageName; myWithSubpackages = withSubpackages; } public String getPackageName() { return myPackageName; } public boolean isWithSubpackages() { return myWithSubpackages; } public boolean matchesPackageName(String packageName) { if (myPackageName.length() == 0 && myWithSubpackages) return true; if (packageName.startsWith(myPackageName)) { if (packageName.length() == myPackageName.length()) return true; if (myWithSubpackages) { if (packageName.charAt(myPackageName.length()) == '.') return true; } } return false; } public boolean matchesClassName(String className) { int dotIndex = className.lastIndexOf('.'); String packageName = dotIndex < 0 ? "" : className.substring(0, dotIndex); return matchesPackageName(packageName); } public boolean equals(Object obj) { if (!(obj instanceof PackageEntry)) { return false; } PackageEntry entry = (PackageEntry)obj; return entry.myWithSubpackages == myWithSubpackages && Comparing.equal(entry.myPackageName, myPackageName); } public int hashCode() { if (myPackageName == null) { return 0; } return myPackageName.hashCode(); } } public static class EmptyLineEntry implements Entry { public boolean equals(Object obj) { return obj instanceof EmptyLineEntry; } public int hashCode() { return 100; } } public void copyFrom(ImportLayoutTable importLayoutTable) { myEntries = (ArrayList<Entry>)importLayoutTable.myEntries.clone(); } public Entry[] getEntries() { return myEntries.toArray(new Entry[myEntries.size()]); } public void insertEntryAt(Entry entry, int i) { myEntries.add(i, entry); } public void removeEntryAt(int i) { myEntries.remove(i); } public Entry getEntryAt(int i) { return myEntries.get(i); } public int getEntryCount() { return myEntries.size(); } public void setEntryAt(Entry entry, int i) { myEntries.set(i, entry); } public void readExternal(Element element) throws InvalidDataException { myEntries.clear(); List children = element.getChildren(); for (final Object aChildren : children) { @NonNls Element e = (Element)aChildren; @NonNls String name = e.getName(); if ("package".equals(name)) { String packageName = e.getAttributeValue("name"); boolean withSubpackages = Boolean.parseBoolean(e.getAttributeValue("withSubpackages")); if (packageName == null) { throw new InvalidDataException(); } myEntries.add(new PackageEntry(packageName, withSubpackages)); } else { if ("emptyLine".equals(name)) { myEntries.add(new EmptyLineEntry()); } } } } public void writeExternal(Element parentNode) throws WriteExternalException { for (Entry myEntry : myEntries) { if (myEntry instanceof PackageEntry) { PackageEntry entry = (PackageEntry)myEntry; @NonNls Element element = new Element("package"); parentNode.addContent(element); element.setAttribute("name", entry.getPackageName()); element.setAttribute("withSubpackages", entry.isWithSubpackages() ? "true" : "false"); } else { if (myEntry instanceof EmptyLineEntry) { @NonNls Element element = new Element("emptyLine"); parentNode.addContent(element); } } } } public boolean equals(Object obj) { if (!(obj instanceof ImportLayoutTable)) { return false; } ImportLayoutTable other = (ImportLayoutTable)obj; if (other.myEntries.size() != myEntries.size()) { return false; } for (int i = 0; i < myEntries.size(); i++) { Entry entry = myEntries.get(i); Entry otherentry = other.myEntries.get(i); if (!Comparing.equal(entry, otherentry)) { return false; } } return true; } public int hashCode() { if (!myEntries.isEmpty() && myEntries.get(0) != null) { return myEntries.get(0).hashCode(); } return 0; } public Object clone() throws CloneNotSupportedException { ImportLayoutTable clon = (ImportLayoutTable)ImportLayoutTable.super.clone(); clon.myEntries = (ArrayList<Entry>)myEntries.clone(); return clon; } } private void registerAdditionalIndentOptions(FileType fileType, IndentOptions options) { ourAdditionalIndentOptions.put(fileType, options); } public IndentOptions getAdditionalIndentOptions(FileType fileType) { IndentOptions result = ourAdditionalIndentOptions.get(fileType); if (result == null) { final FileTypeIndentOptionsProvider[] fileTypeIndentOptionsProviders = Extensions.getExtensions(FileTypeIndentOptionsProvider.EP_NAME); for (final FileTypeIndentOptionsProvider provider : fileTypeIndentOptionsProviders) { if (fileType == provider.getFileType()) { result = provider.createIndentOptions(); registerAdditionalIndentOptions(provider.getFileType(), result); } } } return result; } }
IDEADEV-27424 fixed
lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettings.java
IDEADEV-27424 fixed
<ide><path>ang-api/src/com/intellij/psi/codeStyle/CodeStyleSettings.java <ide> public void writeExternal(Element element) throws WriteExternalException { <ide> final CodeStyleSettings parentSettings = new CodeStyleSettings(); <ide> DefaultJDOMExternalizer.writeExternal(this, element, new DifferenceFilter<CodeStyleSettings>(this, parentSettings)); <del> for (final CustomCodeStyleSettings settings : myCustomSettings.values()) { <add> List<CustomCodeStyleSettings> customSettings = new ArrayList<CustomCodeStyleSettings>(myCustomSettings.values()); <add> <add> Collections.sort(customSettings, new Comparator<CustomCodeStyleSettings>(){ <add> public int compare(final CustomCodeStyleSettings o1, final CustomCodeStyleSettings o2) { <add> return o1.getTagName().compareTo(o2.getTagName()); <add> } <add> }); <add> <add> for (final CustomCodeStyleSettings settings : customSettings) { <ide> final CustomCodeStyleSettings parentCustomSettings = parentSettings.getCustomSettings(settings.getClass()); <ide> assert parentCustomSettings != null; <ide> settings.writeExternal(element, parentCustomSettings);
Java
apache-2.0
25839434729cb1a1fc2237b799e8e855cd1a9edc
0
apache/tinkerpop,velo/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,edgarRd/incubator-tinkerpop,samiunn/incubator-tinkerpop,vtslab/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,krlohnes/tinkerpop,velo/incubator-tinkerpop,pluradj/incubator-tinkerpop,vtslab/incubator-tinkerpop,robertdale/tinkerpop,newkek/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,artem-aliev/tinkerpop,rmagen/incubator-tinkerpop,jorgebay/tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,apache/incubator-tinkerpop,newkek/incubator-tinkerpop,rmagen/incubator-tinkerpop,krlohnes/tinkerpop,vtslab/incubator-tinkerpop,dalaro/incubator-tinkerpop,krlohnes/tinkerpop,krlohnes/tinkerpop,mike-tr-adamson/incubator-tinkerpop,edgarRd/incubator-tinkerpop,artem-aliev/tinkerpop,PommeVerte/incubator-tinkerpop,n-tran/incubator-tinkerpop,artem-aliev/tinkerpop,robertdale/tinkerpop,gdelafosse/incubator-tinkerpop,apache/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,edgarRd/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,n-tran/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,n-tran/incubator-tinkerpop,samiunn/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,jorgebay/tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,jorgebay/tinkerpop,krlohnes/tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,RussellSpitzer/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,newkek/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,jorgebay/tinkerpop,velo/incubator-tinkerpop,rmagen/incubator-tinkerpop,samiunn/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,apache/tinkerpop,BrynCooke/incubator-tinkerpop,dalaro/incubator-tinkerpop,robertdale/tinkerpop,BrynCooke/incubator-tinkerpop,artem-aliev/tinkerpop,robertdale/tinkerpop,dalaro/incubator-tinkerpop,robertdale/tinkerpop,apache/tinkerpop
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.process.graph.traversal; import org.apache.tinkerpop.gremlin.process.TraversalContext; import org.apache.tinkerpop.gremlin.process.TraversalEngine; import org.apache.tinkerpop.gremlin.process.TraversalStrategies; import org.apache.tinkerpop.gremlin.process.TraversalStrategy; import org.apache.tinkerpop.gremlin.process.computer.GraphComputer; import org.apache.tinkerpop.gremlin.process.graph.traversal.step.sideEffect.GraphStep; import org.apache.tinkerpop.gremlin.process.traversal.engine.ComputerTraversalEngine; import org.apache.tinkerpop.gremlin.process.traversal.engine.StandardTraversalEngine; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Transaction; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.util.StringFactory; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class GraphTraversalContext implements TraversalContext { public static final Builder standard = GraphTraversalContext.build().engine(StandardTraversalEngine.build()); public static final Builder computer = GraphTraversalContext.build().engine(ComputerTraversalEngine.build()); public static Builder computer(final Class<? extends GraphComputer> graphComputerClass) { return GraphTraversalContext.build().engine(ComputerTraversalEngine.build().computer(graphComputerClass)); } //// private final transient Graph graph; private final TraversalEngine.Builder engine; private final TraversalStrategies strategies; public GraphTraversalContext(final Graph graph, final TraversalEngine.Builder engine, final TraversalStrategy... strategies) { this.graph = graph; this.engine = engine; final TraversalStrategies temp = TraversalStrategies.GlobalCache.getStrategies(this.graph.getClass()); try { this.strategies = strategies.length == 0 ? temp : temp.clone().addStrategies(strategies); } catch (CloneNotSupportedException cnse) { // seems unlikely that this should happen so propogate as a runtime issue. throw new RuntimeException(cnse); } } public GraphTraversal<Vertex, Vertex> V(final Object... vertexIds) { final GraphTraversal.Admin<Vertex, Vertex> traversal = new DefaultGraphTraversal<>(this); traversal.setEngine(this.engine.create(this.graph)); traversal.setStrategies(this.strategies); return traversal.addStep(new GraphStep<>(traversal, this.graph, Vertex.class, vertexIds)); } public GraphTraversal<Edge, Edge> E(final Object... edgesIds) { final GraphTraversal.Admin<Edge, Edge> traversal = new DefaultGraphTraversal<>(this); traversal.setEngine(this.engine.create(this.graph)); traversal.setStrategies(this.strategies); return traversal.addStep(new GraphStep<>(traversal, this.graph, Edge.class, edgesIds)); } public Transaction tx() { return this.graph.tx(); } public static Builder build() { return new Builder(); } @Override public Optional<GraphComputer> getGraphComputer() { return this.engine.create(this.graph).getGraphComputer(); } @Override public Optional<Graph> getGraph() { return Optional.ofNullable(this.graph); } @Override public GraphTraversalContext.Builder asBuilder() { return GraphTraversalContext.build().engine(this.engine); // TODO: add strategies } @Override public String toString() { return StringFactory.traversalContextString(this); } ////// public static class Builder implements TraversalContext.Builder<GraphTraversalContext> { private TraversalEngine.Builder engineBuilder = StandardTraversalEngine.build(); private List<TraversalStrategy> strategies = new ArrayList<>(); public Builder engine(final TraversalEngine.Builder engineBuilder) { this.engineBuilder = engineBuilder; return this; } public Builder strategy(final TraversalStrategy strategy) { this.strategies.add(strategy); return this; } public GraphTraversalContext create(final Graph graph) { return new GraphTraversalContext(graph, this.engineBuilder, this.strategies.toArray(new TraversalStrategy[this.strategies.size()])); } } }
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/graph/traversal/GraphTraversalContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.process.graph.traversal; import org.apache.tinkerpop.gremlin.process.TraversalContext; import org.apache.tinkerpop.gremlin.process.TraversalEngine; import org.apache.tinkerpop.gremlin.process.TraversalStrategies; import org.apache.tinkerpop.gremlin.process.TraversalStrategy; import org.apache.tinkerpop.gremlin.process.computer.GraphComputer; import org.apache.tinkerpop.gremlin.process.graph.traversal.step.sideEffect.GraphStep; import org.apache.tinkerpop.gremlin.process.traversal.engine.ComputerTraversalEngine; import org.apache.tinkerpop.gremlin.process.traversal.engine.StandardTraversalEngine; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Transaction; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.util.StringFactory; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class GraphTraversalContext implements TraversalContext { public static final Builder standard = GraphTraversalContext.build().engine(StandardTraversalEngine.build()); public static final Builder computer = GraphTraversalContext.build().engine(ComputerTraversalEngine.build()); public static Builder computer(final Class<? extends GraphComputer> graphComputerClass) { return GraphTraversalContext.build().engine(ComputerTraversalEngine.build().computer(graphComputerClass)); } //// private final transient Graph graph; private final TraversalEngine.Builder engine; private final TraversalStrategies strategies; public GraphTraversalContext(final Graph graph, final TraversalEngine.Builder engine, final TraversalStrategy... strategies) { this.graph = graph; this.engine = engine; this.strategies = TraversalStrategies.GlobalCache.getStrategies(this.graph.getClass()).addStrategies(strategies); } public GraphTraversal<Vertex, Vertex> V(final Object... vertexIds) { final GraphTraversal.Admin<Vertex, Vertex> traversal = new DefaultGraphTraversal<>(this); traversal.setEngine(this.engine.create(this.graph)); traversal.setStrategies(this.strategies); return traversal.addStep(new GraphStep<>(traversal, this.graph, Vertex.class, vertexIds)); } public GraphTraversal<Edge, Edge> E(final Object... edgesIds) { final GraphTraversal.Admin<Edge, Edge> traversal = new DefaultGraphTraversal<>(this); traversal.setEngine(this.engine.create(this.graph)); traversal.setStrategies(this.strategies); return traversal.addStep(new GraphStep<>(traversal, this.graph, Edge.class, edgesIds)); } public Transaction tx() { return this.graph.tx(); } public static Builder build() { return new Builder(); } @Override public Optional<GraphComputer> getGraphComputer() { return this.engine.create(this.graph).getGraphComputer(); } @Override public Optional<Graph> getGraph() { return Optional.ofNullable(this.graph); } @Override public GraphTraversalContext.Builder asBuilder() { return GraphTraversalContext.build().engine(this.engine); // TODO: add strategies } @Override public String toString() { return StringFactory.traversalContextString(this); } ////// public static class Builder implements TraversalContext.Builder<GraphTraversalContext> { private TraversalEngine.Builder engineBuilder = StandardTraversalEngine.build(); private List<TraversalStrategy> strategies = new ArrayList<>(); public Builder engine(final TraversalEngine.Builder engineBuilder) { this.engineBuilder = engineBuilder; return this; } public Builder strategy(final TraversalStrategy strategy) { this.strategies.add(strategy); return this; } public GraphTraversalContext create(final Graph graph) { return new GraphTraversalContext(graph, this.engineBuilder, this.strategies.toArray(new TraversalStrategy[this.strategies.size()])); } } }
Strategies should be local to a context not added to the global strategy cache.
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/graph/traversal/GraphTraversalContext.java
Strategies should be local to a context not added to the global strategy cache.
<ide><path>remlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/graph/traversal/GraphTraversalContext.java <ide> public GraphTraversalContext(final Graph graph, final TraversalEngine.Builder engine, final TraversalStrategy... strategies) { <ide> this.graph = graph; <ide> this.engine = engine; <del> this.strategies = TraversalStrategies.GlobalCache.getStrategies(this.graph.getClass()).addStrategies(strategies); <add> final TraversalStrategies temp = TraversalStrategies.GlobalCache.getStrategies(this.graph.getClass()); <add> <add> try { <add> this.strategies = strategies.length == 0 ? temp : temp.clone().addStrategies(strategies); <add> } catch (CloneNotSupportedException cnse) { <add> // seems unlikely that this should happen so propogate as a runtime issue. <add> throw new RuntimeException(cnse); <add> } <ide> } <ide> <ide> public GraphTraversal<Vertex, Vertex> V(final Object... vertexIds) {
Java
apache-2.0
f751b1f5e6070aaaf3d14b679f528a4fb373c501
0
googlesamples/android-testdpc,googlesamples/android-testdpc
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.afwsamples.testdpc.feedback; import static android.util.Log.ERROR; import static android.util.Log.INFO; import static com.google.common.truth.Truth.assertThat; import static org.robolectric.Shadows.shadowOf; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.SharedPreferences; import android.os.Build.VERSION_CODES; import androidx.enterprise.feedback.KeyedAppState; import androidx.enterprise.feedback.ReceivedKeyedAppState; import androidx.preference.PreferenceManager; import com.afwsamples.testdpc.R; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; @RunWith(RobolectricTestRunner.class) @Config(minSdk=VERSION_CODES.N) // Feedback channel is supported from N onwards public class AppStatesServiceTest { private static final String REQUEST_SYNC_LOG_TEXT = "SYNC REQUESTED"; private static final ReceivedKeyedAppState STATE1 = ReceivedKeyedAppState.builder() .setPackageName("test.package") .setTimestamp(123L) .setSeverity(KeyedAppState.SEVERITY_INFO) .setKey("key1") .setMessage("message1") .setData("data1") .build(); private static final ReceivedKeyedAppState STATE1_DIFFERENT_MESSAGE = ReceivedKeyedAppState.builder() .setPackageName("test.package") .setTimestamp(123L) .setSeverity(KeyedAppState.SEVERITY_INFO) .setKey("key1") .setMessage("different message1") .setData("data1") .build(); private static final ReceivedKeyedAppState STATE2 = ReceivedKeyedAppState.builder() .setPackageName("test.package") .setTimestamp(123L) .setSeverity(KeyedAppState.SEVERITY_ERROR) .setKey("key2") .setMessage("message2") .setData("data2") .build(); private static final ReceivedKeyedAppState INFO_STATE = STATE1; private static final ReceivedKeyedAppState ERROR_STATE = STATE2; private final Context context = RuntimeEnvironment.application; private final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); private final NotificationManager notificationManager = context.getSystemService(NotificationManager.class); private final AppStatesService service = Robolectric.buildService(AppStatesService.class).get(); @Test public void onReceive_shouldNotNotify_noNotification() { setNotificationPreference(false); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); assertThat(shadowOf(notificationManager).getActiveNotifications()).isEmpty(); } @Test public void onReceive_shouldNotNotify_noLogs() { setNotificationPreference(false); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); assertThat(ShadowLog.getLogsForTag(AppStatesService.TAG)).isEmpty(); } @Test public void onReceive_shouldNotify_logContainsRequiredInformation() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); assertThatLogContainsRequiredInformation( ShadowLog.getLogsForTag(AppStatesService.TAG).get(0), STATE1); } private void assertThatLogContainsRequiredInformation( ShadowLog.LogItem logItem, ReceivedKeyedAppState state) { assertThat(logItem.msg).contains(Long.toString(state.timestamp())); assertThat(logItem.msg).contains(state.packageName()); assertThat(logItem.msg).contains(state.key()); assertThat(logItem.msg).contains(state.data()); assertThat(logItem.msg).contains(state.message()); } @Test public void onReceive_infoLog_shouldNotify_logIsInfoLevel() { setNotificationPreference(true); service.onReceive(Arrays.asList(INFO_STATE), /* requestSync= */ false); assertThat(ShadowLog.getLogsForTag(AppStatesService.TAG).get(0).type).isEqualTo(INFO); } @Test public void onReceive_errorLog_shouldNotify_logIsErrorLevel() { setNotificationPreference(true); service.onReceive(Arrays.asList(ERROR_STATE), /* requestSync= */ false); assertThat(ShadowLog.getLogsForTag(AppStatesService.TAG).get(0).type).isEqualTo(ERROR); } @Test public void onReceive_shouldNotify_noRequestSync_logDoesNotContainRequestSync() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); ShadowLog.LogItem logItem = ShadowLog.getLogsForTag(AppStatesService.TAG).get(0); assertThat(logItem.msg).doesNotContain(REQUEST_SYNC_LOG_TEXT); } @Test public void onReceive_shouldNotify_requestSync_logContainsRequestSync() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ true); ShadowLog.LogItem logItem = ShadowLog.getLogsForTag(AppStatesService.TAG).get(0); assertThat(logItem.msg).contains(REQUEST_SYNC_LOG_TEXT); } @Test public void onReceive_shouldNotify_oneLogPerState() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1, STATE2), /* requestSync= */ false); assertThat(ShadowLog.getLogsForTag(AppStatesService.TAG)).hasSize(2); } @Test public void onReceive_shouldNotify_notificationContainsRequiredInformation() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); assertThatNotificationContainsRequiredInformation( shadowOf(notificationManager).getAllNotifications().get(0), STATE1 ); } private void assertThatNotificationContainsRequiredInformation( Notification notification, ReceivedKeyedAppState state) { assertThat(shadowOf(notification).getContentTitle().toString()).contains(state.packageName()); assertThat(shadowOf(notification).getContentTitle().toString()).contains(state.key()); assertThat(shadowOf(notification).getContentText().toString()) .contains(Long.toString(state.timestamp())); assertThat(shadowOf(notification).getContentText().toString()).contains(state.data()); assertThat(shadowOf(notification).getContentText().toString()).contains(state.message()); } @Test public void onReceive_infoLog_shouldNotify_notificationTitleIncludesInfo() { setNotificationPreference(true); service.onReceive(Arrays.asList(INFO_STATE), /* requestSync= */ false); final Notification notification = shadowOf(notificationManager).getAllNotifications().get(0); assertThat( shadowOf(notification).getContentTitle().toString()).contains("INFO"); } @Test public void onReceive_errorLog_shouldNotify_notificationTitleIncludesError() { setNotificationPreference(true); service.onReceive(Arrays.asList(ERROR_STATE), /* requestSync= */ false); final Notification notification = shadowOf(notificationManager).getAllNotifications().get(0); assertThat( shadowOf(notification).getContentTitle().toString()).contains("ERROR"); } @Test public void onReceive_shouldNotify_noRequestSync_notificationDoesNotContainRequestSync() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); final Notification notification = shadowOf(notificationManager).getAllNotifications().get(0); assertThat( shadowOf(notification).getContentText().toString()).doesNotContain(REQUEST_SYNC_LOG_TEXT); } @Test public void onReceive_shouldNotify_requestSync_notificationContainsRequestSync() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ true); final Notification notification = shadowOf(notificationManager).getAllNotifications().get(0); assertThat(shadowOf(notification).getContentText().toString()).contains(REQUEST_SYNC_LOG_TEXT); } @Test public void onReceive_shouldNotify_oneNotificationPerKey() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1, STATE2), /* requestSync= */ false); assertThat(shadowOf(notificationManager).getAllNotifications()).hasSize(2); } @Test public void onReceive_multiple_shouldNotify_oneNotificationPerKey() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); service.onReceive(Arrays.asList(STATE2), /* requestSync= */ false); assertThat(shadowOf(notificationManager).getAllNotifications()).hasSize(2); } @Test public void onReceive_shouldNotify_sameKeyUpdatesNotification() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); service.onReceive(Arrays.asList(STATE1_DIFFERENT_MESSAGE), /* requestSync= */ false); assertThat(shadowOf(notificationManager).getAllNotifications()).hasSize(1); } private void setNotificationPreference(boolean shouldNotify) { preferences.edit() .putBoolean(context.getString(R.string.app_feedback_notifications), shouldNotify) .commit(); } }
app/src/test/java/com/afwsamples/testdpc/feedback/AppStatesServiceTest.java
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.afwsamples.testdpc.feedback; import static android.util.Log.ERROR; import static android.util.Log.INFO; import static com.google.common.truth.Truth.assertThat; import static org.robolectric.Shadows.shadowOf; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.SharedPreferences; import android.os.Build.VERSION_CODES; import android.support.v7.preference.PreferenceManager; import androidx.enterprise.feedback.KeyedAppState; import androidx.enterprise.feedback.ReceivedKeyedAppState; import com.afwsamples.testdpc.R; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowNotification; import org.robolectric.shadows.ShadowNotificationManager; @RunWith(RobolectricTestRunner.class) @Config(minSdk=VERSION_CODES.N) // Feedback channel is supported from N onwards public class AppStatesServiceTest { private static final String REQUEST_SYNC_LOG_TEXT = "SYNC REQUESTED"; private static final ReceivedKeyedAppState STATE1 = ReceivedKeyedAppState.builder() .setPackageName("test.package") .setTimestamp(123L) .setSeverity(KeyedAppState.SEVERITY_INFO) .setKey("key1") .setMessage("message1") .setData("data1") .build(); private static final ReceivedKeyedAppState STATE1_DIFFERENT_MESSAGE = ReceivedKeyedAppState.builder() .setPackageName("test.package") .setTimestamp(123L) .setSeverity(KeyedAppState.SEVERITY_INFO) .setKey("key1") .setMessage("different message1") .setData("data1") .build(); private static final ReceivedKeyedAppState STATE2 = ReceivedKeyedAppState.builder() .setPackageName("test.package") .setTimestamp(123L) .setSeverity(KeyedAppState.SEVERITY_ERROR) .setKey("key2") .setMessage("message2") .setData("data2") .build(); private static final ReceivedKeyedAppState INFO_STATE = STATE1; private static final ReceivedKeyedAppState ERROR_STATE = STATE2; private final Context context = RuntimeEnvironment.application; private final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); private final NotificationManager notificationManager = context.getSystemService(NotificationManager.class); private final AppStatesService service = Robolectric.buildService(AppStatesService.class).get(); @Test public void onReceive_shouldNotNotify_noNotification() { setNotificationPreference(false); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); assertThat(shadowOf(notificationManager).getActiveNotifications()).isEmpty(); } @Test public void onReceive_shouldNotNotify_noLogs() { setNotificationPreference(false); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); assertThat(ShadowLog.getLogsForTag(AppStatesService.TAG)).isEmpty(); } @Test public void onReceive_shouldNotify_logContainsRequiredInformation() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); assertThatLogContainsRequiredInformation( ShadowLog.getLogsForTag(AppStatesService.TAG).get(0), STATE1); } private void assertThatLogContainsRequiredInformation( ShadowLog.LogItem logItem, ReceivedKeyedAppState state) { assertThat(logItem.msg).contains(Long.toString(state.timestamp())); assertThat(logItem.msg).contains(state.packageName()); assertThat(logItem.msg).contains(state.key()); assertThat(logItem.msg).contains(state.data()); assertThat(logItem.msg).contains(state.message()); } @Test public void onReceive_infoLog_shouldNotify_logIsInfoLevel() { setNotificationPreference(true); service.onReceive(Arrays.asList(INFO_STATE), /* requestSync= */ false); assertThat(ShadowLog.getLogsForTag(AppStatesService.TAG).get(0).type).isEqualTo(INFO); } @Test public void onReceive_errorLog_shouldNotify_logIsErrorLevel() { setNotificationPreference(true); service.onReceive(Arrays.asList(ERROR_STATE), /* requestSync= */ false); assertThat(ShadowLog.getLogsForTag(AppStatesService.TAG).get(0).type).isEqualTo(ERROR); } @Test public void onReceive_shouldNotify_noRequestSync_logDoesNotContainRequestSync() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); ShadowLog.LogItem logItem = ShadowLog.getLogsForTag(AppStatesService.TAG).get(0); assertThat(logItem.msg).doesNotContain(REQUEST_SYNC_LOG_TEXT); } @Test public void onReceive_shouldNotify_requestSync_logContainsRequestSync() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ true); ShadowLog.LogItem logItem = ShadowLog.getLogsForTag(AppStatesService.TAG).get(0); assertThat(logItem.msg).contains(REQUEST_SYNC_LOG_TEXT); } @Test public void onReceive_shouldNotify_oneLogPerState() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1, STATE2), /* requestSync= */ false); assertThat(ShadowLog.getLogsForTag(AppStatesService.TAG)).hasSize(2); } @Test public void onReceive_shouldNotify_notificationContainsRequiredInformation() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); assertThatNotificationContainsRequiredInformation( shadowOf(notificationManager).getAllNotifications().get(0), STATE1 ); } private void assertThatNotificationContainsRequiredInformation( Notification notification, ReceivedKeyedAppState state) { assertThat(shadowOf(notification).getContentTitle().toString()).contains(state.packageName()); assertThat(shadowOf(notification).getContentTitle().toString()).contains(state.key()); assertThat(shadowOf(notification).getContentText().toString()) .contains(Long.toString(state.timestamp())); assertThat(shadowOf(notification).getContentText().toString()).contains(state.data()); assertThat(shadowOf(notification).getContentText().toString()).contains(state.message()); } @Test public void onReceive_infoLog_shouldNotify_notificationTitleIncludesInfo() { setNotificationPreference(true); service.onReceive(Arrays.asList(INFO_STATE), /* requestSync= */ false); final Notification notification = shadowOf(notificationManager).getAllNotifications().get(0); assertThat( shadowOf(notification).getContentTitle().toString()).contains("INFO"); } @Test public void onReceive_errorLog_shouldNotify_notificationTitleIncludesError() { setNotificationPreference(true); service.onReceive(Arrays.asList(ERROR_STATE), /* requestSync= */ false); final Notification notification = shadowOf(notificationManager).getAllNotifications().get(0); assertThat( shadowOf(notification).getContentTitle().toString()).contains("ERROR"); } @Test public void onReceive_shouldNotify_noRequestSync_notificationDoesNotContainRequestSync() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); final Notification notification = shadowOf(notificationManager).getAllNotifications().get(0); assertThat( shadowOf(notification).getContentText().toString()).doesNotContain(REQUEST_SYNC_LOG_TEXT); } @Test public void onReceive_shouldNotify_requestSync_notificationContainsRequestSync() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ true); final Notification notification = shadowOf(notificationManager).getAllNotifications().get(0); assertThat(shadowOf(notification).getContentText().toString()).contains(REQUEST_SYNC_LOG_TEXT); } @Test public void onReceive_shouldNotify_oneNotificationPerKey() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1, STATE2), /* requestSync= */ false); assertThat(shadowOf(notificationManager).getAllNotifications()).hasSize(2); } @Test public void onReceive_multiple_shouldNotify_oneNotificationPerKey() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); service.onReceive(Arrays.asList(STATE2), /* requestSync= */ false); assertThat(shadowOf(notificationManager).getAllNotifications()).hasSize(2); } @Test public void onReceive_shouldNotify_sameKeyUpdatesNotification() { setNotificationPreference(true); service.onReceive(Arrays.asList(STATE1), /* requestSync= */ false); service.onReceive(Arrays.asList(STATE1_DIFFERENT_MESSAGE), /* requestSync= */ false); assertThat(shadowOf(notificationManager).getAllNotifications()).hasSize(1); } private void setNotificationPreference(boolean shouldNotify) { preferences.edit() .putBoolean(context.getString(R.string.app_feedback_notifications), shouldNotify) .commit(); } }
fix error in AppStatesServiceTest Test: ./gradlew test Change-Id: Icfa9e7aa5ce62bd2d355b0a2cb5b66b2da1df9b4
app/src/test/java/com/afwsamples/testdpc/feedback/AppStatesServiceTest.java
fix error in AppStatesServiceTest
<ide><path>pp/src/test/java/com/afwsamples/testdpc/feedback/AppStatesServiceTest.java <ide> import android.content.Context; <ide> import android.content.SharedPreferences; <ide> import android.os.Build.VERSION_CODES; <del>import android.support.v7.preference.PreferenceManager; <ide> import androidx.enterprise.feedback.KeyedAppState; <ide> import androidx.enterprise.feedback.ReceivedKeyedAppState; <add>import androidx.preference.PreferenceManager; <ide> import com.afwsamples.testdpc.R; <ide> import java.util.Arrays; <ide> import org.junit.Test; <ide> import org.robolectric.RuntimeEnvironment; <ide> import org.robolectric.annotation.Config; <ide> import org.robolectric.shadows.ShadowLog; <del>import org.robolectric.shadows.ShadowNotification; <del>import org.robolectric.shadows.ShadowNotificationManager; <ide> <ide> @RunWith(RobolectricTestRunner.class) <ide> @Config(minSdk=VERSION_CODES.N) // Feedback channel is supported from N onwards
JavaScript
apache-2.0
7b12302898a5eb052c47a931d28ee9513209a950
0
amcharts/export
/* Plugin Name: amCharts Export Description: Adds export capabilities to amCharts products Author: Benjamin Maertz, amCharts Version: 1.0 Author URI: http://www.amcharts.com/ Copyright 2015 amCharts Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Please note that the above license covers only this plugin. It by all means does not apply to any other amCharts products that are covered by different licenses. */ AmCharts.addInitHandler( function( chart ) { var _this = { name: "export", version: "1.0", libs: { autoLoad: true, path: "./plugins/export/libs/", resources: [ { "pdfmake/pdfmake.js": [ "pdfmake/vfs_fonts.js" ], "jszip/jszip.js": [ "xlsx/xlsx.js" ] }, "fabric.js/fabric.js", "FileSaver.js/FileSaver.js" ], loaded: 0 }, config: {}, setup: {}, drawing: { enabled: false, actions: [ "undo", "redo", "done", "cancel" ], undos: [], undo: function() { var last = _this.drawing.undos.pop(); if ( last ) { _this.drawing.redos.push( last ); last.path.remove(); } }, redos: [], redo: function() { var last = _this.drawing.redos.pop(); if ( last ) { _this.setup.fabric.add( last.path ); _this.drawing.undos.push( last ); } }, done: function() { _this.drawing.enabled = false; _this.drawing.undos = []; _this.drawing.redos = []; _this.setup.fabric.renderAll(); _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas" ); _this.createMenu( _this.config.menu ); } }, defaults: { position: "top-right", fileName: "amCharts", action: "download", formats: { JPG: { mimeType: "image/jpg", extension: "jpg", capture: true }, PNG: { mimeType: "image/png", extension: "png", capture: true }, SVG: { mimeType: "text/xml", extension: "svg", capture: true }, PDF: { mimeType: "application/pdf", extension: "pdf", capture: true }, CSV: { mimeType: "text/plain", extension: "csv" }, JSON: { mimeType: "text/plain", extension: "json" }, XLSX: { mimeType: "application/octet-stream", extension: "xlsx" } }, fabric: { backgroundColor: "#FFFFFF", isDrawingMode: false, selection: false, removeImages: true }, pdfMake: { pageSize: "A4", pageOrientation: "portrait", images: {}, content: [ { image: "reference", fit: [ 523.28, 769.89 ] } ] }, menu: [ { class: "export-main", label: "Export", menu: [ { label: "Download as ...", menu: [ "PNG", "JPG", "SVG", { format: "PDF", content: [ "Saved from:", window.location.href, { image: "reference", fit: [ 523.28, 769.89 ] // fit image to A4 } ] } ] }, { label: "Save data ...", menu: [ "CSV", "XLSX", "JSON" ] }, { label: "Annotate", action: "draw", menu: [ { class: "export-drawing", menu: [ { label: "Color ...", menu: [ { class: "export-drawing-color export-drawing-color-black", label: "Black", click: function() { this.setup.fabric.freeDrawingBrush.color = "#000"; } }, { class: "export-drawing-color export-drawing-color-white", label: "White", click: function() { this.setup.fabric.freeDrawingBrush.color = "#fff"; } }, { class: "export-drawing-color export-drawing-color-red", label: "Red", click: function() { this.setup.fabric.freeDrawingBrush.color = "#f00"; } }, { class: "export-drawing-color export-drawing-color-green", label: "Green", click: function() { this.setup.fabric.freeDrawingBrush.color = "#0f0"; } }, { class: "export-drawing-color export-drawing-color-blue", label: "Blue", click: function() { this.setup.fabric.freeDrawingBrush.color = "#00f"; } } ] }, "UNDO", "REDO", { label: "Save as ...", menu: [ "PNG", "JPG", "SVG", { format: "PDF", content: [ "Saved from:", window.location.href, { image: "reference", fit: [ 523.28, 769.89 ] // fit image to A4 } ] } ] }, { format: "PRINT", label: "Print" }, "CANCEL" ] } ] }, { format: "PRINT", label: "Print" } ] } ] }, download: function( data, type, filename ) { var blob = _this.toBlob( { data: data, type: type }, function( data ) { if ( window.saveAs ) { saveAs( data, filename ); } else { throw new Error( "Unable to create file. Ensure saveAs (FileSaver.js) is supported." ); } } ); return data; }, loadResource: function( src, addons ) { var node, url = src.indexOf( "//" ) != -1 ? src : [ _this.libs.path, src ].join( "" ); function callback() { _this.libs.loaded++; if ( addons ) { for ( i in addons ) { _this.loadResource( addons[ i ] ); } } } if ( src.indexOf( ".js" ) != -1 ) { node = document.createElement( "script" ); node.setAttribute( "type", "text/javascript" ); node.setAttribute( "src", url ); } else if ( src.indexOf( ".css" ) != -1 ) { node = document.createElement( "link" ); node.setAttribute( "type", "text/css" ); node.setAttribute( "rel", "stylesheet" ); node.setAttribute( "href", url ); } if ( node ) { node.addEventListener( "load", callback ); document.head.appendChild( node ); } else { callback(); } }, loadDependencies: function() { if ( !_this.libs.loaded && _this.libs.autoLoad ) { for ( i in _this.libs.resources ) { if ( typeof _this.libs.resources[ i ] == "object" ) { for ( i2 in _this.libs.resources[ i ] ) { var addons = _this.libs.resources[ i ][ i2 ]; _this.loadResource( i2, addons ); } } else { _this.loadResource( _this.libs.resources[ i ] ); } } } }, pxToNumber: function( attr ) { return Number( String( attr ).replace( "px", "" ) ) || 0; }, deepMerge: function( a, b, overwrite ) { for ( i in b ) { var v = b[ i ]; // NEW if ( a[ i ] == undefined || overwrite ) { if ( v instanceof Array ) { a[ i ] = new Array(); } else if ( v instanceof Function ) { a[ i ] = new Function(); } else if ( v instanceof Date ) { a[ i ] = new Date(); } else if ( v instanceof Object ) { a[ i ] = new Object(); } else if ( v instanceof Number ) { a[ i ] = new Number(); } else if ( v instanceof String ) { a[ i ] = new String(); } } if ( !( v instanceof Function || v instanceof Date ) && ( v instanceof Object || v instanceof Array ) ) { _this.deepMerge( a[ i ], v, overwrite ); } else { if ( a instanceof Array && !overwrite ) { a.push( v ); } else { a[ i ] = v; } } } return a; }, // CAPTURE EMOTIONAL MOMENT capture: function( options, callback ) { var cfg = _this.deepMerge( _this.deepMerge( {}, _this.config.fabric ), options || {} ); var i1, i2, i3 = 0; var groups = []; var offset = { x: 0, y: 0, width: _this.setup.chart.divRealWidth, height: _this.setup.chart.divRealHeight }; // GATHER SVGs var svgs = _this.setup.chart.containerDiv.getElementsByTagName( "svg" ); for ( i1 = 0; i1 < svgs.length; i1++ ) { var group = { svg: svgs[ i1 ], parent: svgs[ i1 ].parentNode, offset: { x: 0, y: 0 }, patterns: {}, clippings: {} } // GATHER CLIPPATHS; make them invisible var items = svgs[ i1 ].getElementsByTagName( "clipPath" ); for ( i2 = 0; i2 < items.length; i2++ ) { for ( i3 = 0; i3 < items[ i2 ].childNodes.length; i3++ ) { items[ i2 ].childNodes[ i3 ].setAttribute( "fill", "transparent" ); } group.clippings[ items[ i2 ].id ] = items[ i2 ]; } // GATHER PATTERNS var items = svgs[ i1 ].getElementsByTagName( "pattern" ); for ( i2 = 0; i2 < items.length; i2++ ) { var props = { node: items[ i2 ], source: items[ i2 ].getAttribute( "xlink:href" ), width: Number( items[ i2 ].getAttribute( "width" ) ), height: Number( items[ i2 ].getAttribute( "height" ) ), repeat: "repeat" } // REPLACE SOURCE var rect = items[ i2 ].getElementsByTagName( "rect" ); if ( rect.length > 0 ) { var IMG = new Image(); IMG.src = props.source; var PSC = new fabric.StaticCanvas( undefined, { width: props.width, height: props.height, backgroundColor: rect[ 0 ].getAttribute( "fill" ) } ); var RECT = new fabric.Rect( { width: props.width, height: props.height, fill: new fabric.Pattern( { source: IMG, repeat: "repeat" } ) } ); PSC.add( RECT ); props.source = PSC.toDataURL(); } // BUFFER PATTERN group.patterns[ items[ i2 ].id ] = new fabric.Pattern( props ); } // APPEND GROUP groups.push( group ); } // GATHER EXTERNAL LEGEND if ( _this.config.legend && _this.setup.chart.legend && _this.setup.chart.legend.position == "outside" ) { var group = { svg: _this.setup.chart.legend.container.container, parent: _this.setup.chart.legend.container.div, offset: { x: 0, y: 0 }, legend: { type: [ "top", "left" ].indexOf( _this.config.legend.position ) != -1 ? "unshift" : "push", position: _this.config.legend.position, width: _this.config.legend.width ? _this.config.legend.width : _this.setup.chart.legend.container.width, height: _this.config.legend.height ? _this.config.legend.height : _this.setup.chart.legend.container.height } } // Adapt canvas dimensions if ( [ "left", "right" ].indexOf( group.legend.position ) != -1 ) { offset.width += group.legend.width; offset.height = group.legend.height > offset.height ? group.legend.height : offset.height; } else if ( [ "top", "bottom" ].indexOf( group.legend.position ) != -1 ) { offset.height += group.legend.height; } // PRE/APPEND SVG groups[ group.legend.type ]( group ); } // STOCK CHART if ( _this.setup.chart.type == "stock" ) { if ( _this.setup.chart.leftContainer ) { offset.width -= _this.pxToNumber( _this.setup.chart.leftContainer.style.width ); _this.setup.wrapper.style.paddingLeft = _this.pxToNumber( _this.setup.chart.leftContainer.style.width ) + _this.setup.chart.panelsSettings.panelSpacing * 2; } if ( _this.setup.chart.rightContainer ) { offset.width -= _this.pxToNumber( _this.setup.chart.rightContainer.style.width ); _this.setup.wrapper.style.paddingRight = _this.pxToNumber( _this.setup.chart.rightContainer.style.width ) + _this.setup.chart.panelsSettings.panelSpacing * 2; } if ( _this.setup.chart.periodSelector && [ "top", "bottom" ].indexOf( _this.setup.chart.periodSelector.position ) != -1 ) { offset.height -= _this.setup.chart.periodSelector.offsetHeight + _this.setup.chart.panelsSettings.panelSpacing; } if ( _this.setup.chart.dataSetSelector && [ "top", "bottom" ].indexOf( _this.setup.chart.dataSetSelector.position ) != -1 ) { offset.height -= _this.setup.chart.dataSetSelector.offsetHeight; } } // CLEAR IF EXIST _this.drawing.enabled = cfg.isDrawingMode = ( cfg.drawing && cfg.drawing.enabled ) ? true : cfg.action == "draw"; if ( !_this.setup.wrapper ) { _this.setup.wrapper = document.createElement( "div" ); _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas" ); _this.setup.wrapper.appendChild( _this.setup.canvas ); } else { _this.setup.wrapper.innerHTML = ""; } _this.setup.canvas = document.createElement( "canvas" ); _this.setup.wrapper.appendChild( _this.setup.canvas ); _this.setup.fabric = new fabric.Canvas( _this.setup.canvas, _this.deepMerge( { width: offset.width, height: offset.height }, cfg ) ); _this.deepMerge( _this.setup.fabric, cfg ); // OBSERVE MOUSE _this.setup.fabric.on( "path:created", function( path ) { _this.drawing.undos.push( path ); } ); // DRAWING if ( _this.drawing.enabled ) { _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas active" ); } else { _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas" ); } for ( i1 = 0; i1 < groups.length; i1++ ) { var group = groups[ i1 ]; // GATHER POSITION if ( group.parent.style.top || group.parent.style.left ) { group.offset.y = _this.pxToNumber( group.parent.style.top ); group.offset.x = _this.pxToNumber( group.parent.style.left ); } else { // EXTERNAL LEGEND if ( group.legend ) { if ( group.legend.position == "left" ) { offset.x += chart.legend.container.width; } else if ( group.legend.position == "right" ) { group.offset.x += offset.width - group.legend.width; } else if ( group.legend.position == "top" ) { offset.y += group.legend.height; } else if ( group.legend.position == "bottom" ) { group.offset.y += offset.height - group.legend.height; // offset.y } // NORMAL } else { group.offset.x = offset.x; group.offset.y = offset.y; offset.y += _this.pxToNumber( group.parent.style.height ); } // PANEL if ( group.parent && ( group.parent.getAttribute( "class" ) || "" ).split( " " ).indexOf( "amChartsLegend" ) != -1 ) { offset.y += _this.pxToNumber( group.parent.parentNode.parentNode.style.marginTop ); group.offset.y += _this.pxToNumber( group.parent.parentNode.parentNode.style.marginTop ); } } // ADD TO CANVAS fabric.parseSVGDocument( group.svg, ( function( group ) { return function( objects, options ) { var g = fabric.util.groupSVGElements( objects, options ); var tmp = { top: group.offset.y, left: group.offset.x }; for ( i1 in g.paths ) { // OPACITY; TODO: Distinguish opacity types if ( g.paths[ i1 ] ) { // CHECK ORIGIN; REMOVE TAINTED if ( cfg.removeImages && g.paths[ i1 ][ "xlink:href" ] && g.paths[ i1 ][ "xlink:href" ].indexOf( location.origin ) == -1 ) { g.paths.splice( i1, 1 ); } // SET OPACITY if ( g.paths[ i1 ].fill instanceof Object ) { // MISINTERPRETATION OF FABRIC if ( g.paths[ i1 ].fill.type == "radial" ) { g.paths[ i1 ].fill.coords.r2 = g.paths[ i1 ].fill.coords.r1 * -1; g.paths[ i1 ].fill.coords.r1 = 0; } g.paths[ i1 ].set( { opacity: g.paths[ i1 ].fillOpacity } ); // PATTERN; TODO: Distinguish opacity types } else if ( String( g.paths[ i1 ].fill ).slice( 0, 3 ) == "url" ) { var PID = g.paths[ i1 ].fill.slice( 5, -1 ); if ( group.patterns[ PID ] ) { g.paths[ i1 ].set( { fill: group.patterns[ PID ], opacity: g.paths[ i1 ].fillOpacity } ); } } if ( String( g.paths[ i1 ].clipPath ).slice( 0, 3 ) == "url" ) { var PID = g.paths[ i1 ].clipPath.slice( 5, -1 ); if ( group.clippings[ PID ] ) { var mask = group.clippings[ PID ].childNodes[ 0 ]; var transform = g.paths[ i1 ].svg.getAttribute( "transform" ) || "translate(0,0)"; transform = transform.slice( 10, -1 ).split( "," ); g.paths[ i1 ].set( { clipTo: ( function( mask, transform ) { return function( ctx ) { var width = Number( mask.getAttribute( "width" ) || "0" ); var height = Number( mask.getAttribute( "height" ) || "0" ); var x = Number( mask.getAttribute( "x" ) || "0" ); var y = Number( mask.getAttribute( "y" ) || "0" ); ctx.rect( Number( transform[ 0 ] ) * -1 + x, Number( transform[ 1 ] ) * -1 + y, width, height ); } } )( mask, transform ) } ); } } } } g.set( tmp ); _this.setup.fabric.add( g ); // ADD BALLOONS var balloons = group.svg.parentNode.getElementsByClassName( "amcharts-balloon-div" ); for ( i = 0; i < balloons.length; i++ ) { if ( cfg.balloonFunction instanceof Function ) { cfg.balloonFunction.apply( _this, [ balloons[ i ], group ] ); } else { var parent = balloons[ i ]; var text = parent.childNodes[ 0 ]; var label = new fabric.Text( text.innerText || text.innerHTML, { fontSize: _this.pxToNumber( text.style.fontSize ), fontFamily: text.style.fontFamily, fill: text.style.color, top: _this.pxToNumber( parent.style.top ) + group.offset.y, left: _this.pxToNumber( parent.style.left ) + group.offset.x } ); _this.setup.fabric.add( label ); } } if ( group.svg.nextSibling && group.svg.nextSibling.tagName == "A" ) { var label = new fabric.Text( group.svg.nextSibling.innerText || group.svg.nextSibling.innerHTML, { fontSize: _this.pxToNumber( group.svg.nextSibling.style.fontSize ), fontFamily: group.svg.nextSibling.style.fontFamily, fill: group.svg.nextSibling.style.color, top: _this.pxToNumber( group.svg.nextSibling.style.top ) + group.offset.y, left: _this.pxToNumber( group.svg.nextSibling.style.left ) + group.offset.x } ); _this.setup.fabric.add( label ); } groups.pop(); if ( !groups.length ) { _this.handleCallback( callback ); } } // Identify elements through classnames } )( group ), function( svg, obj ) { var className = svg.getAttribute( "class" ) || svg.parentNode.getAttribute( "class" ) || ""; var visibility = svg.getAttribute( "visibility" ) || svg.parentNode.getAttribute( "visibility" ) || svg.parentNode.parentNode.getAttribute( "visibility" ) || ""; var clipPath = svg.getAttribute( "clip-path" ) || svg.parentNode.getAttribute( "clip-path" ) || ""; obj.className = className; obj.clipPath = clipPath; obj.svg = svg; // HIDE HIDDEN ELEMENTS; TODO: Find a better way to handle that if ( visibility == "hidden" ) { obj.opacity = 0; // WALKTHROUGH ELEMENTS } else { // TRANSPORT FILL/STROKE OPACITY var attrs = [ "fill", "stroke" ]; for ( i1 in attrs ) { var attr = attrs[ i1 ] var attrVal = String( svg.getAttribute( attr ) || "" ); var attrOpacity = Number( svg.getAttribute( attr + "-opacity" ) || "1" ); var attrRGBA = fabric.Color.fromHex( attrVal ).getSource(); // EXCEPTION if ( obj.className == "amcharts-guide-fill" && !attrVal ) { attrOpacity = 0; attrRGBA = fabric.Color.fromHex( "#000000" ).getSource(); } if ( attrRGBA ) { attrRGBA.pop(); attrRGBA.push( attrOpacity ) obj[ attr ] = "rgba(" + attrRGBA.join() + ")"; obj[ _this.capitalize( attr + "-opacity" ) ] = attrOpacity; } } } } ); } }, toCanvas: function( options, callback ) { var cfg = _this.deepMerge( { // Nuffin }, options || {} ); var data = _this.setup.canvas; _this.handleCallback( callback, data ); return data; }, toBlob: function( options, callback ) { var cfg = _this.deepMerge( { data: "empty", type: "text/plain" }, options || {} ); var isBase64 = /^data:.+;base64,(.*)$/.exec( cfg.data ); // GATHER BODY if ( isBase64 ) { cfg.data = isBase64[ 0 ]; cfg.type = cfg.data.slice( 5, cfg.data.indexOf( "," ) - 7 ); cfg.data = _this.toByteArray( { data: cfg.data.slice( cfg.data.indexOf( "," ) + 1, cfg.data.length ) } ); } if ( cfg.getByteArray ) { data = cfg.data; } else { data = new Blob( [ cfg.data ], { type: cfg.type } ); } _this.handleCallback( callback, data ); return data; }, toJPG: function( options, callback ) { var cfg = _this.deepMerge( { format: "jpeg", quality: 1, multiplier: 1, background: "#FF00FF" }, options || {} ); var data = _this.setup.fabric.toDataURL( cfg ); _this.handleCallback( callback, data ); return data; }, toPNG: function( options, callback ) { var cfg = _this.deepMerge( { format: "png", quality: 1, multiplier: 1 }, options || {} ); var data = _this.setup.fabric.toDataURL( cfg ); _this.handleCallback( callback, data ); return data; }, toSVG: function( options, callback ) { var cfg = _this.deepMerge( { // nothing in here }, options || {} ); var data = _this.setup.fabric.toSVG( cfg ); _this.handleCallback( callback, data ); return data; }, toPDF: function( options, callback ) { var cfg = _this.deepMerge( _this.deepMerge( { multiplier: 2 }, _this.config.pdfMake ), options || {}, true ); cfg.images.reference = _this.toPNG( cfg ); var data = new pdfMake.createPdf( cfg ); if ( callback ) { data.getDataUrl( ( function( callback ) { return function() { callback.apply( _this, arguments ); } } )( callback ) ); } return data; }, toPRINT: function( options, callback ) { var cfg = _this.deepMerge( { // nothing in here }, options || {} ); var data = _this.toPNG( cfg ); var states = []; var items = document.body.childNodes; var img = document.createElement( "img" ); img.src = data; img.setAttribute( "style", "width: 100%; max-height: 100%;" ); for ( i in items ) { if ( items[ i ].nodeType === 1 ) { states[ i ] = items[ i ].style.display; items[ i ].style.display = "none"; } } document.body.appendChild( img ); window.print(); for ( i in items ) { if ( items[ i ].nodeType === 1 ) { items[ i ].style.display = states[ i ]; } } img.remove(); _this.handleCallback( callback, data ); return true; }, toJSON: function( options, callback ) { var cfg = _this.deepMerge( { data: _this.getChartData() }, options || {}, true ); var data = JSON.stringify( cfg.data, undefined, "\t" ); _this.handleCallback( callback, data ); return data; }, toCSV: function( options, callback ) { var cfg = _this.deepMerge( { data: _this.getChartData(), delimiter: ",", quotes: true, escape: true, dateFields: [], dateFormat: _this.setup.chart.dataDateFormat || "YYYY-MM-DD" }, options || {}, true ); var data = ""; if ( _this.setup.chart.categoryAxis && _this.setup.chart.categoryAxis.parseDates && _this.setup.chart.categoryField ) { cfg.dateFields.push( _this.setup.chart.categoryField ); } for ( row in cfg.data ) { var buffer = []; for ( col in cfg.data[ row ] ) { var value = cfg.data[ row ][ col ]; // HEADER if ( row == 0 ) { value = col; // BODY } else { if ( typeof value === "string" ) { value = value; } else if ( cfg.dateFormat && value instanceof Date && cfg.dateFields.indexOf( col ) != -1 ) { value = AmCharts.formatDate( value, cfg.dateFormat ); } } // WRAP IN QUOTES if ( typeof value === "string" ) { if ( cfg.escape ) { value = value.replace( '"', '""' ); } if ( cfg.quotes ) { value = [ '"', value, '"' ].join( "" ); } } buffer.push( value ); } data += buffer.join( cfg.delimiter ) + "\n"; } _this.handleCallback( callback, data ); return data; }, toXLSX: function( options, callback ) { var cfg = _this.deepMerge( { data: _this.getChartData(), name: "amCharts", withHeader: true }, options || {}, true ); var data = ""; var wb = { SheetNames: [], Sheets: {} } function datenum( v, date1904 ) { if ( date1904 ) v += 1462; var epoch = Date.parse( v ); return ( epoch - new Date( Date.UTC( 1899, 11, 30 ) ) ) / ( 24 * 60 * 60 * 1000 ); } function sheet_from_array_of_arrays( data, opts ) { var ws = {}; var range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } }; for ( var R = 0; R != data.length; ++R ) { for ( var C = 0; C != data[ R ].length; ++C ) { if ( range.s.r > R ) range.s.r = R; if ( range.s.c > C ) range.s.c = C; if ( range.e.r < R ) range.e.r = R; if ( range.e.c < C ) range.e.c = C; var cell = { v: data[ R ][ C ] }; if ( cell.v == null ) continue; var cell_ref = XLSX.utils.encode_cell( { c: C, r: R } ); if ( typeof cell.v === "number" ) cell.t = "n"; else if ( typeof cell.v === "boolean" ) cell.t = "b"; else if ( cell.v instanceof Date ) { cell.t = "n"; cell.z = XLSX.SSF._table[ 14 ]; cell.v = datenum( cell.v ); } else cell.t = "s"; ws[ cell_ref ] = cell; } } if ( range.s.c < 10000000 ) ws[ "!ref" ] = XLSX.utils.encode_range( range ); return ws; } wb.SheetNames.push( cfg.name ); wb.Sheets[ cfg.name ] = sheet_from_array_of_arrays( _this.toArray( cfg ) ); data = XLSX.write( wb, { bookType: "xlsx", bookSST: true, type: "base64" } ); data = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + data; _this.handleCallback( callback, data ); return data; }, toArray: function( options, callback ) { var cfg = _this.deepMerge( { data: _this.getChartData(), dateFields: [], dateFormat: _this.setup.chart.dataDateFormat || "YYYY-MM-DD", withHeader: false }, options || {}, true ); var data = []; var cols = []; if ( _this.setup.chart.categoryAxis && _this.setup.chart.categoryAxis.parseDates && _this.setup.chart.categoryField ) { cfg.dateFields.push( _this.setup.chart.categoryField ); } // HEADER if ( cfg.withHeader ) { for ( col in cfg.data[ 0 ] ) { cols.push( col ); } data.push( cols ); } // BODY for ( row in cfg.data ) { var buffer = []; for ( col in cols ) { var col = cols[ col ]; var value = cfg.data[ row ][ col ] || ""; if ( cfg.dateFormat && value instanceof Date && cfg.dateFields.indexOf( col ) != -1 ) { value = AmCharts.formatDate( value, cfg.dateFormat ); } else { value = String( value ) } buffer.push( value ); } data.push( buffer ); } _this.handleCallback( callback, data ); return data; }, toByteArray: function( options, callback ) { var cfg = _this.deepMerge( { // Nuffin }, options || {} ); var Arr = ( typeof Uint8Array !== 'undefined' ) ? Uint8Array : Array var PLUS = '+'.charCodeAt( 0 ) var SLASH = '/'.charCodeAt( 0 ) var NUMBER = '0'.charCodeAt( 0 ) var LOWER = 'a'.charCodeAt( 0 ) var UPPER = 'A'.charCodeAt( 0 ) var data = b64ToByteArray( cfg.data ); function decode( elt ) { var code = elt.charCodeAt( 0 ) if ( code === PLUS ) return 62 // '+' if ( code === SLASH ) return 63 // '/' if ( code < NUMBER ) return -1 //no match if ( code < NUMBER + 10 ) return code - NUMBER + 26 + 26 if ( code < UPPER + 26 ) return code - UPPER if ( code < LOWER + 26 ) return code - LOWER + 26 } function b64ToByteArray( b64 ) { var i, j, l, tmp, placeHolders, arr if ( b64.length % 4 > 0 ) { throw new Error( 'Invalid string. Length must be a multiple of 4' ) } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt( len - 2 ) ? 2 : '=' === b64.charAt( len - 1 ) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr( b64.length * 3 / 4 - placeHolders ) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push( v ) { arr[ L++ ] = v } for ( i = 0, j = 0; i < l; i += 4, j += 3 ) { tmp = ( decode( b64.charAt( i ) ) << 18 ) | ( decode( b64.charAt( i + 1 ) ) << 12 ) | ( decode( b64.charAt( i + 2 ) ) << 6 ) | decode( b64.charAt( i + 3 ) ) push( ( tmp & 0xFF0000 ) >> 16 ) push( ( tmp & 0xFF00 ) >> 8 ) push( tmp & 0xFF ) } if ( placeHolders === 2 ) { tmp = ( decode( b64.charAt( i ) ) << 2 ) | ( decode( b64.charAt( i + 1 ) ) >> 4 ) push( tmp & 0xFF ) } else if ( placeHolders === 1 ) { tmp = ( decode( b64.charAt( i ) ) << 10 ) | ( decode( b64.charAt( i + 1 ) ) << 4 ) | ( decode( b64.charAt( i + 2 ) ) >> 2 ) push( ( tmp >> 8 ) & 0xFF ) push( tmp & 0xFF ) } return arr } _this.handleCallback( callback, data ); return data; }, // CALLBACK HANDLER handleCallback: function( callback, data ) { if ( callback ) { callback.apply( _this, [ data ] ); } }, getChartData: function() { var data = []; if ( _this.setup.chart.type == "stock" ) { data = _this.setup.chart.mainDataSet.dataProvider; } else if ( _this.setup.chart.type == "gantt" ) { var segmentsField = _this.setup.chart.segmentsField; for ( var i1 = 0; i1 < _this.setup.chart.dataProvider.length; i1++ ) { if ( _this.setup.chart.dataProvider[ i1 ][ segmentsField ] ) { for ( var i2 = 0; i2 < _this.setup.chart.dataProvider[ i1 ][ segmentsField ].length; i2++ ) { data.push( _this.setup.chart.dataProvider[ i1 ][ segmentsField ][ i2 ] ) } } } } else { data = _this.setup.chart.dataProvider; } return data; }, capitalize: function( string ) { return string.charAt( 0 ).toUpperCase() + string.slice( 1 ).toLowerCase(); }, // MENU BUILDER createMenu: function( list ) { function buildList( list, container ) { var ul = document.createElement( "ul" ); for ( i in list ) { var item = typeof list[ i ] === "string" ? { format: list[ i ] } : list[ i ]; var li = document.createElement( "li" ); var a = document.createElement( "a" ); var img = document.createElement( "img" ); var span = document.createElement( "span" ); var action = String( item.action ? item.action : item.format ).toLowerCase(); item.format = String( item.format ).toUpperCase(); // MERGE WITH GIVEN FORMAT if ( _this.config.formats[ item.format ] ) { item = _this.deepMerge( { label: item.icon ? "" : item.format, format: item.format, mimeType: _this.config.formats[ item.format ].mimeType, extension: _this.config.formats[ item.format ].extension, capture: _this.config.formats[ item.format ].capture, action: _this.config.action, fileName: _this.config.fileName }, item ); } else if ( !item.menu && !item.items ) { item.label = item.label ? item.label : _this.capitalize( action ); } // FILTER; TOGGLE FLAG if ( [ "CSV", "JSON", "XLSX" ].indexOf( item.format ) != -1 && [ "map", "gauge" ].indexOf( _this.setup.chart.type ) != -1 ) { continue; } // ADD CLICK HANDLER if ( !item.click && !item.menu && !item.items ) { // DRAWING METHODS if ( _this.drawing.actions.indexOf( action ) != -1 ) { item.action = action; item.click = ( function( item ) { return function() { this.drawing[ item.action ](); } } )( item ); // DRAWING } else if ( _this.drawing.enabled ) { item.click = ( function( item ) { return function() { this[ "to" + item.format ]( item, function( data ) { if ( item.action != "print" && item.format != "PRINT" ) { this.download( data, item.mimeType, [ item.fileName, item.extension ].join( "." ) ); } this.drawing.done(); } ); } } )( item ); // REGULAR } else if ( item.format != "UNKNOWN" ) { item.click = ( function( item ) { return function() { if ( item.capture || ( item.action == "print" || item.format == "PRINT" ) ) { this.capture( item, function() { this[ "to" + item.format ]( item, function( data ) { if ( item.action == "download" ) { this.download( data, item.mimeType, [ item.fileName, item.extension ].join( "." ) ); } } ); } ) } else if ( this[ "to" + item.format ] ) { this[ "to" + item.format ]( item, function( data ) { this.download( data, item.mimeType, [ item.fileName, item.extension ].join( "." ) ); } ); } else { throw new Error( 'Invalid format. Could not determine output type.' ); } } } )( item ); } // DRAWING } else if ( item.action == "draw" ) { item.click = ( function( item ) { return function() { this.capture( item, function() { this.createMenu( item.menu, item ); } ); } } )( item ); } // ADD LINK ATTR a.setAttribute( "href", "#" ); a.addEventListener( "click", ( function( callback ) { return function( e ) { callback.apply( _this, arguments ); e.preventDefault(); } } )( item.click || function( e ) { e.preventDefault(); } ) ); li.appendChild( a ); // ADD LABEL span.innerHTML = item.label; // APPEND ITEMS if ( item[ "class" ] ) { li.className = item[ "class" ]; } if ( item.icon ) { img.setAttribute( "src", ( item.icon.slice( 0, 10 ).indexOf( "//" ) == -1 ? chart.pathToImages : "" ) + item.icon ); a.appendChild( img ); } if ( item.label ) { a.appendChild( span ); } if ( item.title ) { a.setAttribute( "title", item.title ); } // CALLBACK; REVIVER FOR MENU ITEMS if ( _this.config.menuReviver ) { li = _this.config.menuReviver.apply( _this, [ item, li ] ); } // ADD SUBLIST; JUST WITH ENTRIES if ( ( item.menu || item.items ) && item.action != "draw" ) { if ( buildList( item.menu || item.items, li ).childNodes.length ) { ul.appendChild( li ); } } else { ul.appendChild( li ); } } // JUST ADD THOSE WITH ENTRIES return container.appendChild( ul ); } var div = _this.setup.chart.containerDiv.getElementsByClassName( "amcharts-export-menu" ); if ( div.length ) { div = div[ 0 ]; div.innerHTML = ""; } else { var div = document.createElement( "div" ); div.setAttribute( "class", "amExportButton amcharts-export-menu amcharts-export-menu-" + _this.config.position ); _this.setup.menu = div; } // CALLBACK; REPLACES THE MENU WALKER if ( _this.config.menuWalker ) { buildList = _this.config.menuWalker; } buildList( list, div ); _this.setup.chart.containerDiv.appendChild( div ); return div; }, migrateSetup: function( chart ) { if ( chart.amExport || chart.exportConfig ) { var config = _this.deepMerge( { enabled: true, migrated: true, libs: { autoLoad: false } }, _this.defaults ); function crawler( object ) { for ( key in object ) { var value = object[ key ]; if ( key.slice( 0, 6 ) == "export" && value ) { config.menu.push( key.slice( 6 ) ); } else if ( key == "userCFG" ) { crawler( value ); } else if ( key == "menuItems" ) { config.menu = value; } else if ( key == "libs" ) { config.libs = value; } } } crawler( chart.amExport || chart.exportConfig ); chart[ "export" ] = config; } return chart; }, // INITIATE init: function( chart ) { _this.setup.canvas = document.createElement( "canvas" ); _this.setup.wrapper = document.createElement( "div" ); _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas" ); _this.setup.wrapper.appendChild( _this.setup.canvas ); _this.setup.chart.containerDiv.appendChild( _this.setup.wrapper ); _this.setup.chart.AmExport = _this; // CREATE MENU _this.timer = setTimeout( function() { clearTimeout( _this.timer ); _this.createMenu( _this.config.menu ); }, AmCharts.updateRate ); } } // EXTEND DRAWING TO SUPPORT "CANCEL" MENU ACTION _this.drawing.cancel = _this.drawing.done; // MIRGRATE _this.setup.chart = _this.migrateSetup( chart ); // ENABLED-I-O? if ( undefined === _this.setup.chart[ "export" ] || !_this.setup.chart[ "export" ].enabled ) { return; } // POLYFILL BLOB if ( !window.Blob ) { _this.libs.resources.push( "blob.js/blob.js" ); } // MERGE SETTINGS _this.deepMerge( _this.libs, _this.setup.chart[ "export" ].libs || {}, true ); _this.deepMerge( _this.defaults.pdfMake, _this.setup.chart[ "export" ] ); _this.deepMerge( _this.defaults.fabric, _this.setup.chart[ "export" ] ); _this.config = _this.deepMerge( _this.defaults, _this.setup.chart[ "export" ], true ); _this.setup.chart[ "export" ] = _this; _this.setup.chart.addClassNames = true; // WITH IE? if ( AmCharts.isIE && AmCharts.IEversion < 9 ) { return; } // LOAD DEPENDENCIES _this.loadDependencies(); // WAIT FOR CONTAINER _this.timer = setInterval( function() { if ( _this.setup.chart.containerDiv ) { clearTimeout( _this.timer ); _this.init(); } }, AmCharts.updateRate ); }, [ "pie", "serial", "xy", "funnel", "radar", "gauge", "stock", "map", "gantt" ] );
export.js
/* Plugin Name: amCharts Export Description: Adds export capabilities to amCharts products Author: Benjamin Maertz, amCharts Version: 1.0 Author URI: http://www.amcharts.com/ Copyright 2015 amCharts Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Please note that the above license covers only this plugin. It by all means does not apply to any other amCharts products that are covered by different licenses. */ AmCharts.addInitHandler( function( chart ) { var _this = { name: "export", version: "1.0", libs: { autoLoad: true, path: "./plugins/export/libs/", resources: [ { "pdfmake/pdfmake.js": [ "pdfmake/vfs_fonts.js" ], "jszip/jszip.js": [ "xlsx/xlsx.js" ] }, "fabric.js/fabric.js", "FileSaver.js/FileSaver.js" ], loaded: 0 }, config: {}, setup: {}, drawing: { enabled: false, actions: [ "undo", "redo", "done", "cancel" ], undos: [], undo: function() { var last = _this.drawing.undos.pop(); if ( last ) { _this.drawing.redos.push( last ); last.path.remove(); } }, redos: [], redo: function() { var last = _this.drawing.redos.pop(); if ( last ) { _this.setup.fabric.add( last.path ); _this.drawing.undos.push( last ); } }, done: function() { _this.drawing.enabled = false; _this.drawing.undos = []; _this.drawing.redos = []; _this.setup.fabric.renderAll(); _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas" ); _this.createMenu( _this.config.menu ); } }, defaults: { position: "top-right", fileName: "amCharts", action: "download", formats: { "JPG": { mimeType: "image/jpg", extension: "jpg", capture: true }, "PNG": { mimeType: "image/png", extension: "png", capture: true }, "SVG": { mimeType: "text/xml", extension: "svg", capture: true }, "PDF": { mimeType: "application/pdf", extension: "pdf", capture: true }, "CSV": { mimeType: "text/plain", extension: "csv" }, "JSON": { mimeType: "text/plain", extension: "json" }, "XLSX": { mimeType: "application/octet-stream", extension: "xlsx" } }, fabric: { backgroundColor: "#FFFFFF", isDrawingMode: false, selection: false, removeImages: true }, pdfMake: { pageSize: "A4", pageOrientation: "portrait", images: {}, content: [ { image: "reference", fit: [ 523.28, 769.89 ] } ] }, "menu": [ { "class": "export-main", "label": "Export", "menu": [ { "label": "Download as ...", "menu": [ "PNG", "JPG", "SVG", { "format": "PDF", "content": [ "Saved from:", window.location.href, { "image": "reference", "fit": [ 523.28, 769.89 ] // fit image to A4 } ] } ] }, { "label": "Save data ...", "menu": [ "CSV", "XLSX", "JSON" ] }, { "label": "Annotate", "action": "draw", "menu": [ { "class": "export-drawing", "menu": [ { "label": "Color ...", "menu": [ { "class": "export-drawing-color export-drawing-color-black", "label": "Black", "click": function () { this.setup.fabric.freeDrawingBrush.color = "#000"; } }, { "class": "export-drawing-color export-drawing-color-white", "label": "White", "click": function () { this.setup.fabric.freeDrawingBrush.color = "#fff"; } }, { "class": "export-drawing-color export-drawing-color-red", "label": "Red", "click": function () { this.setup.fabric.freeDrawingBrush.color = "#f00"; } }, { "class": "export-drawing-color export-drawing-color-green", "label": "Green", "click": function () { this.setup.fabric.freeDrawingBrush.color = "#0f0"; } }, { "class": "export-drawing-color export-drawing-color-blue", "label": "Blue", "click": function () { this.setup.fabric.freeDrawingBrush.color = "#00f"; } } ] }, "UNDO", "REDO", { "label": "Save as ...", "menu": [ "PNG", "JPG", "SVG", { "format": "PDF", "content": [ "Saved from:", window.location.href, { "image": "reference", "fit": [ 523.28, 769.89 ] // fit image to A4 } ] } ] }, { "format": "PRINT", "label": "Print" }, "CANCEL" ] } ] }, { "format": "PRINT", "label": "Print" } ] } ] }, download: function( data, type, filename ) { var blob = _this.toBlob( { data: data, type: type }, function( data ) { if ( window.saveAs ) { saveAs( data, filename ); } else { throw new Error( "Unable to create file. Ensure saveAs (FileSaver.js) is supported." ); } } ); return data; }, loadResource: function( src, addons ) { var node, url = src.indexOf( "//" ) != -1 ? src : [ _this.libs.path, src ].join( "" ); function callback() { _this.libs.loaded++; if ( addons ) { for ( i in addons ) { _this.loadResource( addons[ i ] ); } } } if ( src.indexOf( ".js" ) != -1 ) { node = document.createElement( "script" ); node.setAttribute( "type", "text/javascript" ); node.setAttribute( "src", url ); } else if ( src.indexOf( ".css" ) != -1 ) { node = document.createElement( "link" ); node.setAttribute( "type", "text/css" ); node.setAttribute( "rel", "stylesheet" ); node.setAttribute( "href", url ); } if ( node ) { node.addEventListener( "load", callback ); document.head.appendChild( node ); } else { callback(); } }, loadDependencies: function() { if ( !_this.libs.loaded && _this.libs.autoLoad ) { for ( i in _this.libs.resources ) { if ( typeof _this.libs.resources[ i ] == "object" ) { for ( i2 in _this.libs.resources[ i ] ) { var addons = _this.libs.resources[ i ][ i2 ]; _this.loadResource( i2, addons ); } } else { _this.loadResource( _this.libs.resources[ i ] ); } } } }, pxToNumber: function( attr ) { return Number( String( attr ).replace( "px", "" ) ) || 0; }, deepMerge: function( a, b, overwrite ) { for ( i in b ) { var v = b[ i ]; // NEW if ( a[ i ] == undefined || overwrite ) { if ( v instanceof Array ) { a[ i ] = new Array(); } else if ( v instanceof Function ) { a[ i ] = new Function(); } else if ( v instanceof Date ) { a[ i ] = new Date(); } else if ( v instanceof Object ) { a[ i ] = new Object(); } else if ( v instanceof Number ) { a[ i ] = new Number(); } else if ( v instanceof String ) { a[ i ] = new String(); } } if ( !( v instanceof Function || v instanceof Date ) && ( v instanceof Object || v instanceof Array ) ) { _this.deepMerge( a[ i ], v, overwrite ); } else { if ( a instanceof Array && !overwrite ) { a.push( v ); } else { a[ i ] = v; } } } return a; }, // CAPTURE EMOTIONAL MOMENT capture: function( options, callback ) { var cfg = _this.deepMerge( _this.deepMerge( {}, _this.config.fabric ), options || {} ); var i1, i2, i3 = 0; var groups = []; var offset = { x: 0, y: 0, width: _this.setup.chart.divRealWidth, height: _this.setup.chart.divRealHeight }; // GATHER SVGs var svgs = _this.setup.chart.containerDiv.getElementsByTagName( "svg" ); for ( i1 = 0; i1 < svgs.length; i1++ ) { var group = { svg: svgs[ i1 ], parent: svgs[ i1 ].parentNode, offset: { x: 0, y: 0 }, patterns: {}, clippings: {} } // GATHER CLIPPATHS; make them invisible var items = svgs[ i1 ].getElementsByTagName( "clipPath" ); for ( i2 = 0; i2 < items.length; i2++ ) { for ( i3 = 0; i3 < items[ i2 ].childNodes.length; i3++ ) { items[ i2 ].childNodes[ i3 ].setAttribute( "fill", "transparent" ); } group.clippings[ items[ i2 ].id ] = items[ i2 ]; } // GATHER PATTERNS var items = svgs[ i1 ].getElementsByTagName( "pattern" ); for ( i2 = 0; i2 < items.length; i2++ ) { var props = { node: items[ i2 ], source: items[ i2 ].getAttribute( "xlink:href" ), width: Number( items[ i2 ].getAttribute( "width" ) ), height: Number( items[ i2 ].getAttribute( "height" ) ), repeat: "repeat" } // REPLACE SOURCE var rect = items[ i2 ].getElementsByTagName( "rect" ); if ( rect.length > 0 ) { var IMG = new Image(); IMG.src = props.source; var PSC = new fabric.StaticCanvas( undefined, { width: props.width, height: props.height, backgroundColor: rect[ 0 ].getAttribute( "fill" ) } ); var RECT = new fabric.Rect( { width: props.width, height: props.height, fill: new fabric.Pattern( { source: IMG, repeat: "repeat" } ) } ); PSC.add( RECT ); props.source = PSC.toDataURL(); } // BUFFER PATTERN group.patterns[ items[ i2 ].id ] = new fabric.Pattern( props ); } // APPEND GROUP groups.push( group ); } // GATHER EXTERNAL LEGEND if ( _this.config.legend && _this.setup.chart.legend && _this.setup.chart.legend.position == "outside" ) { var group = { svg: _this.setup.chart.legend.container.container, parent: _this.setup.chart.legend.container.div, offset: { x: 0, y: 0 }, legend: { type: [ "top", "left" ].indexOf( _this.config.legend.position ) != -1 ? "unshift" : "push", position: _this.config.legend.position, width: _this.config.legend.width ? _this.config.legend.width : _this.setup.chart.legend.container.width, height: _this.config.legend.height ? _this.config.legend.height : _this.setup.chart.legend.container.height } } // Adapt canvas dimensions if ( [ "left", "right" ].indexOf( group.legend.position ) != -1 ) { offset.width += group.legend.width; offset.height = group.legend.height > offset.height ? group.legend.height : offset.height; } else if ( [ "top", "bottom" ].indexOf( group.legend.position ) != -1 ) { offset.height += group.legend.height; } // PRE/APPEND SVG groups[ group.legend.type ]( group ); } // STOCK CHART if ( _this.setup.chart.type == "stock" ) { if ( _this.setup.chart.leftContainer ) { offset.width -= _this.pxToNumber( _this.setup.chart.leftContainer.style.width ); _this.setup.wrapper.style.paddingLeft = _this.pxToNumber( _this.setup.chart.leftContainer.style.width ) + _this.setup.chart.panelsSettings.panelSpacing * 2; } if ( _this.setup.chart.rightContainer ) { offset.width -= _this.pxToNumber( _this.setup.chart.rightContainer.style.width ); _this.setup.wrapper.style.paddingRight = _this.pxToNumber( _this.setup.chart.rightContainer.style.width ) + _this.setup.chart.panelsSettings.panelSpacing * 2; } if ( _this.setup.chart.periodSelector && [ "top", "bottom" ].indexOf( _this.setup.chart.periodSelector.position ) != -1 ) { offset.height -= _this.setup.chart.periodSelector.offsetHeight + _this.setup.chart.panelsSettings.panelSpacing; } if ( _this.setup.chart.dataSetSelector && [ "top", "bottom" ].indexOf( _this.setup.chart.dataSetSelector.position ) != -1 ) { offset.height -= _this.setup.chart.dataSetSelector.offsetHeight; } } // CLEAR IF EXIST _this.drawing.enabled = cfg.isDrawingMode = ( cfg.drawing && cfg.drawing.enabled ) ? true : cfg.action == "draw"; if ( !_this.setup.wrapper ) { _this.setup.wrapper = document.createElement( "div" ); _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas" ); _this.setup.wrapper.appendChild( _this.setup.canvas ); } else { _this.setup.wrapper.innerHTML = ""; } _this.setup.canvas = document.createElement( "canvas" ); _this.setup.wrapper.appendChild( _this.setup.canvas ); _this.setup.fabric = new fabric.Canvas( _this.setup.canvas, _this.deepMerge( { width: offset.width, height: offset.height }, cfg ) ); _this.deepMerge( _this.setup.fabric, cfg ); // OBSERVE MOUSE _this.setup.fabric.on( "path:created", function( path ) { _this.drawing.undos.push( path ); } ); // DRAWING if ( _this.drawing.enabled ) { _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas active" ); } else { _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas" ); } for ( i1 = 0; i1 < groups.length; i1++ ) { var group = groups[ i1 ]; // GATHER POSITION if ( group.parent.style.top || group.parent.style.left ) { group.offset.y = _this.pxToNumber( group.parent.style.top ); group.offset.x = _this.pxToNumber( group.parent.style.left ); } else { // EXTERNAL LEGEND if ( group.legend ) { if ( group.legend.position == "left" ) { offset.x += chart.legend.container.width; } else if ( group.legend.position == "right" ) { group.offset.x += offset.width - group.legend.width; } else if ( group.legend.position == "top" ) { offset.y += group.legend.height; } else if ( group.legend.position == "bottom" ) { group.offset.y += offset.height - group.legend.height; // offset.y } // NORMAL } else { group.offset.x = offset.x; group.offset.y = offset.y; offset.y += _this.pxToNumber( group.parent.style.height ); } // PANEL if ( group.parent && ( group.parent.getAttribute( "class" ) || "" ).split( " " ).indexOf( "amChartsLegend" ) != -1 ) { offset.y += _this.pxToNumber( group.parent.parentNode.parentNode.style.marginTop ); group.offset.y += _this.pxToNumber( group.parent.parentNode.parentNode.style.marginTop ); } } // ADD TO CANVAS fabric.parseSVGDocument( group.svg, ( function( group ) { return function( objects, options ) { var g = fabric.util.groupSVGElements( objects, options ); var tmp = { top: group.offset.y, left: group.offset.x }; for ( i1 in g.paths ) { // CHECK ORIGIN; REMOVE TAINTED if ( cfg.removeImages && g.paths[ i1 ][ "xlink:href" ] && g.paths[ i1 ][ "xlink:href" ].indexOf( location.origin ) == -1 ) { g.paths.splice( i1, 1 ); } // OPACITY; TODO: Distinguish opacity types if ( g.paths[ i1 ] ) { if ( g.paths[ i1 ].fill instanceof Object ) { g.paths[ i1 ].set( { opacity: g.paths[ i1 ].fillOpacity } ); // PATTERN; TODO: Distinguish opacity types } else if ( String( g.paths[ i1 ].fill ).slice( 0, 3 ) == "url" ) { var PID = g.paths[ i1 ].fill.slice( 5, -1 ); if ( group.patterns[ PID ] ) { g.paths[ i1 ].set( { fill: group.patterns[ PID ], opacity: g.paths[ i1 ].fillOpacity } ); } } if ( String( g.paths[ i1 ].clipPath ).slice( 0, 3 ) == "url" ) { var PID = g.paths[ i1 ].clipPath.slice( 5, -1 ); if ( group.clippings[ PID ] ) { var mask = group.clippings[ PID ].childNodes[ 0 ]; var transform = g.paths[ i1 ].svg.getAttribute( "transform" ) || "translate(0,0)"; transform = transform.slice( 10, -1 ).split( "," ); g.paths[ i1 ].set( { clipTo: ( function( mask, transform ) { return function( ctx ) { var width = Number( mask.getAttribute( "width" ) || "0" ); var height = Number( mask.getAttribute( "height" ) || "0" ); var x = Number( mask.getAttribute( "x" ) || "0" ); var y = Number( mask.getAttribute( "y" ) || "0" ); ctx.rect( Number( transform[ 0 ] ) * -1 + x, Number( transform[ 1 ] ) * -1 + y, width, height ); } } )( mask, transform ) } ); } } } } g.set( tmp ); _this.setup.fabric.add( g ); // ADD BALLOONS var balloons = group.svg.parentNode.getElementsByClassName( "amcharts-balloon-div" ); for ( i = 0; i < balloons.length; i++ ) { if ( cfg.balloonFunction instanceof Function ) { cfg.balloonFunction.apply( _this, [ balloons[ i ], group ] ); } else { var parent = balloons[ i ]; var text = parent.childNodes[ 0 ]; var label = new fabric.Text( text.innerText || text.innerHTML, { fontSize: _this.pxToNumber( text.style.fontSize ), fontFamily: text.style.fontFamily, fill: text.style.color, top: _this.pxToNumber( parent.style.top ) + group.offset.y, left: _this.pxToNumber( parent.style.left ) + group.offset.x } ); _this.setup.fabric.add( label ); } } if ( group.svg.nextSibling && group.svg.nextSibling.tagName == "A" ) { var label = new fabric.Text( group.svg.nextSibling.innerText || group.svg.nextSibling.innerHTML, { fontSize: _this.pxToNumber( group.svg.nextSibling.style.fontSize ), fontFamily: group.svg.nextSibling.style.fontFamily, fill: group.svg.nextSibling.style.color, top: _this.pxToNumber( group.svg.nextSibling.style.top ) + group.offset.y, left: _this.pxToNumber( group.svg.nextSibling.style.left ) + group.offset.x } ); _this.setup.fabric.add( label ); } groups.pop(); if ( !groups.length ) { _this.handleCallback( callback ); } } // Identify elements through classnames } )( group ), function( svg, obj ) { var className = svg.getAttribute( "class" ) || svg.parentNode.getAttribute( "class" ) || ""; var visibility = svg.getAttribute( "visibility" ) || svg.parentNode.getAttribute( "visibility" ) || svg.parentNode.parentNode.getAttribute( "visibility" ) || ""; var clipPath = svg.getAttribute( "clip-path" ) || svg.parentNode.getAttribute( "clip-path" ) || ""; obj.className = className; obj.clipPath = clipPath; obj.svg = svg; // HIDE HIDDEN ELEMENTS; TODO: Find a better way to handle that if ( visibility == "hidden" ) { obj.opacity = 0; // WALKTHROUGH ELEMENTS } else { // TRANSPORT FILL/STROKE OPACITY var attrs = [ "fill", "stroke" ]; for ( i1 in attrs ) { var attr = attrs[ i1 ] var attrVal = String( svg.getAttribute( attr ) || "" ); var attrOpacity = Number( svg.getAttribute( attr + "-opacity" ) || "1" ); var attrRGBA = fabric.Color.fromHex( attrVal ).getSource(); // EXCEPTION if ( obj.className == "amcharts-guide-fill" && !attrVal ) { attrOpacity = 0; attrRGBA = fabric.Color.fromHex( "#000000" ).getSource(); } if ( attrRGBA ) { attrRGBA.pop(); attrRGBA.push( attrOpacity ) obj[ attr ] = "rgba(" + attrRGBA.join() + ")"; obj[ _this.capitalize( attr + "-opacity" ) ] = attrOpacity; } } } } ); } }, toCanvas: function( options, callback ) { var cfg = _this.deepMerge( { // Nuffin }, options || {} ); var data = _this.setup.canvas; _this.handleCallback( callback, data ); return data; }, toBlob: function( options, callback ) { var cfg = _this.deepMerge( { data: "empty", type: "text/plain" }, options || {} ); var isBase64 = /^data:.+;base64,(.*)$/.exec( cfg.data ); // GATHER BODY if ( isBase64 ) { cfg.data = isBase64[ 0 ]; cfg.type = cfg.data.slice( 5, cfg.data.indexOf( "," ) - 7 ); cfg.data = _this.toByteArray( { data: cfg.data.slice( cfg.data.indexOf( "," ) + 1, cfg.data.length ) } ); } if ( cfg.getByteArray ) { data = cfg.data; } else { data = new Blob( [ cfg.data ], { type: cfg.type } ); } _this.handleCallback( callback, data ); return data; }, toJPG: function( options, callback ) { var cfg = _this.deepMerge( { format: "jpeg", quality: 1, multiplier: 1, background: "#FF00FF" }, options || {} ); var data = _this.setup.fabric.toDataURL( cfg ); _this.handleCallback( callback, data ); return data; }, toPNG: function( options, callback ) { var cfg = _this.deepMerge( { format: "png", quality: 1, multiplier: 1 }, options || {} ); var data = _this.setup.fabric.toDataURL( cfg ); _this.handleCallback( callback, data ); return data; }, toSVG: function( options, callback ) { var cfg = _this.deepMerge( { // nothing in here }, options || {} ); var data = _this.setup.fabric.toSVG( cfg ); _this.handleCallback( callback, data ); return data; }, toPDF: function( options, callback ) { var cfg = _this.deepMerge( _this.deepMerge( { multiplier: 2 }, _this.config.pdfMake ), options || {}, true ); cfg.images.reference = _this.toPNG( cfg ); var data = new pdfMake.createPdf( cfg ); if ( callback ) { data.getDataUrl( ( function( callback ) { return function() { callback.apply( _this, arguments ); } } )( callback ) ); } return data; }, toPRINT: function( options, callback ) { var cfg = _this.deepMerge( { // nothing in here }, options || {} ); var data = _this.toPNG( cfg ); var states = []; var items = document.body.childNodes; var img = document.createElement( "img" ); img.src = data; img.setAttribute( "style", "width: 100%; max-height: 100%;" ); for ( i in items ) { if ( items[ i ].nodeType === 1 ) { states[ i ] = items[ i ].style.display; items[ i ].style.display = "none"; } } document.body.appendChild( img ); window.print(); for ( i in items ) { if ( items[ i ].nodeType === 1 ) { items[ i ].style.display = states[ i ]; } } img.remove(); _this.handleCallback( callback, data ); return true; }, toJSON: function( options, callback ) { var cfg = _this.deepMerge( { data: _this.getChartData() }, options || {}, true ); var data = JSON.stringify( cfg.data, undefined, "\t" ); _this.handleCallback( callback, data ); return data; }, toCSV: function( options, callback ) { var cfg = _this.deepMerge( { data: _this.getChartData(), delimiter: ",", quotes: true, escape: true, dateFields: [], dateFormat: _this.setup.chart.dataDateFormat || "YYYY-MM-DD" }, options || {}, true ); var data = ""; if ( _this.setup.chart.categoryAxis && _this.setup.chart.categoryAxis.parseDates && _this.setup.chart.categoryField ) { cfg.dateFields.push( _this.setup.chart.categoryField ); } for ( row in cfg.data ) { var buffer = []; for ( col in cfg.data[ row ] ) { var value = cfg.data[ row ][ col ]; // HEADER if ( row == 0 ) { value = col; // BODY } else { if ( typeof value === "string" ) { value = value; } else if ( cfg.dateFormat && value instanceof Date && cfg.dateFields.indexOf( col ) != -1 ) { value = AmCharts.formatDate( value, cfg.dateFormat ); } } // WRAP IN QUOTES if ( typeof value === "string" ) { if ( cfg.escape ) { value = value.replace( '"', '""' ); } if ( cfg.quotes ) { value = [ '"', value, '"' ].join( "" ); } } buffer.push( value ); } data += buffer.join( cfg.delimiter ) + "\n"; } _this.handleCallback( callback, data ); return data; }, toXLSX: function( options, callback ) { var cfg = _this.deepMerge( { data: _this.getChartData(), name: "amCharts", withHeader: true }, options || {}, true ); var data = ""; var wb = { SheetNames: [], Sheets: {} } function datenum( v, date1904 ) { if ( date1904 ) v += 1462; var epoch = Date.parse( v ); return ( epoch - new Date( Date.UTC( 1899, 11, 30 ) ) ) / ( 24 * 60 * 60 * 1000 ); } function sheet_from_array_of_arrays( data, opts ) { var ws = {}; var range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } }; for ( var R = 0; R != data.length; ++R ) { for ( var C = 0; C != data[ R ].length; ++C ) { if ( range.s.r > R ) range.s.r = R; if ( range.s.c > C ) range.s.c = C; if ( range.e.r < R ) range.e.r = R; if ( range.e.c < C ) range.e.c = C; var cell = { v: data[ R ][ C ] }; if ( cell.v == null ) continue; var cell_ref = XLSX.utils.encode_cell( { c: C, r: R } ); if ( typeof cell.v === "number" ) cell.t = "n"; else if ( typeof cell.v === "boolean" ) cell.t = "b"; else if ( cell.v instanceof Date ) { cell.t = "n"; cell.z = XLSX.SSF._table[ 14 ]; cell.v = datenum( cell.v ); } else cell.t = "s"; ws[ cell_ref ] = cell; } } if ( range.s.c < 10000000 ) ws[ "!ref" ] = XLSX.utils.encode_range( range ); return ws; } wb.SheetNames.push( cfg.name ); wb.Sheets[ cfg.name ] = sheet_from_array_of_arrays( _this.toArray( cfg ) ); data = XLSX.write( wb, { bookType: "xlsx", bookSST: true, type: "base64" } ); data = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + data; _this.handleCallback( callback, data ); return data; }, toArray: function( options, callback ) { var cfg = _this.deepMerge( { data: _this.getChartData(), dateFields: [], dateFormat: _this.setup.chart.dataDateFormat || "YYYY-MM-DD", withHeader: false }, options || {}, true ); var data = []; var cols = []; if ( _this.setup.chart.categoryAxis && _this.setup.chart.categoryAxis.parseDates && _this.setup.chart.categoryField ) { cfg.dateFields.push( _this.setup.chart.categoryField ); } // HEADER if ( cfg.withHeader ) { for ( col in cfg.data[ 0 ] ) { cols.push( col ); } data.push( cols ); } // BODY for ( row in cfg.data ) { var buffer = []; for ( col in cols ) { var col = cols[ col ]; var value = cfg.data[ row ][ col ] || ""; if ( cfg.dateFormat && value instanceof Date && cfg.dateFields.indexOf( col ) != -1 ) { value = AmCharts.formatDate( value, cfg.dateFormat ); } else { value = String( value ) } buffer.push( value ); } data.push( buffer ); } _this.handleCallback( callback, data ); return data; }, toByteArray: function( options, callback ) { var cfg = _this.deepMerge( { // Nuffin }, options || {} ); var Arr = ( typeof Uint8Array !== 'undefined' ) ? Uint8Array : Array var PLUS = '+'.charCodeAt( 0 ) var SLASH = '/'.charCodeAt( 0 ) var NUMBER = '0'.charCodeAt( 0 ) var LOWER = 'a'.charCodeAt( 0 ) var UPPER = 'A'.charCodeAt( 0 ) var data = b64ToByteArray( cfg.data ); function decode( elt ) { var code = elt.charCodeAt( 0 ) if ( code === PLUS ) return 62 // '+' if ( code === SLASH ) return 63 // '/' if ( code < NUMBER ) return -1 //no match if ( code < NUMBER + 10 ) return code - NUMBER + 26 + 26 if ( code < UPPER + 26 ) return code - UPPER if ( code < LOWER + 26 ) return code - LOWER + 26 } function b64ToByteArray( b64 ) { var i, j, l, tmp, placeHolders, arr if ( b64.length % 4 > 0 ) { throw new Error( 'Invalid string. Length must be a multiple of 4' ) } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt( len - 2 ) ? 2 : '=' === b64.charAt( len - 1 ) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr( b64.length * 3 / 4 - placeHolders ) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push( v ) { arr[ L++ ] = v } for ( i = 0, j = 0; i < l; i += 4, j += 3 ) { tmp = ( decode( b64.charAt( i ) ) << 18 ) | ( decode( b64.charAt( i + 1 ) ) << 12 ) | ( decode( b64.charAt( i + 2 ) ) << 6 ) | decode( b64.charAt( i + 3 ) ) push( ( tmp & 0xFF0000 ) >> 16 ) push( ( tmp & 0xFF00 ) >> 8 ) push( tmp & 0xFF ) } if ( placeHolders === 2 ) { tmp = ( decode( b64.charAt( i ) ) << 2 ) | ( decode( b64.charAt( i + 1 ) ) >> 4 ) push( tmp & 0xFF ) } else if ( placeHolders === 1 ) { tmp = ( decode( b64.charAt( i ) ) << 10 ) | ( decode( b64.charAt( i + 1 ) ) << 4 ) | ( decode( b64.charAt( i + 2 ) ) >> 2 ) push( ( tmp >> 8 ) & 0xFF ) push( tmp & 0xFF ) } return arr } _this.handleCallback( callback, data ); return data; }, // CALLBACK HANDLER handleCallback: function( callback, data ) { if ( callback ) { callback.apply( _this, [ data ] ); } }, getChartData: function() { var data = []; if ( _this.setup.chart.type == "stock" ) { data = _this.setup.chart.mainDataSet.dataProvider; } else if ( _this.setup.chart.type == "gantt" ) { var segmentsField = _this.setup.chart.segmentsField; for ( var i1 = 0; i1 < _this.setup.chart.dataProvider.length; i1++ ) { if ( _this.setup.chart.dataProvider[ i1 ][ segmentsField ] ) { for ( var i2 = 0; i2 < _this.setup.chart.dataProvider[ i1 ][ segmentsField ].length; i2++ ) { data.push( _this.setup.chart.dataProvider[ i1 ][ segmentsField ][ i2 ] ) } } } } else { data = _this.setup.chart.dataProvider; } return data; }, capitalize: function( string ) { return string.charAt( 0 ).toUpperCase() + string.slice( 1 ).toLowerCase(); }, // MENU BUILDER createMenu: function( list ) { function buildList( list, container ) { var ul = document.createElement( "ul" ); for ( i in list ) { var item = typeof list[ i ] === "string" ? { format: list[ i ] } : list[ i ]; var li = document.createElement( "li" ); var a = document.createElement( "a" ); var img = document.createElement( "img" ); var span = document.createElement( "span" ); var action = String( item.action ? item.action : item.format ).toLowerCase(); item.format = String( item.format ).toUpperCase(); // MERGE WITH GIVEN FORMAT if ( _this.config.formats[ item.format ] ) { item = _this.deepMerge( { label: item.icon ? "" : item.format, format: item.format, mimeType: _this.config.formats[ item.format ].mimeType, extension: _this.config.formats[ item.format ].extension, capture: _this.config.formats[ item.format ].capture, action: _this.config.action, fileName: _this.config.fileName }, item ); } else if ( !item.menu && !item.items ) { item.label = item.label ? item.label : _this.capitalize( action ); } // FILTER; TOGGLE FLAG if ( [ "CSV", "JSON", "XLSX" ].indexOf( item.format ) != -1 && [ "map", "gauge" ].indexOf( _this.setup.chart.type ) != -1 ) { continue; } // ADD CLICK HANDLER if ( !item.click && !item.menu && !item.items ) { // DRAWING METHODS if ( _this.drawing.actions.indexOf( action ) != -1 ) { item.action = action; item.click = ( function( item ) { return function() { this.drawing[ item.action ](); } } )( item ); // DRAWING } else if ( _this.drawing.enabled ) { item.click = ( function( item ) { return function() { this[ "to" + item.format ]( item, function( data ) { if ( item.action != "print" && item.format != "PRINT" ) { this.download( data, item.mimeType, [ item.fileName, item.extension ].join( "." ) ); } this.drawing.done(); } ); } } )( item ); // REGULAR } else if ( item.format != "UNKNOWN" ) { item.click = ( function( item ) { return function() { if ( item.capture || ( item.action == "print" || item.format == "PRINT" ) ) { this.capture( item, function() { this[ "to" + item.format ]( item, function( data ) { if ( item.action == "download" ) { this.download( data, item.mimeType, [ item.fileName, item.extension ].join( "." ) ); } } ); } ) } else if ( this[ "to" + item.format ] ) { this[ "to" + item.format ]( item, function( data ) { this.download( data, item.mimeType, [ item.fileName, item.extension ].join( "." ) ); } ); } else { throw new Error( 'Invalid format. Could not determine output type.' ); } } } )( item ); } // DRAWING } else if ( item.action == "draw" ) { item.click = ( function( item ) { return function() { this.capture( item, function() { this.createMenu( item.menu, item ); } ); } } )( item ); } // ADD LINK ATTR a.setAttribute( "href", "#" ); a.addEventListener( "click", ( function( callback ) { return function( e ) { callback.apply( _this, arguments ); e.preventDefault(); } } )( item.click || function( e ) { e.preventDefault(); } ) ); li.appendChild( a ); // ADD LABEL span.innerHTML = item.label; // APPEND ITEMS if ( item[ "class" ] ) { li.className = item[ "class" ]; } if ( item.icon ) { img.setAttribute( "src", ( item.icon.slice( 0, 10 ).indexOf( "//" ) == -1 ? chart.pathToImages : "" ) + item.icon ); a.appendChild( img ); } if ( item.label ) { a.appendChild( span ); } if ( item.title ) { a.setAttribute( "title", item.title ); } // CALLBACK; REVIVER FOR MENU ITEMS if ( _this.config.menuReviver ) { li = _this.config.menuReviver.apply( _this, [ item, li ] ); } // ADD SUBLIST; JUST WITH ENTRIES if ( ( item.menu || item.items ) && item.action != "draw" ) { if ( buildList( item.menu || item.items, li ).childNodes.length ) { ul.appendChild( li ); } } else { ul.appendChild( li ); } } // JUST ADD THOSE WITH ENTRIES return container.appendChild( ul ); } var div = _this.setup.chart.containerDiv.getElementsByClassName( "amcharts-export-menu" ); if ( div.length ) { div = div[ 0 ]; div.innerHTML = ""; } else { var div = document.createElement( "div" ); div.setAttribute( "class", "amExportButton amcharts-export-menu amcharts-export-menu-" + _this.config.position ); _this.setup.menu = div; } // CALLBACK; REPLACES THE MENU WALKER if ( _this.config.menuWalker ) { buildList = _this.config.menuWalker; } buildList( list, div ); _this.setup.chart.containerDiv.appendChild( div ); return div; }, migrateSetup: function( chart ) { if ( chart.amExport || chart.exportConfig ) { var config = _this.deepMerge( { enabled: true, migrated: true, libs: { autoLoad: false } }, _this.defaults ); function crawler( object ) { for ( key in object ) { var value = object[ key ]; if ( key.slice( 0, 6 ) == "export" && value ) { config.menu.push( key.slice( 6 ) ); } else if ( key == "userCFG" ) { crawler( value ); } else if ( key == "menuItems" ) { config.menu = value; } else if ( key == "libs" ) { config.libs = value; } } } crawler( chart.amExport || chart.exportConfig ); chart[ "export" ] = config; } return chart; }, // INITIATE init: function( chart ) { _this.setup.canvas = document.createElement( "canvas" ); _this.setup.wrapper = document.createElement( "div" ); _this.setup.wrapper.setAttribute( "class", "amcharts-export-canvas" ); _this.setup.wrapper.appendChild( _this.setup.canvas ); _this.setup.chart.containerDiv.appendChild( _this.setup.wrapper ); _this.setup.chart.AmExport = _this; // CREATE MENU _this.timer = setTimeout( function() { clearTimeout( _this.timer ); _this.createMenu( _this.config.menu ); }, AmCharts.updateRate ); } } // EXTEND DRAWING TO SUPPORT "CANCEL" MENU ACTION _this.drawing.cancel = _this.drawing.done; // MIRGRATE _this.setup.chart = _this.migrateSetup( chart ); // ENABLED-I-O? if ( undefined === _this.setup.chart[ "export" ] || !_this.setup.chart[ "export" ].enabled ) { return; } // POLYFILL BLOB if ( !window.Blob ) { _this.libs.resources.push( "blob.js/blob.js" ); } // MERGE SETTINGS _this.deepMerge( _this.libs, _this.setup.chart[ "export" ].libs || {}, true ); _this.deepMerge( _this.defaults.pdfMake, _this.setup.chart[ "export" ] ); _this.deepMerge( _this.defaults.fabric, _this.setup.chart[ "export" ] ); _this.config = _this.deepMerge( _this.defaults, _this.setup.chart[ "export" ], true ); _this.setup.chart[ "export" ] = _this; _this.setup.chart.addClassNames = true; // WITH IE? if ( AmCharts.isIE && AmCharts.IEversion < 9 ) { return; } // LOAD DEPENDENCIES _this.loadDependencies(); // WAIT FOR CONTAINER _this.timer = setInterval( function() { if ( _this.setup.chart.containerDiv ) { clearTimeout( _this.timer ); _this.init(); } }, AmCharts.updateRate ); }, [ "pie", "serial", "xy", "funnel", "radar", "gauge", "stock", "map", "gantt" ] );
Bubble bullet fix and polishing
export.js
Bubble bullet fix and polishing
<ide><path>xport.js <ide> fileName: "amCharts", <ide> action: "download", <ide> formats: { <del> "JPG": { <add> JPG: { <ide> mimeType: "image/jpg", <ide> extension: "jpg", <ide> capture: true <ide> }, <del> "PNG": { <add> PNG: { <ide> mimeType: "image/png", <ide> extension: "png", <ide> capture: true <ide> }, <del> "SVG": { <add> SVG: { <ide> mimeType: "text/xml", <ide> extension: "svg", <ide> capture: true <ide> }, <del> "PDF": { <add> PDF: { <ide> mimeType: "application/pdf", <ide> extension: "pdf", <ide> capture: true <ide> }, <del> "CSV": { <add> CSV: { <ide> mimeType: "text/plain", <ide> extension: "csv" <ide> }, <del> "JSON": { <add> JSON: { <ide> mimeType: "text/plain", <ide> extension: "json" <ide> }, <del> "XLSX": { <add> XLSX: { <ide> mimeType: "application/octet-stream", <ide> extension: "xlsx" <ide> } <ide> fit: [ 523.28, 769.89 ] <ide> } ] <ide> }, <del> "menu": [ { <del> "class": "export-main", <del> "label": "Export", <del> "menu": [ { <del> "label": "Download as ...", <del> "menu": [ "PNG", "JPG", "SVG", { <del> "format": "PDF", <del> "content": [ "Saved from:", window.location.href, { <del> "image": "reference", <del> "fit": [ 523.28, 769.89 ] // fit image to A4 <add> menu: [ { <add> class: "export-main", <add> label: "Export", <add> menu: [ { <add> label: "Download as ...", <add> menu: [ "PNG", "JPG", "SVG", { <add> format: "PDF", <add> content: [ "Saved from:", window.location.href, { <add> image: "reference", <add> fit: [ 523.28, 769.89 ] // fit image to A4 <ide> } ] <ide> } ] <ide> }, { <del> "label": "Save data ...", <del> "menu": [ "CSV", "XLSX", "JSON" ] <add> label: "Save data ...", <add> menu: [ "CSV", "XLSX", "JSON" ] <ide> }, { <del> "label": "Annotate", <del> "action": "draw", <del> "menu": [ { <del> "class": "export-drawing", <del> "menu": [ { <del> "label": "Color ...", <del> "menu": [ { <del> "class": "export-drawing-color export-drawing-color-black", <del> "label": "Black", <del> "click": function () { <add> label: "Annotate", <add> action: "draw", <add> menu: [ { <add> class: "export-drawing", <add> menu: [ { <add> label: "Color ...", <add> menu: [ { <add> class: "export-drawing-color export-drawing-color-black", <add> label: "Black", <add> click: function() { <ide> this.setup.fabric.freeDrawingBrush.color = "#000"; <ide> } <ide> }, { <del> "class": "export-drawing-color export-drawing-color-white", <del> "label": "White", <del> "click": function () { <add> class: "export-drawing-color export-drawing-color-white", <add> label: "White", <add> click: function() { <ide> this.setup.fabric.freeDrawingBrush.color = "#fff"; <ide> } <ide> }, { <del> "class": "export-drawing-color export-drawing-color-red", <del> "label": "Red", <del> "click": function () { <add> class: "export-drawing-color export-drawing-color-red", <add> label: "Red", <add> click: function() { <ide> this.setup.fabric.freeDrawingBrush.color = "#f00"; <ide> } <ide> }, { <del> "class": "export-drawing-color export-drawing-color-green", <del> "label": "Green", <del> "click": function () { <add> class: "export-drawing-color export-drawing-color-green", <add> label: "Green", <add> click: function() { <ide> this.setup.fabric.freeDrawingBrush.color = "#0f0"; <ide> } <ide> }, { <del> "class": "export-drawing-color export-drawing-color-blue", <del> "label": "Blue", <del> "click": function () { <add> class: "export-drawing-color export-drawing-color-blue", <add> label: "Blue", <add> click: function() { <ide> this.setup.fabric.freeDrawingBrush.color = "#00f"; <ide> } <ide> } ] <ide> }, "UNDO", "REDO", { <del> "label": "Save as ...", <del> "menu": [ "PNG", "JPG", "SVG", { <del> "format": "PDF", <del> "content": [ "Saved from:", window.location.href, { <del> "image": "reference", <del> "fit": [ 523.28, 769.89 ] // fit image to A4 <add> label: "Save as ...", <add> menu: [ "PNG", "JPG", "SVG", { <add> format: "PDF", <add> content: [ "Saved from:", window.location.href, { <add> image: "reference", <add> fit: [ 523.28, 769.89 ] // fit image to A4 <ide> } ] <ide> } ] <ide> }, { <del> "format": "PRINT", <del> "label": "Print" <add> format: "PRINT", <add> label: "Print" <ide> }, "CANCEL" ] <ide> } ] <ide> }, { <del> "format": "PRINT", <del> "label": "Print" <add> format: "PRINT", <add> label: "Print" <ide> } ] <ide> } ] <ide> }, <ide> <ide> for ( i1 in g.paths ) { <ide> <del> // CHECK ORIGIN; REMOVE TAINTED <del> if ( cfg.removeImages && g.paths[ i1 ][ "xlink:href" ] && g.paths[ i1 ][ "xlink:href" ].indexOf( location.origin ) == -1 ) { <del> g.paths.splice( i1, 1 ); <del> } <del> <ide> // OPACITY; TODO: Distinguish opacity types <ide> if ( g.paths[ i1 ] ) { <add> <add> // CHECK ORIGIN; REMOVE TAINTED <add> if ( cfg.removeImages && g.paths[ i1 ][ "xlink:href" ] && g.paths[ i1 ][ "xlink:href" ].indexOf( location.origin ) == -1 ) { <add> g.paths.splice( i1, 1 ); <add> } <add> <add> // SET OPACITY <ide> if ( g.paths[ i1 ].fill instanceof Object ) { <add> <add> // MISINTERPRETATION OF FABRIC <add> if ( g.paths[ i1 ].fill.type == "radial" ) { <add> g.paths[ i1 ].fill.coords.r2 = g.paths[ i1 ].fill.coords.r1 * -1; <add> g.paths[ i1 ].fill.coords.r1 = 0; <add> } <add> <ide> g.paths[ i1 ].set( { <ide> opacity: g.paths[ i1 ].fillOpacity <ide> } );
JavaScript
agpl-3.0
87c00840a410db3bb9d2e8dd43bd0aa088528ee9
0
tocco/tocco-client,tocco/tocco-client,tocco/tocco-client
import PropTypes from 'prop-types' import {appFactory} from 'tocco-app-extensions' import {reducer as reducerUtil, appContext, env} from 'tocco-util' import UserMenu from './components/UserMenu' import {getDispatchActions} from './input' import reducers, {sagas} from './modules/reducers' const packageName = 'user-menu' const initApp = (id, input, events, publicPath) => { env.setInputEnvs(input) const content = <UserMenu /> const store = appFactory.createStore(reducers, sagas, input, packageName) return appFactory.createApp(packageName, content, store, { input, events, actions: getDispatchActions(), publicPath, textResourceModules: ['component', 'common', packageName] }) } ;(() => { if (__PACKAGE_NAME__ === packageName) { appFactory.registerAppInRegistry(packageName, initApp) if (__DEV__) { const input = require('./dev/input.json') if (!__NO_MOCK__) { const fetchMock = require('fetch-mock').default fetchMock.config.overwriteRoutes = false const setupFetchMocks = require('./dev/fetchMocks').default setupFetchMocks(packageName, fetchMock) fetchMock.spy() } const app = initApp(packageName, input) if (module.hot) { module.hot.accept('./modules/reducers', () => { const hotReducers = require('./modules/reducers').default reducerUtil.hotReloadReducers(app.store, hotReducers) }) } appFactory.renderApp(app.component) } } })() const UserMenuApp = props => { const {component} = appFactory.useApp({initApp, props, packageName}) return component } UserMenuApp.propTypes = { appContext: appContext.propTypes.isRequired, logoutRedirectUrl: PropTypes.string } export default UserMenuApp export const app = appFactory.createBundleableApp(packageName, initApp, UserMenuApp)
packages/widgets/user-menu/src/main.js
import PropTypes from 'prop-types' import {appFactory} from 'tocco-app-extensions' import {reducer as reducerUtil, appContext} from 'tocco-util' import UserMenu from './components/UserMenu' import {getDispatchActions} from './input' import reducers, {sagas} from './modules/reducers' const packageName = 'user-menu' const initApp = (id, input, events, publicPath) => { const content = <UserMenu /> const store = appFactory.createStore(reducers, sagas, input, packageName) return appFactory.createApp(packageName, content, store, { input, events, actions: getDispatchActions(), publicPath, textResourceModules: ['component', 'common', packageName] }) } ;(() => { if (__PACKAGE_NAME__ === packageName) { appFactory.registerAppInRegistry(packageName, initApp) if (__DEV__) { const input = require('./dev/input.json') if (!__NO_MOCK__) { const fetchMock = require('fetch-mock').default fetchMock.config.overwriteRoutes = false const setupFetchMocks = require('./dev/fetchMocks').default setupFetchMocks(packageName, fetchMock) fetchMock.spy() } const app = initApp(packageName, input) if (module.hot) { module.hot.accept('./modules/reducers', () => { const hotReducers = require('./modules/reducers').default reducerUtil.hotReloadReducers(app.store, hotReducers) }) } appFactory.renderApp(app.component) } } })() const UserMenuApp = props => { const {component} = appFactory.useApp({initApp, props, packageName}) return component } UserMenuApp.propTypes = { appContext: appContext.propTypes.isRequired, logoutRedirectUrl: PropTypes.string } export default UserMenuApp export const app = appFactory.createBundleableApp(packageName, initApp, UserMenuApp)
fix(user-menu): add missing setInputEnvs Changelog: add missing setInputEnvs Refs: TOCDEV-5750
packages/widgets/user-menu/src/main.js
fix(user-menu): add missing setInputEnvs
<ide><path>ackages/widgets/user-menu/src/main.js <ide> import PropTypes from 'prop-types' <ide> import {appFactory} from 'tocco-app-extensions' <del>import {reducer as reducerUtil, appContext} from 'tocco-util' <add>import {reducer as reducerUtil, appContext, env} from 'tocco-util' <ide> <ide> import UserMenu from './components/UserMenu' <ide> import {getDispatchActions} from './input' <ide> const packageName = 'user-menu' <ide> <ide> const initApp = (id, input, events, publicPath) => { <add> env.setInputEnvs(input) <add> <ide> const content = <UserMenu /> <ide> <ide> const store = appFactory.createStore(reducers, sagas, input, packageName)
JavaScript
mit
f33594f1c91ed978e1b9d7ff46f3e4bedd600ac3
0
mjmlio/mjml-app,mjmlio/mjml-app,mjmlio/mjml-app
import { handleActions } from 'redux-actions' const state = [] export default handleActions( { ALERT_ADD: (state, { payload: alert }) => [alert, ...state].slice(0, 5), ALERT_REMOVE: (state, { payload: id }) => state.filter(a => a.id !== id), }, state, ) let __ID__ = 0 export function addAlert(message, type = 'info', { autoHide = true } = {}) { return dispatch => { const alert = { id: __ID__++, message, type } dispatch({ type: 'ALERT_ADD', payload: alert }) if (autoHide) setTimeout(() => dispatch(removeAlert(alert.id)), 2e3) } } export function removeAlert(id) { return { type: 'ALERT_REMOVE', payload: id } }
src/reducers/alerts.js
import { handleActions } from 'redux-actions' const state = [] export default handleActions( { ALERT_ADD: (state, { payload: alert }) => [alert, ...state].slice(0, 5), ALERT_REMOVE: (state, { payload: id }) => state.filter(a => a.id !== id), }, state, ) let __ID__ = 0 export function addAlert(message, type = 'info', { autoHide = true }) { return dispatch => { const alert = { id: __ID__++, message, type } dispatch({ type: 'ALERT_ADD', payload: alert }) if (autoHide) setTimeout(() => dispatch(removeAlert(alert.id)), 2e3) } } export function removeAlert(id) { return { type: 'ALERT_REMOVE', payload: id } }
fix crash now happening when alerts calls don't set autoHide
src/reducers/alerts.js
fix crash now happening when alerts calls don't set autoHide
<ide><path>rc/reducers/alerts.js <ide> <ide> let __ID__ = 0 <ide> <del>export function addAlert(message, type = 'info', { autoHide = true }) { <add>export function addAlert(message, type = 'info', { autoHide = true } = {}) { <ide> return dispatch => { <ide> const alert = { id: __ID__++, message, type } <ide> dispatch({ type: 'ALERT_ADD', payload: alert })
Java
apache-2.0
bd22f845e27f0a348abad6a1a83b80e1590ee0b8
0
bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.joynr.jeeintegration; import static java.lang.String.format; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Set; import javax.ejb.EJBException; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Injector; import io.joynr.dispatcher.rpc.MultiReturnValuesContainer; import io.joynr.exceptions.JoynrException; import io.joynr.jeeintegration.api.ServiceProvider; import io.joynr.jeeintegration.api.security.JoynrCallingPrincipal; import io.joynr.jeeintegration.context.JoynrJeeMessageContext; import io.joynr.jeeintegration.multicast.SubscriptionPublisherInjectionWrapper; import io.joynr.messaging.JoynrMessageCreator; import io.joynr.messaging.JoynrMessageMetaInfo; import io.joynr.provider.AbstractDeferred; import io.joynr.provider.Deferred; import io.joynr.provider.DeferredVoid; import io.joynr.provider.JoynrProvider; import io.joynr.provider.MultiValueDeferred; import io.joynr.provider.Promise; import io.joynr.provider.SubscriptionPublisher; import io.joynr.provider.SubscriptionPublisherInjection; import joynr.exceptions.ApplicationException; import joynr.exceptions.ProviderRuntimeException; /** * This class wraps an EJB which is decorated with {@link io.joynr.jeeintegration.api.ServiceProvider} and has a valid * service interface specified (that is it extends {@link JoynrProvider}). When the bean is discovered in * {@link JoynrIntegrationBean#initialise()} an instance of this class is registered as the provider with the joynr * runtime. When joynr wants to call a method of the specified service interface, then this instance will obtain a * reference to the bean via the {@link JoynrIntegrationBean#beanManager} and will delegate to the corresponding method * on that bean (i.e. with the same name and parameters). The result is then wrapped in a deferred / promise and * returned. */ public class ProviderWrapper implements InvocationHandler { private static final Logger logger = LoggerFactory.getLogger(ProviderWrapper.class); private static final List<Method> OBJECT_METHODS = Arrays.asList(Object.class.getMethods()); private static final String SET_SUBSCRIPTION_PUBLISHER_METHOD_NAME = "setSubscriptionPublisher"; // Sanity check that the method exists static { try { SubscriptionPublisherInjection.class.getMethod(SET_SUBSCRIPTION_PUBLISHER_METHOD_NAME, SubscriptionPublisher.class); } catch (NoSuchMethodException e) { logger.error("Expecting to find method named {} with one argument of type {}, but not found on {}", SET_SUBSCRIPTION_PUBLISHER_METHOD_NAME, SubscriptionPublisher.class, SubscriptionPublisherInjection.class); } } private Bean<?> bean; private BeanManager beanManager; private Injector injector; private Class<?> serviceInterface; /** * Initialises the instance with the service interface which will be exposed and the bean reference it is meant to * wrap. * * @param bean * the bean reference to which calls will be delegated. * @param beanManager * the bean manager. * @param injector the Guice injector. */ public ProviderWrapper(Bean<?> bean, BeanManager beanManager, Injector injector) { ServiceProvider serviceProvider = bean.getBeanClass().getAnnotation(ServiceProvider.class); serviceInterface = serviceProvider.serviceInterface(); this.bean = bean; this.beanManager = beanManager; this.injector = injector; } /** * When a method is invoked via a joynr call, then it is delegated to an instance of the bean with which this * instance was initialised, if the method is part of the business interface and to this instance if it was part of * the {@link JoynrProvider} interface or the <code>Object</code> class. * * @param proxy * the proxy object on which the method was called. * @param method * the specific method which was called. * @param args * the arguments with which the method was called. * * @return the result of the delegate method call on the EJB, but wrapped in a promise, as all the provider methods * in joynr are declared that way. */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { boolean isProviderMethod = matchesJoynrProviderMethod(method); Method delegateToMethod = getMethodFromInterfaces(bean.getBeanClass(), method, isProviderMethod); Object delegate = createDelegateForMethod(method, isProviderMethod); Object result = null; try { if (isProviderMethod(method, delegateToMethod)) { JoynrJeeMessageContext.getInstance().activate(); copyMessageCreatorInfo(); copyMessageContext(); } JoynrException joynrException = null; try { result = delegateToMethod.invoke(delegate, args); } catch (InvocationTargetException e) { joynrException = getJoynrExceptionFromInvocationException(e); } if (delegate != this) { AbstractDeferred deferred = createAndResolveOrRejectDeferred(delegateToMethod, result, joynrException); Promise<AbstractDeferred> promiseResult = new Promise<>(deferred); return promiseResult; } } finally { if (isProviderMethod(method, delegateToMethod)) { JoynrJeeMessageContext.getInstance().deactivate(); } } return result; } @SuppressWarnings("unchecked") private AbstractDeferred createAndResolveOrRejectDeferred(Method method, Object result, JoynrException joynrException) { AbstractDeferred deferred; if (result == null && method.getReturnType().getTypeName().equals("void")) { deferred = new DeferredVoid(); if (joynrException == null) { ((DeferredVoid) deferred).resolve(); } } else { if (result instanceof MultiReturnValuesContainer) { deferred = new MultiValueDeferred(); if (joynrException == null) { ((MultiValueDeferred) deferred).resolve(((MultiReturnValuesContainer) result).getValues()); } } else { deferred = new Deferred<Object>(); if (joynrException == null) { ((Deferred<Object>) deferred).resolve(result); } } } if (joynrException != null) { logger.debug("Provider method invocation resulted in provider runtime exception - rejecting the deferred {} with {}", deferred, joynrException); if (joynrException instanceof ApplicationException) { try { Method rejectMethod = AbstractDeferred.class.getDeclaredMethod("reject", new Class[]{ JoynrException.class }); rejectMethod.setAccessible(true); rejectMethod.invoke(deferred, new Object[]{ joynrException }); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { logger.warn("Unable to set {} as rejection reason on {}. Wrapping in ProviderRuntimeException instead.", joynrException, deferred); deferred.reject(new ProviderRuntimeException(((ApplicationException) joynrException).getMessage())); } } else if (joynrException instanceof ProviderRuntimeException) { deferred.reject((ProviderRuntimeException) joynrException); } } return deferred; } private JoynrException getJoynrExceptionFromInvocationException(InvocationTargetException e) throws InvocationTargetException { JoynrException joynrException = null; Throwable cause = e.getCause(); if (cause instanceof EJBException) { // an EJBException is only thrown when the exception is not in the throws declaration // ApplicationExceptions are always declared with throw and thus EJBExceptions won't be caused by them. Exception exception = ((EJBException) cause).getCausedByException(); if (exception instanceof ProviderRuntimeException) { joynrException = (ProviderRuntimeException) exception; } else { joynrException = new ProviderRuntimeException("Unexpected exception from provider: " + (exception == null ? cause.toString() : exception.toString())); } } else if (cause instanceof ProviderRuntimeException || cause instanceof ApplicationException) { joynrException = (JoynrException) cause; } else if (cause instanceof Exception) { joynrException = new ProviderRuntimeException("Unexpected exception from provider: " + cause.toString()); } if (joynrException == null) { throw e; } logger.trace("Returning joynr exception: {}", joynrException); return joynrException; } private boolean isProviderMethod(Method method, Method delegateToMethod) { boolean result = delegateToMethod != method; if (method.getDeclaringClass().equals(SubscriptionPublisherInjection.class)) { result = false; } return result; } private void copyMessageCreatorInfo() { JoynrMessageCreator joynrMessageCreator = injector.getInstance(JoynrMessageCreator.class); JoynrCallingPrincipal reference = getUniqueBeanReference(JoynrCallingPrincipal.class); String messageCreatorId = joynrMessageCreator.getMessageCreatorId(); logger.trace("Setting user '{}' for message processing context.", messageCreatorId); reference.setUsername(messageCreatorId); } private void copyMessageContext() { JoynrMessageMetaInfo joynrMessageContext = injector.getInstance(JoynrMessageMetaInfo.class); JoynrJeeMessageMetaInfo jeeMessageContext = getUniqueBeanReference(JoynrJeeMessageMetaInfo.class); logger.trace("Setting message context for message processing context."); jeeMessageContext.setMessageContext(joynrMessageContext.getMessageContext()); } private <T> T getUniqueBeanReference(Class<T> beanClass) { Set<Bean<?>> beans = beanManager.getBeans(beanClass); if (beans.size() != 1) { throw new IllegalStateException("There must be exactly one EJB of type " + beanClass.getName() + ". Found " + beans.size()); } @SuppressWarnings("unchecked") Bean<T> bean = (Bean<T>) beans.iterator().next(); @SuppressWarnings("unchecked") T reference = (T) beanManager.getReference(bean, beanClass, beanManager.createCreationalContext(bean)); return reference; } private Object createDelegateForMethod(Method method, boolean isProviderMethod) { if (OBJECT_METHODS.contains(method) || isProviderMethod) { return this; } if (SET_SUBSCRIPTION_PUBLISHER_METHOD_NAME.equals(method.getName()) && SubscriptionPublisherInjection.class.isAssignableFrom(method.getDeclaringClass())) { return SubscriptionPublisherInjectionWrapper.createInvocationHandler(bean, beanManager).createProxy(); } return beanManager.getReference(bean, serviceInterface, beanManager.createCreationalContext(bean)); } private Method getMethodFromInterfaces(Class<?> beanClass, Method method, boolean isProviderMethod) throws NoSuchMethodException { String name = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); Method result = method; if (!isProviderMethod) { result = null; for (Class<?> interfaceClass : beanClass.getInterfaces()) { try { if ((result = interfaceClass.getMethod(name, parameterTypes)) != null) { break; } } catch (NoSuchMethodException | SecurityException e) { if (logger.isTraceEnabled()) { logger.trace(format("Method %s not found on interface %s", name, interfaceClass)); } } } } return result == null ? method : result; } private boolean matchesJoynrProviderMethod(Method method) { boolean result = false; for (Method joynrProviderMethod : JoynrProvider.class.getMethods()) { if (joynrProviderMethod.getName().equals(method.getName()) && Arrays.equals(joynrProviderMethod.getParameterTypes(), method.getParameterTypes())) { result = true; break; } } return result; } }
java/jeeintegration/src/main/java/io/joynr/jeeintegration/ProviderWrapper.java
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.joynr.jeeintegration; import static java.lang.String.format; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Set; import javax.ejb.EJBException; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Injector; import io.joynr.dispatcher.rpc.MultiReturnValuesContainer; import io.joynr.exceptions.JoynrException; import io.joynr.jeeintegration.api.ServiceProvider; import io.joynr.jeeintegration.api.security.JoynrCallingPrincipal; import io.joynr.jeeintegration.context.JoynrJeeMessageContext; import io.joynr.jeeintegration.multicast.SubscriptionPublisherInjectionWrapper; import io.joynr.messaging.JoynrMessageCreator; import io.joynr.messaging.JoynrMessageMetaInfo; import io.joynr.provider.AbstractDeferred; import io.joynr.provider.Deferred; import io.joynr.provider.DeferredVoid; import io.joynr.provider.JoynrProvider; import io.joynr.provider.MultiValueDeferred; import io.joynr.provider.Promise; import io.joynr.provider.SubscriptionPublisher; import io.joynr.provider.SubscriptionPublisherInjection; import joynr.exceptions.ApplicationException; import joynr.exceptions.ProviderRuntimeException; /** * This class wraps an EJB which is decorated with {@link io.joynr.jeeintegration.api.ServiceProvider} and has a valid * service interface specified (that is it extends {@link JoynrProvider}). When the bean is discovered in * {@link JoynrIntegrationBean#initialise()} an instance of this class is registered as the provider with the joynr * runtime. When joynr wants to call a method of the specified service interface, then this instance will obtain a * reference to the bean via the {@link JoynrIntegrationBean#beanManager} and will delegate to the corresponding method * on that bean (i.e. with the same name and parameters). The result is then wrapped in a deferred / promise and * returned. */ public class ProviderWrapper implements InvocationHandler { private static final Logger logger = LoggerFactory.getLogger(ProviderWrapper.class); private static final List<Method> OBJECT_METHODS = Arrays.asList(Object.class.getMethods()); private static final String SET_SUBSCRIPTION_PUBLISHER_METHOD_NAME = "setSubscriptionPublisher"; // Sanity check that the method exists static { try { SubscriptionPublisherInjection.class.getMethod(SET_SUBSCRIPTION_PUBLISHER_METHOD_NAME, SubscriptionPublisher.class); } catch (NoSuchMethodException e) { logger.error("Expecting to find method named {} with one argument of type {}, but not found on {}", SET_SUBSCRIPTION_PUBLISHER_METHOD_NAME, SubscriptionPublisher.class, SubscriptionPublisherInjection.class); } } private Bean<?> bean; private BeanManager beanManager; private Injector injector; private Class<?> serviceInterface; /** * Initialises the instance with the service interface which will be exposed and the bean reference it is meant to * wrap. * * @param bean * the bean reference to which calls will be delegated. * @param beanManager * the bean manager. * @param injector the Guice injector. */ public ProviderWrapper(Bean<?> bean, BeanManager beanManager, Injector injector) { ServiceProvider serviceProvider = bean.getBeanClass().getAnnotation(ServiceProvider.class); serviceInterface = serviceProvider.serviceInterface(); this.bean = bean; this.beanManager = beanManager; this.injector = injector; } /** * When a method is invoked via a joynr call, then it is delegated to an instance of the bean with which this * instance was initialised, if the method is part of the business interface and to this instance if it was part of * the {@link JoynrProvider} interface or the <code>Object</code> class. * * @param proxy * the proxy object on which the method was called. * @param method * the specific method which was called. * @param args * the arguments with which the method was called. * * @return the result of the delegate method call on the EJB, but wrapped in a promise, as all the provider methods * in joynr are declared that way. */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { boolean isProviderMethod = matchesJoynrProviderMethod(method); Method delegateToMethod = getMethodFromInterfaces(bean.getBeanClass(), method, isProviderMethod); Object delegate = createDelegateForMethod(method, isProviderMethod); Object result = null; try { if (isProviderMethod(method, delegateToMethod)) { JoynrJeeMessageContext.getInstance().activate(); copyMessageCreatorInfo(); copyMessageContext(); } JoynrException joynrException = null; try { result = delegateToMethod.invoke(delegate, args); } catch (InvocationTargetException e) { joynrException = getJoynrExceptionFromInvocationException(e); } if (delegate != this) { AbstractDeferred deferred = createAndResolveOrRejectDeferred(delegateToMethod, result, joynrException); Promise<AbstractDeferred> promiseResult = new Promise<>(deferred); return promiseResult; } } finally { if (isProviderMethod(method, delegateToMethod)) { JoynrJeeMessageContext.getInstance().deactivate(); } } return result; } @SuppressWarnings("unchecked") private AbstractDeferred createAndResolveOrRejectDeferred(Method method, Object result, JoynrException joynrException) { AbstractDeferred deferred; if (result == null && method.getReturnType().getTypeName().equals("void")) { deferred = new DeferredVoid(); if (joynrException == null) { ((DeferredVoid) deferred).resolve(); } } else { if (result instanceof MultiReturnValuesContainer) { deferred = new MultiValueDeferred(); if (joynrException == null) { ((MultiValueDeferred) deferred).resolve(((MultiReturnValuesContainer) result).getValues()); } } else { deferred = new Deferred<Object>(); if (joynrException == null) { ((Deferred<Object>) deferred).resolve(result); } } } if (joynrException != null) { logger.debug("Provider method invocation resulted in provider runtime exception - rejecting the deferred {} with {}", deferred, joynrException); if (joynrException instanceof ApplicationException) { try { Method rejectMethod = AbstractDeferred.class.getDeclaredMethod("reject", new Class[]{ JoynrException.class }); rejectMethod.setAccessible(true); rejectMethod.invoke(deferred, new Object[]{ joynrException }); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { logger.warn("Unable to set {} as rejection reason on {}. Wrapping in ProviderRuntimeException instead.", joynrException, deferred); deferred.reject(new ProviderRuntimeException(((ApplicationException) joynrException).getMessage())); } } else if (joynrException instanceof ProviderRuntimeException) { deferred.reject((ProviderRuntimeException) joynrException); } } return deferred; } private JoynrException getJoynrExceptionFromInvocationException(InvocationTargetException e) throws InvocationTargetException { JoynrException joynrException = null; if (e.getCause() instanceof EJBException) { // an EJBException is only thrown when the exception is not in the throws declaration // ApplicationExceptions are always declared with throw and thus EJBExceptions won't be caused by them. Exception exception = ((EJBException) e.getCause()).getCausedByException(); if (exception instanceof ProviderRuntimeException) { joynrException = (ProviderRuntimeException) exception; } else { joynrException = new ProviderRuntimeException("Unexpected exception from provider: " + (exception == null ? e.getCause().toString() : exception.toString())); } } else if (e.getCause() instanceof ProviderRuntimeException || e.getCause() instanceof ApplicationException) { joynrException = (JoynrException) e.getCause(); } if (joynrException == null) { throw e; } logger.trace("Returning joynr exception: {}", joynrException); return joynrException; } private boolean isProviderMethod(Method method, Method delegateToMethod) { boolean result = delegateToMethod != method; if (method.getDeclaringClass().equals(SubscriptionPublisherInjection.class)) { result = false; } return result; } private void copyMessageCreatorInfo() { JoynrMessageCreator joynrMessageCreator = injector.getInstance(JoynrMessageCreator.class); JoynrCallingPrincipal reference = getUniqueBeanReference(JoynrCallingPrincipal.class); String messageCreatorId = joynrMessageCreator.getMessageCreatorId(); logger.trace("Setting user '{}' for message processing context.", messageCreatorId); reference.setUsername(messageCreatorId); } private void copyMessageContext() { JoynrMessageMetaInfo joynrMessageContext = injector.getInstance(JoynrMessageMetaInfo.class); JoynrJeeMessageMetaInfo jeeMessageContext = getUniqueBeanReference(JoynrJeeMessageMetaInfo.class); logger.trace("Setting message context for message processing context."); jeeMessageContext.setMessageContext(joynrMessageContext.getMessageContext()); } private <T> T getUniqueBeanReference(Class<T> beanClass) { Set<Bean<?>> beans = beanManager.getBeans(beanClass); if (beans.size() != 1) { throw new IllegalStateException("There must be exactly one EJB of type " + beanClass.getName() + ". Found " + beans.size()); } @SuppressWarnings("unchecked") Bean<T> bean = (Bean<T>) beans.iterator().next(); @SuppressWarnings("unchecked") T reference = (T) beanManager.getReference(bean, beanClass, beanManager.createCreationalContext(bean)); return reference; } private Object createDelegateForMethod(Method method, boolean isProviderMethod) { if (OBJECT_METHODS.contains(method) || isProviderMethod) { return this; } if (SET_SUBSCRIPTION_PUBLISHER_METHOD_NAME.equals(method.getName()) && SubscriptionPublisherInjection.class.isAssignableFrom(method.getDeclaringClass())) { return SubscriptionPublisherInjectionWrapper.createInvocationHandler(bean, beanManager).createProxy(); } return beanManager.getReference(bean, serviceInterface, beanManager.createCreationalContext(bean)); } private Method getMethodFromInterfaces(Class<?> beanClass, Method method, boolean isProviderMethod) throws NoSuchMethodException { String name = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); Method result = method; if (!isProviderMethod) { result = null; for (Class<?> interfaceClass : beanClass.getInterfaces()) { try { if ((result = interfaceClass.getMethod(name, parameterTypes)) != null) { break; } } catch (NoSuchMethodException | SecurityException e) { if (logger.isTraceEnabled()) { logger.trace(format("Method %s not found on interface %s", name, interfaceClass)); } } } } return result == null ? method : result; } private boolean matchesJoynrProviderMethod(Method method) { boolean result = false; for (Method joynrProviderMethod : JoynrProvider.class.getMethods()) { if (joynrProviderMethod.getName().equals(method.getName()) && Arrays.equals(joynrProviderMethod.getParameterTypes(), method.getParameterTypes())) { result = true; break; } } return result; } }
[Java] Improved handling of unexpected exceptions in ProviderWrapper * Wrap unexpected exceptions (which are neither ProviderRuntimeException nor ApplicationException) into ProviderRuntimeException
java/jeeintegration/src/main/java/io/joynr/jeeintegration/ProviderWrapper.java
[Java] Improved handling of unexpected exceptions in ProviderWrapper
<ide><path>ava/jeeintegration/src/main/java/io/joynr/jeeintegration/ProviderWrapper.java <ide> <ide> private JoynrException getJoynrExceptionFromInvocationException(InvocationTargetException e) throws InvocationTargetException { <ide> JoynrException joynrException = null; <del> if (e.getCause() instanceof EJBException) { <add> Throwable cause = e.getCause(); <add> if (cause instanceof EJBException) { <ide> // an EJBException is only thrown when the exception is not in the throws declaration <ide> // ApplicationExceptions are always declared with throw and thus EJBExceptions won't be caused by them. <del> Exception exception = ((EJBException) e.getCause()).getCausedByException(); <add> Exception exception = ((EJBException) cause).getCausedByException(); <ide> if (exception instanceof ProviderRuntimeException) { <ide> joynrException = (ProviderRuntimeException) exception; <ide> } else { <ide> joynrException = new ProviderRuntimeException("Unexpected exception from provider: " <del> + (exception == null ? e.getCause().toString() : exception.toString())); <del> } <del> } else if (e.getCause() instanceof ProviderRuntimeException || e.getCause() instanceof ApplicationException) { <del> joynrException = (JoynrException) e.getCause(); <add> + (exception == null ? cause.toString() : exception.toString())); <add> } <add> } else if (cause instanceof ProviderRuntimeException || cause instanceof ApplicationException) { <add> joynrException = (JoynrException) cause; <add> } else if (cause instanceof Exception) { <add> joynrException = new ProviderRuntimeException("Unexpected exception from provider: " + cause.toString()); <ide> } <ide> <ide> if (joynrException == null) {
Java
apache-2.0
98b6a01114a2d32285c71f66708279e4fddac28f
0
BastiOfBerlin/BigDataObjectSerializer
package de.tub.cit.slist.bdos; import java.io.Serializable; import java.lang.reflect.UndeclaredThrowableException; import java.util.AbstractSequentialList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.Consumer; import de.tub.cit.slist.bdos.OffHeapSerializer.MemoryLocation; import de.tub.cit.slist.bdos.OffHeapSerializer.SizeType; import de.tub.cit.slist.bdos.util.BigDataCollectionHelper; import de.tub.cit.slist.bdos.util.UnsafeHelper; public class BigDataLinkedList<T extends Serializable> extends AbstractSequentialList<T> implements List<T>, Deque<T>, java.io.Serializable { private static final long serialVersionUID = 6295395861024765218L; /** 1 Byte Status already allocated + 2x4 Bytes pointer next/prev */ private static final int METADATA_BYTES = 8; private final OffHeapSerializer<T> serializer; /** class to be saved */ private final Class<T> baseClass; /** index offset to first free element */ private int firstFree = 0; /** actual size of the list, i.e. number of elements */ private int size = 0; /** index offset to first element */ private int first = -1; /** index offset to last element */ private int last = -1; public BigDataLinkedList(final Class<T> baseClass, final long size, final SizeType sizeType, final MemoryLocation location) { this.baseClass = baseClass; serializer = new OffHeapSerializer<>(baseClass, size, sizeType, location, METADATA_BYTES); } private int getNextPointer(final int idx) { return BigDataCollectionHelper.getNextPointer(serializer, idx); } private void setNextPointer(final int idx, final int pointer) { BigDataCollectionHelper.setNextPointer(serializer, idx, pointer); } private int getPrevPointer(final int idx) { return BigDataCollectionHelper.getPrevPointer(serializer, idx); } private void setPrevPointer(final int idx, final int pointer) { BigDataCollectionHelper.setPrevPointer(serializer, idx, pointer); } /** * Tells if the argument is the index of an existing element. */ private boolean isElementIndex(final long index) { return index >= 0 && index < size; } /** * Tells if the argument is the index of a valid position for an iterator or an add operation. */ private boolean isPositionIndex(final long index) { return index >= 0 && index <= size; } /** * Constructs an IndexOutOfBoundsException detail message. Of the many possible refactorings of the error handling code, this "outlining" performs best with * both server and client VMs. */ private String outOfBoundsMsg(final long index) { return "Index: " + index + ", Size: " + size; } private void checkElementIndex(final long index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void checkPositionIndex(final long index) { if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * Sets the first free block and manages the linked list of free blocks * * @param element * @return index of the new block */ private int setFirstFree(final T element) { final int idx = firstFree; serializer.setRandomAccess(idx, element); firstFree = getNextPointer(idx); // the pointer will be 0 if it was not unlinked before if (firstFree == 0) { firstFree = idx + 1; } return idx; } /** * Deletes a block (nullify) and updates the linked list of free blocks * * @param idx of the to-be-deleted block */ private void deleteElement(final int idx) { serializer.setRandomAccess(idx, null); if (idx < firstFree) { setNextPointer(idx, firstFree); setPrevPointer(idx, 0); firstFree = idx; } else { int free = firstFree; int lastFree = 0; while (free < idx) { lastFree = free; free = getNextPointer(free); } setNextPointer(lastFree, idx); setNextPointer(idx, free); } } /** * Links element as first element. */ private void linkFirst(final T element) { final int f = first; final int newNode = setFirstFree(element); setNextPointer(newNode, f); setPrevPointer(newNode, -1); // undefined first = newNode; if (f == -1) { last = newNode; } else { setPrevPointer(f, newNode); } size++; modCount++; } /** * Links element as last element. */ private void linkLast(final T element) { final int l = last; final int newNode = setFirstFree(element); setNextPointer(newNode, -1); // undefined setPrevPointer(newNode, l); last = newNode; if (l == -1) { first = newNode; } else { setNextPointer(l, newNode); } size++; modCount++; } /** * Inserts element e before non-null Node succ. */ void linkBefore(final T e, final int succ) { assert (succ > 0); final int pred = getPrevPointer(succ); final int newNode = setFirstFree(e); setNextPointer(newNode, succ); setPrevPointer(newNode, pred); setPrevPointer(succ, newNode); if (pred == -1) { first = newNode; } else { setNextPointer(pred, newNode); } size++; modCount++; } /** * Unlinks first node idx. */ private T unlinkFirst(final int idx) { final T element = serializer.getRandomAccess(idx); final int next = getNextPointer(idx); first = next; if (next == -1) { last = -1; } else { setPrevPointer(next, -1); } deleteElement(idx); size--; modCount++; return element; } /** * Unlinks last node idx. */ private T unlinkLast(final int idx) { final T element = serializer.getRandomAccess(idx); final int prev = getPrevPointer(idx); last = prev; if (prev == -1) { first = -1; } else { setNextPointer(prev, -1); } deleteElement(idx); size--; modCount++; return element; } /** * Unlinks non-null node x. */ private T unlink(final int idx) { final T element = serializer.getRandomAccess(idx); final int next = getNextPointer(idx); final int prev = getPrevPointer(idx); if (prev == -1) { first = next; } else { setNextPointer(prev, next); } if (next == -1) { last = prev; } else { setPrevPointer(next, prev); } deleteElement(idx); size--; modCount++; return element; } @Override public void addFirst(final T e) { linkFirst(e); } @Override public void addLast(final T e) { linkLast(e); } /** * Appends the specified element to the end of this list. * * <p> * This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ @Override public boolean add(final T e) { linkLast(e); return true; } /** * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any * subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public void add(final int index, final T element) { checkPositionIndex(index); if (index == size) { linkLast(element); } else { linkBefore(element, node(index)); } } @Override public boolean addAll(final Collection<? extends T> c) { return addAll(size, c); } /** * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * * @param index index at which to insert the first element * from the specified collection * @param c collection containing elements to be added to this list * @return {@code true} if this list changed as a result of the call * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null */ @Override public boolean addAll(final int index, final Collection<? extends T> c) { checkPositionIndex(index); final Object[] a = c.toArray(); final int numNew = a.length; if (numNew == 0) return false; int pred, succ; if (index == size) { succ = -1; pred = last; } else { succ = index; pred = getPrevPointer(succ); } for (final Object o : a) { @SuppressWarnings("unchecked") final T e = (T) o; final int newNode = setFirstFree(e); setPrevPointer(newNode, pred); setNextPointer(newNode, -1); if (pred == -1) { first = newNode; } else { setNextPointer(pred, newNode); } pred = newNode; } if (succ == -1) { last = pred; } else { setNextPointer(pred, succ); setPrevPointer(succ, pred); } size += numNew; modCount++; return true; } @Override public boolean offerFirst(final T e) { if (isFull()) return false; addFirst(e); return true; } @Override public boolean offerLast(final T e) { if (isFull()) return false; addLast(e); return true; } private boolean isFull() { return size >= serializer.getMaxElementCount(); } @Override public boolean remove(final Object o) { try { @SuppressWarnings("unchecked") final T compare = (T) UnsafeHelper.getUnsafe().allocateInstance(baseClass); if (o == null) { for (int x = first; x != -1; x = getNextPointer(x)) { if (serializer.getRandomAccess(compare, x) == null) { unlink(x); return true; } } } else { for (int x = first; x != -1; x = getNextPointer(x)) { if (o.equals(serializer.getRandomAccess(compare, x))) { unlink(x); return true; } } } } catch (final InstantiationException e) { throw new UndeclaredThrowableException(e); } return false; } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public T remove(final int index) { checkElementIndex(index); return unlink(node(index)); } @Override public void clear() { serializer.clear(); firstFree = 0; first = last = -1; size = 0; modCount++; } /** * @throws NoSuchElementException if this list is empty */ @Override public T removeFirst() { final int f = first; if (f == -1) throw new NoSuchElementException(); return unlinkFirst(f); } /** * @throws NoSuchElementException if this list is empty */ @Override public T removeLast() { final int l = last; if (l == -1) throw new NoSuchElementException(); return unlinkLast(l); } @Override public T pollFirst() { final int f = first; return (f == -1) ? null : unlinkFirst(f); } @Override public T pollLast() { final int l = last; return (l == -1) ? null : unlinkLast(l); } /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public T get(final int index) { checkElementIndex(index); return serializer.getRandomAccess(node(index)); } /** * @throws NoSuchElementException if this list is empty */ @Override public T getFirst() { final int f = first; if (f == -1) throw new NoSuchElementException(); return serializer.getRandomAccess(f); } /** * @throws NoSuchElementException if this list is empty */ @Override public T getLast() { final int l = last; if (l == -1) throw new NoSuchElementException(); return serializer.getRandomAccess(l); } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public T set(final int index, final T element) { checkElementIndex(index); final int x = node(index); final T oldVal = serializer.getRandomAccess(x); serializer.setRandomAccess(x, element); return oldVal; } @Override public T peekFirst() { final int f = first; return (f == -1) ? null : serializer.getRandomAccess(f); } @Override public T peekLast() { final int l = last; return (l == -1) ? null : serializer.getRandomAccess(l); } @Override public boolean removeFirstOccurrence(final Object o) { return remove(o); } @Override public boolean removeLastOccurrence(final Object o) { try { @SuppressWarnings("unchecked") final T compare = (T) UnsafeHelper.getUnsafe().allocateInstance(baseClass); if (o == null) { for (int x = last; x != -1; x = getPrevPointer(x)) { if (serializer.getRandomAccess(compare, x) == null) { unlink(x); return true; } } } else { for (int x = last; x != -1; x = getPrevPointer(x)) { if (o.equals(serializer.getRandomAccess(compare, x))) { unlink(x); return true; } } } } catch (final InstantiationException e) { throw new UndeclaredThrowableException(e); } return false; } @Override public boolean offer(final T e) { if (isFull()) return false; return add(e); } @Override public T remove() { return removeFirst(); } @Override public T poll() { final int f = first; return (f == -1) ? null : unlinkFirst(f); } /** * @throws NoSuchElementException if this list is empty */ @Override public T element() { return getFirst(); } @Override public T peek() { final int f = first; return (f == -1) ? null : serializer.getRandomAccess(f); } @Override public void push(final T e) { addFirst(e); } @Override public T pop() { return removeFirst(); } /** * Returns the (non-null) Node at the specified element index. * * @param index * @return */ int node(final int index) { if (index < (size >> 1)) { int x = first; for (long l = 0; l < index; l++) { x = getNextPointer(x); } return x; } else { int x = last; for (long l = size - 1; l > index; l--) { x = getPrevPointer(x); } return x; } } @Override public int indexOf(final Object o) { try { @SuppressWarnings("unchecked") final T compare = (T) UnsafeHelper.getUnsafe().allocateInstance(baseClass); int index = 0; if (o == null) { for (int x = first; x != -1; x = getNextPointer(x)) { if (serializer.getRandomAccess(compare, x) == null) return index; index++; } } else { for (int x = first; x != -1; x = getNextPointer(x)) { if (o.equals(serializer.getRandomAccess(compare, x))) return index; index++; } } } catch (final InstantiationException e) { throw new UndeclaredThrowableException(e); } return -1; } @Override public boolean contains(final Object o) { return indexOf(o) != -1; } @Override public int lastIndexOf(final Object o) { try { @SuppressWarnings("unchecked") final T compare = (T) UnsafeHelper.getUnsafe().allocateInstance(baseClass); int index = size; if (o == null) { for (int x = last; x != -1; x = getPrevPointer(x)) { index--; if (serializer.getRandomAccess(compare, x) == null) return index; } } else { for (int x = last; x != -1; x = getPrevPointer(x)) { index--; if (o.equals(serializer.getRandomAccess(compare, x))) return index; } } } catch (final InstantiationException e) { throw new UndeclaredThrowableException(e); } return -1; } @Override public Iterator<T> descendingIterator() { return new DescendingIterator(); } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public ListIterator<T> listIterator(final int index) { checkPositionIndex(index); return new ListItr(index); } @Override public int size() { return size; } @Override public Object[] toArray() { final Object[] result = new Object[size]; int i = 0; for (int x = first; x != -1; x = getNextPointer(x)) { result[i++] = serializer.getRandomAccess(x); } return result; } /** * Returns an array containing all of the elements in this list in * proper sequence (from first to last element); the runtime type of * the returned array is that of the specified array. If the list fits * in the specified array, it is returned therein. Otherwise, a new * array is allocated with the runtime type of the specified array and * the size of this list. * * <p> * If the list fits in the specified array with room to spare (i.e., * the array has more elements than the list), the element in the array * immediately following the end of the list is set to {@code null}. * (This is useful in determining the length of the list <i>only</i> if * the caller knows that the list does not contain any null elements.) * * <p> * Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p> * Suppose {@code x} is a list known to contain only strings. * The following code can be used to dump the list into a newly * allocated array of {@code String}: * * <pre> * String[] y = x.toArray(new String[0]); * </pre> * * Note that {@code toArray(new Object[0])} is identical in function to * {@code toArray()}. * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ @Override @SuppressWarnings("unchecked") public <X> X[] toArray(X[] a) { if (a.length < size) { a = (X[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); } int i = 0; final Object[] result = a; for (int x = first; x != -1; x = getNextPointer(x)) { result[i++] = serializer.getRandomAccess(x); } if (a.length > size) { a[size] = null; } return a; } private class ListItr implements ListIterator<T> { private int lastReturned = -1; private int next = -1; private int nextIndex; private int expectedModCount = modCount; ListItr(final int index) { // assert isPositionIndex(index); next = (index == size) ? null : node(index); nextIndex = index; } @Override public boolean hasNext() { return nextIndex < size; } @Override public T next() { checkForComodification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = getNextPointer(next); nextIndex++; return serializer.getRandomAccess(lastReturned); } @Override public boolean hasPrevious() { return nextIndex > 0; } @Override public T previous() { checkForComodification(); if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = next = (next == -1) ? last : getPrevPointer(next); nextIndex--; return serializer.getRandomAccess(lastReturned); } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void remove() { checkForComodification(); if (lastReturned == -1) throw new IllegalStateException(); final int lastNext = getNextPointer(lastReturned); unlink(lastReturned); if (next == lastReturned) { next = lastNext; } else { nextIndex--; } expectedModCount++; } @Override public void set(final T e) { if (lastReturned == -1) throw new IllegalStateException(); checkForComodification(); serializer.setRandomAccess(lastReturned, e); } @Override public void add(final T e) { checkForComodification(); lastReturned = -1; if (next == -1) { linkLast(e); } else { linkBefore(e, next); } nextIndex++; expectedModCount++; } @Override public void forEachRemaining(final Consumer<? super T> action) { Objects.requireNonNull(action); while (modCount == expectedModCount && nextIndex < size) { action.accept(serializer.getRandomAccess(next)); lastReturned = next; next = getNextPointer(next); nextIndex++; } checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** * Adapter to provide descending iterators via ListItr.previous */ private class DescendingIterator implements Iterator<T> { private final ListItr itr = new ListItr(size()); @Override public boolean hasNext() { return itr.hasPrevious(); } @Override public T next() { return itr.previous(); } @Override public void remove() { itr.remove(); } } @Override protected void finalize() throws Throwable { serializer.destroy(); super.finalize(); } }
src/main/java/de/tub/cit/slist/bdos/BigDataLinkedList.java
package de.tub.cit.slist.bdos; import java.io.Serializable; import java.lang.reflect.UndeclaredThrowableException; import java.util.AbstractSequentialList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.Consumer; import de.tub.cit.slist.bdos.OffHeapSerializer.MemoryLocation; import de.tub.cit.slist.bdos.OffHeapSerializer.SizeType; import de.tub.cit.slist.bdos.util.BigDataCollectionHelper; import de.tub.cit.slist.bdos.util.UnsafeHelper; public class BigDataLinkedList<T extends Serializable> extends AbstractSequentialList<T> implements List<T>, Deque<T>, java.io.Serializable { private static final long serialVersionUID = 6295395861024765218L; /** 1 Byte Status already allocated + 2x4 Bytes pointer next/prev */ private static final int METADATA_BYTES = 8; private final OffHeapSerializer<T> serializer; /** class to be saved */ private final Class<T> baseClass; /** index offset to first free element */ private int firstFree = 0; /** actual size of the list, i.e. number of elements */ private int size = 0; /** index offset to first element */ private int first = -1; /** index offset to last element */ private int last = -1; public BigDataLinkedList(final Class<T> baseClass, final long size, final SizeType sizeType, final MemoryLocation location) { this.baseClass = baseClass; serializer = new OffHeapSerializer<>(baseClass, size, sizeType, location, METADATA_BYTES); } private int getNextPointer(final int idx) { return BigDataCollectionHelper.getNextPointer(serializer, idx); } private void setNextPointer(final int idx, final int pointer) { BigDataCollectionHelper.setNextPointer(serializer, idx, pointer); } private int getPrevPointer(final int idx) { return BigDataCollectionHelper.getPrevPointer(serializer, idx); } private void setPrevPointer(final int idx, final int pointer) { BigDataCollectionHelper.setPrevPointer(serializer, idx, pointer); } /** * Tells if the argument is the index of an existing element. */ private boolean isElementIndex(final long index) { return index >= 0 && index < size; } /** * Tells if the argument is the index of a valid position for an iterator or an add operation. */ private boolean isPositionIndex(final long index) { return index >= 0 && index <= size; } /** * Constructs an IndexOutOfBoundsException detail message. Of the many possible refactorings of the error handling code, this "outlining" performs best with * both server and client VMs. */ private String outOfBoundsMsg(final long index) { return "Index: " + index + ", Size: " + size; } private void checkElementIndex(final long index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void checkPositionIndex(final long index) { if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * Sets the first free block and manages the linked list of free blocks * * @param element * @return index of the new block */ private int setFirstFree(final T element) { final int idx = firstFree; serializer.setRandomAccess(idx, element); firstFree = getNextPointer(idx); // the pointer will be 0 if it was not unlinked before if (firstFree == 0) { firstFree = idx + 1; } return idx; } /** * Deletes a block (nullify) and updates the linked list of free blocks * * @param idx of the to-be-deleted block */ private void deleteElement(final int idx) { serializer.setRandomAccess(idx, null); if (idx < firstFree) { setNextPointer(idx, firstFree); setPrevPointer(idx, 0); firstFree = idx; } else { int free = firstFree; int lastFree = 0; while (free < idx) { lastFree = free; free = getNextPointer(free); } setNextPointer(lastFree, idx); setNextPointer(idx, free); } } /** * Links element as first element. */ private void linkFirst(final T element) { final int f = first; final int newNode = setFirstFree(element); setNextPointer(newNode, f); setPrevPointer(newNode, -1); // undefined first = newNode; if (f == -1) { last = newNode; } else { setPrevPointer(f, newNode); } size++; modCount++; } /** * Links element as last element. */ private void linkLast(final T element) { final int l = last; final int newNode = setFirstFree(element); setNextPointer(newNode, -1); // undefined setPrevPointer(newNode, l); last = newNode; if (l == -1) { first = newNode; } else { setNextPointer(l, newNode); } size++; modCount++; } /** * Inserts element e before non-null Node succ. */ void linkBefore(final T e, final int succ) { assert (succ > 0); final int pred = getPrevPointer(succ); final int newNode = setFirstFree(e); setNextPointer(newNode, succ); setPrevPointer(newNode, pred); setPrevPointer(succ, newNode); if (pred == -1) { first = newNode; } else { setNextPointer(pred, newNode); } size++; modCount++; } /** * Unlinks first node idx. */ private T unlinkFirst(final int idx) { final T element = serializer.getRandomAccess(idx); final int next = getNextPointer(idx); first = next; if (next == -1) { last = -1; } else { setPrevPointer(next, -1); } deleteElement(idx); size--; modCount++; return element; } /** * Unlinks last node idx. */ private T unlinkLast(final int idx) { final T element = serializer.getRandomAccess(idx); final int prev = getPrevPointer(idx); last = prev; if (prev == -1) { first = -1; } else { setNextPointer(prev, -1); } deleteElement(idx); size--; modCount++; return element; } /** * Unlinks non-null node x. */ private T unlink(final int idx) { final T element = serializer.getRandomAccess(idx); final int next = getNextPointer(idx); final int prev = getPrevPointer(idx); if (prev == -1) { first = next; } else { setNextPointer(prev, next); } if (next == -1) { last = prev; } else { setPrevPointer(next, prev); } deleteElement(idx); size--; modCount++; return element; } @Override public void addFirst(final T e) { linkFirst(e); } @Override public void addLast(final T e) { linkLast(e); } /** * Appends the specified element to the end of this list. * * <p> * This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ @Override public boolean add(final T e) { linkLast(e); return true; } /** * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any * subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public void add(final int index, final T element) { checkPositionIndex(index); if (index == size) { linkLast(element); } else { linkBefore(element, node(index)); } } @Override public boolean addAll(final Collection<? extends T> c) { return addAll(size, c); } /** * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * * @param index index at which to insert the first element * from the specified collection * @param c collection containing elements to be added to this list * @return {@code true} if this list changed as a result of the call * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null */ @Override public boolean addAll(final int index, final Collection<? extends T> c) { checkPositionIndex(index); final Object[] a = c.toArray(); final int numNew = a.length; if (numNew == 0) return false; int pred, succ; if (index == size) { succ = -1; pred = last; } else { succ = index; pred = getPrevPointer(succ); } for (final Object o : a) { @SuppressWarnings("unchecked") final T e = (T) o; final int newNode = setFirstFree(e); setPrevPointer(newNode, pred); setNextPointer(newNode, -1); if (pred == -1) { first = newNode; } else { setNextPointer(pred, newNode); } pred = newNode; } if (succ == -1) { last = pred; } else { setNextPointer(pred, succ); setPrevPointer(succ, pred); } size += numNew; modCount++; return true; } @Override public boolean offerFirst(final T e) { addFirst(e); return true; } @Override public boolean offerLast(final T e) { addLast(e); return true; } @Override public boolean remove(final Object o) { try { @SuppressWarnings("unchecked") final T compare = (T) UnsafeHelper.getUnsafe().allocateInstance(baseClass); if (o == null) { for (int x = first; x != -1; x = getNextPointer(x)) { if (serializer.getRandomAccess(compare, x) == null) { unlink(x); return true; } } } else { for (int x = first; x != -1; x = getNextPointer(x)) { if (o.equals(serializer.getRandomAccess(compare, x))) { unlink(x); return true; } } } } catch (final InstantiationException e) { throw new UndeclaredThrowableException(e); } return false; } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public T remove(final int index) { checkElementIndex(index); return unlink(node(index)); } @Override public void clear() { serializer.clear(); firstFree = 0; first = last = -1; size = 0; modCount++; } /** * @throws NoSuchElementException if this list is empty */ @Override public T removeFirst() { final int f = first; if (f == -1) throw new NoSuchElementException(); return unlinkFirst(f); } /** * @throws NoSuchElementException if this list is empty */ @Override public T removeLast() { final int l = last; if (l == -1) throw new NoSuchElementException(); return unlinkLast(l); } @Override public T pollFirst() { final int f = first; return (f == -1) ? null : unlinkFirst(f); } @Override public T pollLast() { final int l = last; return (l == -1) ? null : unlinkLast(l); } /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public T get(final int index) { checkElementIndex(index); return serializer.getRandomAccess(node(index)); } /** * @throws NoSuchElementException if this list is empty */ @Override public T getFirst() { final int f = first; if (f == -1) throw new NoSuchElementException(); return serializer.getRandomAccess(f); } /** * @throws NoSuchElementException if this list is empty */ @Override public T getLast() { final int l = last; if (l == -1) throw new NoSuchElementException(); return serializer.getRandomAccess(l); } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public T set(final int index, final T element) { checkElementIndex(index); final int x = node(index); final T oldVal = serializer.getRandomAccess(x); serializer.setRandomAccess(x, element); return oldVal; } @Override public T peekFirst() { final int f = first; return (f == -1) ? null : serializer.getRandomAccess(f); } @Override public T peekLast() { final int l = last; return (l == -1) ? null : serializer.getRandomAccess(l); } @Override public boolean removeFirstOccurrence(final Object o) { return remove(o); } @Override public boolean removeLastOccurrence(final Object o) { try { @SuppressWarnings("unchecked") final T compare = (T) UnsafeHelper.getUnsafe().allocateInstance(baseClass); if (o == null) { for (int x = last; x != -1; x = getPrevPointer(x)) { if (serializer.getRandomAccess(compare, x) == null) { unlink(x); return true; } } } else { for (int x = last; x != -1; x = getPrevPointer(x)) { if (o.equals(serializer.getRandomAccess(compare, x))) { unlink(x); return true; } } } } catch (final InstantiationException e) { throw new UndeclaredThrowableException(e); } return false; } @Override public boolean offer(final T e) { return add(e); } @Override public T remove() { return removeFirst(); } @Override public T poll() { final int f = first; return (f == -1) ? null : unlinkFirst(f); } /** * @throws NoSuchElementException if this list is empty */ @Override public T element() { return getFirst(); } @Override public T peek() { final int f = first; return (f == -1) ? null : serializer.getRandomAccess(f); } @Override public void push(final T e) { addFirst(e); } @Override public T pop() { return removeFirst(); } /** * Returns the (non-null) Node at the specified element index. * * @param index * @return */ int node(final int index) { if (index < (size >> 1)) { int x = first; for (long l = 0; l < index; l++) { x = getNextPointer(x); } return x; } else { int x = last; for (long l = size - 1; l > index; l--) { x = getPrevPointer(x); } return x; } } @Override public int indexOf(final Object o) { try { @SuppressWarnings("unchecked") final T compare = (T) UnsafeHelper.getUnsafe().allocateInstance(baseClass); int index = 0; if (o == null) { for (int x = first; x != -1; x = getNextPointer(x)) { if (serializer.getRandomAccess(compare, x) == null) return index; index++; } } else { for (int x = first; x != -1; x = getNextPointer(x)) { if (o.equals(serializer.getRandomAccess(compare, x))) return index; index++; } } } catch (final InstantiationException e) { throw new UndeclaredThrowableException(e); } return -1; } @Override public boolean contains(final Object o) { return indexOf(o) != -1; } @Override public int lastIndexOf(final Object o) { try { @SuppressWarnings("unchecked") final T compare = (T) UnsafeHelper.getUnsafe().allocateInstance(baseClass); int index = size; if (o == null) { for (int x = last; x != -1; x = getPrevPointer(x)) { index--; if (serializer.getRandomAccess(compare, x) == null) return index; } } else { for (int x = last; x != -1; x = getPrevPointer(x)) { index--; if (o.equals(serializer.getRandomAccess(compare, x))) return index; } } } catch (final InstantiationException e) { throw new UndeclaredThrowableException(e); } return -1; } @Override public Iterator<T> descendingIterator() { return new DescendingIterator(); } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public ListIterator<T> listIterator(final int index) { checkPositionIndex(index); return new ListItr(index); } @Override public int size() { return size; } @Override public Object[] toArray() { final Object[] result = new Object[size]; int i = 0; for (int x = first; x != -1; x = getNextPointer(x)) { result[i++] = serializer.getRandomAccess(x); } return result; } /** * Returns an array containing all of the elements in this list in * proper sequence (from first to last element); the runtime type of * the returned array is that of the specified array. If the list fits * in the specified array, it is returned therein. Otherwise, a new * array is allocated with the runtime type of the specified array and * the size of this list. * * <p> * If the list fits in the specified array with room to spare (i.e., * the array has more elements than the list), the element in the array * immediately following the end of the list is set to {@code null}. * (This is useful in determining the length of the list <i>only</i> if * the caller knows that the list does not contain any null elements.) * * <p> * Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p> * Suppose {@code x} is a list known to contain only strings. * The following code can be used to dump the list into a newly * allocated array of {@code String}: * * <pre> * String[] y = x.toArray(new String[0]); * </pre> * * Note that {@code toArray(new Object[0])} is identical in function to * {@code toArray()}. * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ @Override @SuppressWarnings("unchecked") public <X> X[] toArray(X[] a) { if (a.length < size) { a = (X[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); } int i = 0; final Object[] result = a; for (int x = first; x != -1; x = getNextPointer(x)) { result[i++] = serializer.getRandomAccess(x); } if (a.length > size) { a[size] = null; } return a; } private class ListItr implements ListIterator<T> { private int lastReturned = -1; private int next = -1; private int nextIndex; private int expectedModCount = modCount; ListItr(final int index) { // assert isPositionIndex(index); next = (index == size) ? null : node(index); nextIndex = index; } @Override public boolean hasNext() { return nextIndex < size; } @Override public T next() { checkForComodification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = getNextPointer(next); nextIndex++; return serializer.getRandomAccess(lastReturned); } @Override public boolean hasPrevious() { return nextIndex > 0; } @Override public T previous() { checkForComodification(); if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = next = (next == -1) ? last : getPrevPointer(next); nextIndex--; return serializer.getRandomAccess(lastReturned); } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void remove() { checkForComodification(); if (lastReturned == -1) throw new IllegalStateException(); final int lastNext = getNextPointer(lastReturned); unlink(lastReturned); if (next == lastReturned) { next = lastNext; } else { nextIndex--; } expectedModCount++; } @Override public void set(final T e) { if (lastReturned == -1) throw new IllegalStateException(); checkForComodification(); serializer.setRandomAccess(lastReturned, e); } @Override public void add(final T e) { checkForComodification(); lastReturned = -1; if (next == -1) { linkLast(e); } else { linkBefore(e, next); } nextIndex++; expectedModCount++; } @Override public void forEachRemaining(final Consumer<? super T> action) { Objects.requireNonNull(action); while (modCount == expectedModCount && nextIndex < size) { action.accept(serializer.getRandomAccess(next)); lastReturned = next; next = getNextPointer(next); nextIndex++; } checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** * Adapter to provide descending iterators via ListItr.previous */ private class DescendingIterator implements Iterator<T> { private final ListItr itr = new ListItr(size()); @Override public boolean hasNext() { return itr.hasPrevious(); } @Override public T next() { return itr.previous(); } @Override public void remove() { itr.remove(); } } @Override protected void finalize() throws Throwable { serializer.destroy(); super.finalize(); } }
ofer(): returning false iff underlying memory is already full
src/main/java/de/tub/cit/slist/bdos/BigDataLinkedList.java
ofer(): returning false iff underlying memory is already full
<ide><path>rc/main/java/de/tub/cit/slist/bdos/BigDataLinkedList.java <ide> <ide> @Override <ide> public boolean offerFirst(final T e) { <add> if (isFull()) return false; <ide> addFirst(e); <ide> return true; <ide> } <ide> <ide> @Override <ide> public boolean offerLast(final T e) { <add> if (isFull()) return false; <ide> addLast(e); <ide> return true; <add> } <add> <add> private boolean isFull() { <add> return size >= serializer.getMaxElementCount(); <ide> } <ide> <ide> @Override <ide> <ide> @Override <ide> public boolean offer(final T e) { <add> if (isFull()) return false; <ide> return add(e); <ide> } <ide>
Java
apache-2.0
2640753a388e6066a7075e7bf6aeb9179f897425
0
data-integrations/database-delta-plugins
/* * Copyright © 2020 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.delta.mysql; import io.cdap.cdap.api.data.format.StructuredRecord; import io.cdap.delta.api.DDLEvent; import io.cdap.delta.api.DDLOperation; import io.cdap.delta.api.DMLEvent; import io.cdap.delta.api.DMLOperation; import io.cdap.delta.api.DeltaSourceContext; import io.cdap.delta.api.EventEmitter; import io.cdap.delta.api.Offset; import io.cdap.delta.common.Records; import io.debezium.connector.mysql.MySqlValueConverters; import io.debezium.relational.Table; import io.debezium.relational.TableId; import io.debezium.relational.Tables; import io.debezium.relational.ddl.DdlParser; import io.debezium.relational.ddl.DdlParserListener; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.source.SourceRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; /** * Record consumer for MySQL. */ public class MySqlRecordConsumer implements Consumer<SourceRecord> { private static final Logger LOG = LoggerFactory.getLogger(MySqlRecordConsumer.class); private final DeltaSourceContext context; private final EventEmitter emitter; private final DdlParser ddlParser; private final MySqlValueConverters mySqlValueConverters; private final Tables tables; public MySqlRecordConsumer(DeltaSourceContext context, EventEmitter emitter, DdlParser ddlParser, MySqlValueConverters mySqlValueConverters, Tables tables) { this.context = context; this.emitter = emitter; this.ddlParser = ddlParser; this.mySqlValueConverters = mySqlValueConverters; this.tables = tables; } @Override public void accept(SourceRecord sourceRecord) { /* For ddl, struct contains 3 top level fields: source struct databaseName string ddl string Before every DDL event, a weird event with ddl='# Dum' is consumed before the actual event. source is a struct with 14 fields: 0 - version string (debezium version) 1 - connector string 2 - name string (name of the consumer, set when creating the Configuration) 3 - server_id int64 4 - ts_sec int64 5 - gtid string 6 - file string 7 - pos int64 (there can be multiple events for the same file and position. Everything in same position seems to be anything done in the same query) 8 - row int32 (if multiple rows are involved in the same transaction, this is the row #) 9 - snapshot boolean (null is the same as false) 10 - thread int64 11 - db string 12 - table string 13 - query string For dml, struct contains 5 top level fields: 0 - before struct 1 - after struct 2 - source struct 3 - op string (c for create or insert, u for update, d for delete, and r for read) not sure when 'r' happens, it's not for select queries... 4 - ts_ms int64 (this is *not* the timestamp of the event, but the timestamp when Debezium read it) before is a struct representing the row before the operation. It will have a schema matching the table schema after is a struct representing the row after the operation. It will have a schema matching the table schema */ try { context.setOK(); } catch (IOException e) { LOG.warn("Unable to set source state to OK.", e); } if (sourceRecord.value() == null) { return; } Map<String, String> deltaOffset = generateCdapOffsets(sourceRecord); Offset recordOffset = new Offset(deltaOffset); StructuredRecord val = Records.convert((Struct) sourceRecord.value()); String ddl = val.get("ddl"); StructuredRecord source = val.get("source"); if (source == null) { // This should not happen, 'source' is a mandatory field in sourceRecord from debezium return; } boolean isSnapshot = Boolean.TRUE.equals(source.get(MySqlConstantOffsetBackingStore.SNAPSHOT)); if (ddl != null) { ddlParser.getDdlChanges().reset(); ddlParser.parse(ddl, tables); ddlParser.getDdlChanges().groupEventsByDatabase((databaseName, events) -> { for (DdlParserListener.Event event : events) { DDLEvent.Builder builder = DDLEvent.builder() .setDatabase(databaseName) .setOffset(recordOffset) .setSnapshot(isSnapshot); switch (event.type()) { case ALTER_TABLE: DdlParserListener.TableAlteredEvent alteredEvent = (DdlParserListener.TableAlteredEvent) event; if (alteredEvent.previousTableId() != null) { builder.setOperation(DDLOperation.RENAME_TABLE) .setPrevTable(alteredEvent.previousTableId().table()); } else { builder.setOperation(DDLOperation.ALTER_TABLE); } TableId tableId = alteredEvent.tableId(); Table table = tables.forTable(tableId); emitter.emit(builder.setTable(tableId.table()) .setSchema(Records.getSchema(table, mySqlValueConverters)) .setPrimaryKey(table.primaryKeyColumnNames()) .build()); break; case DROP_TABLE: DdlParserListener.TableDroppedEvent droppedEvent = (DdlParserListener.TableDroppedEvent) event; emitter.emit(builder.setOperation(DDLOperation.DROP_TABLE) .setTable(droppedEvent.tableId().table()) .build()); break; case CREATE_TABLE: DdlParserListener.TableCreatedEvent createdEvent = (DdlParserListener.TableCreatedEvent) event; tableId = createdEvent.tableId(); table = tables.forTable(tableId); emitter.emit(builder.setOperation(DDLOperation.CREATE_TABLE) .setTable(tableId.table()) .setSchema(Records.getSchema(table, mySqlValueConverters)) .setPrimaryKey(table.primaryKeyColumnNames()) .build()); break; case DROP_DATABASE: emitter.emit(builder.setOperation(DDLOperation.DROP_DATABASE).build()); break; case CREATE_DATABASE: emitter.emit(builder.setOperation(DDLOperation.CREATE_DATABASE).build()); break; case TRUNCATE_TABLE: DdlParserListener.TableTruncatedEvent truncatedEvent = (DdlParserListener.TableTruncatedEvent) event; emitter.emit(builder.setOperation(DDLOperation.TRUNCATE_TABLE) .setTable(truncatedEvent.tableId().table()) .build()); break; default: return; } } }); return; } DMLOperation op; String opStr = val.get("op"); if ("c".equals(opStr)) { op = DMLOperation.INSERT; } else if ("u".equals(opStr)) { op = DMLOperation.UPDATE; } else if ("d".equals(opStr)) { op = DMLOperation.DELETE; } else { LOG.warn("Skipping unknown operation type '{}'", opStr); return; } String database = source.get("db"); String table = source.get("table"); String transactionId = source.get("gtid"); if (transactionId == null) { // this is not really a transaction id, but we don't get an event when a transaction started/ended transactionId = String.format("%s:%d", source.get(MySqlConstantOffsetBackingStore.FILE), source.get(MySqlConstantOffsetBackingStore.POS)); } StructuredRecord before = val.get("before"); StructuredRecord after = val.get("after"); Long ingestTime = val.get("ts_ms"); DMLEvent.Builder builder = DMLEvent.builder() .setOffset(recordOffset) .setOperation(op) .setDatabase(database) .setTable(table) .setTransactionId(transactionId) .setIngestTimestamp(ingestTime) .setSnapshot(isSnapshot); // It is required for the source to provide the previous row if the dml operation is 'UPDATE' if (op == DMLOperation.UPDATE) { emitter.emit(builder.setPreviousRow(before).setRow(after).build()); } else if (op == DMLOperation.DELETE) { emitter.emit(builder.setRow(before).build()); } else { emitter.emit(builder.setRow(after).build()); } } // This method is used for generating a cdap offsets from debezium sourceRecord. private Map<String, String> generateCdapOffsets(SourceRecord sourceRecord) { Map<String, String> deltaOffset = new HashMap<>(); Struct value = (Struct) sourceRecord.value(); if (value == null) { // safety check to avoid NPE return deltaOffset; } Struct source = (Struct) value.get("source"); if (source == null) { // safety check to avoid NPE return deltaOffset; } String binlogFile = (String) source.get(MySqlConstantOffsetBackingStore.FILE); Long binlogPosition = (Long) source.get(MySqlConstantOffsetBackingStore.POS); Boolean snapshot = (Boolean) source.get(MySqlConstantOffsetBackingStore.SNAPSHOT); if (binlogFile != null) { deltaOffset.put(MySqlConstantOffsetBackingStore.FILE, binlogFile); } if (binlogPosition != null) { deltaOffset.put(MySqlConstantOffsetBackingStore.POS, String.valueOf(binlogPosition)); } if (snapshot != null) { deltaOffset.put(MySqlConstantOffsetBackingStore.SNAPSHOT, String.valueOf(snapshot)); } return deltaOffset; } }
mysql-delta-plugins/src/main/java/io/cdap/delta/mysql/MySqlRecordConsumer.java
/* * Copyright © 2020 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.delta.mysql; import io.cdap.cdap.api.data.format.StructuredRecord; import io.cdap.delta.api.DDLEvent; import io.cdap.delta.api.DDLOperation; import io.cdap.delta.api.DMLEvent; import io.cdap.delta.api.DMLOperation; import io.cdap.delta.api.DeltaSourceContext; import io.cdap.delta.api.EventEmitter; import io.cdap.delta.api.Offset; import io.cdap.delta.common.Records; import io.debezium.connector.mysql.MySqlValueConverters; import io.debezium.relational.Table; import io.debezium.relational.TableId; import io.debezium.relational.Tables; import io.debezium.relational.ddl.DdlParser; import io.debezium.relational.ddl.DdlParserListener; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.source.SourceRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; /** * Record consumer for MySQL. */ public class MySqlRecordConsumer implements Consumer<SourceRecord> { private static final Logger LOG = LoggerFactory.getLogger(MySqlRecordConsumer.class); private final DeltaSourceContext context; private final EventEmitter emitter; private final DdlParser ddlParser; private final MySqlValueConverters mySqlValueConverters; private final Tables tables; public MySqlRecordConsumer(DeltaSourceContext context, EventEmitter emitter, DdlParser ddlParser, MySqlValueConverters mySqlValueConverters, Tables tables) { this.context = context; this.emitter = emitter; this.ddlParser = ddlParser; this.mySqlValueConverters = mySqlValueConverters; this.tables = tables; } @Override public void accept(SourceRecord sourceRecord) { /* For ddl, struct contains 3 top level fields: source struct databaseName string ddl string Before every DDL event, a weird event with ddl='# Dum' is consumed before the actual event. source is a struct with 14 fields: 0 - version string (debezium version) 1 - connector string 2 - name string (name of the consumer, set when creating the Configuration) 3 - server_id int64 4 - ts_sec int64 5 - gtid string 6 - file string 7 - pos int64 (there can be multiple events for the same file and position. Everything in same position seems to be anything done in the same query) 8 - row int32 (if multiple rows are involved in the same transaction, this is the row #) 9 - snapshot boolean (null is the same as false) 10 - thread int64 11 - db string 12 - table string 13 - query string For dml, struct contains 5 top level fields: 0 - before struct 1 - after struct 2 - source struct 3 - op string (c for create or insert, u for update, d for delete, and r for read) not sure when 'r' happens, it's not for select queries... 4 - ts_ms int64 (this is *not* the timestamp of the event, but the timestamp when Debezium read it) before is a struct representing the row before the operation. It will have a schema matching the table schema after is a struct representing the row after the operation. It will have a schema matching the table schema */ try { context.setOK(); } catch (IOException e) { LOG.warn("Unable to set source state to OK.", e); } if (sourceRecord.value() == null) { return; } Map<String, String> deltaOffset = generateCdapOffsets(sourceRecord); Offset recordOffset = new Offset(deltaOffset); StructuredRecord val = Records.convert((Struct) sourceRecord.value()); String ddl = val.get("ddl"); StructuredRecord source = val.get("source"); if (source == null) { // This should not happen, 'source' is a mandatory field in sourceRecord from debezium return; } boolean isSnapshot = Boolean.TRUE.equals(source.get("snapshot")); if (ddl != null) { ddlParser.getDdlChanges().reset(); ddlParser.parse(ddl, tables); ddlParser.getDdlChanges().groupEventsByDatabase((databaseName, events) -> { for (DdlParserListener.Event event : events) { DDLEvent.Builder builder = DDLEvent.builder() .setDatabase(databaseName) .setOffset(recordOffset) .setSnapshot(isSnapshot); switch (event.type()) { case ALTER_TABLE: DdlParserListener.TableAlteredEvent alteredEvent = (DdlParserListener.TableAlteredEvent) event; if (alteredEvent.previousTableId() != null) { builder.setOperation(DDLOperation.RENAME_TABLE) .setPrevTable(alteredEvent.previousTableId().table()); } else { builder.setOperation(DDLOperation.ALTER_TABLE); } TableId tableId = alteredEvent.tableId(); Table table = tables.forTable(tableId); emitter.emit(builder.setTable(tableId.table()) .setSchema(Records.getSchema(table, mySqlValueConverters)) .setPrimaryKey(table.primaryKeyColumnNames()) .build()); break; case DROP_TABLE: DdlParserListener.TableDroppedEvent droppedEvent = (DdlParserListener.TableDroppedEvent) event; emitter.emit(builder.setOperation(DDLOperation.DROP_TABLE) .setTable(droppedEvent.tableId().table()) .build()); break; case CREATE_TABLE: DdlParserListener.TableCreatedEvent createdEvent = (DdlParserListener.TableCreatedEvent) event; tableId = createdEvent.tableId(); table = tables.forTable(tableId); emitter.emit(builder.setOperation(DDLOperation.CREATE_TABLE) .setTable(tableId.table()) .setSchema(Records.getSchema(table, mySqlValueConverters)) .setPrimaryKey(table.primaryKeyColumnNames()) .build()); break; case DROP_DATABASE: emitter.emit(builder.setOperation(DDLOperation.DROP_DATABASE).build()); break; case CREATE_DATABASE: emitter.emit(builder.setOperation(DDLOperation.CREATE_DATABASE).build()); break; case TRUNCATE_TABLE: DdlParserListener.TableTruncatedEvent truncatedEvent = (DdlParserListener.TableTruncatedEvent) event; emitter.emit(builder.setOperation(DDLOperation.TRUNCATE_TABLE) .setTable(truncatedEvent.tableId().table()) .build()); break; default: return; } } }); return; } DMLOperation op; String opStr = val.get("op"); if ("c".equals(opStr)) { op = DMLOperation.INSERT; } else if ("u".equals(opStr)) { op = DMLOperation.UPDATE; } else if ("d".equals(opStr)) { op = DMLOperation.DELETE; } else { LOG.warn("Skipping unknown operation type '{}'", opStr); return; } String database = source.get("db"); String table = source.get("table"); String transactionId = source.get("gtid"); if (transactionId == null) { // this is not really a transaction id, but we don't get an event when a transaction started/ended transactionId = String.format("%s:%d", source.get(MySqlConstantOffsetBackingStore.FILE), source.get(MySqlConstantOffsetBackingStore.POS)); } StructuredRecord before = val.get("before"); StructuredRecord after = val.get("after"); Long ingestTime = val.get("ts_ms"); DMLEvent.Builder builder = DMLEvent.builder() .setOffset(recordOffset) .setOperation(op) .setDatabase(database) .setTable(table) .setTransactionId(transactionId) .setIngestTimestamp(ingestTime) .setSnapshot(isSnapshot); // It is required for the source to provide the previous row if the dml operation is 'UPDATE' if (op == DMLOperation.UPDATE) { emitter.emit(builder.setPreviousRow(before).setRow(after).build()); } else if (op == DMLOperation.DELETE) { emitter.emit(builder.setRow(before).build()); } else { emitter.emit(builder.setRow(after).build()); } } // This method is used for generating a cdap offsets from debezium sourceRecord. private Map<String, String> generateCdapOffsets(SourceRecord sourceRecord) { Map<String, String> deltaOffset = new HashMap<>(); Struct value = (Struct) sourceRecord.value(); if (value == null) { // safety check to avoid NPE return deltaOffset; } Struct source = (Struct) value.get("source"); if (source == null) { // safety check to avoid NPE return deltaOffset; } String binlogFile = (String) source.get(MySqlConstantOffsetBackingStore.FILE); Long binlogPosition = (Long) source.get(MySqlConstantOffsetBackingStore.POS); Boolean snapshot = (Boolean) source.get(MySqlConstantOffsetBackingStore.SNAPSHOT); if (binlogFile != null) { deltaOffset.put(MySqlConstantOffsetBackingStore.FILE, binlogFile); } if (binlogPosition != null) { deltaOffset.put(MySqlConstantOffsetBackingStore.POS, String.valueOf(binlogPosition)); } if (snapshot != null) { deltaOffset.put(MySqlConstantOffsetBackingStore.SNAPSHOT, String.valueOf(snapshot)); } return deltaOffset; } }
Reuse the static Snapshot variable.
mysql-delta-plugins/src/main/java/io/cdap/delta/mysql/MySqlRecordConsumer.java
Reuse the static Snapshot variable.
<ide><path>ysql-delta-plugins/src/main/java/io/cdap/delta/mysql/MySqlRecordConsumer.java <ide> // This should not happen, 'source' is a mandatory field in sourceRecord from debezium <ide> return; <ide> } <del> boolean isSnapshot = Boolean.TRUE.equals(source.get("snapshot")); <add> boolean isSnapshot = Boolean.TRUE.equals(source.get(MySqlConstantOffsetBackingStore.SNAPSHOT)); <ide> if (ddl != null) { <ide> ddlParser.getDdlChanges().reset(); <ide> ddlParser.parse(ddl, tables);
Java
mit
51eab6debe3e99a34f0fb0068afc8db252652e5d
0
Moudoux/EMC
package me.deftware.client.framework.event.events; import me.deftware.client.framework.event.Event; import me.deftware.client.framework.network.IPacket; import me.deftware.client.framework.network.packets.*; import net.minecraft.network.Packet; import net.minecraft.server.network.packet.GuiCloseC2SPacket; import net.minecraft.server.network.packet.PlayerMoveC2SPacket; /** * Triggered when packet is being sent to the server */ @SuppressWarnings("ConstantConditions") public class EventPacketSend extends Event { private Packet<?> packet; public EventPacketSend(Packet<?> packet) { this.packet = packet; } public Packet<?> getPacket() { return packet; } public void setPacket(Packet<?> packet) { this.packet = packet; } public void setPacket(IPacket packet) { this.packet = packet.getPacket(); } public IPacket getIPacket() { if (packet instanceof PlayerMoveC2SPacket) { return new ICPacketPlayer(packet); } else if (packet instanceof PlayerMoveC2SPacket.Both) { return new ICPacketPositionRotation(packet); } else if (packet instanceof PlayerMoveC2SPacket.LookOnly) { return new ICPacketRotation(packet); } else if (packet instanceof PlayerMoveC2SPacket.PositionOnly) { return new ICPacketPosition(packet); } else if (packet instanceof GuiCloseC2SPacket) { return new ICPacketCloseWindow(packet); } return new IPacket(packet); } }
src/main/java/me/deftware/client/framework/event/events/EventPacketSend.java
package me.deftware.client.framework.event.events; import me.deftware.client.framework.event.Event; import me.deftware.client.framework.network.IPacket; import me.deftware.client.framework.network.packets.*; import net.minecraft.network.Packet; import net.minecraft.server.network.packet.GuiCloseC2SPacket; import net.minecraft.server.network.packet.PlayerMoveC2SPacket; /** * Triggered when packet is being sent to the server */ public class EventPacketSend extends Event { private Packet<?> packet; public EventPacketSend(Packet<?> packet) { this.packet = packet; } public Packet<?> getPacket() { return packet; } public void setPacket(Packet<?> packet) { this.packet = packet; } public void setPacket(IPacket packet) { this.packet = packet.getPacket(); } public IPacket getIPacket() { if (packet instanceof PlayerMoveC2SPacket.Both) { return new ICPacketPositionRotation(packet); } else if (packet instanceof PlayerMoveC2SPacket.LookOnly) { return new ICPacketRotation(packet); } else if (packet instanceof PlayerMoveC2SPacket.PositionOnly) { return new ICPacketPosition(packet); } else if (packet instanceof PlayerMoveC2SPacket) { return new ICPacketPlayer(packet); } else if (packet instanceof GuiCloseC2SPacket) { return new ICPacketCloseWindow(packet); } return new IPacket(packet); } }
[Fix] Fix getIPacket, and suppress Warnings from it
src/main/java/me/deftware/client/framework/event/events/EventPacketSend.java
[Fix] Fix getIPacket, and suppress Warnings from it
<ide><path>rc/main/java/me/deftware/client/framework/event/events/EventPacketSend.java <ide> * Triggered when packet is being sent to the server <ide> */ <ide> <add>@SuppressWarnings("ConstantConditions") <ide> public class EventPacketSend extends Event { <ide> <ide> private Packet<?> packet; <ide> } <ide> <ide> public IPacket getIPacket() { <del> if (packet instanceof PlayerMoveC2SPacket.Both) { <add> if (packet instanceof PlayerMoveC2SPacket) { <add> return new ICPacketPlayer(packet); <add> } else if (packet instanceof PlayerMoveC2SPacket.Both) { <ide> return new ICPacketPositionRotation(packet); <ide> } else if (packet instanceof PlayerMoveC2SPacket.LookOnly) { <ide> return new ICPacketRotation(packet); <ide> } else if (packet instanceof PlayerMoveC2SPacket.PositionOnly) { <ide> return new ICPacketPosition(packet); <del> } else if (packet instanceof PlayerMoveC2SPacket) { <del> return new ICPacketPlayer(packet); <ide> } else if (packet instanceof GuiCloseC2SPacket) { <ide> return new ICPacketCloseWindow(packet); <ide> }
JavaScript
bsd-3-clause
5967940b83c14f5047863f1a6529c40f20af676b
0
justinforce/jquery-sameheight
/* * sameHeight jQuery plugin * http://github.com/sidewaysmilk/jquery-sameheight * * Copyright 2011, Justin Force * Licensed under the MIT license */ jQuery.fn.sameHeight = function() { var these = this; function setHeight() { var max = 0; these.height('auto').each(function() { max = Math.max(max, jQuery(this).height()); }).height(max); }; jQuery(window).resize(setHeight); setHeight(); return this; };
jquery.sameheight.js
(function($) { $.fn.sameHeight = function() { var these = this; function setHeight() { var max = 0; these.height('auto').each(function() { max = Math.max(max, $(this).height()); }).height(max); }; $(window).resize(setHeight); setHeight(); return this; }; })(jQuery);
Add header and don't use $ for jQuery
jquery.sameheight.js
Add header and don't use $ for jQuery
<ide><path>query.sameheight.js <del>(function($) { <del> $.fn.sameHeight = function() { <del> var these = this; <del> function setHeight() { <del> var max = 0; <del> these.height('auto').each(function() { <del> max = Math.max(max, $(this).height()); <del> }).height(max); <del> }; <del> $(window).resize(setHeight); <del> setHeight(); <del> return this; <add>/* <add>* sameHeight jQuery plugin <add>* http://github.com/sidewaysmilk/jquery-sameheight <add>* <add>* Copyright 2011, Justin Force <add>* Licensed under the MIT license <add>*/ <add>jQuery.fn.sameHeight = function() { <add> var these = this; <add> function setHeight() { <add> var max = 0; <add> these.height('auto').each(function() { <add> max = Math.max(max, jQuery(this).height()); <add> }).height(max); <ide> }; <del>})(jQuery); <add> jQuery(window).resize(setHeight); <add> setHeight(); <add> return this; <add>}; <add>
Java
apache-2.0
2cbeb61e7d72863266482357d07b0526a1c47c24
0
EvilMcJerkface/Aeron,mikeb01/Aeron,galderz/Aeron,mikeb01/Aeron,galderz/Aeron,real-logic/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron,galderz/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,galderz/Aeron,real-logic/Aeron,real-logic/Aeron
/* * Copyright 2014-2017 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.samples; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.agrona.concurrent.UnsafeBuffer; import java.util.Arrays; @RunWith(Parameterized.class) public class LogInspectorAsciiFormatBytesTest { private static final String FORMAT_KEY = "aeron.log.inspector.data.format"; private String originalDataFormatProperty; private byte buffer; private char expected; public LogInspectorAsciiFormatBytesTest(final int buffer, final int expected) { this.buffer = (byte)buffer; this.expected = (char)expected; } @Parameters(name = "{index}: ascii format[{0}]={1}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][] { { 0x17, 0x17 }, { 0, 0 }, { -1, 0 }, { Byte.MAX_VALUE, Byte.MAX_VALUE }, { Byte.MIN_VALUE, 0 }, }); } @Before public void before() { originalDataFormatProperty = System.getProperty(FORMAT_KEY); } @After public void after() { if (null == originalDataFormatProperty) { System.clearProperty(FORMAT_KEY); } else { System.setProperty(FORMAT_KEY, originalDataFormatProperty); } } @Test public void shouldFormatBytesToAscii() { System.setProperty(FORMAT_KEY, "ascii"); final char[] formattedBytes = LogInspector.formatBytes(new UnsafeBuffer(new byte[]{ buffer }), 0, 1); Assert.assertEquals(expected, formattedBytes[0]); } }
aeron-samples/src/test/java/io/aeron/samples/LogInspectorAsciiFormatBytesTest.java
/* * Copyright 2014-2017 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.samples; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.agrona.concurrent.UnsafeBuffer; import java.util.Arrays; @RunWith(Parameterized.class) public class LogInspectorAsciiFormatBytesTest { private static final String FORMAT_KEY = "aeron.log.inspector.data.format"; private String originalDataFormatProperty; private byte buffer; private char expected; public LogInspectorAsciiFormatBytesTest(final int buffer, final int expected) { this.buffer = (byte)buffer; this.expected = (char)expected; } @Parameters(name = "{index}: ascii format[{0}]={1}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][] { { 0x17, 0x17 }, { 0, 0 }, { -1, 0 }, { Byte.MAX_VALUE, Byte.MAX_VALUE }, { Byte.MIN_VALUE, 0 }, }); } @Test public void shouldFormatBytesToAscii() { System.setProperty(FORMAT_KEY, "ascii"); final char[] formattedBytes = LogInspector.formatBytes(new UnsafeBuffer(new byte[]{ buffer }), 0, 1); Assert.assertEquals(expected, formattedBytes[0]); } @Before public void setUp() { originalDataFormatProperty = System.getProperty(FORMAT_KEY); } @After public void tearDown() { if (null == originalDataFormatProperty) { System.clearProperty(FORMAT_KEY); } else { System.setProperty(FORMAT_KEY, originalDataFormatProperty); } } }
[Java] Test consistency.
aeron-samples/src/test/java/io/aeron/samples/LogInspectorAsciiFormatBytesTest.java
[Java] Test consistency.
<ide><path>eron-samples/src/test/java/io/aeron/samples/LogInspectorAsciiFormatBytesTest.java <ide> }); <ide> } <ide> <del> @Test <del> public void shouldFormatBytesToAscii() <del> { <del> System.setProperty(FORMAT_KEY, "ascii"); <del> final char[] formattedBytes = LogInspector.formatBytes(new UnsafeBuffer(new byte[]{ buffer }), 0, 1); <del> <del> Assert.assertEquals(expected, formattedBytes[0]); <del> } <del> <ide> @Before <del> public void setUp() <add> public void before() <ide> { <ide> originalDataFormatProperty = System.getProperty(FORMAT_KEY); <ide> } <ide> <ide> @After <del> public void tearDown() <add> public void after() <ide> { <ide> if (null == originalDataFormatProperty) <ide> { <ide> System.setProperty(FORMAT_KEY, originalDataFormatProperty); <ide> } <ide> } <add> <add> @Test <add> public void shouldFormatBytesToAscii() <add> { <add> System.setProperty(FORMAT_KEY, "ascii"); <add> final char[] formattedBytes = LogInspector.formatBytes(new UnsafeBuffer(new byte[]{ buffer }), 0, 1); <add> <add> Assert.assertEquals(expected, formattedBytes[0]); <add> } <ide> }
Java
apache-2.0
a7b12dcce48a908aa751014179b4036a748083cc
0
JWimsingues/infonuagique-tp2
package ca.polymtl.inf4410.tp2.repartitor; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.rmi.AccessException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.concurrent.Semaphore; import ca.polymtl.inf4410.tp2.shared.CalculousServerInterface; public class Repartitor { /** * Path to the calculous servers configuration */ private static final String PATH_CONFIG_CALCULOUS_SERVERS = "./config/servers.config"; /** * Command to compute the file */ private static final String CMD_COMPUTE = "compute"; /** * Command to exit the program */ private static final String CMD_EXIT = "exit"; /** * Number of token for the calculous semaphore */ private static final int SEM_C_NUMBER_OF_TOKEN = 1; /** * Number of token for the to verify calculous semaphore */ private static final int SEM_TVC_NUMBER_OF_TOKEN = 1; /** * Number of token for the result semaphore */ private static final int SEM_R_NUMBER_OF_TOKEN = 1; /** * Argument of the command line for to enable the safe mode */ private static final String SAFE_ARGUMENT = "-S"; /** * Error exit IO code */ private static final int ERROR_IO = -10; /** * Error exit not bound code */ private static final int ERROR_NOT_BOUND = -30; /** * Error exit access code */ private static final int ERROR_ACCESS = -40; /** * ArrayList to store the calculations to do */ private ArrayList<String> calculations; /** * Semaphore to provide access to the calculations structure */ private Semaphore calculationsSemaphore; /** * ArrayList to store the calculations to verify */ private ArrayList<Task> toVerifyCalculations; /** * Semaphore to provide access to the calculations to verify structure */ private Semaphore toVerifyCalculationsSemaphore; /** * Boolean to know if the repartitor is in safe mode or not */ private boolean safeMode; /** * Boolean to control threads ending */ private boolean threadsShouldEnd = false; /** * Arrayslist of our different thread */ private ArrayList<Thread> threads; /** * GlobalResult is an array of size 2 in order to be able to give it by * reference to threads index 0 => the result index 1 => number of operation * stacked in result */ private int[] globalResult; /** * Semaphore protecting globalresult */ private Semaphore globalResultLock; /** * number of operation provided to the repartitor */ private int operationNumber; /** * Array containing all the server instance */ private ArrayList<CalculousServerInterface> CalculousServeurs; /** * Public constructor to create a Repartiteur instance * */ public Repartitor(boolean isSafe) { // Enable of not the safe mode safeMode = isSafe; // Creation of calculous data structure calculationsSemaphore = new Semaphore(SEM_C_NUMBER_OF_TOKEN); calculations = new ArrayList<>(); // Creation of to verify calculous data structure toVerifyCalculationsSemaphore = new Semaphore(SEM_TVC_NUMBER_OF_TOKEN); toVerifyCalculations = new ArrayList<>(); // Create the list of servers CalculousServeurs = new ArrayList<>(); // Create the list of threads threads = new ArrayList<>(); // Initialize the result structure globalResult = new int[2]; globalResult[0] = 0; globalResult[1] = 0; globalResultLock = new Semaphore(SEM_R_NUMBER_OF_TOKEN); // Set the security manager if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } } /** * Main point of the program * * @param args * @throws java.lang.InterruptedException */ public static void main(String[] args) throws InterruptedException { // Checking safe mode boolean isSafe = false; if (args.length >= 1 && args[0].equals(SAFE_ARGUMENT)) { isSafe = true; System.out.println("Mode \"safe\" detecte : les calculs seront tous verifies."); } else { System.out.println("Mode \"non safe\" detecte : les calculs ne seront pas verifies."); } // Creation of the repartitor instance Repartitor repartiteur = new Repartitor(isSafe); // Start repartitor's job repartiteur.runRepartitor(); } /** * Main private method to run the repartitor */ private void runRepartitor() throws InterruptedException { String commande = null; String commandes[] = null; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Chargement des serveurs ..."); loadServerFromConfigFile(); System.out.println("Attente des commandes ..."); try { while ((commande = reader.readLine()) != null) { commandes = commande.split(" "); String command = commandes[0]; switch (command) { case CMD_COMPUTE: String filename = commandes[1]; try { parseCalculousFileToCalculous(filename); } catch (IOException e) { System.err.println("Le fichier " + filename + " est inacessible."); } // Start the threads startThreadsThenJoin(); break; case CMD_EXIT: System.out.println("Sortie du programme ..."); System.exit(0); break; default: System.out.println("Commande inconnue : compute nomFichier ou exit sont les " + "deux seules commandes possibles."); break; } } } catch (IOException e) { System.err.println("Erreur dans la lecture du flux d'entree sortie."); e.printStackTrace(); System.exit(ERROR_IO); } } /** * Load all the configuration of the calculous servers */ private void loadServerFromConfigFile() { try { FileReader fr = new FileReader(PATH_CONFIG_CALCULOUS_SERVERS); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { String[] array = line.split(" "); CalculousServerInterface csi = loadServerStub(array[0], Integer.parseInt(array[1])); CalculousServeurs.add(csi); // Avoid empty line crash if (array.length == 0) { continue; } } br.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Private method to load the server * * @param hostname * @return */ private CalculousServerInterface loadServerStub(String hostname, int port) { CalculousServerInterface stub = null; try { Registry registry = LocateRegistry.getRegistry(hostname, port); stub = (CalculousServerInterface) registry.lookup(hostname); } catch (NotBoundException e) { System.err.println("Erreur : Le nom " + e.getMessage() + " n'est pas defini dans le registre."); System.exit(ERROR_NOT_BOUND); } catch (AccessException e) { System.err.println("Erreur : " + e.getMessage()); System.exit(ERROR_ACCESS); } catch (RemoteException e) { System.err.println("Erreur: impossible de connecter la machine " + hostname + " sur le port " + port); System.err.println("Verifier votre configuration un servuer a pu ne pas etre pris en consideration."); } return stub; } /** * Private method to launch one thread by server, one coordination thread * and then wait the end of threads work to print the resul * * @throws IOException * @throws InterruptedException */ private void startThreadsThenJoin() throws IOException, InterruptedException { long firstTime = System.currentTimeMillis(); // Create threads depending on the safety parameter if (!safeMode) { for (CalculousServerInterface server : CalculousServeurs) { SafeRepartitorThread thread = new SafeRepartitorThread(this, server, calculations, calculationsSemaphore, globalResult, globalResultLock); threads.add(thread); thread.start(); } } else { for (CalculousServerInterface server : CalculousServeurs) { UnsafeRepartitorThread thread = new UnsafeRepartitorThread(this, server, calculations, calculationsSemaphore, globalResult, globalResultLock, toVerifyCalculations, toVerifyCalculationsSemaphore); threads.add(thread); thread.start(); } } // Create the thread to coordinate all the results Thread coordinationThread = new CoordinateThread(this, globalResult, globalResultLock, operationNumber); coordinationThread.start(); // Threads synchronisation coordinationThread.join(); long secondTime = System.currentTimeMillis(); for (Thread thread : threads) { thread.join(); } // Print the results System.out.println("Resultats des calculs ! " + globalResult[0]); System.out.println("Ce calcul a ete effectue en : " + (secondTime - firstTime) + " millisecondes"); } /** * Private method to store the initial calculations to do * * @param filename * @throws IOException */ private void parseCalculousFileToCalculous(String filename) throws IOException { // Some declarations String line = null; FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); // Add each line of the file to the datastructure while ((line = br.readLine()) != null) { calculations.add(line); } // Close the buffer br.close(); operationNumber = calculations.size(); } /** * safeMode getter * * @return safeMode */ public boolean isSafeMode() { return this.safeMode; } /** * threadsShouldEnd getter * * @return the inverse of threadsShouldEnd */ public boolean threadsShouldContinue() { return !threadsShouldEnd; } /** * set threadsShouldEnd to true */ public void stopTheThreads() { threadsShouldEnd = true; } }
v0/src/ca/polymtl/inf4410/tp2/repartitor/Repartitor.java
package ca.polymtl.inf4410.tp2.repartitor; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.rmi.AccessException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.concurrent.Semaphore; import ca.polymtl.inf4410.tp2.shared.CalculousServerInterface; public class Repartitor { /** * Path to the calculous servers configuration */ private static final String PATH_CONFIG_CALCULOUS_SERVERS = "./config/servers.config"; /** * Command to compute the file */ private static final String CMD_COMPUTE = "compute"; /** * Command to exit the program */ private static final String CMD_EXIT = "exit"; /** * Number of token for the calculous semaphore */ private static final int SEM_C_NUMBER_OF_TOKEN = 1; /** * Number of token for the to verify calculous semaphore */ private static final int SEM_TVC_NUMBER_OF_TOKEN = 1; /** * Number of token for the result semaphore */ private static final int SEM_R_NUMBER_OF_TOKEN = 1; /** * Argument of the command line for to enable the safe mode */ private static final String SAFE_ARGUMENT = "-S"; /** * Error exit IO code */ private static final int ERROR_IO = -10; /** * Error exit RMI code */ private static final int ERROR_RMI = -20; /** * Error exit not bound code */ private static final int ERROR_NOT_BOUND = -30; /** * Error exit access code */ private static final int ERROR_ACCESS = -40; /** * ArrayList to store the calculations to do */ private ArrayList<String> calculations; /** * Semaphore to provide access to the calculations structure */ private Semaphore calculationsSemaphore; /** * ArrayList to store the calculations to verify */ private ArrayList<Task> toVerifyCalculations; /** * Semaphore to provide access to the calculations to verify structure */ private Semaphore toVerifyCalculationsSemaphore; /** * Boolean to know if the repartitor is in safe mode or not */ private boolean safeMode; /** * Boolean to control threads ending */ private boolean threadsShouldEnd = false; /** * Arrayslist of our different thread */ private ArrayList<Thread> threads; /** * GlobalResult is an array of size 2 in order to be able to give it by * reference to threads index 0 => the result index 1 => number of operation * stacked in result */ private int[] globalResult; /** * Semaphore protecting globalresult */ private Semaphore globalResultLock; /** * number of operation provided to the repartitor */ private int operationNumber; /** * Array containing all the server instance */ private ArrayList<CalculousServerInterface> CalculousServeurs; /** * Public constructor to create a Repartiteur instance * */ public Repartitor(boolean isSafe) { // Enable of not the safe mode safeMode = isSafe; // Creation of calculous data structure calculationsSemaphore = new Semaphore(SEM_C_NUMBER_OF_TOKEN); calculations = new ArrayList<>(); // Creation of to verify calculous data structure toVerifyCalculationsSemaphore = new Semaphore(SEM_TVC_NUMBER_OF_TOKEN); toVerifyCalculations = new ArrayList<>(); // Create the list of servers CalculousServeurs = new ArrayList<>(); // Create the list of threads threads = new ArrayList<>(); // Initialize the result structure globalResult = new int[2]; globalResult[0] = 0; globalResult[1] = 0; globalResultLock = new Semaphore(SEM_R_NUMBER_OF_TOKEN); // Set the security manager if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } } /** * Main point of the program * * @param args * @throws java.lang.InterruptedException */ public static void main(String[] args) throws InterruptedException { // Checking safe mode boolean isSafe = false; if (args.length >= 1 && args[0].equals(SAFE_ARGUMENT)) { isSafe = true; System.out.println("Mode \"safe\" detecte : les calculs seront tous verifies."); } else { System.out.println("Mode \"non safe\" detecte : les calculs ne seront pas verifies."); } // Creation of the repartitor instance Repartitor repartiteur = new Repartitor(isSafe); // Start repartitor's job repartiteur.runRepartitor(); } /** * Main private method to run the repartitor */ private void runRepartitor() throws InterruptedException { String commande = null; String commandes[] = null; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Chargement des serveurs ..."); loadServerFromConfigFile(); System.out.println("Attente des commandes ..."); try { while ((commande = reader.readLine()) != null) { commandes = commande.split(" "); String command = commandes[0]; switch (command) { case CMD_COMPUTE: String filename = commandes[1]; try { parseCalculousFileToCalculous(filename); } catch (IOException e) { System.err.println("Le fichier " + filename + " est inacessible."); } // Start the threads startThreadsThenJoin(); break; case CMD_EXIT: System.out.println("Sortie du programme ..."); System.exit(0); break; default: System.out.println("Commande inconnue : compute nomFichier ou exit sont les " + "deux seules commandes possibles."); break; } } } catch (IOException e) { System.err.println("Erreur dans la lecture du flux d'entree sortie."); e.printStackTrace(); System.exit(ERROR_IO); } } /** * Load all the configuration of the calculous servers */ private void loadServerFromConfigFile() { try { FileReader fr = new FileReader(PATH_CONFIG_CALCULOUS_SERVERS); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { String[] array = line.split(" "); CalculousServerInterface csi = loadServerStub(array[0], Integer.parseInt(array[1])); CalculousServeurs.add(csi); // Avoid empty line crash if(array.length == 0) { continue; } } br.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Private method to load the server * * @param hostname * @return */ private CalculousServerInterface loadServerStub(String hostname, int port) { CalculousServerInterface stub = null; try { Registry registry = LocateRegistry.getRegistry(hostname, port); stub = (CalculousServerInterface) registry.lookup(hostname); } catch (NotBoundException e) { System.err.println("Erreur : Le nom " + e.getMessage() + " n'est pas defini dans le registre."); System.exit(ERROR_NOT_BOUND); } catch (AccessException e) { System.err.println("Erreur : " + e.getMessage()); System.err.println("test"); System.exit(ERROR_ACCESS); } catch (RemoteException e) { System.err.println("Erreur: " + e.getMessage()); System.err.println("test2"); System.exit(ERROR_RMI); } return stub; } /** * Private method to launch one thread by server, one coordination thread * and then wait the end of threads work to print the resul * * @throws IOException * @throws InterruptedException */ private void startThreadsThenJoin() throws IOException, InterruptedException { long firstTime = System.currentTimeMillis(); // Create threads depending on the safety parameter if (!safeMode) { for (CalculousServerInterface server : CalculousServeurs) { SafeRepartitorThread thread = new SafeRepartitorThread(this, server, calculations, calculationsSemaphore, globalResult, globalResultLock); threads.add(thread); thread.start(); } } else { for (CalculousServerInterface server : CalculousServeurs) { UnsafeRepartitorThread thread = new UnsafeRepartitorThread(this, server, calculations, calculationsSemaphore, globalResult, globalResultLock, toVerifyCalculations, toVerifyCalculationsSemaphore); threads.add(thread); thread.start(); } } // Create the thread to coordinate all the results Thread coordinationThread = new CoordinateThread(this, globalResult, globalResultLock, operationNumber); coordinationThread.start(); // Threads synchronisation coordinationThread.join(); long secondTime = System.currentTimeMillis(); for (Thread thread : threads) { thread.join(); } // Print the results System.out.println("Resultats des calculs ! " + globalResult[0]); System.out.println("Ce calcul a ete effectue en : " + (secondTime - firstTime) + " millisecondes"); } /** * Private method to store the initial calculations to do * * @param filename * @throws IOException */ private void parseCalculousFileToCalculous(String filename) throws IOException { // Some declarations String line = null; FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); // Add each line of the file to the datastructure while ((line = br.readLine()) != null) { calculations.add(line); } // Close the buffer br.close(); operationNumber = calculations.size(); } /** * safeMode getter * * @return safeMode */ public boolean isSafeMode() { return this.safeMode; } /** * threadsShouldEnd getter * * @return the inverse of threadsShouldEnd */ public boolean threadsShouldContinue() { return !threadsShouldEnd; } /** * set threadsShouldEnd to true */ public void stopTheThreads() { threadsShouldEnd = true; } }
[Fix] non bloquant sur erreur connexion
v0/src/ca/polymtl/inf4410/tp2/repartitor/Repartitor.java
[Fix] non bloquant sur erreur connexion
<ide><path>0/src/ca/polymtl/inf4410/tp2/repartitor/Repartitor.java <ide> * Error exit IO code <ide> */ <ide> private static final int ERROR_IO = -10; <del> <del> /** <del> * Error exit RMI code <del> */ <del> private static final int ERROR_RMI = -20; <ide> <ide> /** <ide> * Error exit not bound code <ide> CalculousServerInterface csi = loadServerStub(array[0], Integer.parseInt(array[1])); <ide> CalculousServeurs.add(csi); <ide> // Avoid empty line crash <del> if(array.length == 0) { <add> if (array.length == 0) { <ide> continue; <ide> } <ide> } <ide> System.exit(ERROR_NOT_BOUND); <ide> } catch (AccessException e) { <ide> System.err.println("Erreur : " + e.getMessage()); <del> System.err.println("test"); <ide> System.exit(ERROR_ACCESS); <ide> } catch (RemoteException e) { <del> System.err.println("Erreur: " + e.getMessage()); <del> System.err.println("test2"); <del> System.exit(ERROR_RMI); <del> } <add> System.err.println("Erreur: impossible de connecter la machine " + hostname + " sur le port " + port); <add> System.err.println("Verifier votre configuration un servuer a pu ne pas etre pris en consideration."); <add> } <ide> <ide> return stub; <ide> }
Java
agpl-3.0
9def18a90bfda09251fbdcd6a2ae0e7d564851d0
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
336dfe52-2e62-11e5-9284-b827eb9e62be
hello.java
3368980e-2e62-11e5-9284-b827eb9e62be
336dfe52-2e62-11e5-9284-b827eb9e62be
hello.java
336dfe52-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>3368980e-2e62-11e5-9284-b827eb9e62be <add>336dfe52-2e62-11e5-9284-b827eb9e62be
Java
apache-2.0
59248a35dbb8645ffe7ece3f2041ca38ac1fc05c
0
wealthworks/AndroidBaseLibrary
package com.licaigc; /** * Created by walfud on 2016/8/19. */ public class Constants { public static final String TAG = "Constants"; // 平台 public static final int OS_UNKNOWN = 0; public static final int OS_ANDROID = 1; public static final int OS_IOS = 2; // Package Name public static final String PKG_TALICAI = "com.talicai.talicaiclient"; public static final String PKG_GUIHUA = "com.haoguihua.app"; public static final String PKG_TIMI = "com.talicai.timiclient"; public static final String PKG_JIJINDOU = "com.jijindou.android.fund"; // 应用 Id public static final int APP_ID_UNKNOWN = 0; public static final int APP_ID_TALICAI = 1; public static final int APP_ID_GUIHUA = 2; public static final int APP_ID_TIMI = 3; public static final int APP_ID_JIJINDOU = 4; // 网络类型 public static final int NETWORK_NONE = 0; public static final int NETWORK_WIFI = 1; public static final int NETWORK_2G = 2; public static final int NETWORK_3G = 3; public static final int NETWORK_4G = 4; public static final int NETWORK_5G = 5; // Primary Color public static final int APP_PRIMARY_COLOR_UNKNOWN = 0xFF3F51B5; public static final int APP_PRIMARY_COLOR_TALICAI = 0xFFDA5C83; public static final int APP_PRIMARY_COLOR_GUIHUA = 0xFF6192B3; public static final int APP_PRIMARY_COLOR_TIMI = 0xFFF5A623; public static final int APP_PRIMARY_COLOR_JIJINDOU = 0xFFDA5162; }
library/src/main/java/com/licaigc/Constants.java
package com.licaigc; /** * Created by walfud on 2016/8/19. */ public class Constants { public static final String TAG = "Constants"; // 平台 public static final int OS_UNKNOWN = 0; public static final int OS_ANDROID = 1; public static final int OS_IOS = 2; // Package Name public static final String PKG_TALICAI = "com.talicai.talicaiclient"; public static final String PKG_GUIHUA = "com.haoguihua.app"; public static final String PKG_TIMI = "com.talicai.timiclient"; public static final String PKG_JIJINDOU = "com.jijindou.android.fund"; // 应用 Id public static final int APP_ID_UNKNOWN = 0; public static final int APP_ID_TALICAI = 1; public static final int APP_ID_GUIHUA = 2; public static final int APP_ID_TIMI = 3; public static final int APP_ID_JIJINDOU = 4; // 网络类型 public static final int NETWORK_NONE = 0; public static final int NETWORK_WIFI = 1; public static final int NETWORK_2G = 2; public static final int NETWORK_3G = 3; public static final int NETWORK_4G = 4; public static final int NETWORK_5G = 5; // Primary Color public static final int APP_PRIMARY_COLOR_UNKNOWN = 0xFF3F51B5; public static final int APP_PRIMARY_COLOR_TALICAI = 0xFFDA5C83; public static final int APP_PRIMARY_COLOR_GUIHUA = 0xFF30455D; public static final int APP_PRIMARY_COLOR_TIMI = 0xFFF5A623; public static final int APP_PRIMARY_COLOR_JIJINDOU = 0xFFDA5162; }
好规划颜色
library/src/main/java/com/licaigc/Constants.java
好规划颜色
<ide><path>ibrary/src/main/java/com/licaigc/Constants.java <ide> // Primary Color <ide> public static final int APP_PRIMARY_COLOR_UNKNOWN = 0xFF3F51B5; <ide> public static final int APP_PRIMARY_COLOR_TALICAI = 0xFFDA5C83; <del> public static final int APP_PRIMARY_COLOR_GUIHUA = 0xFF30455D; <add> public static final int APP_PRIMARY_COLOR_GUIHUA = 0xFF6192B3; <ide> public static final int APP_PRIMARY_COLOR_TIMI = 0xFFF5A623; <ide> public static final int APP_PRIMARY_COLOR_JIJINDOU = 0xFFDA5162; <ide> }
Java
apache-2.0
e0fce4b82a6957f81908dc481529b3f45a181ec7
0
fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode
package com.fishercoder.solutions; public class _639 { public static class Solution1 { /** * reference: https://leetcode.com/articles/decode-ways-ii/#approach-2-dynamic-programming-accepted */ int m = 1000000007; public int numDecodings(String s) { long[] dp = new long[s.length() + 1]; dp[0] = 1; dp[1] = s.charAt(0) == '*' ? 9 : s.charAt(0) == '0' ? 0 : 1; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == '*') { dp[i + 1] = 9 * dp[i]; if (s.charAt(i - 1) == '1') { dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % m; } else if (s.charAt(i - 1) == '2') { dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % m; } else if (s.charAt(i - 1) == '*') { dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % m; } } else { dp[i + 1] = s.charAt(i) != '0' ? dp[i] : 0; if (s.charAt(i - 1) == '1') { dp[i + 1] = (dp[i + 1] + dp[i - 1]) % m; } else if (s.charAt(i - 1) == '2' && s.charAt(i) <= '6') { dp[i + 1] = (dp[i + 1] + dp[i - 1]) % m; } else if (s.charAt(i - 1) == '*') { dp[i + 1] = (dp[i + 1] + (s.charAt(i) <= '6' ? 2 : 1) * dp[i - 1]) % m; } } } return (int) dp[s.length()]; } } }
src/main/java/com/fishercoder/solutions/_639.java
package com.fishercoder.solutions; /** * 639. Decode Ways II * * A message containing letters from A-Z is being encoded to numbers using the following mapping way: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Beyond that, now the encoded string can also contain the character '*', which can be treated as one of the numbers from 1 to 9. Given the encoded message containing digits and the character '*', return the total number of ways to decode it. Also, since the answer may be very large, you should return the output mod 109 + 7. Example 1: Input: "*" Output: 9 Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I". Example 2: Input: "1*" Output: 9 + 9 = 18 Note: The length of the input string will fit in range [1, 105]. The input string will only contain the character '*' and digits '0' - '9'. */ public class _639 { public static class Solution1 { /** * reference: https://leetcode.com/articles/decode-ways-ii/#approach-2-dynamic-programming-accepted */ int m = 1000000007; public int numDecodings(String s) { long[] dp = new long[s.length() + 1]; dp[0] = 1; dp[1] = s.charAt(0) == '*' ? 9 : s.charAt(0) == '0' ? 0 : 1; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == '*') { dp[i + 1] = 9 * dp[i]; if (s.charAt(i - 1) == '1') { dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % m; } else if (s.charAt(i - 1) == '2') { dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % m; } else if (s.charAt(i - 1) == '*') { dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % m; } } else { dp[i + 1] = s.charAt(i) != '0' ? dp[i] : 0; if (s.charAt(i - 1) == '1') { dp[i + 1] = (dp[i + 1] + dp[i - 1]) % m; } else if (s.charAt(i - 1) == '2' && s.charAt(i) <= '6') { dp[i + 1] = (dp[i + 1] + dp[i - 1]) % m; } else if (s.charAt(i - 1) == '*') { dp[i + 1] = (dp[i + 1] + (s.charAt(i) <= '6' ? 2 : 1) * dp[i - 1]) % m; } } } return (int) dp[s.length()]; } } }
refactor 639
src/main/java/com/fishercoder/solutions/_639.java
refactor 639
<ide><path>rc/main/java/com/fishercoder/solutions/_639.java <ide> package com.fishercoder.solutions; <ide> <del>/** <del> * 639. Decode Ways II <del> * <del> * A message containing letters from A-Z is being encoded to numbers using the following mapping way: <del> <del> 'A' -> 1 <del> 'B' -> 2 <del> ... <del> 'Z' -> 26 <del> Beyond that, now the encoded string can also contain the character '*', <del> which can be treated as one of the numbers from 1 to 9. <del> <del> Given the encoded message containing digits and the character '*', <del> return the total number of ways to decode it. <del> <del> Also, since the answer may be very large, you should return the output mod 109 + 7. <del> <del> Example 1: <del> Input: "*" <del> Output: 9 <del> Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I". <del> Example 2: <del> Input: "1*" <del> Output: 9 + 9 = 18 <del> <del> Note: <del> The length of the input string will fit in range [1, 105]. <del> The input string will only contain the character '*' and digits '0' - '9'. <del> <del> */ <ide> public class _639 { <ide> public static class Solution1 { <ide> /**
Java
apache-2.0
error: pathspec 'openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaDisclosureRepository.java' did not match any file(s) known to git
d5d16a882fb832c8ce57e4f1b6c1d6dcbcfda37c
1
Unicon/openregistry,Jasig/openregistry,Rutgers-IDM/openregistry,sheliu/openregistry,msidd/openregistry,sheliu/openregistry,Unicon/openregistry,msidd/openregistry,msidd/openregistry,Jasig/openregistry,Jasig/openregistry,Rutgers-IDM/openregistry,msidd/openregistry,Rutgers-IDM/openregistry,Rutgers-IDM/openregistry,sheliu/openregistry,msidd/openregistry,sheliu/openregistry,Jasig/openregistry,Unicon/openregistry,Unicon/openregistry,Jasig/openregistry,Unicon/openregistry,Jasig/openregistry,Unicon/openregistry,Rutgers-IDM/openregistry,Unicon/openregistry,sheliu/openregistry
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.openregistry.core.repository.jpa; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.openregistry.core.domain.DisclosureSettings; import org.openregistry.core.repository.DisclosureRepository; import org.springframework.stereotype.Repository; /** * DisclosureRepository implementation with JPA * @author llevkovi * @version $Id$ */ @Repository (value = "disclosureRepository") public class JpaDisclosureRepository implements DisclosureRepository { @PersistenceContext private EntityManager entityManager; /** * @see org.openregistry.core.repository.DisclosureRepository#saveDisclosureSettings(org.openregistry.core.domain.DisclosureSettings) */ public DisclosureSettings saveDisclosureSettings(DisclosureSettings disclosure) { return this.entityManager.merge(disclosure); } }
openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaDisclosureRepository.java
Repository implementation for disclosure settings - initial version git-svn-id: 996c6d7d570f9e8d676b69394667d4ecb3e4cdb3@25086 1580c273-15eb-1042-8a87-dc5d815c88a0
openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaDisclosureRepository.java
Repository implementation for disclosure settings - initial version
<ide><path>penregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaDisclosureRepository.java <add>/** <add> * Licensed to Jasig under one or more contributor license <add> * agreements. See the NOTICE file distributed with this work <add> * for additional information regarding copyright ownership. <add> * Jasig licenses this file to you under the Apache License, <add> * Version 2.0 (the "License"); you may not use this file <add> * except in compliance with the License. You may obtain a <add> * copy of the License at: <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, <add> * software distributed under the License is distributed on <add> * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add> * KIND, either express or implied. See the License for the <add> * specific language governing permissions and limitations <add> * under the License. <add> */ <add>package org.openregistry.core.repository.jpa; <add> <add>import javax.persistence.EntityManager; <add>import javax.persistence.PersistenceContext; <add> <add>import org.openregistry.core.domain.DisclosureSettings; <add>import org.openregistry.core.repository.DisclosureRepository; <add>import org.springframework.stereotype.Repository; <add> <add>/** <add> * DisclosureRepository implementation with JPA <add> * @author llevkovi <add> * @version $Id$ <add> */ <add>@Repository (value = "disclosureRepository") <add>public class JpaDisclosureRepository implements DisclosureRepository { <add> <add> @PersistenceContext <add> private EntityManager entityManager; <add> <add> /** <add> * @see org.openregistry.core.repository.DisclosureRepository#saveDisclosureSettings(org.openregistry.core.domain.DisclosureSettings) <add> */ <add> public DisclosureSettings saveDisclosureSettings(DisclosureSettings disclosure) { <add> return this.entityManager.merge(disclosure); <add> } <add>}
Java
mit
e58abcac71f7212be228583ec53000f9cffa7386
0
hhaslam11/Text-Fighter
package com.hotmail.kalebmarc.textfighter.main; import javax.swing.*; import java.io.IOException; import java.util.Scanner; public class Ui { public static boolean guiEnabled = true; private final static Scanner IN = new Scanner(System.in); private Ui() { } public static boolean isDecimalNumber(String string) { if (string == null) { return false; } //Search for 1 or more digits followed by a `.` and 1 or more digits after the dot return string.matches("\\d+\\.\\d+"); } public static boolean isNumber(String string) { if (string == null) return false; //Search for any character that is not a digit //If you find a non-digit char, return false return !string.matches("\\D"); } /* * The whole purpose of this class is to make it easy to change from using the Console to other * ways to output information. For example, switching to a GUI application, instead of changing * every System.out.println() in the program, you can change just the methods in this class. * * Also to control whether popup should actually be a popup or not, based on user preference */ public static <T> void print(T input){ System.out.print(String.valueOf(input)); } public static <T> void println(T input){ System.out.println(String.valueOf(input)); } public static void print(){ System.out.print(""); } public static void println(){ System.out.println(""); } /** * Clears screen, prints msg, then calls pause();. * * @param msg string to output */ public static void msg(String msg) {//TODO use this instead throughout project if (msg == null || msg.equals("")) { cls(); pause(); } cls(); println(msg); pause(); } /** * @param msgType Ex. JOptionPane.ERROR_MESSAGE */ public static void popup(String body, String title, int msgType) { if (guiEnabled) { JOptionPane.showMessageDialog(null, body, title, msgType); } else { msg(body); } } public static int confirmPopup(String body, String title) { if (guiEnabled) { return JOptionPane.showConfirmDialog(null, body, title, JOptionPane.YES_NO_OPTION); } else { cls(); println(body); println("(Y/N)"); //TODO Replace this next snippet when using JTools lib //TODO Or.. Just write this better. //---------------------------------------------------- java.util.Scanner in = new java.util.Scanner(System.in); while (!in.hasNextLine()) { in.nextLine(); } String valid = in.nextLine(); valid = valid.toUpperCase(); if (valid.isEmpty()) { return 1; } char input = valid.charAt(0); //----------------------------------------------------- cls(); if (input == 'Y') return 0; return 1; } } /* * Clears the console by attempting to run either the 'cls' (Windows CMD) or * 'clear' (Other terminals) command. If this is interrupted, the terminal * will be brute-force cleared */ public static void cls() { try { if (System.getProperty("os.name").contains("Windows")) new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); else Runtime.getRuntime().exec("clear"); } catch (IOException | InterruptedException exception) { for (int i = 1; i < 50; i++) println("\n"); } } public static int getValidInt() { while (!IN.hasNextInt()) { IN.nextLine(); } return IN.nextInt(); } public static int getValidInt(int min, int max) { int value = getValidInt(); while (min > value || value > max) value = getValidInt(); return value; } public static String getValidString() { IN.reset(); return IN.next(); } /* * Stops the program until the user presses enter, then continues */ public static void pause() { try { Scanner pauseScan = new Scanner(System.in); String temp = pauseScan.nextLine(); println(temp); } catch (Exception e) { //Blank for a reason - Not supposed to do anything. } } }
src/com/hotmail/kalebmarc/textfighter/main/Ui.java
package com.hotmail.kalebmarc.textfighter.main; import javax.swing.*; import java.io.IOException; import java.util.Scanner; public class Ui { public static boolean guiEnabled = true; private final static Scanner IN = new Scanner(System.in); private Ui() { } public static boolean isDecimalNumber(String string) { if (string == null) { return false; } int length = string.length(); if (length == 1) { return false; } int i = 0; if (string.charAt(0) == '-') { if (length < 3) { return false; } i = 1; } int numOfDot = 0; for (; i < length; i++) { char c = string.charAt(i); if (c == '.') numOfDot++; else if (c == '/') return false; else if (c < '.' || c > '9') { return false; } } return (numOfDot == 1); } public static boolean isNumber(String string) { if (string == null) return false; int length = string.length(); if (length == 0) return false; int i = 0; if (string.charAt(0) == '-') { if (length == 1) return false; i = 1; } for (; i < length; i++) { char c = string.charAt(i); if (c <= '/' || c >= ':') return false; } return true; } /* * The whole purpose of this class is to make it easy to change from using the Console to other * ways to output information. For example, switching to a GUI application, instead of changing * every System.out.println() in the program, you can change just the methods in this class. * * Also to control whether popup should actually be a popup or not, based on user preference */ public static <T> void print(T input){ System.out.print(String.valueOf(input)); } public static <T> void println(T input){ System.out.println(String.valueOf(input)); } public static void print(){ System.out.print(""); } public static void println(){ System.out.println(""); } /** * Clears screen, prints msg, then calls pause();. * * @param msg string to output */ public static void msg(String msg) {//TODO use this instead throughout project if (msg == null || msg.equals("")) { cls(); pause(); } cls(); println(msg); pause(); } /** * @param msgType Ex. JOptionPane.ERROR_MESSAGE */ public static void popup(String body, String title, int msgType) { if (guiEnabled) { JOptionPane.showMessageDialog(null, body, title, msgType); } else { msg(body); } } public static int confirmPopup(String body, String title) { if (guiEnabled) { return JOptionPane.showConfirmDialog(null, body, title, JOptionPane.YES_NO_OPTION); } else { cls(); println(body); println("(Y/N)"); //TODO Replace this next snippet when using JTools lib //TODO Or.. Just write this better. //---------------------------------------------------- java.util.Scanner in = new java.util.Scanner(System.in); while (!in.hasNextLine()) { in.nextLine(); } String valid = in.nextLine(); valid = valid.toUpperCase(); if (valid.isEmpty()) { return 1; } char input = valid.charAt(0); //----------------------------------------------------- cls(); if (input == 'Y') return 0; return 1; } } /* * Clears the console by attempting to run either the 'cls' (Windows CMD) or * 'clear' (Other terminals) command. If this is interrupted, the terminal * will be brute-force cleared */ public static void cls() { try { if (System.getProperty("os.name").contains("Windows")) new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); else Runtime.getRuntime().exec("clear"); } catch (IOException | InterruptedException exception) { for (int i = 1; i < 50; i++) println("\n"); } } public static int getValidInt() { while (!IN.hasNextInt()) { IN.nextLine(); } return IN.nextInt(); } public static int getValidInt(int min, int max) { int value = getValidInt(); while (min > value || value > max) value = getValidInt(); return value; } public static String getValidString() { IN.reset(); return IN.next(); } /* * Stops the program until the user presses enter, then continues */ public static void pause() { try { Scanner pauseScan = new Scanner(System.in); String temp = pauseScan.nextLine(); println(temp); } catch (Exception e) { //Blank for a reason - Not supposed to do anything. } } }
Simplify isNumber & isDecimalNumber using regular expressions
src/com/hotmail/kalebmarc/textfighter/main/Ui.java
Simplify isNumber & isDecimalNumber using regular expressions
<ide><path>rc/com/hotmail/kalebmarc/textfighter/main/Ui.java <ide> return false; <ide> } <ide> <del> int length = string.length(); <del> <del> if (length == 1) { <del> return false; <del> } <del> <del> int i = 0; <del> <del> if (string.charAt(0) == '-') { <del> if (length < 3) { <del> return false; <del> } <del> i = 1; <del> } <del> <del> int numOfDot = 0; <del> <del> for (; i < length; i++) { <del> char c = string.charAt(i); <del> if (c == '.') <del> numOfDot++; <del> else if (c == '/') <del> return false; <del> else if (c < '.' || c > '9') { <del> return false; <del> } <del> } <del> <del> return (numOfDot == 1); <add> //Search for 1 or more digits followed by a `.` and 1 or more digits after the dot <add> return string.matches("\\d+\\.\\d+"); <ide> } <ide> <ide> public static boolean isNumber(String string) { <ide> if (string == null) return false; <ide> <del> int length = string.length(); <del> <del> if (length == 0) return false; <del> <del> int i = 0; <del> <del> if (string.charAt(0) == '-') { <del> if (length == 1) return false; <del> <del> i = 1; <del> } <del> <del> for (; i < length; i++) { <del> char c = string.charAt(i); <del> <del> if (c <= '/' || c >= ':') return false; <del> } <del> return true; <add> //Search for any character that is not a digit <add> //If you find a non-digit char, return false <add> return !string.matches("\\D"); <ide> } <ide> <ide> /* <ide> public static void println(){ <ide> System.out.println(""); <ide> } <del> <add> <ide> /** <ide> * Clears screen, prints msg, then calls pause();. <ide> *
Java
apache-2.0
d0f066dca8e608a2fc6d7b2d0d4252aa2d32b96a
0
axxter99/profileWOW,axxter99/profileWOW,axxter99/profileWOW
package org.sakaiproject.profilewow.tool.producers; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.api.common.edu.person.SakaiPerson; import org.sakaiproject.api.common.edu.person.SakaiPersonManager; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.entitybroker.DeveloperHelperService; import org.sakaiproject.entitybroker.EntityReference; import org.sakaiproject.profilewow.tool.params.SakaiPersonViewParams; import org.sakaiproject.profilewow.tool.params.SearchViewParamaters; import org.sakaiproject.profilewow.tool.producers.templates.SearchBoxRenderer; import org.sakaiproject.search.api.SearchList; import org.sakaiproject.search.api.SearchResult; import org.sakaiproject.search.api.SearchService; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.UserNotDefinedException; import uk.org.ponder.messageutil.TargettedMessageList; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.rsf.viewstate.ViewParamsReporter; public class SearchResultProducer implements ViewComponentProducer,ViewParamsReporter { private static Log log = LogFactory.getLog(SearchResultProducer.class); public static final String VIEW_ID= "searchProfile"; public String getViewID() { // TODO Auto-generated method stub return VIEW_ID; } private SakaiPersonManager sakaiPersonManager; public void setSakaiPersonManager(SakaiPersonManager in) { sakaiPersonManager = in; } private TargettedMessageList messages; public void setMessages(TargettedMessageList messages) { this.messages = messages; } private SecurityService securityService; public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } private UserDirectoryService userDirectoryService; public void setUserDirectoryService(UserDirectoryService uds) { this.userDirectoryService = uds; } private SearchBoxRenderer searchBoxRenderer; public void setSearchBoxRenderer(SearchBoxRenderer searchBoxRenderer) { this.searchBoxRenderer = searchBoxRenderer; } private ServerConfigurationService serverConfigurationService; public void setServerConfigurationService( ServerConfigurationService serverConfigurationService) { this.serverConfigurationService = serverConfigurationService; } private SearchService searchService; public void setSearchService(SearchService searchService) { this.searchService = searchService; } private DeveloperHelperService developerHelperService; public void setDeveloperHelperService( DeveloperHelperService developerhelperSerive) { this.developerHelperService = developerhelperSerive; } private static final int SEARCH_PAGING_SIZE = 20; /** * prefix for profile objects */ private static String PROFILE_PREFIX = "profile"; public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { SearchViewParamaters svp = (SearchViewParamaters)viewparams; String searchString = svp.searchText; log.debug("search string is: " + searchString); int start = 0; if (svp.start != null) { start = Integer.valueOf(svp.start).intValue(); } List<SakaiPerson> profiles = this.findProfiles(searchString, start, start + SEARCH_PAGING_SIZE); UIMessage.make(tofill, "searchTitle", "searchTitle", new Object[]{ searchString}); if (useSearchService() && SEARCH_PAGING_SIZE == profiles.size()) { UIInternalLink.make(tofill, "searchNext", new SearchViewParamaters(svp.viewID, Integer.valueOf(SEARCH_PAGING_SIZE +1).toString())); } if (useSearchService() && start != 0) { UIInternalLink.make(tofill, "searchBack", new SearchViewParamaters(svp.viewID, Integer.valueOf(start - SEARCH_PAGING_SIZE).toString())); } searchBoxRenderer.renderSearchBox(tofill, "search:"); for (int i =0 ; i < profiles.size(); i++) { SakaiPerson sPerson = (SakaiPerson) profiles.get(i); log.debug("creating row for " + sPerson.getGivenName()); UIBranchContainer row = UIBranchContainer.make(tofill, "resultRow:"); String eid = null; try { eid = userDirectoryService.getUserEid(sPerson.getAgentUuid()); } catch (UserNotDefinedException e) { // could be an orphaned record log.debug("user does not exits" + sPerson.getAgentUuid()); continue; } if(sPerson.getSurname()==null && sPerson.getGivenName()==null){ UIInternalLink.make(row, "resultLink", eid, new SakaiPersonViewParams(ViewProfileProducer.VIEW_ID, eid)); } else{ String label = sPerson.getSurname() == null ? "" : sPerson.getSurname(); label += (sPerson.getSurname() != null && sPerson.getGivenName()!=null) ? ", " : ""; label += sPerson.getGivenName()==null ? "" : sPerson.getGivenName(); UIInternalLink.make(row, "resultLink", label, new SakaiPersonViewParams(ViewProfileProducer.VIEW_ID, eid)); } } if(profiles.size() == 15 && useSearchService()) UIOutput.make(tofill, "limitmessage"); log.info(profiles.size()); } public ViewParameters getViewParameters() { // TODO Auto-generated method stub return new SearchViewParamaters(); } private List<SakaiPerson> findProfiles(String searchString, int start, int end) { if (useSearchService()) return findProfilesSearch(searchString, start, end); else return findProfilesDB(searchString); } private boolean useSearchService() { return serverConfigurationService.getBoolean("profilewow.useSearch", false) && searchService.isEnabled(); } private List<SakaiPerson> findProfilesSearch(String searchString, int start, int end) { List<SakaiPerson> searchResults = new ArrayList<SakaiPerson> (); List<String> contexts = new ArrayList<String>(); contexts.add("~global"); contexts.add(developerHelperService.getCurrentLocationId()); log.debug("searchString: " + searchString); String searchFor ="+" + searchString; // + " +tool:" + PROFILE_PREFIX; log.debug("were going to search for: " + searchFor); long startTime = System.currentTimeMillis(); SearchList res = searchService.search(searchFor, contexts, start, end); long endTime = System.currentTimeMillis(); log.info("got " + res.size() + " search results in: " + (endTime - startTime) + " ms"); for (int i =0; i < res.size(); i++) { SearchResult resI = (SearchResult) res.get(i); String ref = resI.getReference(); log.debug("ref: " + ref); String id = EntityReference.getIdFromRefByKey(ref, "id"); String prefix = EntityReference.getPrefix(ref); if (!PROFILE_PREFIX.equals(prefix)) { log.warn(ref + " is not a profile object"); continue; } log.debug("getting id: " + id); SakaiPerson profile = sakaiPersonManager.getSakaiPerson(id, sakaiPersonManager.getUserMutableType()); // Select the user mutable profile for display on if the public information is viewable. if ((profile != null) && profile.getTypeUuid().equals(sakaiPersonManager.getUserMutableType().getUuid())) { if ((getCurrentUserId().equals(profile.getAgentUuid()) || securityService.isSuperUser())) { // allow user to search and view own profile and superuser to view all profiles searchResults.add(profile); } else if ((profile.getHidePublicInfo() != null) && (profile.getHidePublicInfo().booleanValue() != true)) { if (profile.getHidePrivateInfo() != null && profile.getHidePrivateInfo().booleanValue() != true) { searchResults.add(profile); } else { searchResults.add(getOnlyPublicProfile(profile)); } } } } return searchResults; } private List<SakaiPerson> findProfilesDB(String searchString) { if (log.isDebugEnabled()) { log.debug("findProfiles(" + searchString + ")"); } if (searchString == null || searchString.length() < 4) throw new IllegalArgumentException("Illegal searchString argument passed!"); List<SakaiPerson> profiles = sakaiPersonManager.findSakaiPerson(searchString); List<SakaiPerson> searchResults = new ArrayList<SakaiPerson>(); SakaiPerson profile; if ((profiles != null) && (profiles.size() > 0)) { Iterator<SakaiPerson> profileIterator = profiles.iterator(); while (profileIterator.hasNext()) { profile = (SakaiPerson) profileIterator.next(); // Select the user mutable profile for display on if the public information is viewable. if ((profile != null) && profile.getTypeUuid().equals(sakaiPersonManager.getUserMutableType().getUuid())) { if ((getCurrentUserId().equals(profile.getAgentUuid()) || securityService.isSuperUser())) { // allow user to search and view own profile and superuser to view all profiles searchResults.add(profile); } else if ((profile.getHidePublicInfo() != null) && (profile.getHidePublicInfo().booleanValue() != true)) { if (profile.getHidePrivateInfo() != null && profile.getHidePrivateInfo().booleanValue() != true) { searchResults.add(profile); } else { searchResults.add(getOnlyPublicProfile(profile)); } } } if(searchResults.size() == 15) break; } } log.info("found a resultsList of: " + searchResults.size()); return searchResults; } private SakaiPerson getOnlyPublicProfile(SakaiPerson profile) { if (log.isDebugEnabled()) { log.debug("getOnlyPublicProfile(Profile" + profile + ")"); } profile.setJpegPhoto(null); profile.setPictureUrl(null); profile.setMail(null); profile.setLabeledURI(null); profile.setHomePhone(null); profile.setNotes(null); return profile; } private String getCurrentUserId() { return userDirectoryService.getCurrentUser().getId(); } }
tool/src/java/org/sakaiproject/profilewow/tool/producers/SearchResultProducer.java
package org.sakaiproject.profilewow.tool.producers; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.api.common.edu.person.SakaiPerson; import org.sakaiproject.api.common.edu.person.SakaiPersonManager; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.entitybroker.DeveloperHelperService; import org.sakaiproject.entitybroker.EntityReference; import org.sakaiproject.profilewow.tool.params.SakaiPersonViewParams; import org.sakaiproject.profilewow.tool.params.SearchViewParamaters; import org.sakaiproject.profilewow.tool.producers.templates.SearchBoxRenderer; import org.sakaiproject.search.api.SearchList; import org.sakaiproject.search.api.SearchResult; import org.sakaiproject.search.api.SearchService; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.UserNotDefinedException; import uk.org.ponder.messageutil.TargettedMessageList; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.rsf.viewstate.ViewParamsReporter; public class SearchResultProducer implements ViewComponentProducer,ViewParamsReporter { private static Log log = LogFactory.getLog(SearchResultProducer.class); public static final String VIEW_ID= "searchProfile"; public String getViewID() { // TODO Auto-generated method stub return VIEW_ID; } private SakaiPersonManager sakaiPersonManager; public void setSakaiPersonManager(SakaiPersonManager in) { sakaiPersonManager = in; } private TargettedMessageList messages; public void setMessages(TargettedMessageList messages) { this.messages = messages; } private SecurityService securityService; public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } private UserDirectoryService userDirectoryService; public void setUserDirectoryService(UserDirectoryService uds) { this.userDirectoryService = uds; } private SearchBoxRenderer searchBoxRenderer; public void setSearchBoxRenderer(SearchBoxRenderer searchBoxRenderer) { this.searchBoxRenderer = searchBoxRenderer; } private ServerConfigurationService serverConfigurationService; public void setServerConfigurationService( ServerConfigurationService serverConfigurationService) { this.serverConfigurationService = serverConfigurationService; } private SearchService searchService; public void setSearchService(SearchService searchService) { this.searchService = searchService; } private DeveloperHelperService developerHelperService; public void setDeveloperHelperService( DeveloperHelperService developerhelperSerive) { this.developerHelperService = developerhelperSerive; } private static final int SEARCH_PAGING_SIZE = 20; /** * prefix for profile objects */ private static String PROFILE_PREFIX = "profile"; public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { SearchViewParamaters svp = (SearchViewParamaters)viewparams; String searchString = svp.searchText; log.debug("search string is: " + searchString); int start = 0; if (svp.start != null) { start = Integer.valueOf(svp.start).intValue(); } List<SakaiPerson> profiles = this.findProfiles(searchString, start, start + SEARCH_PAGING_SIZE); UIMessage.make(tofill, "searchTitle", "searchTitle", new Object[]{ searchString}); if (useSearchService() && SEARCH_PAGING_SIZE == profiles.size()) { UIInternalLink.make(tofill, "searchNext", new SearchViewParamaters(svp.viewID, Integer.valueOf(SEARCH_PAGING_SIZE +1).toString())); } if (useSearchService() && start != 0) { UIInternalLink.make(tofill, "searchBack", new SearchViewParamaters(svp.viewID, Integer.valueOf(start - SEARCH_PAGING_SIZE).toString())); } searchBoxRenderer.renderSearchBox(tofill, "search:"); for (int i =0 ; i < profiles.size(); i++) { SakaiPerson sPerson = (SakaiPerson) profiles.get(i); log.debug("creating row for " + sPerson.getGivenName()); UIBranchContainer row = UIBranchContainer.make(tofill, "resultRow:"); String eid = null; try { eid = userDirectoryService.getUserEid(sPerson.getAgentUuid()); } catch (UserNotDefinedException e) { // could be an orphaned record log.debug("user does not exits" + sPerson.getAgentUuid()); continue; } if(sPerson.getSurname()==null && sPerson.getGivenName()==null){ UIInternalLink.make(row, "resultLink", eid, new SakaiPersonViewParams(ViewProfileProducer.VIEW_ID, eid)); } else{ String label = sPerson.getSurname() == null ? "" : sPerson.getSurname(); label += (sPerson.getSurname() != null && sPerson.getGivenName()!=null) ? ", " : ""; label += sPerson.getGivenName()==null ? "" : sPerson.getGivenName(); UIInternalLink.make(row, "resultLink", label, new SakaiPersonViewParams(ViewProfileProducer.VIEW_ID, eid)); } } if(profiles.size() == 15 && useSearchService()) UIOutput.make(tofill, "limitmessage"); log.info(profiles.size()); } public ViewParameters getViewParameters() { // TODO Auto-generated method stub return new SearchViewParamaters(); } private List<SakaiPerson> findProfiles(String searchString, int start, int end) { if (useSearchService()) return findProfilesSearch(searchString, start, end); else return findProfilesDB(searchString); } private boolean useSearchService() { return serverConfigurationService.getBoolean("profilewow.useSearch", false) && searchService.isEnabled(); } private List<SakaiPerson> findProfilesSearch(String searchString, int start, int end) { List<SakaiPerson> searchResults = new ArrayList<SakaiPerson> (); List<String> contexts = new ArrayList<String>(); contexts.add("~global"); contexts.add(developerHelperService.getCurrentLocationId()); log.debug("searchString: " + searchString); String searchFor ="+" + searchString; // + " +tool:" + PROFILE_PREFIX; log.debug("were going to search for: " + searchFor); long startTime = System.currentTimeMillis(); SearchList res = searchService.search(searchFor, contexts, start, end); long endTime = System.currentTimeMillis(); log.info("got " + res.size() + " search results in: " + (endTime - startTime) + " ms"); for (int i =0; i < res.size(); i++) { SearchResult resI = (SearchResult) res.get(i); String ref = resI.getReference(); log.debug("ref: " + ref); String id = EntityReference.getIdFromRefByKey(ref, "id"); String prefix = EntityReference.getPrefix(ref); if (!PROFILE_PREFIX.equals(prefix)) { log.warn(ref + " is not a profile object"); continue; } log.debug("getting id: " + id); SakaiPerson profile = sakaiPersonManager.getSakaiPerson(id, sakaiPersonManager.getUserMutableType()); // Select the user mutable profile for display on if the public information is viewable. if ((profile != null) && profile.getTypeUuid().equals(sakaiPersonManager.getUserMutableType().getUuid())) { if ((getCurrentUserId().equals(profile.getAgentUuid()) || securityService.isSuperUser())) { // allow user to search and view own profile and superuser to view all profiles searchResults.add(profile); } else if ((profile.getHidePublicInfo() != null) && (profile.getHidePublicInfo().booleanValue() != true)) { if (profile.getHidePrivateInfo() != null && profile.getHidePrivateInfo().booleanValue() != true) { searchResults.add(profile); } else { searchResults.add(getOnlyPublicProfile(profile)); } } } if(searchResults.size() == 15) break; } return searchResults; } private List<SakaiPerson> findProfilesDB(String searchString) { if (log.isDebugEnabled()) { log.debug("findProfiles(" + searchString + ")"); } if (searchString == null || searchString.length() < 4) throw new IllegalArgumentException("Illegal searchString argument passed!"); List<SakaiPerson> profiles = sakaiPersonManager.findSakaiPerson(searchString); List<SakaiPerson> searchResults = new ArrayList<SakaiPerson>(); SakaiPerson profile; if ((profiles != null) && (profiles.size() > 0)) { Iterator<SakaiPerson> profileIterator = profiles.iterator(); while (profileIterator.hasNext()) { profile = (SakaiPerson) profileIterator.next(); // Select the user mutable profile for display on if the public information is viewable. if ((profile != null) && profile.getTypeUuid().equals(sakaiPersonManager.getUserMutableType().getUuid())) { if ((getCurrentUserId().equals(profile.getAgentUuid()) || securityService.isSuperUser())) { // allow user to search and view own profile and superuser to view all profiles searchResults.add(profile); } else if ((profile.getHidePublicInfo() != null) && (profile.getHidePublicInfo().booleanValue() != true)) { if (profile.getHidePrivateInfo() != null && profile.getHidePrivateInfo().booleanValue() != true) { searchResults.add(profile); } else { searchResults.add(getOnlyPublicProfile(profile)); } } } if(searchResults.size() == 15) break; } } log.info("found a resultsList of: " + searchResults.size()); return searchResults; } private SakaiPerson getOnlyPublicProfile(SakaiPerson profile) { if (log.isDebugEnabled()) { log.debug("getOnlyPublicProfile(Profile" + profile + ")"); } profile.setJpegPhoto(null); profile.setPictureUrl(null); profile.setMail(null); profile.setLabeledURI(null); profile.setHomePhone(null); profile.setNotes(null); return profile; } private String getCurrentUserId() { return userDirectoryService.getCurrentUser().getId(); } }
VULA-214 no longer break in search mode
tool/src/java/org/sakaiproject/profilewow/tool/producers/SearchResultProducer.java
VULA-214 no longer break in search mode
<ide><path>ool/src/java/org/sakaiproject/profilewow/tool/producers/SearchResultProducer.java <ide> <ide> } <ide> } <del> if(searchResults.size() == 15) <del> break; <add> <ide> } <ide> return searchResults; <ide> }
Java
epl-1.0
3f2b73f68023a5fa94901538f5f0cd4d1dd56f5e
0
rgom/Pydev,RandallDW/Aruba_plugin,fabioz/Pydev,fabioz/Pydev,akurtakov/Pydev,rajul/Pydev,rgom/Pydev,akurtakov/Pydev,akurtakov/Pydev,fabioz/Pydev,akurtakov/Pydev,RandallDW/Aruba_plugin,akurtakov/Pydev,RandallDW/Aruba_plugin,rgom/Pydev,rajul/Pydev,RandallDW/Aruba_plugin,rgom/Pydev,akurtakov/Pydev,fabioz/Pydev,RandallDW/Aruba_plugin,rajul/Pydev,fabioz/Pydev,fabioz/Pydev,rajul/Pydev,rgom/Pydev,rajul/Pydev,rajul/Pydev,rgom/Pydev,RandallDW/Aruba_plugin
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package org.python.pydev.editorinput; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.window.Window; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IPathEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.part.FileEditorInput; import org.python.pydev.core.IPyStackFrame; import org.python.pydev.core.IPythonPathNature; import org.python.pydev.core.log.Log; import org.python.pydev.editor.PyEdit; import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.plugin.nature.PythonNature; import org.python.pydev.shared_core.io.FileUtils; import org.python.pydev.shared_core.string.StringUtils; import org.python.pydev.shared_core.structure.Tuple; import org.python.pydev.ui.filetypes.FileTypesPreferencesPage; /** * Refactored from the PydevPlugin: helpers to find some IFile / IEditorInput * from a Path (or java.io.File) * * @author fabioz */ public class PySourceLocatorBase { /** * This method will try to find the most likely file that matches the given path, * considering: * - The workspace files * - The open editors * * and if all fails, it'll still ask the user which path should be used. * * * @param path * @return */ public IEditorInput createEditorInput(IPath path, IProject project) { return createEditorInput(path, true, null, project); } public IEditorInput createEditorInput(IPath path) { return createEditorInput(path, true, null, null); } public IFile[] getFilesForLocation(IPath location, IProject project, boolean stopOnFirst) { return GetFiles.getFilesForLocation(location, project, stopOnFirst); } public IFile getFileForLocation(IPath location, IProject project) { return GetFiles.getFileForLocation(location, project); } /** * @param file the file we want to get in the workspace * @return a workspace file that matches the given file. */ public IFile getWorkspaceFile(File file, IProject project) { return getFileForLocation(Path.fromOSString(file.getAbsolutePath()), project); } /** * @param file the file we want to get in the workspace * @return a workspace file that matches the given file. */ public IFile[] getWorkspaceFiles(File file) { boolean stopOnFirst = false; IFile[] files = getFilesForLocation(Path.fromOSString(file.getAbsolutePath()), null, stopOnFirst); if (files == null || files.length == 0) { return null; } return files; } public IContainer getContainerForLocation(IPath location, IProject project) { return GetContainers.getContainerForLocation(location, project); } public IContainer[] getContainersForLocation(IPath location) { boolean stopOnFirst = false; return GetContainers.getContainersForLocation(location, null, stopOnFirst); } //---------------------------------- PRIVATE API BELOW -------------------------------------------- /** * Creates the editor input from a given path. * * @param path the path for the editor input we're looking * @param askIfDoesNotExist if true, it'll try to ask the user/check existing editors and look * in the workspace for matches given the name * @param project if provided, and if a matching file is found in this project, that file will be * opened before asking the user to select from a list of all matches * * @return the editor input found or none if None was available for the given path */ public IEditorInput createEditorInput(IPath path, boolean askIfDoesNotExist, IPyStackFrame pyStackFrame, IProject project) { int onSourceNotFound = PySourceLocatorPrefs.getOnSourceNotFound(); IEditorInput edInput = null; String pathTranslation = PySourceLocatorPrefs.getPathTranslation(path); if (pathTranslation != null) { if (!pathTranslation.equals(PySourceLocatorPrefs.DONTASK)) { //change it for the registered translation path = Path.fromOSString(pathTranslation); } else { //DONTASK!! askIfDoesNotExist = false; } } IFile fileForLocation = getFileForLocation(path, project); if (fileForLocation != null && fileForLocation.exists()) { //if a project was specified, make sure the file found comes from that project return new FileEditorInput(fileForLocation); } //getFileForLocation() will search all projects starting with the one we pass and references, //so, if not found there, it is probably an external file File systemFile = path.toFile(); if (systemFile.exists()) { edInput = PydevFileEditorInput.create(systemFile, true); } if (edInput == null) { //here we can do one more thing: if the file matches some opened editor, let's use it... //(this is done because when debugging, we don't want to be asked over and over //for the same file) IEditorInput input = getEditorInputFromExistingEditors(systemFile.getName()); if (input != null) { return input; } if (askIfDoesNotExist && (onSourceNotFound == PySourceLocatorPrefs.ASK_FOR_FILE || onSourceNotFound == PySourceLocatorPrefs.ASK_FOR_FILE_GET_FROM_SERVER)) { //this is the last resort... First we'll try to check for a 'good' match, //and if there's more than one we'll ask it to the user IWorkspace w = ResourcesPlugin.getWorkspace(); List<IFile> likelyFiles = getLikelyFiles(path, w); IFile iFile = selectWorkspaceFile(likelyFiles.toArray(new IFile[0])); if (iFile != null) { IPath location = iFile.getLocation(); if (location != null) { PySourceLocatorPrefs.addPathTranslation(path, location); return new FileEditorInput(iFile); } } //ok, ask the user for any file in the computer IEditorInput pydevFileEditorInput = selectFilesystemFileForPath(path); input = pydevFileEditorInput; if (input != null) { File file = PydevFileEditorInput.getFile(pydevFileEditorInput); if (file != null) { PySourceLocatorPrefs.addPathTranslation(path, Path.fromOSString(FileUtils.getFileAbsolutePath(file))); return input; } } PySourceLocatorPrefs.setIgnorePathTranslation(path); } } if (edInput == null && (onSourceNotFound == PySourceLocatorPrefs.ASK_FOR_FILE_GET_FROM_SERVER || onSourceNotFound == PySourceLocatorPrefs.GET_FROM_SERVER)) { if (pyStackFrame != null) { try { String fileContents = pyStackFrame.getFileContents(); if (fileContents != null && fileContents.length() > 0) { String lastSegment = path.lastSegment(); File workspaceMetadataFile = PydevPlugin.getWorkspaceMetadataFile("temporary_files"); if (!workspaceMetadataFile.exists()) { workspaceMetadataFile.mkdirs(); } File file = new File(workspaceMetadataFile, lastSegment); try { if (file.exists()) { file.delete(); } } catch (Exception e) { } FileUtils.writeStrToFile(fileContents, file); try { file.setReadOnly(); } catch (Exception e) { } edInput = PydevFileEditorInput.create(file, true); } } catch (Exception e) { Log.log(e); } } } return edInput; } /** * @param matchName the name to match in the editor * @return an editor input from an existing editor available */ private IEditorInput getEditorInputFromExistingEditors(final String matchName) { final Tuple<IWorkbenchWindow, IEditorInput> workbenchAndReturn = new Tuple<IWorkbenchWindow, IEditorInput>( PlatformUI.getWorkbench().getActiveWorkbenchWindow(), null); Runnable r = new Runnable() { public void run() { IWorkbenchWindow workbenchWindow = workbenchAndReturn.o1; if (workbenchWindow == null) { workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); } if (workbenchWindow == null) { return; } IWorkbenchPage activePage = workbenchWindow.getActivePage(); if (activePage == null) { return; } IEditorReference[] editorReferences = activePage.getEditorReferences(); for (IEditorReference editorReference : editorReferences) { IEditorPart editor = editorReference.getEditor(false); if (editor != null) { if (editor instanceof PyEdit) { PyEdit pyEdit = (PyEdit) editor; IEditorInput editorInput = pyEdit.getEditorInput(); if (editorInput instanceof IPathEditorInput) { IPathEditorInput pathEditorInput = (IPathEditorInput) editorInput; IPath localPath = pathEditorInput.getPath(); if (localPath != null) { String considerName = localPath.segment(localPath.segmentCount() - 1); if (matchName.equals(considerName)) { workbenchAndReturn.o2 = editorInput; return; } } } else { File editorFile = pyEdit.getEditorFile(); if (editorFile != null) { if (editorFile.getName().equals(matchName)) { workbenchAndReturn.o2 = editorInput; return; } } } } } } } }; if (workbenchAndReturn.o1 == null) { //not ui-thread Display.getDefault().syncExec(r); } else { r.run(); } return workbenchAndReturn.o2; } /** * This is the last resort... pointing to some filesystem file to get the editor for some path. */ protected IEditorInput selectFilesystemFileForPath(final IPath path) { final List<String> l = new ArrayList<String>(); Runnable r = new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); FileDialog dialog = new FileDialog(shell); dialog.setText(path + " - select correspondent filesystem file."); String[] wildcardValidSourceFiles = FileTypesPreferencesPage.getWildcardValidSourceFiles(); wildcardValidSourceFiles = StringUtils.addString(wildcardValidSourceFiles, "*"); dialog.setFilterExtensions(wildcardValidSourceFiles); String string = dialog.open(); if (string != null) { l.add(string); } } }; if (Display.getCurrent() == null) { //not ui-thread Display.getDefault().syncExec(r); } else { r.run(); } if (l.size() > 0) { String fileAbsolutePath = FileUtils.getFileAbsolutePath(l.get(0)); return PydevFileEditorInput.create(new File(fileAbsolutePath), true); } return null; } /** * This method will pass all the files in the workspace and check if there's a file that might * be a match to some path (use only as an almost 'last-resort'). */ private List<IFile> getLikelyFiles(IPath path, IWorkspace w) { List<IFile> ret = new ArrayList<IFile>(); try { IResource[] resources = w.getRoot().members(); getLikelyFiles(path, ret, resources); } catch (CoreException e) { Log.log(e); } return ret; } /** * Used to recursively get the likely files given the first set of containers */ private void getLikelyFiles(IPath path, List<IFile> ret, IResource[] resources) throws CoreException { String strPath = path.removeFileExtension().lastSegment().toLowerCase(); //this will return something as 'foo' for (IResource resource : resources) { if (resource instanceof IFile) { IFile f = (IFile) resource; if (PythonPathHelper.isValidSourceFile(f)) { if (resource.getFullPath().removeFileExtension().lastSegment().toLowerCase().equals(strPath)) { ret.add((IFile) resource); } } } else if (resource instanceof IContainer) { getLikelyFiles(path, ret, ((IContainer) resource).members()); } } } /** * Ask the user to select one file of the given list of files (if some is available) * * @param files the files available for selection. * @return the selected file (from the files passed) or null if there was no file available for * selection or if the user canceled it. */ private IFile selectWorkspaceFile(final IFile[] files) { if (files == null || files.length == 0) { return null; } if (files.length == 1) { return files[0]; } final List<IFile> selected = new ArrayList<IFile>(); Runnable r = new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); ElementListSelectionDialog dialog = new ElementListSelectionDialog(shell, new PyFileLabelProvider()); dialog.setElements(files); dialog.setTitle("Select Workspace File"); dialog.setMessage("File may be matched to multiple files in the workspace."); if (dialog.open() == Window.OK) { selected.add((IFile) dialog.getFirstResult()); } } }; if (Display.getCurrent() == null) { //not ui-thread Display.getDefault().syncExec(r); } else { r.run(); } if (selected.size() > 0) { return selected.get(0); } return null; } private static class GetFiles { /** * This method is a workaround for w.getRoot().getFileForLocation(path); which does not work consistently because * it filters out files which should not be filtered (i.e.: if a project is not in the workspace but imported). * * Also, it can fail to get resources in linked folders in the pythonpath. * * @param project is optional (may be null): if given we'll search in it dependencies first. */ private static IFile getFileForLocation(IPath location, IProject project) { boolean stopOnFirst = true; IFile[] filesForLocation = getFilesForLocation(location, project, stopOnFirst); if (filesForLocation != null && filesForLocation.length > 0) { return filesForLocation[0]; } return null; } /** * This method is a workaround for w.getRoot().getFilesForLocation(path); which does not work consistently because * it filters out files which should not be filtered (i.e.: if a project is not in the workspace but imported). * * Also, it can fail to get resources in linked folders in the pythonpath. * * @param project is optional (may be null): if given we'll search in it dependencies first. */ private static IFile[] getFilesForLocation(IPath location, IProject project, boolean stopOnFirst) { ArrayList<IFile> lst = new ArrayList<>(); HashSet<IProject> checked = new HashSet<>(); IWorkspace w = ResourcesPlugin.getWorkspace(); if (project != null) { checked.add(project); IFile f = getFileInProject(location, project); if (f != null) { if (stopOnFirst) { return new IFile[] { f }; } else { lst.add(f); } } try { IProject[] referencedProjects = project.getDescription().getReferencedProjects(); for (int i = 0; i < referencedProjects.length; i++) { IProject p = referencedProjects[i]; checked.add(p); f = getFileInProject(location, p); if (f != null) { if (stopOnFirst) { return new IFile[] { f }; } else { lst.add(f); } } } } catch (CoreException e) { Log.log(e); } } IProject[] projects = w.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); for (int i = 0; i < projects.length; i++) { IProject p = projects[i]; if (checked.contains(p)) { continue; } checked.add(p); IFile f = getFileInProject(location, p); if (f != null) { if (stopOnFirst) { return new IFile[] { f }; } else { lst.add(f); } } } return lst.toArray(new IFile[lst.size()]); } /** * Gets an IFile inside a container given a path in the filesystem (resolves the full path of the container and * checks if the location given is under it). */ private static IFile getFileInContainer(IPath location, IContainer container) { IPath projectLocation = container.getLocation(); if (projectLocation != null) { if (projectLocation.isPrefixOf(location)) { int segmentsToRemove = projectLocation.segmentCount(); IPath removingFirstSegments = location.removeFirstSegments(segmentsToRemove); if (removingFirstSegments.segmentCount() == 0) { //It's equal: as we want a file in the container, and the path to the file is equal to the //container, we have to return null (because it's equal to the container it cannot be a file). return null; } IFile file = container.getFile(removingFirstSegments); if (file.exists()) { return file; } } } else { if (container instanceof IProject) { Log.logInfo("Info: Project: " + container + " has no associated location."); } } return null; } /** * Tries to get a file from a project. Considers source folders (which could be linked) or resources directly beneath * the project. * @param location this is the path location to be gotten. * @param project this is the project we're searching. * @return the file found or null if it was not found. */ private static IFile getFileInProject(IPath location, IProject project) { IFile file = getFileInContainer(location, project); if (file != null) { return file; } PythonNature nature = PythonNature.getPythonNature(project); if (nature != null) { IPythonPathNature pythonPathNature = nature.getPythonPathNature(); try { //Paths Set<IResource> projectSourcePathSet = pythonPathNature.getProjectSourcePathFolderSet(); for (IResource iResource : projectSourcePathSet) { if (iResource instanceof IContainer) { //I.e.: don't consider zip files IContainer iContainer = (IContainer) iResource; file = getFileInContainer(location, iContainer); if (file != null) { return file; } } } } catch (CoreException e) { Log.log(e); } } return null; } } private static class GetContainers { /** * This method is a workaround for w.getRoot().getContainerForLocation(path); which does not work consistently because * it filters out files which should not be filtered (i.e.: if a project is not in the workspace but imported). * * Also, it can fail to get resources in linked folders in the pythonpath. * * @param project is optional (may be null): if given we'll search in it dependencies first. */ private static IContainer getContainerForLocation(IPath location, IProject project) { boolean stopOnFirst = true; IContainer[] filesForLocation = getContainersForLocation(location, project, stopOnFirst); if (filesForLocation != null && filesForLocation.length > 0) { return filesForLocation[0]; } return null; } /** * This method is a workaround for w.getRoot().getContainersForLocation(path); which does not work consistently because * it filters out files which should not be filtered (i.e.: if a project is not in the workspace but imported). * * Also, it can fail to get resources in linked folders in the pythonpath. * * @param project is optional (may be null): if given we'll search in it dependencies first. */ private static IContainer[] getContainersForLocation(IPath location, IProject project, boolean stopOnFirst) { ArrayList<IContainer> lst = new ArrayList<>(); HashSet<IProject> checked = new HashSet<>(); IWorkspace w = ResourcesPlugin.getWorkspace(); if (project != null) { checked.add(project); IContainer f = getContainerInProject(location, project); if (f != null) { if (stopOnFirst) { return new IContainer[] { f }; } else { lst.add(f); } } try { IProject[] referencedProjects = project.getDescription().getReferencedProjects(); for (int i = 0; i < referencedProjects.length; i++) { IProject p = referencedProjects[i]; checked.add(p); f = getContainerInProject(location, p); if (f != null) { if (stopOnFirst) { return new IContainer[] { f }; } else { lst.add(f); } } } } catch (CoreException e) { Log.log(e); } } IProject[] projects = w.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); for (int i = 0; i < projects.length; i++) { IProject p = projects[i]; if (checked.contains(p)) { continue; } checked.add(p); IContainer f = getContainerInProject(location, p); if (f != null) { if (stopOnFirst) { return new IContainer[] { f }; } else { lst.add(f); } } } return lst.toArray(new IContainer[lst.size()]); } /** * Gets an IContainer inside a container given a path in the filesystem (resolves the full path of the container and * checks if the location given is under it). */ private static IContainer getContainerInContainer(IPath location, IContainer container) { IPath projectLocation = container.getLocation(); if (projectLocation != null && projectLocation.isPrefixOf(location)) { int segmentsToRemove = projectLocation.segmentCount(); IPath removeFirstSegments = location.removeFirstSegments(segmentsToRemove); if (removeFirstSegments.segmentCount() == 0) { return container; //I.e.: equal to container } IContainer file = container.getFolder(removeFirstSegments); if (file.exists()) { return file; } } return null; } /** * Tries to get a file from a project. Considers source folders (which could be linked) or resources directly beneath * the project. * @param location this is the path location to be gotten. * @param project this is the project we're searching. * @return the file found or null if it was not found. */ private static IContainer getContainerInProject(IPath location, IProject project) { IContainer file = getContainerInContainer(location, project); if (file != null) { return file; } PythonNature nature = PythonNature.getPythonNature(project); if (nature != null) { IPythonPathNature pythonPathNature = nature.getPythonPathNature(); try { //Paths Set<IResource> projectSourcePathSet = pythonPathNature.getProjectSourcePathFolderSet(); for (IResource iResource : projectSourcePathSet) { if (iResource instanceof IContainer) { //I.e.: don't consider zip files IContainer iContainer = (IContainer) iResource; file = getContainerInContainer(location, iContainer); if (file != null) { return file; } } } } catch (CoreException e) { Log.log(e); } } return null; } } }
plugins/org.python.pydev/src/org/python/pydev/editorinput/PySourceLocatorBase.java
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package org.python.pydev.editorinput; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.window.Window; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IPathEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.part.FileEditorInput; import org.python.pydev.core.IPyStackFrame; import org.python.pydev.core.IPythonPathNature; import org.python.pydev.core.log.Log; import org.python.pydev.editor.PyEdit; import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.plugin.nature.PythonNature; import org.python.pydev.shared_core.io.FileUtils; import org.python.pydev.shared_core.string.StringUtils; import org.python.pydev.shared_core.structure.Tuple; import org.python.pydev.ui.filetypes.FileTypesPreferencesPage; /** * Refactored from the PydevPlugin: helpers to find some IFile / IEditorInput * from a Path (or java.io.File) * * @author fabioz */ public class PySourceLocatorBase { /** * This method will try to find the most likely file that matches the given path, * considering: * - The workspace files * - The open editors * * and if all fails, it'll still ask the user which path should be used. * * * @param path * @return */ public IEditorInput createEditorInput(IPath path, IProject project) { return createEditorInput(path, true, null, project); } public IEditorInput createEditorInput(IPath path) { return createEditorInput(path, true, null, null); } public IFile[] getFilesForLocation(IPath location, IProject project, boolean stopOnFirst) { return GetFiles.getFilesForLocation(location, project, stopOnFirst); } public IFile getFileForLocation(IPath location, IProject project) { return GetFiles.getFileForLocation(location, project); } /** * @param file the file we want to get in the workspace * @return a workspace file that matches the given file. */ public IFile getWorkspaceFile(File file, IProject project) { return getFileForLocation(Path.fromOSString(file.getAbsolutePath()), project); } /** * @param file the file we want to get in the workspace * @return a workspace file that matches the given file. */ public IFile[] getWorkspaceFiles(File file) { boolean stopOnFirst = false; IFile[] files = getFilesForLocation(Path.fromOSString(file.getAbsolutePath()), null, stopOnFirst); if (files == null || files.length == 0) { return null; } return files; } public IContainer getContainerForLocation(IPath location, IProject project) { return GetContainers.getContainerForLocation(location, project); } public IContainer[] getContainersForLocation(IPath location) { boolean stopOnFirst = false; return GetContainers.getContainersForLocation(location, null, stopOnFirst); } //---------------------------------- PRIVATE API BELOW -------------------------------------------- /** * Creates the editor input from a given path. * * @param path the path for the editor input we're looking * @param askIfDoesNotExist if true, it'll try to ask the user/check existing editors and look * in the workspace for matches given the name * @param project if provided, and if a matching file is found in this project, that file will be * opened before asking the user to select from a list of all matches * * @return the editor input found or none if None was available for the given path */ public IEditorInput createEditorInput(IPath path, boolean askIfDoesNotExist, IPyStackFrame pyStackFrame, IProject project) { int onSourceNotFound = PySourceLocatorPrefs.getOnSourceNotFound(); IEditorInput edInput = null; String pathTranslation = PySourceLocatorPrefs.getPathTranslation(path); if (pathTranslation != null) { if (!pathTranslation.equals(PySourceLocatorPrefs.DONTASK)) { //change it for the registered translation path = Path.fromOSString(pathTranslation); } else { //DONTASK!! askIfDoesNotExist = false; } } IFile fileForLocation = getFileForLocation(path, project); if (fileForLocation != null && fileForLocation.exists()) { //if a project was specified, make sure the file found comes from that project return new FileEditorInput(fileForLocation); } //getFileForLocation() will search all projects starting with the one we pass and references, //so, if not found there, it is probably an external file File systemFile = path.toFile(); if (systemFile.exists()) { edInput = PydevFileEditorInput.create(systemFile, true); } if (edInput == null) { //here we can do one more thing: if the file matches some opened editor, let's use it... //(this is done because when debugging, we don't want to be asked over and over //for the same file) IEditorInput input = getEditorInputFromExistingEditors(systemFile.getName()); if (input != null) { return input; } if (askIfDoesNotExist && (onSourceNotFound == PySourceLocatorPrefs.ASK_FOR_FILE || onSourceNotFound == PySourceLocatorPrefs.ASK_FOR_FILE_GET_FROM_SERVER)) { //this is the last resort... First we'll try to check for a 'good' match, //and if there's more than one we'll ask it to the user IWorkspace w = ResourcesPlugin.getWorkspace(); List<IFile> likelyFiles = getLikelyFiles(path, w); IFile iFile = selectWorkspaceFile(likelyFiles.toArray(new IFile[0])); if (iFile != null) { PySourceLocatorPrefs.addPathTranslation(path, iFile.getLocation()); return new FileEditorInput(iFile); } //ok, ask the user for any file in the computer IEditorInput pydevFileEditorInput = selectFilesystemFileForPath(path); input = pydevFileEditorInput; if (input != null) { File file = PydevFileEditorInput.getFile(pydevFileEditorInput); if (file != null) { PySourceLocatorPrefs.addPathTranslation(path, Path.fromOSString(FileUtils.getFileAbsolutePath(file))); return input; } } PySourceLocatorPrefs.setIgnorePathTranslation(path); } } if (edInput == null && (onSourceNotFound == PySourceLocatorPrefs.ASK_FOR_FILE_GET_FROM_SERVER || onSourceNotFound == PySourceLocatorPrefs.GET_FROM_SERVER)) { if (pyStackFrame != null) { try { String fileContents = pyStackFrame.getFileContents(); if (fileContents != null && fileContents.length() > 0) { String lastSegment = path.lastSegment(); File workspaceMetadataFile = PydevPlugin.getWorkspaceMetadataFile("temporary_files"); if (!workspaceMetadataFile.exists()) { workspaceMetadataFile.mkdirs(); } File file = new File(workspaceMetadataFile, lastSegment); try { if (file.exists()) { file.delete(); } } catch (Exception e) { } FileUtils.writeStrToFile(fileContents, file); try { file.setReadOnly(); } catch (Exception e) { } edInput = PydevFileEditorInput.create(file, true); } } catch (Exception e) { Log.log(e); } } } return edInput; } /** * @param matchName the name to match in the editor * @return an editor input from an existing editor available */ private IEditorInput getEditorInputFromExistingEditors(final String matchName) { final Tuple<IWorkbenchWindow, IEditorInput> workbenchAndReturn = new Tuple<IWorkbenchWindow, IEditorInput>( PlatformUI.getWorkbench().getActiveWorkbenchWindow(), null); Runnable r = new Runnable() { public void run() { IWorkbenchWindow workbenchWindow = workbenchAndReturn.o1; if (workbenchWindow == null) { workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); } if (workbenchWindow == null) { return; } IWorkbenchPage activePage = workbenchWindow.getActivePage(); if (activePage == null) { return; } IEditorReference[] editorReferences = activePage.getEditorReferences(); for (IEditorReference editorReference : editorReferences) { IEditorPart editor = editorReference.getEditor(false); if (editor != null) { if (editor instanceof PyEdit) { PyEdit pyEdit = (PyEdit) editor; IEditorInput editorInput = pyEdit.getEditorInput(); if (editorInput instanceof IPathEditorInput) { IPathEditorInput pathEditorInput = (IPathEditorInput) editorInput; IPath localPath = pathEditorInput.getPath(); if (localPath != null) { String considerName = localPath.segment(localPath.segmentCount() - 1); if (matchName.equals(considerName)) { workbenchAndReturn.o2 = editorInput; return; } } } else { File editorFile = pyEdit.getEditorFile(); if (editorFile != null) { if (editorFile.getName().equals(matchName)) { workbenchAndReturn.o2 = editorInput; return; } } } } } } } }; if (workbenchAndReturn.o1 == null) { //not ui-thread Display.getDefault().syncExec(r); } else { r.run(); } return workbenchAndReturn.o2; } /** * This is the last resort... pointing to some filesystem file to get the editor for some path. */ protected IEditorInput selectFilesystemFileForPath(final IPath path) { final List<String> l = new ArrayList<String>(); Runnable r = new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); FileDialog dialog = new FileDialog(shell); dialog.setText(path + " - select correspondent filesystem file."); String[] wildcardValidSourceFiles = FileTypesPreferencesPage.getWildcardValidSourceFiles(); wildcardValidSourceFiles = StringUtils.addString(wildcardValidSourceFiles, "*"); dialog.setFilterExtensions(wildcardValidSourceFiles); String string = dialog.open(); if (string != null) { l.add(string); } } }; if (Display.getCurrent() == null) { //not ui-thread Display.getDefault().syncExec(r); } else { r.run(); } if (l.size() > 0) { String fileAbsolutePath = FileUtils.getFileAbsolutePath(l.get(0)); return PydevFileEditorInput.create(new File(fileAbsolutePath), true); } return null; } /** * This method will pass all the files in the workspace and check if there's a file that might * be a match to some path (use only as an almost 'last-resort'). */ private List<IFile> getLikelyFiles(IPath path, IWorkspace w) { List<IFile> ret = new ArrayList<IFile>(); try { IResource[] resources = w.getRoot().members(); getLikelyFiles(path, ret, resources); } catch (CoreException e) { Log.log(e); } return ret; } /** * Used to recursively get the likely files given the first set of containers */ private void getLikelyFiles(IPath path, List<IFile> ret, IResource[] resources) throws CoreException { String strPath = path.removeFileExtension().lastSegment().toLowerCase(); //this will return something as 'foo' for (IResource resource : resources) { if (resource instanceof IFile) { IFile f = (IFile) resource; if (PythonPathHelper.isValidSourceFile(f)) { if (resource.getFullPath().removeFileExtension().lastSegment().toLowerCase().equals(strPath)) { ret.add((IFile) resource); } } } else if (resource instanceof IContainer) { getLikelyFiles(path, ret, ((IContainer) resource).members()); } } } /** * Ask the user to select one file of the given list of files (if some is available) * * @param files the files available for selection. * @return the selected file (from the files passed) or null if there was no file available for * selection or if the user canceled it. */ private IFile selectWorkspaceFile(final IFile[] files) { if (files == null || files.length == 0) { return null; } if (files.length == 1) { return files[0]; } final List<IFile> selected = new ArrayList<IFile>(); Runnable r = new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); ElementListSelectionDialog dialog = new ElementListSelectionDialog(shell, new PyFileLabelProvider()); dialog.setElements(files); dialog.setTitle("Select Workspace File"); dialog.setMessage("File may be matched to multiple files in the workspace."); if (dialog.open() == Window.OK) { selected.add((IFile) dialog.getFirstResult()); } } }; if (Display.getCurrent() == null) { //not ui-thread Display.getDefault().syncExec(r); } else { r.run(); } if (selected.size() > 0) { return selected.get(0); } return null; } private static class GetFiles { /** * This method is a workaround for w.getRoot().getFileForLocation(path); which does not work consistently because * it filters out files which should not be filtered (i.e.: if a project is not in the workspace but imported). * * Also, it can fail to get resources in linked folders in the pythonpath. * * @param project is optional (may be null): if given we'll search in it dependencies first. */ private static IFile getFileForLocation(IPath location, IProject project) { boolean stopOnFirst = true; IFile[] filesForLocation = getFilesForLocation(location, project, stopOnFirst); if (filesForLocation != null && filesForLocation.length > 0) { return filesForLocation[0]; } return null; } /** * This method is a workaround for w.getRoot().getFilesForLocation(path); which does not work consistently because * it filters out files which should not be filtered (i.e.: if a project is not in the workspace but imported). * * Also, it can fail to get resources in linked folders in the pythonpath. * * @param project is optional (may be null): if given we'll search in it dependencies first. */ private static IFile[] getFilesForLocation(IPath location, IProject project, boolean stopOnFirst) { ArrayList<IFile> lst = new ArrayList<>(); HashSet<IProject> checked = new HashSet<>(); IWorkspace w = ResourcesPlugin.getWorkspace(); if (project != null) { checked.add(project); IFile f = getFileInProject(location, project); if (f != null) { if (stopOnFirst) { return new IFile[] { f }; } else { lst.add(f); } } try { IProject[] referencedProjects = project.getDescription().getReferencedProjects(); for (int i = 0; i < referencedProjects.length; i++) { IProject p = referencedProjects[i]; checked.add(p); f = getFileInProject(location, p); if (f != null) { if (stopOnFirst) { return new IFile[] { f }; } else { lst.add(f); } } } } catch (CoreException e) { Log.log(e); } } IProject[] projects = w.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); for (int i = 0; i < projects.length; i++) { IProject p = projects[i]; if (checked.contains(p)) { continue; } checked.add(p); IFile f = getFileInProject(location, p); if (f != null) { if (stopOnFirst) { return new IFile[] { f }; } else { lst.add(f); } } } return lst.toArray(new IFile[lst.size()]); } /** * Gets an IFile inside a container given a path in the filesystem (resolves the full path of the container and * checks if the location given is under it). */ private static IFile getFileInContainer(IPath location, IContainer container) { IPath projectLocation = container.getLocation(); if (projectLocation.isPrefixOf(location)) { int segmentsToRemove = projectLocation.segmentCount(); IPath removingFirstSegments = location.removeFirstSegments(segmentsToRemove); if (removingFirstSegments.segmentCount() == 0) { //It's equal: as we want a file in the container, and the path to the file is equal to the //container, we have to return null (because it's equal to the container it cannot be a file). return null; } IFile file = container.getFile(removingFirstSegments); if (file.exists()) { return file; } } return null; } /** * Tries to get a file from a project. Considers source folders (which could be linked) or resources directly beneath * the project. * @param location this is the path location to be gotten. * @param project this is the project we're searching. * @return the file found or null if it was not found. */ private static IFile getFileInProject(IPath location, IProject project) { IFile file = getFileInContainer(location, project); if (file != null) { return file; } PythonNature nature = PythonNature.getPythonNature(project); if (nature != null) { IPythonPathNature pythonPathNature = nature.getPythonPathNature(); try { //Paths Set<IResource> projectSourcePathSet = pythonPathNature.getProjectSourcePathFolderSet(); for (IResource iResource : projectSourcePathSet) { if (iResource instanceof IContainer) { //I.e.: don't consider zip files IContainer iContainer = (IContainer) iResource; file = getFileInContainer(location, iContainer); if (file != null) { return file; } } } } catch (CoreException e) { Log.log(e); } } return null; } } private static class GetContainers { /** * This method is a workaround for w.getRoot().getContainerForLocation(path); which does not work consistently because * it filters out files which should not be filtered (i.e.: if a project is not in the workspace but imported). * * Also, it can fail to get resources in linked folders in the pythonpath. * * @param project is optional (may be null): if given we'll search in it dependencies first. */ private static IContainer getContainerForLocation(IPath location, IProject project) { boolean stopOnFirst = true; IContainer[] filesForLocation = getContainersForLocation(location, project, stopOnFirst); if (filesForLocation != null && filesForLocation.length > 0) { return filesForLocation[0]; } return null; } /** * This method is a workaround for w.getRoot().getContainersForLocation(path); which does not work consistently because * it filters out files which should not be filtered (i.e.: if a project is not in the workspace but imported). * * Also, it can fail to get resources in linked folders in the pythonpath. * * @param project is optional (may be null): if given we'll search in it dependencies first. */ private static IContainer[] getContainersForLocation(IPath location, IProject project, boolean stopOnFirst) { ArrayList<IContainer> lst = new ArrayList<>(); HashSet<IProject> checked = new HashSet<>(); IWorkspace w = ResourcesPlugin.getWorkspace(); if (project != null) { checked.add(project); IContainer f = getContainerInProject(location, project); if (f != null) { if (stopOnFirst) { return new IContainer[] { f }; } else { lst.add(f); } } try { IProject[] referencedProjects = project.getDescription().getReferencedProjects(); for (int i = 0; i < referencedProjects.length; i++) { IProject p = referencedProjects[i]; checked.add(p); f = getContainerInProject(location, p); if (f != null) { if (stopOnFirst) { return new IContainer[] { f }; } else { lst.add(f); } } } } catch (CoreException e) { Log.log(e); } } IProject[] projects = w.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); for (int i = 0; i < projects.length; i++) { IProject p = projects[i]; if (checked.contains(p)) { continue; } checked.add(p); IContainer f = getContainerInProject(location, p); if (f != null) { if (stopOnFirst) { return new IContainer[] { f }; } else { lst.add(f); } } } return lst.toArray(new IContainer[lst.size()]); } /** * Gets an IContainer inside a container given a path in the filesystem (resolves the full path of the container and * checks if the location given is under it). */ private static IContainer getContainerInContainer(IPath location, IContainer container) { IPath projectLocation = container.getLocation(); if (projectLocation.isPrefixOf(location)) { int segmentsToRemove = projectLocation.segmentCount(); IPath removeFirstSegments = location.removeFirstSegments(segmentsToRemove); if (removeFirstSegments.segmentCount() == 0) { return container; //I.e.: equal to container } IContainer file = container.getFolder(removeFirstSegments); if (file.exists()) { return file; } } return null; } /** * Tries to get a file from a project. Considers source folders (which could be linked) or resources directly beneath * the project. * @param location this is the path location to be gotten. * @param project this is the project we're searching. * @return the file found or null if it was not found. */ private static IContainer getContainerInProject(IPath location, IProject project) { IContainer file = getContainerInContainer(location, project); if (file != null) { return file; } PythonNature nature = PythonNature.getPythonNature(project); if (nature != null) { IPythonPathNature pythonPathNature = nature.getPythonPathNature(); try { //Paths Set<IResource> projectSourcePathSet = pythonPathNature.getProjectSourcePathFolderSet(); for (IResource iResource : projectSourcePathSet) { if (iResource instanceof IContainer) { //I.e.: don't consider zip files IContainer iContainer = (IContainer) iResource; file = getContainerInContainer(location, iContainer); if (file != null) { return file; } } } } catch (CoreException e) { Log.log(e); } } return null; } } }
PYDEV-314: NPE searching for file.
plugins/org.python.pydev/src/org/python/pydev/editorinput/PySourceLocatorBase.java
PYDEV-314: NPE searching for file.
<ide><path>lugins/org.python.pydev/src/org/python/pydev/editorinput/PySourceLocatorBase.java <ide> List<IFile> likelyFiles = getLikelyFiles(path, w); <ide> IFile iFile = selectWorkspaceFile(likelyFiles.toArray(new IFile[0])); <ide> if (iFile != null) { <del> PySourceLocatorPrefs.addPathTranslation(path, iFile.getLocation()); <del> return new FileEditorInput(iFile); <add> IPath location = iFile.getLocation(); <add> if (location != null) { <add> PySourceLocatorPrefs.addPathTranslation(path, location); <add> return new FileEditorInput(iFile); <add> } <ide> } <ide> <ide> //ok, ask the user for any file in the computer <ide> */ <ide> private static IFile getFileInContainer(IPath location, IContainer container) { <ide> IPath projectLocation = container.getLocation(); <del> if (projectLocation.isPrefixOf(location)) { <del> int segmentsToRemove = projectLocation.segmentCount(); <del> IPath removingFirstSegments = location.removeFirstSegments(segmentsToRemove); <del> if (removingFirstSegments.segmentCount() == 0) { <del> //It's equal: as we want a file in the container, and the path to the file is equal to the <del> //container, we have to return null (because it's equal to the container it cannot be a file). <del> return null; <del> } <del> IFile file = container.getFile(removingFirstSegments); <del> if (file.exists()) { <del> return file; <add> if (projectLocation != null) { <add> if (projectLocation.isPrefixOf(location)) { <add> int segmentsToRemove = projectLocation.segmentCount(); <add> IPath removingFirstSegments = location.removeFirstSegments(segmentsToRemove); <add> if (removingFirstSegments.segmentCount() == 0) { <add> //It's equal: as we want a file in the container, and the path to the file is equal to the <add> //container, we have to return null (because it's equal to the container it cannot be a file). <add> return null; <add> } <add> IFile file = container.getFile(removingFirstSegments); <add> if (file.exists()) { <add> return file; <add> } <add> } <add> } else { <add> if (container instanceof IProject) { <add> Log.logInfo("Info: Project: " + container + " has no associated location."); <ide> } <ide> } <ide> return null; <ide> */ <ide> private static IContainer getContainerInContainer(IPath location, IContainer container) { <ide> IPath projectLocation = container.getLocation(); <del> if (projectLocation.isPrefixOf(location)) { <add> if (projectLocation != null && projectLocation.isPrefixOf(location)) { <ide> int segmentsToRemove = projectLocation.segmentCount(); <ide> IPath removeFirstSegments = location.removeFirstSegments(segmentsToRemove); <ide> if (removeFirstSegments.segmentCount() == 0) {
Java
lgpl-2.1
3464c6081bdbcc7e00504d2a7e3a8fda32555ae0
0
viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer
/* * AEInputStream.java * * Created on December 26, 2005, 1:03 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package net.sf.jaer.eventio; import java.util.logging.Level; import net.sf.jaer.aemonitor.*; import net.sf.jaer.util.EngineeringFormat; import java.beans.PropertyChangeSupport; import java.io.*; import java.nio.*; import java.nio.channels.*; import java.util.*; import java.util.logging.Logger; /** * Class to stream in packets of events from binary input stream from a file recorded by AEViewer. *<p> *The file format is simple, it consists of an arbitrary number of timestamped AEs: *<pre> * int32 address *int32 timestamp * * int32 address *int32 timestamp *</pre> <p> (Prior to version 2.0 data files, the address was a 16 bit short value.) <p> An optional ASCII header consisting of lines starting with '#' is skipped when opening the file and may be retrieved. No later comment lines are allowed because the rest ot the file must be pure binary data. * <p> * The first line of the header specifies the file format (for later versions). Files lacking a header * are assumed to be of int16 address form. * <p> * The first line of the header has a value like "#!AER-DAT2.0". The 2.0 is the version number. <p> * <strong>PropertyChangeEvents.</strong> AEFileInputStream has PropertyChangeSupport via getSupport(). PropertyChangeListeners will be informed of the following events <ul> <li> "position" - on any new packet of events, either by time chunk or fixed number of events chunk. <li> "rewind" - on file rewind. <li> "eof" - on end of file. <li> "wrappedTime" - on wrap of time timestamps. This happens every int32 us, which is about 4295 seconds which is 71 minutes. Time is negative, then positive, then negative again. <li> "init" - on initial read of a file (after creating this with a file input stream). This init event is called on the initial packet read because listeners can't be added until the object is created. * <li> "markset" - on setting mark, old and new mark positions. * <li> "markcleared" - on clearing mark, old mark position and zero. </ul> * <strong>Timestamp resets.</strong> AEFileInputStream also supports a special "zero timestamps" operation on reading a file. A bit mask which is normally * zero can be set; if set to a non zero value, then if ORing the bitmask with the raw address results in a nonzero value, then * the timestamps are reset to zero at this point. (A timestamp offset is memorized and subtracted from subsequent timestamps read * from the file.) This allow synchronization using, e.g. bit 15 of the address space. * * @author tobi * @see net.sf.jaer.eventio.AEDataFile */ public class AEFileInputStream extends DataInputStream implements AEFileInputStreamInterface{ // TODO extend AEInputStream // public final static long MAX_FILE_SIZE=200000000; private static final int NUMBER_LINE_SEPARATORS = 2; // number of line separators which AEFileOutputStream // (writeHeaderLine) is writing to ae data files. // important for calculation of header offset private PropertyChangeSupport support = new PropertyChangeSupport(this); static Logger log = Logger.getLogger("net.sf.jaer.eventio"); private FileInputStream fileInputStream = null; long fileSize = 0; // size of file in bytes private File file = null; private Class addressType = Short.TYPE; // default address type, unless file header specifies otherwise public final int MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT = 1000; private int numNonMonotonicTimeExceptionsPrinted = 0; private int markPosition = 0; // a single MARK position for rewinding to private int markOutPosition = 0, markInPosition = 0; // positions for editing (not yet implemented TODO) // private int markInPosition = 0, markOutPosition = 0; // points to mark IN and OUT positions for editing private int eventSizeBytes = AEFileInputStream.EVENT16_SIZE; // size of event in bytes, set finally after reading file header private boolean firstReadCompleted = false; private long absoluteStartingTimeMs = 0; // parsed from filename if possible private boolean enableTimeWrappingExceptionsChecking = true; // private int numEvents,currentEventNumber; // mostRecentTimestamp is the last event sucessfully read // firstTimestamp, lastTimestamp are the first and last timestamps in the file (at least the memory mapped part of the file) private int mostRecentTimestamp, firstTimestamp, lastTimestamp; // this marks the present read time for packets private int currentStartTimestamp; FileChannel fileChannel = null; public static final int MAX_BUFFER_SIZE_EVENTS = 100000; /** With new 32bits addresses, use EVENT32_SIZE, but use EVENT16_SIZE for backward compatibility with 16 bit addresses */ public static final int EVENT16_SIZE = Short.SIZE / 8 + Integer.SIZE / 8; /** (new style) int addr, int timestamp */ public static final int EVENT32_SIZE = Integer.SIZE / 8 + Integer.SIZE / 8; /** the size of the memory mapped part of the input file. This window is centered over the file position except at the start and end of the file. */ private int CHUNK_SIZE_EVENTS = 10000000; private int chunkSizeBytes = CHUNK_SIZE_EVENTS * EVENT16_SIZE; // size of memory mapped file chunk, depends on event size and number of events to map, initialized as though we didn't have a file header // the packet used for reading events private AEPacketRaw packet = new AEPacketRaw(MAX_BUFFER_SIZE_EVENTS); EventRaw tmpEvent = new EventRaw(); MappedByteBuffer byteBuffer = null; private int position = 0; // absolute position in file in events, points to next event number, 0 based (1 means 2nd event) protected ArrayList<String> header = new ArrayList<String>(); private int headerOffset = 0; // this is starting position in file for rewind or to add to positioning via slider private int chunkNumber = 0; // current memory mapped file chunk, starts with 0 past header private long numChunks = 1; // set by parseFileFormatVersion, this is at least 1 and includes the last portion which may be smaller than chunkSizeBytes private final String lineSeparator = System.getProperty("line.separator"); private int timestampResetBitmask=0; // used to memorize timestamp offset. private int timestampOffset=0; // set by nonzero bitmask result on address to that events timestamp, subtracted from all timestamps /** Creates a new instance of AEInputStream @deprecated use the constructor with a File object so that users of this can more easily get file information */ public AEFileInputStream (FileInputStream in) throws IOException{ super(in); init(in); } /** Creates a new instance of AEInputStream @param f the file to open @throws FileNotFoundException if file doesn't exist or can't be read */ public AEFileInputStream (File f) throws IOException{ this(new FileInputStream(f)); setFile(f); } public String toString (){ EngineeringFormat fmt = new EngineeringFormat(); String s = "AEInputStream with size=" + fmt.format(size()) + " events, firstTimestamp=" + getFirstTimestamp() + " lastTimestamp=" + getLastTimestamp() + " duration=" + fmt.format(getDurationUs() / 1e6f) + " s" + " event rate=" + fmt.format(size() / ( getDurationUs() / 1e6f )) + " eps"; return s; } /** fires property change "position". * @throws IOException if file is empty or there is some other error. */ private void init (FileInputStream fileInputStream) throws IOException{ this.fileInputStream = fileInputStream; // System.gc(); readHeader(fileInputStream); // parses header, sets eventSize, chunkSize, throws 0-size IOException mostRecentTimestamp = 0; currentStartTimestamp = 0; // make sure these are initialized correctly so that an event is always read when file is opened setupChunks(); // long totalMemory=Runtime.getRuntime().totalMemory(); // long maxMemory=Runtime.getRuntime().maxMemory(); // long maxSize=3*(maxMemory-totalMemory)/4; // EngineeringFormat fmt=new EngineeringFormat(); // log.info("AEInputStream.init(): trying to open file using memory mapped file of size="+fmt.format(fileSize)+" using memory-limited max size="+fmt.format(maxSize)); // do{ // try{ // fileChannel.position(0); // long size=fileChannel.size(); // if(size>maxSize){ // log.warning("opening file using byteBuffer with size="+maxSize+" but file size="+size); // size=maxSize; // } // byteBuffer=fileChannel.map(FileChannel.MapMode.READ_ONLY,0,size); // openok=true; // }catch(IOException e){ // System.gc(); // long newMaxSize=3*maxSize/4; // log.warning("AEInputStream.init(): cannot open file "+fileInputStream+" with maxSize="+maxSize+" trying again with size="+newMaxSize); // maxSize=newMaxSize; // } // }while(openok==false && maxSize>20000000); // if(!openok){ // throw new RuntimeException("cannot open preview, not enough memory"); // } try{ EventRaw ev = readEventForwards(); // init timestamp firstTimestamp = ev.timestamp; position((int)( size() - 1 )); ev = readEventForwards(); lastTimestamp = ev.timestamp; position(0); currentStartTimestamp = firstTimestamp; mostRecentTimestamp = firstTimestamp; } catch ( IOException e ){ log.warning("couldn't read first event to set starting timestamp - maybe the file is empty?"); } catch ( NonMonotonicTimeException e2 ){ log.warning("On AEInputStream.init() caught "+e2.toString()); } log.info("initialized " + this.toString()); } /** Reads the next event from the stream setting no limit on how far ahead in time it is. * * @return the event. * @throws IOException on reading the file. * @throws net.sf.jaer.eventio.AEFileInputStream.NonMonotonicTimeException if the timestamp is earlier than the one last read. */ private EventRaw readEventForwards() throws IOException, NonMonotonicTimeException{ return readEventForwards(Integer.MAX_VALUE); } /** reads the next event forward, sets mostRecentTimestamp, returns null if the next timestamp is later than maxTimestamp. * @param maxTimestamp the latest timestamp that should be read. @throws EOFException at end of file * @throws NonMonotonicTimeException * @throws WrappedTimeException */ private EventRaw readEventForwards (int maxTimestamp) throws IOException,NonMonotonicTimeException{ int ts = -1; int addr = 0; int lastTs=mostRecentTimestamp; try{ // eventByteBuffer.rewind(); // fileChannel.read(eventByteBuffer); // eventByteBuffer.rewind(); // addr=eventByteBuffer.getShort(); // ts=eventByteBuffer.getInt(); if ( addressType == Integer.TYPE ){ addr = byteBuffer.getInt(); } else{ addr = (byteBuffer.getShort()&0xffff); // TODO reads addr as negative number if msb is set } ts = byteBuffer.getInt(); // log.info("position="+position+" ts="+ts) ; // if(ts==0){ // System.out.println("zero timestamp"); // } // for marking sync in a recording using the result of bitmask with input if ( ( addr & timestampResetBitmask ) != 0 ){ log.log(Level.INFO,"found timestamp reset event addr={0} position={1} timstamp={2}",new Object[ ]{ addr,position,ts }); timestampOffset=ts; } ts-=timestampOffset; // TODO fix extra event no matter what dt if (ts > maxTimestamp) { // push back event position(position()-1); // we haven't updated our position field yet ts=lastTs; // this is the one last read successfully mostRecentTimestamp=ts; return null; } // check for non-monotonic increasing timestamps, if we get one, reset our notion of the starting time if ( isWrappedTime(ts,mostRecentTimestamp,1) ){ throw new WrappedTimeException(ts,mostRecentTimestamp,position); } if ( enableTimeWrappingExceptionsChecking && ts < mostRecentTimestamp ){ // log.warning("AEInputStream.readEventForwards returned ts="+ts+" which goes backwards in time (mostRecentTimestamp="+mostRecentTimestamp+")"); throw new NonMonotonicTimeException(ts,mostRecentTimestamp,position); } tmpEvent.address = addr; tmpEvent.timestamp = ts; position++; return tmpEvent; } catch ( BufferUnderflowException e ){ try{ mapNextChunk(); return readEventForwards(maxTimestamp); } catch ( IOException eof ){ byteBuffer = null; System.gc(); // all the byteBuffers have referred to mapped files and use up all memory, now free them since we're at end of file anyhow getSupport().firePropertyChange(AEInputStream.EVENT_EOF,position(),position()); throw new EOFException("reached end of file"); } } catch ( NullPointerException npe ){ rewind(); return readEventForwards(maxTimestamp); } finally{ mostRecentTimestamp = ts; } } /** Reads the next event backwards and leaves the position and byte buffer pointing to event one earlier than the one we just read. I.e., we back up, read the event, then back up again to leave us in state to either read forwards the event we just read, or to repeat backing up and reading if we read backwards */ private EventRaw readEventBackwards () throws IOException,NonMonotonicTimeException{ // we enter this with position pointing to next event *to read forwards* and byteBuffer also in this state. // therefore we need to decrement the byteBuffer pointer and the position, and read the event. // update the position first to leave us afterwards pointing one before current position int newPos = position - 1; // this is new absolute position if ( newPos < 0 ){ // reached start of file newPos = 0; // System.out.println("readEventBackwards: reached start"); throw new EOFException("reached start of file"); } // normally we just update the postiion to be one less, then move the byteBuffer pointer back by // one event and read that new event. But if we have reached start of byte buffer, we // need to load a new chunk and set the buffer pointer to point to one event before the end int newBufPos; newBufPos = byteBuffer.position() - eventSizeBytes; if ( newBufPos < 0 ){ // check if we need to map a new earlier chunk of the file int newChunkNumber = getChunkNumber(newPos); if ( newChunkNumber != chunkNumber ){ mapPreviousChunk(); // will throw EOFException when reaches start of file newBufPos = ( eventSizeBytes * newPos ) % chunkSizeBytes; byteBuffer.position(newBufPos); // put the buffer pointer at the end of the buffer } } else{ // this is usual situation byteBuffer.position(newBufPos); } // short addr=byteBuffer.getShort(); int addr; // with new 32bits adressses, use getInt, but use getShort for backward compatibility with 16bits if ( addressType == Integer.TYPE ){ addr = byteBuffer.getInt(); } else{ addr = (byteBuffer.getShort()&0xffff); // TODO reads addr as negative number if msb is set if we don't AND with 0xFFFF } int ts = byteBuffer.getInt()-timestampOffset; byteBuffer.position(newBufPos); tmpEvent.address = addr; tmpEvent.timestamp = ts; mostRecentTimestamp = ts; position--; // decrement position before exception to make sure we skip over a bad timestamp if ( enableTimeWrappingExceptionsChecking && isWrappedTime(ts,mostRecentTimestamp,-1) ){ throw new WrappedTimeException(ts,mostRecentTimestamp,position); } if ( enableTimeWrappingExceptionsChecking && ts > mostRecentTimestamp ){ throw new NonMonotonicTimeException(ts,mostRecentTimestamp,position); } return tmpEvent; } /** Uesd to read fixed size packets either forwards or backwards. * Behavior in case of non-monotonic timestamps depends on setting of tim wrapping exception checking. * If exception checking is enabled, then the read will terminate on the first non-monotonic timestamp. @param n the number of events to read @return a raw packet of events of a specfied number of events fires a property change "position" on every call, and a property change "wrappedTime" if time wraps around. */ @Override synchronized public AEPacketRaw readPacketByNumber (int n) throws IOException{ if ( !firstReadCompleted ){ fireInitPropertyChange(); } int an = (int)Math.abs(n); if ( an > MAX_BUFFER_SIZE_EVENTS ){ an = MAX_BUFFER_SIZE_EVENTS; if ( n > 0 ){ n = MAX_BUFFER_SIZE_EVENTS; } else{ n = -MAX_BUFFER_SIZE_EVENTS; } } int[] addr = packet.getAddresses(); int[] ts = packet.getTimestamps(); int oldPosition = position(); EventRaw ev; int count = 0; try{ if ( n > 0 ){ for ( int i = 0 ; i < n ; i++ ){ ev = readEventForwards(); count++; addr[i] = ev.address; ts[i] = ev.timestamp; } } else{ // backwards n = -n; for ( int i = 0 ; i < n ; i++ ){ ev = readEventBackwards(); count++; addr[i] = ev.address; ts[i] = ev.timestamp; } } } catch ( WrappedTimeException e ){ log.warning(e.toString()); getSupport().firePropertyChange(AEInputStream.EVENT_WRAPPED_TIME,e.getPreviousTimestamp(),e.getCurrentTimestamp()); } catch ( NonMonotonicTimeException e ){ getSupport().firePropertyChange(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP,e.getPreviousTimestamp(),e.getCurrentTimestamp()); // log.info(e.getMessage()); } packet.setNumEvents(count); getSupport().firePropertyChange(AEInputStream.EVENT_POSITION,oldPosition,position()); return packet; // return new AEPacketRaw(addr,ts); } /** returns an AEPacketRaw at least dt long up to the max size of the buffer or until end-of-file. *Events are read as long as the timestamp until (and including) the event whose timestamp is greater (for dt>0) than * startTimestamp+dt, where startTimestamp is the currentStartTimestamp. currentStartTimestamp is incremented after the call by dt. *Fires a property change "position" on each call. Fires property change "wrappedTime" when time wraps from positive to negative or vice versa (when playing backwards). * <p> *Non-monotonic timestamps cause warning messages to be printed (up to MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT) and packet * reading is aborted when the non-monotonic timestamp is encountered. Normally this does not cause problems except that the packet * is shorter in duration that called for. But when synchronized playback is enabled it causes the different threads to desynchronize. * Therefore the data files should not contain non-monotonic timestamps when synchronized playback is desired. * *@param dt the timestamp different in units of the timestamp (usually us) *@see #MAX_BUFFER_SIZE_EVENTS */ @Override synchronized public AEPacketRaw readPacketByTime (int dt) throws IOException{ if ( !firstReadCompleted ){ fireInitPropertyChange(); } int endTimestamp = currentStartTimestamp + dt; // check to see if this read will wrap the int32 timestamp around e.g. from >0 to <0 for dt>0 boolean bigWrap = isWrappedTime(endTimestamp,currentStartTimestamp,dt); // if( (dt>0 && mostRecentTimestamp>endTimestamp ) || (dt<0 && mostRecentTimestamp<endTimestamp)){ // boolean lt1=endTimestamp<0, lt2=mostRecentTimestamp<0; // boolean changedSign= ( (lt1 && !lt2) || (!lt1 && lt2) ); // if( !changedSign ){ currentStartTimestamp=endTimestamp; // log.info(this+" returning empty packet because mostRecentTimestamp="+mostRecentTimestamp+" is already later than endTimestamp="+endTimestamp); // return new AEPacketRaw(0); // } // } int startTimestamp = mostRecentTimestamp; int[] addr = packet.getAddresses(); int[] ts = packet.getTimestamps(); int oldPosition = position(); EventRaw ae; int i = 0; // System.out.println("endTimestamp-startTimestamp="+(endTimestamp-startTimestamp)+" mostRecentTimestamp="+mostRecentTimestamp+" startTimestamp="+startTimestamp); try{ if ( dt > 0 ){ // read forwards if ( !bigWrap ){ // normal situation do{ ae = readEventForwards(endTimestamp);// TODO always reads an event even if it occurs after time slice if (ae == null) { break; } addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ( mostRecentTimestamp < endTimestamp && i < addr.length && mostRecentTimestamp >= startTimestamp ); // if time jumps backwards (e.g. timestamp reset during recording) then will read a huge number of events. } else{ // read should wrap around // System.out.println("bigwrap started"); do{ ae = readEventForwards(endTimestamp); if(ae==null) break; addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ( mostRecentTimestamp > 0 && i < addr.length ); // read to where bigwrap occurs, then terminate - but wrapped time exception will happen first // never gets here because of wrap exception // System.out.println("reading one more event after bigwrap"); // ae = readEventForwards(); // addr[i] = ae.address; // ts[i] = ae.timestamp; // i++; } } else{ // read backwards if ( !bigWrap ){ do{ ae = readEventBackwards(); addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ( mostRecentTimestamp > endTimestamp && i < addr.length && mostRecentTimestamp <= startTimestamp ); } else{ do{ ae = readEventBackwards(); addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ( mostRecentTimestamp < 0 && i < addr.length - 1 ); ae = readEventBackwards(); addr[i] = ae.address; ts[i] = ae.timestamp; i++; } } } catch ( WrappedTimeException w ){ log.warning(w.toString()); currentStartTimestamp = w.getCurrentTimestamp(); mostRecentTimestamp = w.getCurrentTimestamp(); getSupport().firePropertyChange(AEInputStream.EVENT_WRAPPED_TIME,w.getPreviousTimestamp(),w.getCurrentTimestamp()); } catch ( NonMonotonicTimeException e ){ // e.printStackTrace(); if ( numNonMonotonicTimeExceptionsPrinted++ < MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT ){ log.log(Level.INFO,"{0} resetting currentStartTimestamp from {1} to {2} and setting mostRecentTimestamp to same value",new Object[ ]{ e,currentStartTimestamp,e.getCurrentTimestamp() }); if ( numNonMonotonicTimeExceptionsPrinted == MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT ){ log.warning("suppressing further warnings about NonMonotonicTimeException"); } } currentStartTimestamp = e.getCurrentTimestamp(); mostRecentTimestamp = e.getCurrentTimestamp(); getSupport().firePropertyChange(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP,lastTimestamp, mostRecentTimestamp); } finally{ // currentStartTimestamp = mostRecentTimestamp; } packet.setNumEvents(i); if(i<1){ log.info(packet.toString()); } getSupport().firePropertyChange(AEInputStream.EVENT_POSITION,oldPosition,position()); // System.out.println("bigwrap="+bigWrap+" read "+packet.getNumEvents()+" mostRecentTimestamp="+mostRecentTimestamp+" currentStartTimestamp="+currentStartTimestamp); return packet; } /** rewind to the start, or to the marked position, if it has been set. Fires a property change "position" followed by "rewind". */ synchronized public void rewind () throws IOException{ int oldPosition = position(); position(markPosition); try{ if ( markPosition == 0 ){ mostRecentTimestamp = firstTimestamp; // skipHeader(); } else{ readEventForwards(); // to set the mostRecentTimestamp } } catch ( NonMonotonicTimeException e ){ log.log(Level.INFO,"rewind from timestamp={0} to timestamp={1}",new Object[ ]{ e.getPreviousTimestamp(),e.getCurrentTimestamp() }); } currentStartTimestamp = mostRecentTimestamp; // System.out.println("AEInputStream.rewind(): set position="+byteBuffer.position()+" mostRecentTimestamp="+mostRecentTimestamp); getSupport().firePropertyChange(AEInputStream.EVENT_POSITION,oldPosition,position()); getSupport().firePropertyChange(AEInputStream.EVENT_REWIND,oldPosition,position()); } /** gets the size of the stream in events @return size in events */ @Override public long size (){ return ( fileSize - headerOffset ) / eventSizeBytes; } /** set position in events from start of file @param event the number of the event, starting with 0 */ @Override synchronized public void position (int event){ // if(event==size()) event=event-1; int newChunkNumber; try{ if ( ( newChunkNumber = getChunkNumber(event) ) != chunkNumber ){ mapChunk(newChunkNumber); } byteBuffer.position(( event * eventSizeBytes ) % chunkSizeBytes); position = event; } catch ( IOException e ){ log.log(Level.WARNING,"caught {0}",e); e.printStackTrace(); } catch ( IllegalArgumentException e2 ){ log.warning("caught " + e2); e2.printStackTrace(); } } /** gets the current position (in events) for reading forwards, i.e., readEventForwards will read this event number. @return position in events. */ @Override synchronized public int position (){ return this.position; } /**Returns the position as a fraction of the total number of events @return fractional position in total events*/ @Override synchronized public float getFractionalPosition (){ return (float)position() / size(); } /** Sets fractional position in events * @param frac 0-1 float range, 0 at start, 1 at end */ @Override synchronized public void setFractionalPosition (float frac){ position((int)( frac * size() )); try{ readEventForwards(); } catch ( Exception e ){ // e.printStackTrace(); } } /** AEFileInputStream has PropertyChangeSupport. This support fires events on certain events such as "rewind". */ public PropertyChangeSupport getSupport (){ return support; } /** mark the current position. * @throws IOException if there is some error in reading the data */ @Override synchronized public void mark () throws IOException{ int old=markPosition; markPosition = position(); markPosition = ( markPosition / eventSizeBytes ) * eventSizeBytes; // to avoid marking inside an event getSupport().firePropertyChange(AEInputStream.EVENT_MARKSET,old,markPosition); // System.out.println("AEInputStream.mark() marked position "+markPosition); } /** mark the current position as the IN point for editing. * @throws IOException if there is some error in reading the data */ synchronized public void markIn () throws IOException{ markInPosition = position(); markInPosition = ( markPosition / eventSizeBytes ) * eventSizeBytes; // to avoid marking inside an event } /** mark the current position as the OUT position for editing. * @throws IOException if there is some error in reading the data */ synchronized public void markOut () throws IOException{ markOutPosition = position(); markOutPosition = ( markPosition / eventSizeBytes ) * eventSizeBytes; // to avoid marking inside an event } /** clear any marked position */ @Override synchronized public void unmark (){ int old=markPosition; markPosition = 0; getSupport().firePropertyChange(AEInputStream.EVENT_MARKCLEARED,old,markPosition); } /** Returns true if mark has been set to nonzero position. * * @return true if set. */ public boolean isMarkSet(){ return markPosition!=0; } @Override public void close () throws IOException{ super.close(); fileChannel.close(); System.gc(); System.runFinalization(); // try to free memory mapped file buffers so file can be deleted.... } /** returns the first timestamp in the stream @return the timestamp */ public int getFirstTimestamp (){ return firstTimestamp; } /** @return last timestamp in file */ public int getLastTimestamp (){ return lastTimestamp; } /** @return the duration of the file in us. <p> * Assumes data file is timestamped in us. This method fails to provide a sensible value if the timestamp wwaps. */ public int getDurationUs (){ return lastTimestamp - firstTimestamp; } /** @return the present value of the startTimestamp for reading data */ synchronized public int getCurrentStartTimestamp (){ return currentStartTimestamp; } public void setCurrentStartTimestamp (int currentStartTimestamp){ this.currentStartTimestamp = currentStartTimestamp; } /** @return returns the most recent timestamp */ public int getMostRecentTimestamp (){ return mostRecentTimestamp; } public void setMostRecentTimestamp (int mostRecentTimestamp){ this.mostRecentTimestamp = mostRecentTimestamp; } /** class used to signal a backwards read from input stream */ public class NonMonotonicTimeException extends Exception{ protected int timestamp, lastTimestamp, position; public NonMonotonicTimeException (){ super(); } public NonMonotonicTimeException (String s){ super(s); } public NonMonotonicTimeException (int ts){ this.timestamp = ts; } /** Constructs a new NonMonotonicTimeException * * @param readTs the timestamp just read * @param lastTs the previous timestamp */ public NonMonotonicTimeException (int readTs,int lastTs){ this.timestamp = readTs; this.lastTimestamp = lastTs; } /** Constructs a new NonMonotonicTimeException * * @param readTs the timestamp just read * @param lastTs the previous timestamp * @param position the current position in the stream */ public NonMonotonicTimeException (int readTs,int lastTs,int position){ this.timestamp = readTs; this.lastTimestamp = lastTs; this.position = position; } public int getCurrentTimestamp (){ return timestamp; } public int getPreviousTimestamp (){ return lastTimestamp; } @Override public String toString (){ return "NonMonotonicTimeException: position=" + position + " timestamp=" + timestamp + " lastTimestamp=" + lastTimestamp + " jumps backwards by " + ( timestamp - lastTimestamp ); } } /** Indicates that timestamp has wrapped around from most positive to most negative signed value. The de-facto timestamp tick is us and timestamps are represented as int32 in jAER. Therefore the largest possible positive timestamp is 2^31-1 ticks which equals 2147.4836 seconds (35.7914 minutes). This wraps to -2147 seconds. The actual total time can be computed taking account of these "big wraps" if the time is increased by 4294.9673 seconds on each WrappedTimeException (when reading file forwards). * @param readTs the current (just read) timestamp * @param lastTs the previous timestamp */ public class WrappedTimeException extends NonMonotonicTimeException{ public WrappedTimeException (int readTs,int lastTs){ super(readTs,lastTs); } public WrappedTimeException (int readTs,int lastTs,int position){ super(readTs,lastTs,position); } @Override public String toString (){ return "WrappedTimeException: timestamp=" + timestamp + " lastTimestamp=" + lastTimestamp + " jumps backwards by " + ( timestamp - lastTimestamp ); } } // checks for wrap (if reading forwards, this timestamp <0 and previous timestamp >0) private boolean isWrappedTime (int read,int prevRead,int dt){ if ( dt > 0 && read <= 0 && prevRead > 0 ){ return true; } if ( dt < 0 && read >= 0 && prevRead < 0 ){ return true; } return false; } /** cuts out the part of the stream from IN to OUT and returns it as a new AEInputStream @return the new stream */ public AEFileInputStream cut (){ AEFileInputStream out = null; return out; } /** copies out the part of the stream from IN to OUT markers and returns it as a new AEInputStream @return the new stream */ public AEFileInputStream copy (){ AEFileInputStream out = null; return out; } /** pastes the in stream at the IN marker into this stream @param in the stream to paste */ public void paste (AEFileInputStream in){ } /** returns the chunk number which starts with 0. For position<CHUNK32_SIZE_BYTES returns 0 */ private int getChunkNumber (int position){ int chunk; chunk = (int)( ( position * eventSizeBytes ) / chunkSizeBytes ); return chunk; } private int positionFromChunk (int chunkNumber){ int pos = chunkNumber * chunkSizeBytes / eventSizeBytes; return pos; } private void mapNextChunk () throws IOException{ chunkNumber++; // increment the chunk number if ( chunkNumber >= numChunks ){ // if we try now to map a chunk past the last one then throw an EOF throw new EOFException("end of file; tried to map chunkNumber=" + chunkNumber + " but file only has numChunks=" + numChunks); } int start = getChunkStartPosition(chunkNumber); if ( start >= fileSize || start < 0 ){ chunkNumber = 0; // overflow will wrap<0 } mapChunk(chunkNumber); } private void mapPreviousChunk () throws IOException{ chunkNumber--; if ( chunkNumber < 0 ){ chunkNumber = 0; } int start = getChunkStartPosition(chunkNumber); if ( start >= fileSize || start < 0 ){ chunkNumber = 0; // overflow will wrap<0 } mapChunk(chunkNumber); } /** memory-maps a chunk of the input file. @param chunkNumber the number of the chunk, starting with 0 */ private void mapChunk (int chunkNumber) throws IOException{ this.chunkNumber = chunkNumber; int start = getChunkStartPosition(chunkNumber); if ( start >= fileSize ){ throw new EOFException("start of chunk=" + start + " but file has fileSize=" + fileSize); } int numBytesToMap = chunkSizeBytes; if ( start + numBytesToMap >= fileSize ){ numBytesToMap = (int)( fileSize - start ); } byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY,start,numBytesToMap); this.position = positionFromChunk(chunkNumber); // log.info("mapped chunk # "+chunkNumber+" of "+numChunks); } /** @return start of chunk in bytes @param chunk the chunk number */ private int getChunkStartPosition (int chunk){ if ( chunk <= 0 ){ return headerOffset; } return ( chunk * chunkSizeBytes ) + headerOffset; } private int getChunkEndPosition (int chunk){ return headerOffset + ( chunk + 1 ) * chunkSizeBytes; } /** skips the header lines (if any) */ protected void skipHeader () throws IOException{ position(headerOffset); } /** reads the header comment lines. Must have eventSize and chunkSizeBytes set for backwards compatiblity for files without headers to short address sizes. */ protected void readHeader (FileInputStream fileInputStream) throws IOException{ if ( fileInputStream == null ){ throw new IOException("null fileInputStream"); } if ( in.available() == 0 ){ throw new IOException("empty file (0 bytes available)"); } BufferedReader bufferedHeaderReader = new BufferedReader(new InputStreamReader(fileInputStream)); headerOffset = 0; // start from 0 if ( !bufferedHeaderReader.markSupported() ){ throw new IOException("no mark supported while reading file header, is this a normal file?"); } String s; // System.out.println("File header:"); while ( ( s = readHeaderLine(bufferedHeaderReader) ) != null ){ header.add(s); parseFileFormatVersion(s); } // we don't map yet until we know eventSize StringBuilder sb = new StringBuilder(); sb.append("File header:"); for ( String str:header ){ sb.append(str); sb.append(lineSeparator); // "\n"); } log.info(sb.toString()); bufferedHeaderReader = null; // mark for GC } /** parses the file format version given a string with the header comment character stripped off. @see net.sf.jaer.eventio.AEDataFile */ protected void parseFileFormatVersion (String s){ float version = 1f; if ( s.startsWith(AEDataFile.DATA_FILE_FORMAT_HEADER) ){ // # stripped off by readHeaderLine try{ version = Float.parseFloat(s.substring(AEDataFile.DATA_FILE_FORMAT_HEADER.length())); } catch ( NumberFormatException numberFormatException ){ log.warning("While parsing header line " + s + " got " + numberFormatException.toString()); } if ( version < 2 ){ addressType = Short.TYPE; eventSizeBytes = Integer.SIZE / 8 + Short.SIZE / 8; } else if ( version >= 2 ){ // this is hack to avoid parsing the AEDataFile. format number string... addressType = Integer.TYPE; eventSizeBytes = Integer.SIZE / 8 + Integer.SIZE / 8; } log.info("Data file version=" + version + " and has addressType=" + addressType); } } void setupChunks () throws IOException{ fileChannel = fileInputStream.getChannel(); fileSize = fileChannel.size(); chunkSizeBytes = eventSizeBytes * CHUNK_SIZE_EVENTS; numChunks = ( fileSize / chunkSizeBytes ) + 1; // used to limit chunkNumber to prevent overflow of position and for EOF log.info("fileSize=" + fileSize + " chunkSizeBytes=" + chunkSizeBytes + " numChunks=" + numChunks); mapChunk(0); } /** assumes we are positioned at start of line and that we may either * read a comment char '#' or something else leaves us after the line at start of next line or of raw data. * Assumes header lines are written using the AEOutputStream.writeHeaderLine(). @return header line */ private String readHeaderLine (BufferedReader reader) throws IOException{ // StringBuffer s = new StringBuffer(); // read header lines from fileInputStream, not byteBuffer, since we have not mapped file yet // reader.mark(1); // max header line length in chars int c = reader.read(); // read single char if ( c != AEDataFile.COMMENT_CHAR ){ // if it's not a comment char return null; // return a null header line } // reader.reset(); // reset to start of header/comment line // we don't push back comment char because we want to parse the file format sans this String s = reader.readLine(); for ( byte b:s.getBytes() ){ if ( b < 32 || b > 126 ){ log.warning("Non printable character (byte value=" + b + ") which is (<32 || >126) detected in header line, aborting header read and resetting to start of file because this file may not have a real header"); return null; } } headerOffset += s.length() + NUMBER_LINE_SEPARATORS + 1; // adds comment char and trailing CRLF newline, assumes CRLF EOL // TODO fix this assumption return s; } /** Gets the header strings from the file @return list of strings, one per line */ public ArrayList<String> getHeader (){ return header; } private void fireInitPropertyChange (){ getSupport().firePropertyChange(AEInputStream.EVENT_INIT,0,0); firstReadCompleted = true; } /** Returns the File that is being read, or null if the instance is constructed from a FileInputStream */ public File getFile (){ return file; } /** Sets the File reference but doesn't open the file */ public void setFile (File f){ this.file = f; absoluteStartingTimeMs = getAbsoluteStartingTimeMsFromFile(getFile()); } /** When the file is opened, the filename is parsed to try to extract the date and time the file was created from the filename. @return the time logging was started in ms since 1970 */ public long getAbsoluteStartingTimeMs (){ return absoluteStartingTimeMs; } public void setAbsoluteStartingTimeMs (long absoluteStartingTimeMs){ this.absoluteStartingTimeMs = absoluteStartingTimeMs; } /**Parses the filename to extract the file logging date from the name of the file. * * @return start of logging time in ms, i.e., in "java" time, since 1970 */ private long getAbsoluteStartingTimeMsFromFile (File f){ if ( f == null ){ return 0; } try{ String fn = f.getName(); String dateStr = fn.substring(fn.indexOf('-') + 1); // guess that datestamp is right after first - which follows Chip classname Date date = AEDataFile.DATE_FORMAT.parse(dateStr); return date.getTime(); } catch ( Exception e ){ log.warning(e.toString()); return 0; } } @Override public boolean isNonMonotonicTimeExceptionsChecked (){ return enableTimeWrappingExceptionsChecking; } @Override public void setNonMonotonicTimeExceptionsChecked (boolean yes){ enableTimeWrappingExceptionsChecking = yes; } /** * * Returns the bitmask that is OR'ed with raw addresses; if result is nonzero then a new timestamp offset is memorized and subtracted from * @return the timestampResetBitmask */ public int getTimestampResetBitmask (){ return timestampResetBitmask; } /** * Sets the bitmask that is OR'ed with raw addresses; if result is nonzero then a new timestamp offset is memorized and subtracted from * all subsequent timestamps. * * @param timestampResetBitmask the timestampResetBitmask to set */ public void setTimestampResetBitmask (int timestampResetBitmask){ this.timestampResetBitmask = timestampResetBitmask; } }
src/net/sf/jaer/eventio/AEFileInputStream.java
/* * AEInputStream.java * * Created on December 26, 2005, 1:03 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package net.sf.jaer.eventio; import java.util.logging.Level; import net.sf.jaer.aemonitor.*; import net.sf.jaer.util.EngineeringFormat; import java.beans.PropertyChangeSupport; import java.io.*; import java.nio.*; import java.nio.channels.*; import java.util.*; import java.util.logging.Logger; /** * Class to stream in packets of events from binary input stream from a file recorded by AEViewer. *<p> *The file format is simple, it consists of an arbitrary number of timestamped AEs: *<pre> * int32 address *int32 timestamp * * int32 address *int32 timestamp *</pre> <p> (Prior to version 2.0 data files, the address was a 16 bit short value.) <p> An optional ASCII header consisting of lines starting with '#' is skipped when opening the file and may be retrieved. No later comment lines are allowed because the rest ot the file must be pure binary data. * <p> * The first line of the header specifies the file format (for later versions). Files lacking a header * are assumed to be of int16 address form. * <p> * The first line of the header has a value like "#!AER-DAT2.0". The 2.0 is the version number. <p> * <strong>PropertyChangeEvents.</strong> AEFileInputStream has PropertyChangeSupport via getSupport(). PropertyChangeListeners will be informed of the following events <ul> <li> "position" - on any new packet of events, either by time chunk or fixed number of events chunk. <li> "rewind" - on file rewind. <li> "eof" - on end of file. <li> "wrappedTime" - on wrap of time timestamps. This happens every int32 us, which is about 4295 seconds which is 71 minutes. Time is negative, then positive, then negative again. <li> "init" - on initial read of a file (after creating this with a file input stream). This init event is called on the initial packet read because listeners can't be added until the object is created. * <li> "markset" - on setting mark, old and new mark positions. * <li> "markcleared" - on clearing mark, old mark position and zero. </ul> * <strong>Timestamp resets.</strong> AEFileInputStream also supports a special "zero timestamps" operation on reading a file. A bit mask which is normally * zero can be set; if set to a non zero value, then if ORing the bitmask with the raw address results in a nonzero value, then * the timestamps are reset to zero at this point. (A timestamp offset is memorized and subtracted from subsequent timestamps read * from the file.) This allow synchronization using, e.g. bit 15 of the address space. * * @author tobi * @see net.sf.jaer.eventio.AEDataFile */ public class AEFileInputStream extends DataInputStream implements AEFileInputStreamInterface{ // TODO extend AEInputStream // public final static long MAX_FILE_SIZE=200000000; private static final int NUMBER_LINE_SEPARATORS = 2; // number of line separators which AEFileOutputStream // (writeHeaderLine) is writing to ae data files. // important for calculation of header offset private PropertyChangeSupport support = new PropertyChangeSupport(this); static Logger log = Logger.getLogger("net.sf.jaer.eventio"); private FileInputStream fileInputStream = null; long fileSize = 0; // size of file in bytes private File file = null; private Class addressType = Short.TYPE; // default address type, unless file header specifies otherwise public final int MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT = 1000; private int numNonMonotonicTimeExceptionsPrinted = 0; private int markPosition = 0; // a single MARK position for rewinding to private int markOutPosition = 0, markInPosition = 0; // positions for editing (not yet implemented TODO) // private int markInPosition = 0, markOutPosition = 0; // points to mark IN and OUT positions for editing private int eventSizeBytes = AEFileInputStream.EVENT16_SIZE; // size of event in bytes, set finally after reading file header private boolean firstReadCompleted = false; private long absoluteStartingTimeMs = 0; // parsed from filename if possible private boolean enableTimeWrappingExceptionsChecking = true; // private int numEvents,currentEventNumber; // mostRecentTimestamp is the last event sucessfully read // firstTimestamp, lastTimestamp are the first and last timestamps in the file (at least the memory mapped part of the file) private int mostRecentTimestamp, firstTimestamp, lastTimestamp; // this marks the present read time for packets private int currentStartTimestamp; FileChannel fileChannel = null; public static final int MAX_BUFFER_SIZE_EVENTS = 100000; /** With new 32bits addresses, use EVENT32_SIZE, but use EVENT16_SIZE for backward compatibility with 16 bit addresses */ public static final int EVENT16_SIZE = Short.SIZE / 8 + Integer.SIZE / 8; /** (new style) int addr, int timestamp */ public static final int EVENT32_SIZE = Integer.SIZE / 8 + Integer.SIZE / 8; /** the size of the memory mapped part of the input file. This window is centered over the file position except at the start and end of the file. */ private int CHUNK_SIZE_EVENTS = 10000000; private int chunkSizeBytes = CHUNK_SIZE_EVENTS * EVENT16_SIZE; // size of memory mapped file chunk, depends on event size and number of events to map, initialized as though we didn't have a file header // the packet used for reading events private AEPacketRaw packet = new AEPacketRaw(MAX_BUFFER_SIZE_EVENTS); EventRaw tmpEvent = new EventRaw(); MappedByteBuffer byteBuffer = null; private int position = 0; // absolute position in file in events, points to next event number, 0 based (1 means 2nd event) protected ArrayList<String> header = new ArrayList<String>(); private int headerOffset = 0; // this is starting position in file for rewind or to add to positioning via slider private int chunkNumber = 0; // current memory mapped file chunk, starts with 0 past header private long numChunks = 1; // set by parseFileFormatVersion, this is at least 1 and includes the last portion which may be smaller than chunkSizeBytes private final String lineSeparator = System.getProperty("line.separator"); private int timestampResetBitmask=0; // used to memorize timestamp offset. private int timestampOffset=0; // set by nonzero bitmask result on address to that events timestamp, subtracted from all timestamps /** Creates a new instance of AEInputStream @deprecated use the constructor with a File object so that users of this can more easily get file information */ public AEFileInputStream (FileInputStream in) throws IOException{ super(in); init(in); } /** Creates a new instance of AEInputStream @param f the file to open @throws FileNotFoundException if file doesn't exist or can't be read */ public AEFileInputStream (File f) throws IOException{ this(new FileInputStream(f)); setFile(f); } public String toString (){ EngineeringFormat fmt = new EngineeringFormat(); String s = "AEInputStream with size=" + fmt.format(size()) + " events, firstTimestamp=" + getFirstTimestamp() + " lastTimestamp=" + getLastTimestamp() + " duration=" + fmt.format(getDurationUs() / 1e6f) + " s" + " event rate=" + fmt.format(size() / ( getDurationUs() / 1e6f )) + " eps"; return s; } /** fires property change "position". * @throws IOException if file is empty or there is some other error. */ private void init (FileInputStream fileInputStream) throws IOException{ this.fileInputStream = fileInputStream; // System.gc(); readHeader(fileInputStream); // parses header, sets eventSize, chunkSize, throws 0-size IOException mostRecentTimestamp = 0; currentStartTimestamp = 0; // make sure these are initialized correctly so that an event is always read when file is opened setupChunks(); // long totalMemory=Runtime.getRuntime().totalMemory(); // long maxMemory=Runtime.getRuntime().maxMemory(); // long maxSize=3*(maxMemory-totalMemory)/4; // EngineeringFormat fmt=new EngineeringFormat(); // log.info("AEInputStream.init(): trying to open file using memory mapped file of size="+fmt.format(fileSize)+" using memory-limited max size="+fmt.format(maxSize)); // do{ // try{ // fileChannel.position(0); // long size=fileChannel.size(); // if(size>maxSize){ // log.warning("opening file using byteBuffer with size="+maxSize+" but file size="+size); // size=maxSize; // } // byteBuffer=fileChannel.map(FileChannel.MapMode.READ_ONLY,0,size); // openok=true; // }catch(IOException e){ // System.gc(); // long newMaxSize=3*maxSize/4; // log.warning("AEInputStream.init(): cannot open file "+fileInputStream+" with maxSize="+maxSize+" trying again with size="+newMaxSize); // maxSize=newMaxSize; // } // }while(openok==false && maxSize>20000000); // if(!openok){ // throw new RuntimeException("cannot open preview, not enough memory"); // } try{ EventRaw ev = readEventForwards(); // init timestamp firstTimestamp = ev.timestamp; position((int)( size() - 1 )); ev = readEventForwards(); lastTimestamp = ev.timestamp; position(0); currentStartTimestamp = firstTimestamp; mostRecentTimestamp = firstTimestamp; } catch ( IOException e ){ log.warning("couldn't read first event to set starting timestamp"); } catch ( NonMonotonicTimeException e2 ){ log.warning("On AEInputStream.init() caught "+e2.toString()); } log.info("initialized " + this.toString()); } private EventRaw readEventForwards() throws IOException, NonMonotonicTimeException{ return readEventForwards(Integer.MAX_VALUE); } /** reads the next event forward, sets mostRecentTimestamp, returns null if the next timestamp is later than maxTimestamp. * @param maxTimestamp the latest timestamp that should be read. @throws EOFException at end of file * @throws NonMonotonicTimeException * @throws WrappedTimeException */ private EventRaw readEventForwards (int maxTimestamp) throws IOException,NonMonotonicTimeException{ int ts = -1; int addr = 0; int lastTs=mostRecentTimestamp; try{ // eventByteBuffer.rewind(); // fileChannel.read(eventByteBuffer); // eventByteBuffer.rewind(); // addr=eventByteBuffer.getShort(); // ts=eventByteBuffer.getInt(); if ( addressType == Integer.TYPE ){ addr = byteBuffer.getInt(); } else{ addr = (byteBuffer.getShort()&0xffff); // TODO reads addr as negative number if msb is set } ts = byteBuffer.getInt(); // log.info("position="+position+" ts="+ts) ; // if(ts==0){ // System.out.println("zero timestamp"); // } // for marking sync in a recording using the result of bitmask with input if ( ( addr & timestampResetBitmask ) != 0 ){ log.log(Level.INFO,"found timestamp reset event addr={0} position={1} timstamp={2}",new Object[ ]{ addr,position,ts }); timestampOffset=ts; } ts-=timestampOffset; // // TODO fix extra event no matter what dt // if (ts > maxTimestamp) { // // push back event // byteBuffer.position(position()-eventSizeBytes); // we haven't updated our position field yet // ts=lastTs; // this is the one last read successfully // mostRecentTimestamp=ts; // return null; // } // check for non-monotonic increasing timestamps, if we get one, reset our notion of the starting time if ( isWrappedTime(ts,mostRecentTimestamp,1) ){ throw new WrappedTimeException(ts,mostRecentTimestamp,position); } if ( enableTimeWrappingExceptionsChecking && ts < mostRecentTimestamp ){ // log.warning("AEInputStream.readEventForwards returned ts="+ts+" which goes backwards in time (mostRecentTimestamp="+mostRecentTimestamp+")"); throw new NonMonotonicTimeException(ts,mostRecentTimestamp,position); } tmpEvent.address = addr; tmpEvent.timestamp = ts; position++; return tmpEvent; } catch ( BufferUnderflowException e ){ try{ mapNextChunk(); return readEventForwards(maxTimestamp); } catch ( IOException eof ){ byteBuffer = null; System.gc(); // all the byteBuffers have referred to mapped files and use up all memory, now free them since we're at end of file anyhow getSupport().firePropertyChange(AEInputStream.EVENT_EOF,position(),position()); throw new EOFException("reached end of file"); } } catch ( NullPointerException npe ){ rewind(); return readEventForwards(maxTimestamp); } finally{ mostRecentTimestamp = ts; } } /** Reads the next event backwards and leaves the position and byte buffer pointing to event one earlier than the one we just read. I.e., we back up, read the event, then back up again to leave us in state to either read forwards the event we just read, or to repeat backing up and reading if we read backwards */ private EventRaw readEventBackwards () throws IOException,NonMonotonicTimeException{ // we enter this with position pointing to next event *to read forwards* and byteBuffer also in this state. // therefore we need to decrement the byteBuffer pointer and the position, and read the event. // update the position first to leave us afterwards pointing one before current position int newPos = position - 1; // this is new absolute position if ( newPos < 0 ){ // reached start of file newPos = 0; // System.out.println("readEventBackwards: reached start"); throw new EOFException("reached start of file"); } // normally we just update the postiion to be one less, then move the byteBuffer pointer back by // one event and read that new event. But if we have reached start of byte buffer, we // need to load a new chunk and set the buffer pointer to point to one event before the end int newBufPos; newBufPos = byteBuffer.position() - eventSizeBytes; if ( newBufPos < 0 ){ // check if we need to map a new earlier chunk of the file int newChunkNumber = getChunkNumber(newPos); if ( newChunkNumber != chunkNumber ){ mapPreviousChunk(); // will throw EOFException when reaches start of file newBufPos = ( eventSizeBytes * newPos ) % chunkSizeBytes; byteBuffer.position(newBufPos); // put the buffer pointer at the end of the buffer } } else{ // this is usual situation byteBuffer.position(newBufPos); } // short addr=byteBuffer.getShort(); int addr; // with new 32bits adressses, use getInt, but use getShort for backward compatibility with 16bits if ( addressType == Integer.TYPE ){ addr = byteBuffer.getInt(); } else{ addr = (byteBuffer.getShort()&0xffff); // TODO reads addr as negative number if msb is set if we don't AND with 0xFFFF } int ts = byteBuffer.getInt()-timestampOffset; byteBuffer.position(newBufPos); tmpEvent.address = addr; tmpEvent.timestamp = ts; mostRecentTimestamp = ts; position--; // decrement position before exception to make sure we skip over a bad timestamp if ( enableTimeWrappingExceptionsChecking && isWrappedTime(ts,mostRecentTimestamp,-1) ){ throw new WrappedTimeException(ts,mostRecentTimestamp,position); } if ( enableTimeWrappingExceptionsChecking && ts > mostRecentTimestamp ){ throw new NonMonotonicTimeException(ts,mostRecentTimestamp,position); } return tmpEvent; } /** Uesd to read fixed size packets either forwards or backwards. * Behavior in case of non-monotonic timestamps depends on setting of tim wrapping exception checking. * If exception checking is enabled, then the read will terminate on the first non-monotonic timestamp. @param n the number of events to read @return a raw packet of events of a specfied number of events fires a property change "position" on every call, and a property change "wrappedTime" if time wraps around. */ synchronized public AEPacketRaw readPacketByNumber (int n) throws IOException{ if ( !firstReadCompleted ){ fireInitPropertyChange(); } int an = (int)Math.abs(n); if ( an > MAX_BUFFER_SIZE_EVENTS ){ an = MAX_BUFFER_SIZE_EVENTS; if ( n > 0 ){ n = MAX_BUFFER_SIZE_EVENTS; } else{ n = -MAX_BUFFER_SIZE_EVENTS; } } int[] addr = packet.getAddresses(); int[] ts = packet.getTimestamps(); int oldPosition = position(); EventRaw ev; int count = 0; try{ if ( n > 0 ){ for ( int i = 0 ; i < n ; i++ ){ ev = readEventForwards(); count++; addr[i] = ev.address; ts[i] = ev.timestamp; } } else{ // backwards n = -n; for ( int i = 0 ; i < n ; i++ ){ ev = readEventBackwards(); count++; addr[i] = ev.address; ts[i] = ev.timestamp; } } } catch ( WrappedTimeException e ){ log.warning(e.toString()); getSupport().firePropertyChange(AEInputStream.EVENT_WRAPPED_TIME,e.getPreviousTimestamp(),e.getCurrentTimestamp()); } catch ( NonMonotonicTimeException e ){ getSupport().firePropertyChange(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP,e.getPreviousTimestamp(),e.getCurrentTimestamp()); // log.info(e.getMessage()); } packet.setNumEvents(count); getSupport().firePropertyChange(AEInputStream.EVENT_POSITION,oldPosition,position()); return packet; // return new AEPacketRaw(addr,ts); } /** returns an AEPacketRaw at least dt long up to the max size of the buffer or until end-of-file. *Events are read as long as the timestamp until (and including) the event whose timestamp is greater (for dt>0) than * startTimestamp+dt, where startTimestamp is the currentStartTimestamp. currentStartTimestamp is incremented after the call by dt. *Fires a property change "position" on each call. Fires property change "wrappedTime" when time wraps from positive to negative or vice versa (when playing backwards). * <p> *Non-monotonic timestamps cause warning messages to be printed (up to MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT) and packet * reading is aborted when the non-monotonic timestamp is encountered. Normally this does not cause problems except that the packet * is shorter in duration that called for. But when synchronized playback is enabled it causes the different threads to desynchronize. * Therefore the data files should not contain non-monotonic timestamps when synchronized playback is desired. * *@param dt the timestamp different in units of the timestamp (usually us) *@see #MAX_BUFFER_SIZE_EVENTS */ synchronized public AEPacketRaw readPacketByTime (int dt) throws IOException{ if ( !firstReadCompleted ){ fireInitPropertyChange(); } int endTimestamp = currentStartTimestamp + dt; // check to see if this read will wrap the int32 timestamp around e.g. from >0 to <0 for dt>0 boolean bigWrap = isWrappedTime(endTimestamp,currentStartTimestamp,dt); // if( (dt>0 && mostRecentTimestamp>endTimestamp ) || (dt<0 && mostRecentTimestamp<endTimestamp)){ // boolean lt1=endTimestamp<0, lt2=mostRecentTimestamp<0; // boolean changedSign= ( (lt1 && !lt2) || (!lt1 && lt2) ); // if( !changedSign ){ // currentStartTimestamp=endTimestamp; // log.info(this+" returning empty packet because mostRecentTimestamp="+mostRecentTimestamp+" is already later than endTimestamp="+endTimestamp); // return new AEPacketRaw(0); // } // } int startTimestamp = mostRecentTimestamp; int[] addr = packet.getAddresses(); int[] ts = packet.getTimestamps(); int oldPosition = position(); EventRaw ae; int i = 0; // System.out.println("endTimestamp-startTimestamp="+(endTimestamp-startTimestamp)+" mostRecentTimestamp="+mostRecentTimestamp+" startTimestamp="+startTimestamp); try{ if ( dt > 0 ){ // read forwards if ( !bigWrap ){ // normal situation do{ ae = readEventForwards(endTimestamp);// TODO always reads an event even if it occurs after time slice if (ae == null) { break; } addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ( mostRecentTimestamp < endTimestamp && i < addr.length && mostRecentTimestamp >= startTimestamp ); // if time jumps backwards (e.g. timestamp reset during recording) then will read a huge number of events. } else{ // read should wrap around // System.out.println("bigwrap started"); do{ ae = readEventForwards(endTimestamp); if(ae==null) break; addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ( mostRecentTimestamp > 0 && i < addr.length ); // read to where bigwrap occurs, then terminate - but wrapped time exception will happen first // never gets here because of wrap exception // System.out.println("reading one more event after bigwrap"); // ae = readEventForwards(); // addr[i] = ae.address; // ts[i] = ae.timestamp; // i++; } } else{ // read backwards if ( !bigWrap ){ do{ ae = readEventBackwards(); addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ( mostRecentTimestamp > endTimestamp && i < addr.length && mostRecentTimestamp <= startTimestamp ); } else{ do{ ae = readEventBackwards(); addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ( mostRecentTimestamp < 0 && i < addr.length - 1 ); ae = readEventBackwards(); addr[i] = ae.address; ts[i] = ae.timestamp; i++; } } } catch ( WrappedTimeException w ){ log.warning(w.toString()); currentStartTimestamp = w.getCurrentTimestamp(); mostRecentTimestamp = w.getCurrentTimestamp(); getSupport().firePropertyChange(AEInputStream.EVENT_WRAPPED_TIME,w.getPreviousTimestamp(),w.getCurrentTimestamp()); } catch ( NonMonotonicTimeException e ){ // e.printStackTrace(); if ( numNonMonotonicTimeExceptionsPrinted++ < MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT ){ log.log(Level.INFO,"{0} resetting currentStartTimestamp from {1} to {2} and setting mostRecentTimestamp to same value",new Object[ ]{ e,currentStartTimestamp,e.getCurrentTimestamp() }); if ( numNonMonotonicTimeExceptionsPrinted == MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT ){ log.warning("suppressing further warnings about NonMonotonicTimeException"); } } currentStartTimestamp = e.getCurrentTimestamp(); mostRecentTimestamp = e.getCurrentTimestamp(); getSupport().firePropertyChange(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP,lastTimestamp, mostRecentTimestamp); } finally{ currentStartTimestamp = mostRecentTimestamp; } packet.setNumEvents(i); // if(i<1){ // log.info(packet.toString()); // } getSupport().firePropertyChange(AEInputStream.EVENT_POSITION,oldPosition,position()); // System.out.println("bigwrap="+bigWrap+" read "+packet.getNumEvents()+" mostRecentTimestamp="+mostRecentTimestamp+" currentStartTimestamp="+currentStartTimestamp); return packet; } /** rewind to the start, or to the marked position, if it has been set. Fires a property change "position" followed by "rewind". */ synchronized public void rewind () throws IOException{ int oldPosition = position(); position(markPosition); try{ if ( markPosition == 0 ){ mostRecentTimestamp = firstTimestamp; // skipHeader(); } else{ readEventForwards(); // to set the mostRecentTimestamp } } catch ( NonMonotonicTimeException e ){ log.log(Level.INFO,"rewind from timestamp={0} to timestamp={1}",new Object[ ]{ e.getPreviousTimestamp(),e.getCurrentTimestamp() }); } currentStartTimestamp = mostRecentTimestamp; // System.out.println("AEInputStream.rewind(): set position="+byteBuffer.position()+" mostRecentTimestamp="+mostRecentTimestamp); getSupport().firePropertyChange(AEInputStream.EVENT_POSITION,oldPosition,position()); getSupport().firePropertyChange(AEInputStream.EVENT_REWIND,oldPosition,position()); } /** gets the size of the stream in events @return size in events */ public long size (){ return ( fileSize - headerOffset ) / eventSizeBytes; } /** set position in events from start of file @param event the number of the event, starting with 0 */ synchronized public void position (int event){ // if(event==size()) event=event-1; int newChunkNumber; try{ if ( ( newChunkNumber = getChunkNumber(event) ) != chunkNumber ){ mapChunk(newChunkNumber); } byteBuffer.position(( event * eventSizeBytes ) % chunkSizeBytes); position = event; } catch ( IOException e ){ log.log(Level.WARNING,"caught {0}",e); e.printStackTrace(); } catch ( IllegalArgumentException e2 ){ log.warning("caught " + e2); e2.printStackTrace(); } } /** gets the current position (in events) for reading forwards, i.e., readEventForwards will read this event number. @return position in events. */ synchronized public int position (){ return this.position; } /**Returns the position as a fraction of the total number of events @return fractional position in total events*/ synchronized public float getFractionalPosition (){ return (float)position() / size(); } /** Sets fractional position in events * @param frac 0-1 float range, 0 at start, 1 at end */ synchronized public void setFractionalPosition (float frac){ position((int)( frac * size() )); try{ readEventForwards(); } catch ( Exception e ){ // e.printStackTrace(); } } /** AEFileInputStream has PropertyChangeSupport. This support fires events on certain events such as "rewind". */ public PropertyChangeSupport getSupport (){ return support; } /** mark the current position. * @throws IOException if there is some error in reading the data */ synchronized public void mark () throws IOException{ int old=markPosition; markPosition = position(); markPosition = ( markPosition / eventSizeBytes ) * eventSizeBytes; // to avoid marking inside an event getSupport().firePropertyChange(AEInputStream.EVENT_MARKSET,old,markPosition); // System.out.println("AEInputStream.mark() marked position "+markPosition); } /** mark the current position as the IN point for editing. * @throws IOException if there is some error in reading the data */ synchronized public void markIn () throws IOException{ markInPosition = position(); markInPosition = ( markPosition / eventSizeBytes ) * eventSizeBytes; // to avoid marking inside an event } /** mark the current position as the OUT position for editing. * @throws IOException if there is some error in reading the data */ synchronized public void markOut () throws IOException{ markOutPosition = position(); markOutPosition = ( markPosition / eventSizeBytes ) * eventSizeBytes; // to avoid marking inside an event } /** clear any marked position */ synchronized public void unmark (){ int old=markPosition; markPosition = 0; getSupport().firePropertyChange(AEInputStream.EVENT_MARKCLEARED,old,markPosition); } /** Returns true if mark has been set to nonzero position. * * @return true if set. */ public boolean isMarkSet(){ return markPosition!=0; } @Override public void close () throws IOException{ super.close(); fileChannel.close(); System.gc(); System.runFinalization(); // try to free memory mapped file buffers so file can be deleted.... } /** returns the first timestamp in the stream @return the timestamp */ public int getFirstTimestamp (){ return firstTimestamp; } /** @return last timestamp in file */ public int getLastTimestamp (){ return lastTimestamp; } /** @return the duration of the file in us. <p> * Assumes data file is timestamped in us. This method fails to provide a sensible value if the timestamp wwaps. */ public int getDurationUs (){ return lastTimestamp - firstTimestamp; } /** @return the present value of the startTimestamp for reading data */ synchronized public int getCurrentStartTimestamp (){ return currentStartTimestamp; } public void setCurrentStartTimestamp (int currentStartTimestamp){ this.currentStartTimestamp = currentStartTimestamp; } /** @return returns the most recent timestamp */ public int getMostRecentTimestamp (){ return mostRecentTimestamp; } public void setMostRecentTimestamp (int mostRecentTimestamp){ this.mostRecentTimestamp = mostRecentTimestamp; } /** class used to signal a backwards read from input stream */ public class NonMonotonicTimeException extends Exception{ protected int timestamp, lastTimestamp, position; public NonMonotonicTimeException (){ super(); } public NonMonotonicTimeException (String s){ super(s); } public NonMonotonicTimeException (int ts){ this.timestamp = ts; } /** Constructs a new NonMonotonicTimeException * * @param readTs the timestamp just read * @param lastTs the previous timestamp */ public NonMonotonicTimeException (int readTs,int lastTs){ this.timestamp = readTs; this.lastTimestamp = lastTs; } /** Constructs a new NonMonotonicTimeException * * @param readTs the timestamp just read * @param lastTs the previous timestamp * @param position the current position in the stream */ public NonMonotonicTimeException (int readTs,int lastTs,int position){ this.timestamp = readTs; this.lastTimestamp = lastTs; this.position = position; } public int getCurrentTimestamp (){ return timestamp; } public int getPreviousTimestamp (){ return lastTimestamp; } public String toString (){ return "NonMonotonicTimeException: position=" + position + " timestamp=" + timestamp + " lastTimestamp=" + lastTimestamp + " jumps backwards by " + ( timestamp - lastTimestamp ); } } /** Indicates that timestamp has wrapped around from most positive to most negative signed value. The de-facto timestamp tick is us and timestamps are represented as int32 in jAER. Therefore the largest possible positive timestamp is 2^31-1 ticks which equals 2147.4836 seconds (35.7914 minutes). This wraps to -2147 seconds. The actual total time can be computed taking account of these "big wraps" if the time is increased by 4294.9673 seconds on each WrappedTimeException (when reading file forwards). * @param readTs the current (just read) timestamp * @param lastTs the previous timestamp */ public class WrappedTimeException extends NonMonotonicTimeException{ public WrappedTimeException (int readTs,int lastTs){ super(readTs,lastTs); } public WrappedTimeException (int readTs,int lastTs,int position){ super(readTs,lastTs,position); } public String toString (){ return "WrappedTimeException: timestamp=" + timestamp + " lastTimestamp=" + lastTimestamp + " jumps backwards by " + ( timestamp - lastTimestamp ); } } // checks for wrap (if reading forwards, this timestamp <0 and previous timestamp >0) private final boolean isWrappedTime (int read,int prevRead,int dt){ if ( dt > 0 && read <= 0 && prevRead > 0 ){ return true; } if ( dt < 0 && read >= 0 && prevRead < 0 ){ return true; } return false; } /** cuts out the part of the stream from IN to OUT and returns it as a new AEInputStream @return the new stream */ public AEFileInputStream cut (){ AEFileInputStream out = null; return out; } /** copies out the part of the stream from IN to OUT markers and returns it as a new AEInputStream @return the new stream */ public AEFileInputStream copy (){ AEFileInputStream out = null; return out; } /** pastes the in stream at the IN marker into this stream @param in the stream to paste */ public void paste (AEFileInputStream in){ } /** returns the chunk number which starts with 0. For position<CHUNK32_SIZE_BYTES returns 0 */ private int getChunkNumber (int position){ int chunk; chunk = (int)( ( position * eventSizeBytes ) / chunkSizeBytes ); return chunk; } private int positionFromChunk (int chunkNumber){ int pos = chunkNumber * chunkSizeBytes / eventSizeBytes; return pos; } private void mapNextChunk () throws IOException{ chunkNumber++; // increment the chunk number if ( chunkNumber >= numChunks ){ // if we try now to map a chunk past the last one then throw an EOF throw new EOFException("end of file; tried to map chunkNumber=" + chunkNumber + " but file only has numChunks=" + numChunks); } int start = getChunkStartPosition(chunkNumber); if ( start >= fileSize || start < 0 ){ chunkNumber = 0; // overflow will wrap<0 } mapChunk(chunkNumber); } private void mapPreviousChunk () throws IOException{ chunkNumber--; if ( chunkNumber < 0 ){ chunkNumber = 0; } int start = getChunkStartPosition(chunkNumber); if ( start >= fileSize || start < 0 ){ chunkNumber = 0; // overflow will wrap<0 } mapChunk(chunkNumber); } /** memory-maps a chunk of the input file. @param chunkNumber the number of the chunk, starting with 0 */ private void mapChunk (int chunkNumber) throws IOException{ this.chunkNumber = chunkNumber; int start = getChunkStartPosition(chunkNumber); if ( start >= fileSize ){ throw new EOFException("start of chunk=" + start + " but file has fileSize=" + fileSize); } int numBytesToMap = chunkSizeBytes; if ( start + numBytesToMap >= fileSize ){ numBytesToMap = (int)( fileSize - start ); } byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY,start,numBytesToMap); this.position = positionFromChunk(chunkNumber); // log.info("mapped chunk # "+chunkNumber+" of "+numChunks); } /** @return start of chunk in bytes @param chunk the chunk number */ private int getChunkStartPosition (int chunk){ if ( chunk <= 0 ){ return headerOffset; } return ( chunk * chunkSizeBytes ) + headerOffset; } private int getChunkEndPosition (int chunk){ return headerOffset + ( chunk + 1 ) * chunkSizeBytes; } /** skips the header lines (if any) */ protected void skipHeader () throws IOException{ position(headerOffset); } /** reads the header comment lines. Must have eventSize and chunkSizeBytes set for backwards compatiblity for files without headers to short address sizes. */ protected void readHeader (FileInputStream fileInputStream) throws IOException{ if ( fileInputStream == null ){ throw new IOException("null fileInputStream"); } if ( in.available() == 0 ){ throw new IOException("empty file (0 bytes available)"); } BufferedReader bufferedHeaderReader = new BufferedReader(new InputStreamReader(fileInputStream)); headerOffset = 0; // start from 0 if ( !bufferedHeaderReader.markSupported() ){ throw new IOException("no mark supported while reading file header, is this a normal file?"); } String s; // System.out.println("File header:"); while ( ( s = readHeaderLine(bufferedHeaderReader) ) != null ){ header.add(s); parseFileFormatVersion(s); } // we don't map yet until we know eventSize StringBuffer sb = new StringBuffer(); sb.append("File header:"); for ( String str:header ){ sb.append(str); sb.append(lineSeparator); // "\n"); } log.info(sb.toString()); bufferedHeaderReader = null; // mark for GC } /** parses the file format version given a string with the header comment character stripped off. @see net.sf.jaer.eventio.AEDataFile */ protected void parseFileFormatVersion (String s){ float version = 1f; if ( s.startsWith(AEDataFile.DATA_FILE_FORMAT_HEADER) ){ // # stripped off by readHeaderLine try{ version = Float.parseFloat(s.substring(AEDataFile.DATA_FILE_FORMAT_HEADER.length())); } catch ( NumberFormatException numberFormatException ){ log.warning("While parsing header line " + s + " got " + numberFormatException.toString()); } if ( version < 2 ){ addressType = Short.TYPE; eventSizeBytes = Integer.SIZE / 8 + Short.SIZE / 8; } else if ( version >= 2 ){ // this is hack to avoid parsing the AEDataFile. format number string... addressType = Integer.TYPE; eventSizeBytes = Integer.SIZE / 8 + Integer.SIZE / 8; } log.info("Data file version=" + version + " and has addressType=" + addressType); } } void setupChunks () throws IOException{ fileChannel = fileInputStream.getChannel(); fileSize = fileChannel.size(); chunkSizeBytes = eventSizeBytes * CHUNK_SIZE_EVENTS; numChunks = ( fileSize / chunkSizeBytes ) + 1; // used to limit chunkNumber to prevent overflow of position and for EOF log.info("fileSize=" + fileSize + " chunkSizeBytes=" + chunkSizeBytes + " numChunks=" + numChunks); mapChunk(0); } /** assumes we are positioned at start of line and that we may either * read a comment char '#' or something else leaves us after the line at start of next line or of raw data. * Assumes header lines are written using the AEOutputStream.writeHeaderLine(). @return header line */ private String readHeaderLine (BufferedReader reader) throws IOException{ // StringBuffer s = new StringBuffer(); // read header lines from fileInputStream, not byteBuffer, since we have not mapped file yet // reader.mark(1); // max header line length in chars int c = reader.read(); // read single char if ( c != AEDataFile.COMMENT_CHAR ){ // if it's not a comment char return null; // return a null header line } // reader.reset(); // reset to start of header/comment line // we don't push back comment char because we want to parse the file format sans this String s = reader.readLine(); for ( byte b:s.getBytes() ){ if ( b < 32 || b > 126 ){ log.warning("Non printable character (byte value=" + b + ") which is (<32 || >126) detected in header line, aborting header read and resetting to start of file because this file may not have a real header"); return null; } } headerOffset += s.length() + NUMBER_LINE_SEPARATORS + 1; // adds comment char and trailing CRLF newline, assumes CRLF EOL // TODO fix this assumption return s; } /** Gets the header strings from the file @return list of strings, one per line */ public ArrayList<String> getHeader (){ return header; } private void fireInitPropertyChange (){ getSupport().firePropertyChange(AEInputStream.EVENT_INIT,0,0); firstReadCompleted = true; } /** Returns the File that is being read, or null if the instance is constructed from a FileInputStream */ public File getFile (){ return file; } /** Sets the File reference but doesn't open the file */ public void setFile (File f){ this.file = f; absoluteStartingTimeMs = getAbsoluteStartingTimeMsFromFile(getFile()); } /** When the file is opened, the filename is parsed to try to extract the date and time the file was created from the filename. @return the time logging was started in ms since 1970 */ public long getAbsoluteStartingTimeMs (){ return absoluteStartingTimeMs; } public void setAbsoluteStartingTimeMs (long absoluteStartingTimeMs){ this.absoluteStartingTimeMs = absoluteStartingTimeMs; } /**Parses the filename to extract the file logging date from the name of the file. * * @return start of logging time in ms, i.e., in "java" time, since 1970 */ private long getAbsoluteStartingTimeMsFromFile (File f){ if ( f == null ){ return 0; } try{ String fn = f.getName(); String dateStr = fn.substring(fn.indexOf('-') + 1); // guess that datestamp is right after first - which follows Chip classname Date date = AEDataFile.DATE_FORMAT.parse(dateStr); return date.getTime(); } catch ( Exception e ){ log.warning(e.toString()); return 0; } } public boolean isNonMonotonicTimeExceptionsChecked (){ return enableTimeWrappingExceptionsChecking; } public void setNonMonotonicTimeExceptionsChecked (boolean yes){ enableTimeWrappingExceptionsChecking = yes; } /** * * Returns the bitmask that is OR'ed with raw addresses; if result is nonzero then a new timestamp offset is memorized and subtracted from * @return the timestampResetBitmask */ public int getTimestampResetBitmask (){ return timestampResetBitmask; } /** * Sets the bitmask that is OR'ed with raw addresses; if result is nonzero then a new timestamp offset is memorized and subtracted from * all subsequent timestamps. * * @param timestampResetBitmask the timestampResetBitmask to set */ public void setTimestampResetBitmask (int timestampResetBitmask){ this.timestampResetBitmask = timestampResetBitmask; } }
AEFileInputStream now returns only the most recent event or packet of events if there are no new events during the desired time slice in readPacketByTime. Previous behavior was that it returned at least one event, even if there were no events in the time slice. This previous behavior meant that when playing back synchronized recordings from multiple sensors (e.g. retina + cochlea) would shoot through a huge segment of retina events if there were no cochlea events. Now the new behavior is that the cochlea events are "frozen" duruing the period there are no retina events. This is still not ideal behavior but at least does not fast forward through retina periods when there is no cochlea activity. But it has the side-effect of returning the same event repeatedly when the time slice is made very small. git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@2685 b7f4320f-462c-0410-a916-d9f35bb82d52
src/net/sf/jaer/eventio/AEFileInputStream.java
AEFileInputStream now returns only the most recent event or packet of events if there are no new events during the desired time slice in readPacketByTime. Previous behavior was that it returned at least one event, even if there were no events in the time slice. This previous behavior meant that when playing back synchronized recordings from multiple sensors (e.g. retina + cochlea) would shoot through a huge segment of retina events if there were no cochlea events. Now the new behavior is that the cochlea events are "frozen" duruing the period there are no retina events. This is still not ideal behavior but at least does not fast forward through retina periods when there is no cochlea activity. But it has the side-effect of returning the same event repeatedly when the time slice is made very small.
<ide><path>rc/net/sf/jaer/eventio/AEFileInputStream.java <ide> currentStartTimestamp = firstTimestamp; <ide> mostRecentTimestamp = firstTimestamp; <ide> } catch ( IOException e ){ <del> log.warning("couldn't read first event to set starting timestamp"); <add> log.warning("couldn't read first event to set starting timestamp - maybe the file is empty?"); <ide> } catch ( NonMonotonicTimeException e2 ){ <ide> log.warning("On AEInputStream.init() caught "+e2.toString()); <ide> } <ide> log.info("initialized " + this.toString()); <ide> } <ide> <add> /** Reads the next event from the stream setting no limit on how far ahead in time it is. <add> * <add> * @return the event. <add> * @throws IOException on reading the file. <add> * @throws net.sf.jaer.eventio.AEFileInputStream.NonMonotonicTimeException if the timestamp is earlier than the one last read. <add> */ <ide> private EventRaw readEventForwards() throws IOException, NonMonotonicTimeException{ <ide> return readEventForwards(Integer.MAX_VALUE); <ide> } <ide> <ide> /** reads the next event forward, sets mostRecentTimestamp, returns null if the next timestamp is later than maxTimestamp. <ide> * @param maxTimestamp the latest timestamp that should be read. <del> @throws EOFException at end of file <add> @throws EOFException at end of file <ide> * @throws NonMonotonicTimeException <ide> * @throws WrappedTimeException <ide> */ <ide> timestampOffset=ts; <ide> } <ide> ts-=timestampOffset; <del>// // TODO fix extra event no matter what dt <del>// if (ts > maxTimestamp) { <del>// // push back event <del>// byteBuffer.position(position()-eventSizeBytes); // we haven't updated our position field yet <del>// ts=lastTs; // this is the one last read successfully <del>// mostRecentTimestamp=ts; <del>// return null; <del>// } <add> // TODO fix extra event no matter what dt <add> if (ts > maxTimestamp) { <add> // push back event <add> position(position()-1); // we haven't updated our position field yet <add> ts=lastTs; // this is the one last read successfully <add> mostRecentTimestamp=ts; <add> return null; <add> } <ide> // check for non-monotonic increasing timestamps, if we get one, reset our notion of the starting time <ide> if ( isWrappedTime(ts,mostRecentTimestamp,1) ){ <ide> throw new WrappedTimeException(ts,mostRecentTimestamp,position); <ide> @return a raw packet of events of a specfied number of events <ide> fires a property change "position" on every call, and a property change "wrappedTime" if time wraps around. <ide> */ <add> @Override <ide> synchronized public AEPacketRaw readPacketByNumber (int n) throws IOException{ <ide> if ( !firstReadCompleted ){ <ide> fireInitPropertyChange(); <ide> *@param dt the timestamp different in units of the timestamp (usually us) <ide> *@see #MAX_BUFFER_SIZE_EVENTS <ide> */ <add> @Override <ide> synchronized public AEPacketRaw readPacketByTime (int dt) throws IOException{ <ide> if ( !firstReadCompleted ){ <ide> fireInitPropertyChange(); <ide> // boolean lt1=endTimestamp<0, lt2=mostRecentTimestamp<0; <ide> // boolean changedSign= ( (lt1 && !lt2) || (!lt1 && lt2) ); <ide> // if( !changedSign ){ <del>// currentStartTimestamp=endTimestamp; <add> currentStartTimestamp=endTimestamp; <ide> // log.info(this+" returning empty packet because mostRecentTimestamp="+mostRecentTimestamp+" is already later than endTimestamp="+endTimestamp); <ide> // return new AEPacketRaw(0); <ide> // } <ide> mostRecentTimestamp = e.getCurrentTimestamp(); <ide> getSupport().firePropertyChange(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP,lastTimestamp, mostRecentTimestamp); <ide> } finally{ <del> currentStartTimestamp = mostRecentTimestamp; <add>// currentStartTimestamp = mostRecentTimestamp; <ide> } <ide> packet.setNumEvents(i); <del>// if(i<1){ <del>// log.info(packet.toString()); <del>// } <add> if(i<1){ <add> log.info(packet.toString()); <add> } <ide> getSupport().firePropertyChange(AEInputStream.EVENT_POSITION,oldPosition,position()); <ide> // System.out.println("bigwrap="+bigWrap+" read "+packet.getNumEvents()+" mostRecentTimestamp="+mostRecentTimestamp+" currentStartTimestamp="+currentStartTimestamp); <ide> return packet; <ide> /** gets the size of the stream in events <ide> @return size in events <ide> */ <add> @Override <ide> public long size (){ <ide> return ( fileSize - headerOffset ) / eventSizeBytes; <ide> } <ide> /** set position in events from start of file <ide> @param event the number of the event, starting with 0 <ide> */ <add> @Override <ide> synchronized public void position (int event){ <ide> // if(event==size()) event=event-1; <ide> int newChunkNumber; <ide> /** gets the current position (in events) for reading forwards, i.e., readEventForwards will read this event number. <ide> @return position in events. <ide> */ <add> @Override <ide> synchronized public int position (){ <ide> return this.position; <ide> } <ide> <ide> /**Returns the position as a fraction of the total number of events <ide> @return fractional position in total events*/ <add> @Override <ide> synchronized public float getFractionalPosition (){ <ide> return (float)position() / size(); <ide> } <ide> /** Sets fractional position in events <ide> * @param frac 0-1 float range, 0 at start, 1 at end <ide> */ <add> @Override <ide> synchronized public void setFractionalPosition (float frac){ <ide> position((int)( frac * size() )); <ide> try{ <ide> /** mark the current position. <ide> * @throws IOException if there is some error in reading the data <ide> */ <add> @Override <ide> synchronized public void mark () throws IOException{ <ide> int old=markPosition; <ide> markPosition = position(); <ide> } <ide> <ide> /** clear any marked position */ <add> @Override <ide> synchronized public void unmark (){ <ide> int old=markPosition; <ide> markPosition = 0; <ide> return lastTimestamp; <ide> } <ide> <add> @Override <ide> public String toString (){ <ide> return "NonMonotonicTimeException: position=" + position + " timestamp=" + timestamp + " lastTimestamp=" + lastTimestamp + " jumps backwards by " + ( timestamp - lastTimestamp ); <ide> } <ide> super(readTs,lastTs,position); <ide> } <ide> <add> @Override <ide> public String toString (){ <ide> return "WrappedTimeException: timestamp=" + timestamp + " lastTimestamp=" + lastTimestamp + " jumps backwards by " + ( timestamp - lastTimestamp ); <ide> } <ide> } <ide> <ide> // checks for wrap (if reading forwards, this timestamp <0 and previous timestamp >0) <del> private final boolean isWrappedTime (int read,int prevRead,int dt){ <add> private boolean isWrappedTime (int read,int prevRead,int dt){ <ide> if ( dt > 0 && read <= 0 && prevRead > 0 ){ <ide> return true; <ide> } <ide> parseFileFormatVersion(s); <ide> } <ide> // we don't map yet until we know eventSize <del> StringBuffer sb = new StringBuffer(); <add> StringBuilder sb = new StringBuilder(); <ide> sb.append("File header:"); <ide> for ( String str:header ){ <ide> sb.append(str); <ide> } <ide> } <ide> <add> @Override <ide> public boolean isNonMonotonicTimeExceptionsChecked (){ <ide> return enableTimeWrappingExceptionsChecking; <ide> } <ide> <add> @Override <ide> public void setNonMonotonicTimeExceptionsChecked (boolean yes){ <ide> enableTimeWrappingExceptionsChecking = yes; <ide> }