id
int64
22
34.9k
comment_id
int64
0
328
comment
stringlengths
2
2.55k
code
stringlengths
31
107k
classification
stringclasses
6 values
isFinished
bool
1 class
code_context_2
stringlengths
21
27.3k
code_context_10
stringlengths
29
27.3k
code_context_20
stringlengths
29
27.3k
448
0
/** * Creates a 2D array of the given width and height, filled with entirely with the value contents. * You may want to use {@link #fill(char[][], char)} to modify an existing 2D array instead. * @param contents the value to fill the array with * @param width the desired width * @param height the desired height * @return a freshly allocated 2D array of the requested dimensions, filled entirely with contents */
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
DESIGN
true
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
449
0
/** * Creates a 2D array of the given width and height, filled with entirely with the value contents. * You may want to use {@link #fill(float[][], float)} to modify an existing 2D array instead. * @param contents the value to fill the array with * @param width the desired width * @param height the desired height * @return a freshly allocated 2D array of the requested dimensions, filled entirely with contents */
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
DESIGN
true
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
450
0
/** * Creates a 2D array of the given width and height, filled with entirely with the value contents. * You may want to use {@link #fill(double[][], double)} to modify an existing 2D array instead. * @param contents the value to fill the array with * @param width the desired width * @param height the desired height * @return a freshly allocated 2D array of the requested dimensions, filled entirely with contents */
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
DESIGN
true
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
451
0
/** * Creates a 2D array of the given width and height, filled with entirely with the value contents. * You may want to use {@link #fill(int[][], int)} to modify an existing 2D array instead. * @param contents the value to fill the array with * @param width the desired width * @param height the desired height * @return a freshly allocated 2D array of the requested dimensions, filled entirely with contents */
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
DESIGN
true
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
452
0
/** * Creates a 2D array of the given width and height, filled with entirely with the value contents. * You may want to use {@link #fill(byte[][], byte)} to modify an existing 2D array instead. * @param contents the value to fill the array with * @param width the desired width * @param height the desired height * @return a freshly allocated 2D array of the requested dimensions, filled entirely with contents */
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
DESIGN
true
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
8,645
0
//:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size());
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
NONSATD
true
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size();
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; }
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required.
8,645
1
// Get the FunctionRef
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
NONSATD
true
List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false;
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName());
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade);
8,645
2
//:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText());
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
NONSATD
true
if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; }
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText();
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
8,645
3
// Get the overloaded operator:
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
NONSATD
true
isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName());
List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator);
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
8,645
4
//:OFF:log.debug(subNodes.get(i).getClass().getName());
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
NONSATD
true
// Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found.");
// Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade);
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
8,645
5
//:OFF:log.debug(" >> Operator :: terminal-node found.");
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
NONSATD
true
//:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } }
boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
8,645
6
//:OFF:log.debug(" >> OPERATOR :: " + operator);
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
NONSATD
true
} String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator);
isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
8,645
7
// TODO: might not to inherit Node, therefore giving statement not required.
@Override public void exitOperator_expr(OperonModuleParser.Operator_exprContext ctx) { //:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
DESIGN
true
String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef);
} // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
//:OFF:log.debug("EXIT Operator_expr :: Stack size :: " + this.stack.size()); List<ParseTree> subNodes = getContextChildNodes(ctx); int subNodesSize = subNodes.size(); // Get the FunctionRef FunctionRef funcRef = (FunctionRef) this.stack.pop(); boolean isCascade = false; if (subNodes.get(subNodes.size() - 2) instanceof TerminalNode && subNodes.get(subNodes.size() - 2).getText().toLowerCase().equals("cascade")) { //:OFF:log.debug(" >> Operator :: set cascade true :: " + subNodes.get(subNodes.size() - 2).getText()); isCascade = true; } // Get the overloaded operator: for (int i = 0; i < subNodesSize; i ++) { //:OFF:log.debug(subNodes.get(i).getClass().getName()); if (subNodes.get(i) instanceof TerminalNode) { //:OFF:log.debug(" >> Operator :: terminal-node found."); } } String operator = subNodes.get(2).getText(); //:OFF:log.debug(" >> OPERATOR :: " + operator); Operator op = new Operator(this.currentStatement); // TODO: might not to inherit Node, therefore giving statement not required. op.setOperator(operator); op.setFunctionRef(funcRef); op.setCascade(isCascade); this.stack.push(op); }
453
0
/** * Creates a 2D array of the given width and height, filled with entirely with the value contents. * You may want to use {@link #fill(boolean[][], boolean)} to modify an existing 2D array instead. * @param contents the value to fill the array with * @param width the desired width * @param height the desired height * @return a freshly allocated 2D array of the requested dimensions, filled entirely with contents */
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { Arrays.fill(next[x], true); } } return next; }
DESIGN
true
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { Arrays.fill(next[x], true); } } return next; }
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { Arrays.fill(next[x], true); } } return next; }
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { Arrays.fill(next[x], true); } } return next; }
25,027
0
// TODO: Return genre map
@Override public Map<String, String> getOptionList(String id) { // TODO: Return genre map return super.getOptionList(id); }
IMPLEMENTATION
true
@Override public Map<String, String> getOptionList(String id) { // TODO: Return genre map return super.getOptionList(id); }
@Override public Map<String, String> getOptionList(String id) { // TODO: Return genre map return super.getOptionList(id); }
@Override public Map<String, String> getOptionList(String id) { // TODO: Return genre map return super.getOptionList(id); }
16,844
0
// TODO: Script tests, should fail with defaultValuesSourceType disabled.
public void testEmpty() throws IOException { final MappedFieldType ft = new NumberFieldMapper.NumberFieldType("field", NumberType.LONG); testCase( stats("_name").field(ft.name()), iw -> {}, stats -> { assertEquals(0d, stats.getCount(), 0); assertEquals(0d, stats.getSum(), 0); assertEquals(Float.NaN, stats.getAvg(), 0); assertEquals(Double.POSITIVE_INFINITY, stats.getMin(), 0); assertEquals(Double.NEGATIVE_INFINITY, stats.getMax(), 0); assertFalse(AggregationInspectionHelper.hasValue(stats)); }, singleton(ft) ); }
TEST
true
public void testEmpty() throws IOException { final MappedFieldType ft = new NumberFieldMapper.NumberFieldType("field", NumberType.LONG); testCase( stats("_name").field(ft.name()), iw -> {}, stats -> { assertEquals(0d, stats.getCount(), 0); assertEquals(0d, stats.getSum(), 0); assertEquals(Float.NaN, stats.getAvg(), 0); assertEquals(Double.POSITIVE_INFINITY, stats.getMin(), 0); assertEquals(Double.NEGATIVE_INFINITY, stats.getMax(), 0); assertFalse(AggregationInspectionHelper.hasValue(stats)); }, singleton(ft) ); }
public void testEmpty() throws IOException { final MappedFieldType ft = new NumberFieldMapper.NumberFieldType("field", NumberType.LONG); testCase( stats("_name").field(ft.name()), iw -> {}, stats -> { assertEquals(0d, stats.getCount(), 0); assertEquals(0d, stats.getSum(), 0); assertEquals(Float.NaN, stats.getAvg(), 0); assertEquals(Double.POSITIVE_INFINITY, stats.getMin(), 0); assertEquals(Double.NEGATIVE_INFINITY, stats.getMax(), 0); assertFalse(AggregationInspectionHelper.hasValue(stats)); }, singleton(ft) ); }
public void testEmpty() throws IOException { final MappedFieldType ft = new NumberFieldMapper.NumberFieldType("field", NumberType.LONG); testCase( stats("_name").field(ft.name()), iw -> {}, stats -> { assertEquals(0d, stats.getCount(), 0); assertEquals(0d, stats.getSum(), 0); assertEquals(Float.NaN, stats.getAvg(), 0); assertEquals(Double.POSITIVE_INFINITY, stats.getMin(), 0); assertEquals(Double.NEGATIVE_INFINITY, stats.getMax(), 0); assertFalse(AggregationInspectionHelper.hasValue(stats)); }, singleton(ft) ); }
16,856
0
/** * Uses the passed path elements (resolved) to try to select the best of the possible trails. * Returns null only if nothing matches at all. * BEST-EFFORT. * <p> * TODO: REVIEW: the possibility of each path elem matching multiple category IDs makes this extremely * complicated; so we ignore the specific implications and just match as much as possible. * <p> * For a trail to be selected, it must "end with" the pathElems; after that, the best trail is one that * has smallest length. */
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
DESIGN
true
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
16,856
1
// sure to fail
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
NONSATD
true
List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size());
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; }
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } }
16,856
2
// simplistic check: ignores exact vs name-only matches, but may be good enough
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
DESIGN
true
AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false;
if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail;
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
16,856
3
// ideal case
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
NONSATD
true
} if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break;
boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
16,856
4
// smaller = better
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
NONSATD
true
bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; }
String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
33,242
0
/** * Retrieves the packet content. May be recomputed if the packet is invalidated or * if there is memory demand (handled by a soft reference). * <p> * {@link FramedPacket#body()} will contain a buffer allocated by this method. */
public @NotNull FramedPacket retrieve() { if (!PacketUtils.CACHED_PACKET) { // TODO: Using a local buffer may be possible return PacketUtils.allocateTrimmedPacket(packet()); } SoftReference<FramedPacket> ref; FramedPacket cache; if (updated == 0 || ((ref = packet) == null || (cache = ref.get()) == null)) { cache = PacketUtils.allocateTrimmedPacket(packet()); this.packet = new SoftReference<>(cache); UPDATER.compareAndSet(this, 0, 1); } return cache; }
NONSATD
true
public @NotNull FramedPacket retrieve() { if (!PacketUtils.CACHED_PACKET) { // TODO: Using a local buffer may be possible return PacketUtils.allocateTrimmedPacket(packet()); } SoftReference<FramedPacket> ref; FramedPacket cache; if (updated == 0 || ((ref = packet) == null || (cache = ref.get()) == null)) { cache = PacketUtils.allocateTrimmedPacket(packet()); this.packet = new SoftReference<>(cache); UPDATER.compareAndSet(this, 0, 1); } return cache; }
public @NotNull FramedPacket retrieve() { if (!PacketUtils.CACHED_PACKET) { // TODO: Using a local buffer may be possible return PacketUtils.allocateTrimmedPacket(packet()); } SoftReference<FramedPacket> ref; FramedPacket cache; if (updated == 0 || ((ref = packet) == null || (cache = ref.get()) == null)) { cache = PacketUtils.allocateTrimmedPacket(packet()); this.packet = new SoftReference<>(cache); UPDATER.compareAndSet(this, 0, 1); } return cache; }
public @NotNull FramedPacket retrieve() { if (!PacketUtils.CACHED_PACKET) { // TODO: Using a local buffer may be possible return PacketUtils.allocateTrimmedPacket(packet()); } SoftReference<FramedPacket> ref; FramedPacket cache; if (updated == 0 || ((ref = packet) == null || (cache = ref.get()) == null)) { cache = PacketUtils.allocateTrimmedPacket(packet()); this.packet = new SoftReference<>(cache); UPDATER.compareAndSet(this, 0, 1); } return cache; }
33,242
1
// TODO: Using a local buffer may be possible
public @NotNull FramedPacket retrieve() { if (!PacketUtils.CACHED_PACKET) { // TODO: Using a local buffer may be possible return PacketUtils.allocateTrimmedPacket(packet()); } SoftReference<FramedPacket> ref; FramedPacket cache; if (updated == 0 || ((ref = packet) == null || (cache = ref.get()) == null)) { cache = PacketUtils.allocateTrimmedPacket(packet()); this.packet = new SoftReference<>(cache); UPDATER.compareAndSet(this, 0, 1); } return cache; }
DESIGN
true
public @NotNull FramedPacket retrieve() { if (!PacketUtils.CACHED_PACKET) { // TODO: Using a local buffer may be possible return PacketUtils.allocateTrimmedPacket(packet()); }
public @NotNull FramedPacket retrieve() { if (!PacketUtils.CACHED_PACKET) { // TODO: Using a local buffer may be possible return PacketUtils.allocateTrimmedPacket(packet()); } SoftReference<FramedPacket> ref; FramedPacket cache; if (updated == 0 || ((ref = packet) == null || (cache = ref.get()) == null)) { cache = PacketUtils.allocateTrimmedPacket(packet()); this.packet = new SoftReference<>(cache); UPDATER.compareAndSet(this, 0, 1);
public @NotNull FramedPacket retrieve() { if (!PacketUtils.CACHED_PACKET) { // TODO: Using a local buffer may be possible return PacketUtils.allocateTrimmedPacket(packet()); } SoftReference<FramedPacket> ref; FramedPacket cache; if (updated == 0 || ((ref = packet) == null || (cache = ref.get()) == null)) { cache = PacketUtils.allocateTrimmedPacket(packet()); this.packet = new SoftReference<>(cache); UPDATER.compareAndSet(this, 0, 1); } return cache; }
33,243
0
/** * We may want to test this method with more then 1 ontology. This is why the implementation is in * aprivate method. This method tests if all the logical axioms in testExpectedID ontology are inferences * of the testID ontology. * * @param testID * // The ID of the ontology to be the input (loaded in the TestData.manager) * @param testExpectedID * // The ID of the ontology which contains logical axioms expected in the result */
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
TEST
true
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
33,243
1
// We prepare the input ontology
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
NONSATD
true
log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology();
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT");
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) {
33,243
2
// Maybe we want to see what is in before
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
NONSATD
true
manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID))
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set
33,243
3
// Now we test the method
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
NONSATD
true
// Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY,
OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>();
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom
33,243
4
// Maybe we want to see the inferred axiom list
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
NONSATD
true
Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log);
OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected);
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology);
33,243
5
// We want only Class related axioms in the result set
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
NONSATD
true
} assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom
Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) {
// Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
33,243
6
// We want to remove the ontology from the manager
private void testClassify(String testID, String testExpectedID) { log.info("Testing the CLASSIFY task"); OWLOntologyManager manager = TestData.manager; // We prepare the input ontology try { OWLOntology testOntology = manager.createOntology(); OWLOntologyID testOntologyID = testOntology.getOntologyID(); log.debug("Created test ontology with ID: {}", testOntologyID); manager.applyChange(new AddImport(testOntology, TestData.factory.getOWLImportsDeclaration(IRI .create(testID)))); // Maybe we want to see what is in before if (log.isDebugEnabled()) TestUtils.debug(manager.getOntology(testOntologyID), log); // Now we test the method log.debug("Running HermiT"); Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
NONSATD
true
|| a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) {
log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false);
manager.getOntology(testOntologyID)); // Maybe we want to see the inferred axiom list if (log.isDebugEnabled()) { TestUtils.debug(inferred, log); } Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)) .getLogicalAxioms(); Set<OWLAxiom> missing = new HashSet<OWLAxiom>(); for (OWLAxiom expected : expectedAxioms) { if (!inferred.contains(expected)) { log.error("missing expected axiom: {}", expected); missing.add(expected); } } assertTrue(missing.isEmpty()); // We want only Class related axioms in the result set for (OWLAxiom a : inferred) { assertTrue(a instanceof OWLClassAssertionAxiom || a instanceof OWLSubClassOfAxiom || a instanceof OWLEquivalentClassesAxiom || a instanceof OWLDisjointClassesAxiom); } // We want to remove the ontology from the manager manager.removeOntology(testOntology); } catch (OWLOntologyCreationException e) { log.error("An {} have been thrown while creating the input ontology for test", e.getClass()); assertTrue(false); } catch (ReasoningServiceException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (InconsistentInputException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } catch (UnsupportedTaskException e) { log.error("An {} have been thrown while executing the reasoning", e.getClass()); assertTrue(false); } }
16,860
0
/** * Return all paths from the given topCategoryIds to the product. * <p> * TODO?: perhaps can cache with UtilCache in future, or read from a cached category tree. */
protected List<List<String>> getProductRollupTrails(Delegator delegator, String productId, Set<String> topCategoryIds) { return ProductWorker.getProductRollupTrails(delegator, productId, topCategoryIds, true); }
IMPLEMENTATION
true
protected List<List<String>> getProductRollupTrails(Delegator delegator, String productId, Set<String> topCategoryIds) { return ProductWorker.getProductRollupTrails(delegator, productId, topCategoryIds, true); }
protected List<List<String>> getProductRollupTrails(Delegator delegator, String productId, Set<String> topCategoryIds) { return ProductWorker.getProductRollupTrails(delegator, productId, topCategoryIds, true); }
protected List<List<String>> getProductRollupTrails(Delegator delegator, String productId, Set<String> topCategoryIds) { return ProductWorker.getProductRollupTrails(delegator, productId, topCategoryIds, true); }
16,861
0
/** * Return all paths from the given topCategoryIds to the category. * <p> * TODO?: perhaps can cache with UtilCache in future, or read from a cached category tree. */
protected List<List<String>> getCategoryRollupTrails(Delegator delegator, String productCategoryId, Set<String> topCategoryIds) { return CategoryWorker.getCategoryRollupTrails(delegator, productCategoryId, topCategoryIds, true); }
IMPLEMENTATION
true
protected List<List<String>> getCategoryRollupTrails(Delegator delegator, String productCategoryId, Set<String> topCategoryIds) { return CategoryWorker.getCategoryRollupTrails(delegator, productCategoryId, topCategoryIds, true); }
protected List<List<String>> getCategoryRollupTrails(Delegator delegator, String productCategoryId, Set<String> topCategoryIds) { return CategoryWorker.getCategoryRollupTrails(delegator, productCategoryId, topCategoryIds, true); }
protected List<List<String>> getCategoryRollupTrails(Delegator delegator, String productCategoryId, Set<String> topCategoryIds) { return CategoryWorker.getCategoryRollupTrails(delegator, productCategoryId, topCategoryIds, true); }
8,668
0
// TODO: get the remark line in there too.
@Test public void testAclExtraction() { CiscoXrConfiguration c = parseVendorConfig("acl"); assertThat(c.getIpv4Acls(), hasKeys("acl")); Ipv4AccessList acl = c.getIpv4Acls().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIpv6Acls(), hasKeys("aclv6")); Ipv6AccessList aclv6 = c.getIpv6Acls().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
DESIGN
true
assertThat(c.getIpv4Acls(), hasKeys("acl")); Ipv4AccessList acl = c.getIpv4Acls().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIpv6Acls(), hasKeys("aclv6"));
@Test public void testAclExtraction() { CiscoXrConfiguration c = parseVendorConfig("acl"); assertThat(c.getIpv4Acls(), hasKeys("acl")); Ipv4AccessList acl = c.getIpv4Acls().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIpv6Acls(), hasKeys("aclv6")); Ipv6AccessList aclv6 = c.getIpv6Acls().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
@Test public void testAclExtraction() { CiscoXrConfiguration c = parseVendorConfig("acl"); assertThat(c.getIpv4Acls(), hasKeys("acl")); Ipv4AccessList acl = c.getIpv4Acls().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIpv6Acls(), hasKeys("aclv6")); Ipv6AccessList aclv6 = c.getIpv6Acls().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
8,668
1
// TODO: get the remark line in there too.
@Test public void testAclExtraction() { CiscoXrConfiguration c = parseVendorConfig("acl"); assertThat(c.getIpv4Acls(), hasKeys("acl")); Ipv4AccessList acl = c.getIpv4Acls().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIpv6Acls(), hasKeys("aclv6")); Ipv6AccessList aclv6 = c.getIpv6Acls().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
DESIGN
true
assertThat(c.getIpv4Acls(), hasKeys("acl")); Ipv4AccessList acl = c.getIpv4Acls().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIpv6Acls(), hasKeys("aclv6"));
@Test public void testAclExtraction() { CiscoXrConfiguration c = parseVendorConfig("acl"); assertThat(c.getIpv4Acls(), hasKeys("acl")); Ipv4AccessList acl = c.getIpv4Acls().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIpv6Acls(), hasKeys("aclv6")); Ipv6AccessList aclv6 = c.getIpv6Acls().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
@Test public void testAclExtraction() { CiscoXrConfiguration c = parseVendorConfig("acl"); assertThat(c.getIpv4Acls(), hasKeys("acl")); Ipv4AccessList acl = c.getIpv4Acls().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIpv6Acls(), hasKeys("aclv6")); Ipv6AccessList aclv6 = c.getIpv6Acls().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
8,669
0
// TODO: get the remark line in there too.
@Test public void testAclConversion() { Configuration c = parseConfig("acl"); assertThat(c.getIpAccessLists(), hasKeys("acl")); IpAccessList acl = c.getIpAccessLists().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIp6AccessLists(), hasKeys("aclv6")); Ip6AccessList aclv6 = c.getIp6AccessLists().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
DESIGN
true
assertThat(c.getIpAccessLists(), hasKeys("acl")); IpAccessList acl = c.getIpAccessLists().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIp6AccessLists(), hasKeys("aclv6"));
@Test public void testAclConversion() { Configuration c = parseConfig("acl"); assertThat(c.getIpAccessLists(), hasKeys("acl")); IpAccessList acl = c.getIpAccessLists().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIp6AccessLists(), hasKeys("aclv6")); Ip6AccessList aclv6 = c.getIp6AccessLists().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
@Test public void testAclConversion() { Configuration c = parseConfig("acl"); assertThat(c.getIpAccessLists(), hasKeys("acl")); IpAccessList acl = c.getIpAccessLists().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIp6AccessLists(), hasKeys("aclv6")); Ip6AccessList aclv6 = c.getIp6AccessLists().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
8,669
1
// TODO: get the remark line in there too.
@Test public void testAclConversion() { Configuration c = parseConfig("acl"); assertThat(c.getIpAccessLists(), hasKeys("acl")); IpAccessList acl = c.getIpAccessLists().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIp6AccessLists(), hasKeys("aclv6")); Ip6AccessList aclv6 = c.getIp6AccessLists().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
DESIGN
true
assertThat(c.getIpAccessLists(), hasKeys("acl")); IpAccessList acl = c.getIpAccessLists().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIp6AccessLists(), hasKeys("aclv6"));
@Test public void testAclConversion() { Configuration c = parseConfig("acl"); assertThat(c.getIpAccessLists(), hasKeys("acl")); IpAccessList acl = c.getIpAccessLists().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIp6AccessLists(), hasKeys("aclv6")); Ip6AccessList aclv6 = c.getIp6AccessLists().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
@Test public void testAclConversion() { Configuration c = parseConfig("acl"); assertThat(c.getIpAccessLists(), hasKeys("acl")); IpAccessList acl = c.getIpAccessLists().get("acl"); // TODO: get the remark line in there too. assertThat(acl.getLines(), hasSize(7)); assertThat(c.getIp6AccessLists(), hasKeys("aclv6")); Ip6AccessList aclv6 = c.getIp6AccessLists().get("aclv6"); // TODO: get the remark line in there too. assertThat(aclv6.getLines(), hasSize(4)); }
16,873
0
// TODO: Caching, don't read inputs for every inference
private List<InferenceInOutSequence> getInputOutputAssets() throws IOException { // TODO: Caching, don't read inputs for every inference List<InferenceInOutSequence> inOutList = getInputOutputAssets(mContext, mInputOutputAssets, mInputOutputDatasets); Boolean lastGolden = null; for (InferenceInOutSequence sequence : inOutList) { mHasGoldenOutputs = sequence.hasGoldenOutput(); if (lastGolden == null) { lastGolden = mHasGoldenOutputs; } else { if (lastGolden != mHasGoldenOutputs) { throw new IllegalArgumentException( "Some inputs for " + mModelName + " have outputs while some don't."); } } } return inOutList; }
IMPLEMENTATION
true
private List<InferenceInOutSequence> getInputOutputAssets() throws IOException { // TODO: Caching, don't read inputs for every inference List<InferenceInOutSequence> inOutList = getInputOutputAssets(mContext, mInputOutputAssets, mInputOutputDatasets);
private List<InferenceInOutSequence> getInputOutputAssets() throws IOException { // TODO: Caching, don't read inputs for every inference List<InferenceInOutSequence> inOutList = getInputOutputAssets(mContext, mInputOutputAssets, mInputOutputDatasets); Boolean lastGolden = null; for (InferenceInOutSequence sequence : inOutList) { mHasGoldenOutputs = sequence.hasGoldenOutput(); if (lastGolden == null) { lastGolden = mHasGoldenOutputs; } else { if (lastGolden != mHasGoldenOutputs) { throw new IllegalArgumentException(
private List<InferenceInOutSequence> getInputOutputAssets() throws IOException { // TODO: Caching, don't read inputs for every inference List<InferenceInOutSequence> inOutList = getInputOutputAssets(mContext, mInputOutputAssets, mInputOutputDatasets); Boolean lastGolden = null; for (InferenceInOutSequence sequence : inOutList) { mHasGoldenOutputs = sequence.hasGoldenOutput(); if (lastGolden == null) { lastGolden = mHasGoldenOutputs; } else { if (lastGolden != mHasGoldenOutputs) { throw new IllegalArgumentException( "Some inputs for " + mModelName + " have outputs while some don't."); } } } return inOutList; }
16,874
0
// TODO: Caching, don't read inputs for every inference
public static List<InferenceInOutSequence> getInputOutputAssets(Context context, InferenceInOutSequence.FromAssets[] inputOutputAssets, InferenceInOutSequence.FromDataset[] inputOutputDatasets) throws IOException { // TODO: Caching, don't read inputs for every inference List<InferenceInOutSequence> inOutList = new ArrayList<>(); if (inputOutputAssets != null) { for (InferenceInOutSequence.FromAssets ioAsset : inputOutputAssets) { inOutList.add(ioAsset.readAssets(context.getAssets())); } } if (inputOutputDatasets != null) { for (InferenceInOutSequence.FromDataset dataset : inputOutputDatasets) { inOutList.addAll(dataset.readDataset(context.getAssets(), context.getCacheDir())); } } return inOutList; }
IMPLEMENTATION
true
InferenceInOutSequence.FromAssets[] inputOutputAssets, InferenceInOutSequence.FromDataset[] inputOutputDatasets) throws IOException { // TODO: Caching, don't read inputs for every inference List<InferenceInOutSequence> inOutList = new ArrayList<>(); if (inputOutputAssets != null) {
public static List<InferenceInOutSequence> getInputOutputAssets(Context context, InferenceInOutSequence.FromAssets[] inputOutputAssets, InferenceInOutSequence.FromDataset[] inputOutputDatasets) throws IOException { // TODO: Caching, don't read inputs for every inference List<InferenceInOutSequence> inOutList = new ArrayList<>(); if (inputOutputAssets != null) { for (InferenceInOutSequence.FromAssets ioAsset : inputOutputAssets) { inOutList.add(ioAsset.readAssets(context.getAssets())); } } if (inputOutputDatasets != null) { for (InferenceInOutSequence.FromDataset dataset : inputOutputDatasets) { inOutList.addAll(dataset.readDataset(context.getAssets(), context.getCacheDir())); }
public static List<InferenceInOutSequence> getInputOutputAssets(Context context, InferenceInOutSequence.FromAssets[] inputOutputAssets, InferenceInOutSequence.FromDataset[] inputOutputDatasets) throws IOException { // TODO: Caching, don't read inputs for every inference List<InferenceInOutSequence> inOutList = new ArrayList<>(); if (inputOutputAssets != null) { for (InferenceInOutSequence.FromAssets ioAsset : inputOutputAssets) { inOutList.add(ioAsset.readAssets(context.getAssets())); } } if (inputOutputDatasets != null) { for (InferenceInOutSequence.FromDataset dataset : inputOutputDatasets) { inOutList.addAll(dataset.readDataset(context.getAssets(), context.getCacheDir())); } } return inOutList; }
33,261
0
// sampler samples (e.g. http request)
@Test public void testJMeterJtlFileWithTransactionsAndTransactionsBug() throws Exception { String[] runArgs = { "--report.dir", temporaryFolder.getRoot().getPath(), "jmeter", "--report-logline-type", "transaction", "-gt", "-gh", "-gr", "-gp", "-group-by-http-status", "src/test/resources/jmeter/result_with_url_and_sample_transaction_lines_with_bug.jtl" }; String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0")); }
NONSATD
true
String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1"));
"transaction", "-gt", "-gh", "-gr", "-gp", "-group-by-http-status", "src/test/resources/jmeter/result_with_url_and_sample_transaction_lines_with_bug.jtl" }; String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0")); }
@Test public void testJMeterJtlFileWithTransactionsAndTransactionsBug() throws Exception { String[] runArgs = { "--report.dir", temporaryFolder.getRoot().getPath(), "jmeter", "--report-logline-type", "transaction", "-gt", "-gh", "-gr", "-gp", "-group-by-http-status", "src/test/resources/jmeter/result_with_url_and_sample_transaction_lines_with_bug.jtl" }; String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0")); }
33,261
1
// transaction controller samples
@Test public void testJMeterJtlFileWithTransactionsAndTransactionsBug() throws Exception { String[] runArgs = { "--report.dir", temporaryFolder.getRoot().getPath(), "jmeter", "--report-logline-type", "transaction", "-gt", "-gh", "-gr", "-gp", "-group-by-http-status", "src/test/resources/jmeter/result_with_url_and_sample_transaction_lines_with_bug.jtl" }; String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0")); }
NONSATD
true
assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1"));
"-gr", "-gp", "-group-by-http-status", "src/test/resources/jmeter/result_with_url_and_sample_transaction_lines_with_bug.jtl" }; String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0")); }
@Test public void testJMeterJtlFileWithTransactionsAndTransactionsBug() throws Exception { String[] runArgs = { "--report.dir", temporaryFolder.getRoot().getPath(), "jmeter", "--report-logline-type", "transaction", "-gt", "-gh", "-gr", "-gp", "-group-by-http-status", "src/test/resources/jmeter/result_with_url_and_sample_transaction_lines_with_bug.jtl" }; String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0")); }
33,261
2
// buggy transaction controller samples, are classified as transactions because URL column is available
@Test public void testJMeterJtlFileWithTransactionsAndTransactionsBug() throws Exception { String[] runArgs = { "--report.dir", temporaryFolder.getRoot().getPath(), "jmeter", "--report-logline-type", "transaction", "-gt", "-gh", "-gr", "-gp", "-group-by-http-status", "src/test/resources/jmeter/result_with_url_and_sample_transaction_lines_with_bug.jtl" }; String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0")); }
NONSATD
true
assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0"));
"src/test/resources/jmeter/result_with_url_and_sample_transaction_lines_with_bug.jtl" }; String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0")); }
"--report.dir", temporaryFolder.getRoot().getPath(), "jmeter", "--report-logline-type", "transaction", "-gt", "-gh", "-gr", "-gp", "-group-by-http-status", "src/test/resources/jmeter/result_with_url_and_sample_transaction_lines_with_bug.jtl" }; String result = LogRaterRunTestUtil.getOutputFromLogRater(runArgs); System.out.printf("[%s]%n", result); // sampler samples (e.g. http request) assertFalse("Contains 1 GET Jaw Kat", result.contains("GET Jaw Kat,200,1")); assertFalse("Contains 1 GET Jaw Yaw", result.contains("GET Jaw Yaw,200,1")); // transaction controller samples assertTrue("Contains 1 cog", result.contains("cog,200,1")); assertTrue("Contains 1 som", result.contains("som,200,1")); // buggy transaction controller samples, are classified as transactions because URL column is available assertTrue("Contains 3 ane transactions", result.contains("ane,204,3")); assertTrue("The files contain 5 lines of which 0 failure lines.", result.contains("total-counter-success-total,5,0")); }
33,268
0
// fetch custom attributes
@Override public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) { return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in UserIdentity id = identities.iterator().next(); CustomProfile profile = extract(mergeAttributes(userAttributes, id.getAttributes())); return profile; }
NONSATD
true
@Override public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac."))
@Override public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) { return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in
@Override public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) { return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in UserIdentity id = identities.iterator().next(); CustomProfile profile = extract(mergeAttributes(userAttributes, id.getAttributes())); return profile; }
33,268
1
// fetch identities
@Override public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) { return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in UserIdentity id = identities.iterator().next(); CustomProfile profile = extract(mergeAttributes(userAttributes, id.getAttributes())); return profile; }
NONSATD
true
.filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) {
@Override public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) { return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in UserIdentity id = identities.iterator().next(); CustomProfile profile = extract(mergeAttributes(userAttributes, id.getAttributes())); return profile; }
@Override public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) { return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in UserIdentity id = identities.iterator().next(); CustomProfile profile = extract(mergeAttributes(userAttributes, id.getAttributes())); return profile; }
33,268
2
// TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in
@Override public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) { return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in UserIdentity id = identities.iterator().next(); CustomProfile profile = extract(mergeAttributes(userAttributes, id.getAttributes())); return profile; }
DESIGN
true
return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in UserIdentity id = identities.iterator().next(); CustomProfile profile = extract(mergeAttributes(userAttributes, id.getAttributes()));
public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) { return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in UserIdentity id = identities.iterator().next(); CustomProfile profile = extract(mergeAttributes(userAttributes, id.getAttributes())); return profile; }
@Override public CustomProfile extractUserProfile(User user) throws InvalidDefinitionException { // fetch custom attributes List<UserAttributes> userAttributes = user.getAttributes().stream() .filter(ua -> !ua.getIdentifier().startsWith("aac.")) .collect(Collectors.toList()); // fetch identities Collection<UserIdentity> identities = user.getIdentities(); if (identities.isEmpty()) { return extract(userAttributes); } // TODO decide how to merge identities into a single profile // for now get first identity, should be last logged in UserIdentity id = identities.iterator().next(); CustomProfile profile = extract(mergeAttributes(userAttributes, id.getAttributes())); return profile; }
16,885
0
/** GETTER * TODO: Write general description for this method */
@JsonGetter("limit") public String getLimit ( ) { return this.limit; }
DOCUMENTATION
true
@JsonGetter("limit") public String getLimit ( ) { return this.limit; }
@JsonGetter("limit") public String getLimit ( ) { return this.limit; }
@JsonGetter("limit") public String getLimit ( ) { return this.limit; }
25,078
0
// import the image data into 1D arrays : TO DO
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
IMPLEMENTATION
true
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData());
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2];
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d();
25,078
1
// create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
NONSATD
true
buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) {
buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null;
int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z;
25,078
2
// main algorithm // 1. define partial voume for each layer, each voxel
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
NONSATD
true
} } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) {
int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel?
intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z;
25,078
3
// 2. build and invert the GLM for each profile / voxel?
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
NONSATD
true
} } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz);
// 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z;
ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx);
25,078
4
// get the next non-zero value
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
NONSATD
true
int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location
for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm);
} // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } }
25,078
5
// build a weighting function based on distance to the original location
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
NONSATD
true
// get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) {
if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp);
float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName();
25,078
6
// invert the linear model
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
NONSATD
true
data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data);
for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } }
float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual);
25,078
7
// output
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
NONSATD
true
} } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping);
Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual");
idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
16,886
0
/** SETTER * TODO: Write general description for this method */
@JsonSetter("limit") public void setLimit (String value) { this.limit = value; }
DOCUMENTATION
true
@JsonSetter("limit") public void setLimit (String value) { this.limit = value; }
@JsonSetter("limit") public void setLimit (String value) { this.limit = value; }
@JsonSetter("limit") public void setLimit (String value) { this.limit = value; }
16,887
0
/** GETTER * TODO: Write general description for this method */
@JsonGetter("offset") public String getOffset ( ) { return this.offset; }
DOCUMENTATION
true
@JsonGetter("offset") public String getOffset ( ) { return this.offset; }
@JsonGetter("offset") public String getOffset ( ) { return this.offset; }
@JsonGetter("offset") public String getOffset ( ) { return this.offset; }
16,888
0
/** SETTER * TODO: Write general description for this method */
@JsonSetter("offset") public void setOffset (String value) { this.offset = value; }
DOCUMENTATION
true
@JsonSetter("offset") public void setOffset (String value) { this.offset = value; }
@JsonSetter("offset") public void setOffset (String value) { this.offset = value; }
@JsonSetter("offset") public void setOffset (String value) { this.offset = value; }
16,892
0
/** * @param pathToMergeSchema * String path to the MergeSchema to be used on this document. Note: Will in future builds * replaced by pathToMergeSchemas which leads to a directory containing MergeSchemas for every * used namespace. * * If <b>null</b> the default MergeSchemas will be used * @author sholzer (12.03.2015) * @return a LeXeMerger */
public static LeXeMerger build(String pathToMergeSchema) { if (builder == null) { builder = new GenericLexemeBuilder(); } return builder.build(pathToMergeSchema); }
NONSATD
true
public static LeXeMerger build(String pathToMergeSchema) { if (builder == null) { builder = new GenericLexemeBuilder(); } return builder.build(pathToMergeSchema); }
public static LeXeMerger build(String pathToMergeSchema) { if (builder == null) { builder = new GenericLexemeBuilder(); } return builder.build(pathToMergeSchema); }
public static LeXeMerger build(String pathToMergeSchema) { if (builder == null) { builder = new GenericLexemeBuilder(); } return builder.build(pathToMergeSchema); }
16,896
0
// we assume this is given by the user
public TypeUse getTypeUse(XSSimpleType owner) { if(typeUse!=null) return typeUse; JCodeModel cm = getCodeModel(); JDefinedClass a; try { a = cm._class(adapter); a.hide(); // we assume this is given by the user a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow( cm.ref(type))); } catch (JClassAlreadyExistsException e) { a = e.getExistingClass(); } // TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that. typeUse = TypeUseFactory.adapt( CBuiltinLeafInfo.STRING, new CAdapter(a)); return typeUse; }
NONSATD
true
try { a = cm._class(adapter); a.hide(); // we assume this is given by the user a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow( cm.ref(type)));
public TypeUse getTypeUse(XSSimpleType owner) { if(typeUse!=null) return typeUse; JCodeModel cm = getCodeModel(); JDefinedClass a; try { a = cm._class(adapter); a.hide(); // we assume this is given by the user a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow( cm.ref(type))); } catch (JClassAlreadyExistsException e) { a = e.getExistingClass(); } // TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that. typeUse = TypeUseFactory.adapt( CBuiltinLeafInfo.STRING, new CAdapter(a));
public TypeUse getTypeUse(XSSimpleType owner) { if(typeUse!=null) return typeUse; JCodeModel cm = getCodeModel(); JDefinedClass a; try { a = cm._class(adapter); a.hide(); // we assume this is given by the user a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow( cm.ref(type))); } catch (JClassAlreadyExistsException e) { a = e.getExistingClass(); } // TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that. typeUse = TypeUseFactory.adapt( CBuiltinLeafInfo.STRING, new CAdapter(a)); return typeUse; }
16,896
1
// TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that.
public TypeUse getTypeUse(XSSimpleType owner) { if(typeUse!=null) return typeUse; JCodeModel cm = getCodeModel(); JDefinedClass a; try { a = cm._class(adapter); a.hide(); // we assume this is given by the user a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow( cm.ref(type))); } catch (JClassAlreadyExistsException e) { a = e.getExistingClass(); } // TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that. typeUse = TypeUseFactory.adapt( CBuiltinLeafInfo.STRING, new CAdapter(a)); return typeUse; }
DESIGN
true
a = e.getExistingClass(); } // TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that. typeUse = TypeUseFactory.adapt( CBuiltinLeafInfo.STRING,
JCodeModel cm = getCodeModel(); JDefinedClass a; try { a = cm._class(adapter); a.hide(); // we assume this is given by the user a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow( cm.ref(type))); } catch (JClassAlreadyExistsException e) { a = e.getExistingClass(); } // TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that. typeUse = TypeUseFactory.adapt( CBuiltinLeafInfo.STRING, new CAdapter(a)); return typeUse; }
public TypeUse getTypeUse(XSSimpleType owner) { if(typeUse!=null) return typeUse; JCodeModel cm = getCodeModel(); JDefinedClass a; try { a = cm._class(adapter); a.hide(); // we assume this is given by the user a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow( cm.ref(type))); } catch (JClassAlreadyExistsException e) { a = e.getExistingClass(); } // TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that. typeUse = TypeUseFactory.adapt( CBuiltinLeafInfo.STRING, new CAdapter(a)); return typeUse; }
8,710
0
/* (non-Javadoc) * @see org.apereo.portal.groups.IEntityGroupStore#searchForGroups(java.lang.String, int, java.lang.Class) */
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query); } return groups.toArray(new EntityIdentifier[groups.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + leaftype.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } }
NONSATD
true
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query); } return groups.toArray(new EntityIdentifier[groups.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + leaftype.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } }
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query); } return groups.toArray(new EntityIdentifier[groups.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + leaftype.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } }
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query); } return groups.toArray(new EntityIdentifier[groups.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + leaftype.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } }
8,710
1
// only search for groups
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query); } return groups.toArray(new EntityIdentifier[groups.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + leaftype.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } }
NONSATD
true
final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {};
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query);
8,710
2
// result groups.
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query); } return groups.toArray(new EntityIdentifier[groups.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + leaftype.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } }
NONSATD
true
LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try {
final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else {
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName());
8,710
3
// TODO: searches need to be performed against the group display // name rather than the group key
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query); } return groups.toArray(new EntityIdentifier[groups.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + leaftype.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } }
DESIGN
true
List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter();
// only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter);
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } }
8,710
4
// is this an exact search or fuzzy
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query); } return groups.toArray(new EntityIdentifier[groups.size()]); } catch (Exception e) { LOGGER.warn( "Exception while attempting to retrieve " + "search results for query " + query + " and entity type " + leaftype.getCanonicalName() + " : " + e.getMessage()); return new EntityIdentifier[] {}; } }
NONSATD
true
GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT");
if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) {
public EntityIdentifier[] searchForGroups( final String query, final SearchMethod method, @SuppressWarnings("unchecked") final Class leaftype) { // only search for groups if (leaftype != IPerson.class) { return new EntityIdentifier[] {}; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Searching Grouper for groups matching query: " + query); } // result groups. List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>(); try { // TODO: searches need to be performed against the group display // name rather than the group key GcFindGroups groupSearch = new GcFindGroups(); WsQueryFilter filter = new WsQueryFilter(); // is this an exact search or fuzzy if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) { filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT"); } else { filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE"); } filter.setGroupName(query); groupSearch.assignQueryFilter(filter); WsFindGroupsResults results = groupSearch.execute(); if (results != null && results.getGroupResults() != null) { for (WsGroup g : results.getGroupResults()) { if (validKey(g.getName())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved group: " + g.getName()); } groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class)); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Returning " + groups.size() + " results for query " + query);
33,286
0
// Validate client version
@Override public void handleIncoming(SoeUdpConnection connection, ClientIdMsg message) throws Exception { // Validate client version if (!message.getClientVersion().equals(requiredClientVersion)) { ErrorMessage error = new ErrorMessage("Login Error", "The client you are attempting to connect with does not match that required by the server.", false); connection.sendMessage(error); logger.info("Sending Client Error"); return; } SoeAccount account = accountService.validateSession(message.getToken()); if (account == null) { ErrorMessage error = new ErrorMessage("Error", "Invalid Session", false); connection.sendMessage(error); logger.info("Invalid Session: " + message.getToken()); return; } connection.setAccountId(account.getId()); connection.setAccountUsername(account.getUsername()); connection.addRole(ConnectionRole.AUTHENTICATED); // TODO: Actually implement permissions ClientPermissionsMessage cpm = new ClientPermissionsMessage(true, true, true, true); connection.sendMessage(cpm); }
NONSATD
true
@Override public void handleIncoming(SoeUdpConnection connection, ClientIdMsg message) throws Exception { // Validate client version if (!message.getClientVersion().equals(requiredClientVersion)) { ErrorMessage error = new ErrorMessage("Login Error", "The client you are attempting to connect with does not match that required by the server.", false);
@Override public void handleIncoming(SoeUdpConnection connection, ClientIdMsg message) throws Exception { // Validate client version if (!message.getClientVersion().equals(requiredClientVersion)) { ErrorMessage error = new ErrorMessage("Login Error", "The client you are attempting to connect with does not match that required by the server.", false); connection.sendMessage(error); logger.info("Sending Client Error"); return; } SoeAccount account = accountService.validateSession(message.getToken()); if (account == null) { ErrorMessage error = new ErrorMessage("Error", "Invalid Session", false); connection.sendMessage(error);
@Override public void handleIncoming(SoeUdpConnection connection, ClientIdMsg message) throws Exception { // Validate client version if (!message.getClientVersion().equals(requiredClientVersion)) { ErrorMessage error = new ErrorMessage("Login Error", "The client you are attempting to connect with does not match that required by the server.", false); connection.sendMessage(error); logger.info("Sending Client Error"); return; } SoeAccount account = accountService.validateSession(message.getToken()); if (account == null) { ErrorMessage error = new ErrorMessage("Error", "Invalid Session", false); connection.sendMessage(error); logger.info("Invalid Session: " + message.getToken()); return; } connection.setAccountId(account.getId()); connection.setAccountUsername(account.getUsername()); connection.addRole(ConnectionRole.AUTHENTICATED); // TODO: Actually implement permissions ClientPermissionsMessage cpm = new ClientPermissionsMessage(true, true, true, true); connection.sendMessage(cpm); }
33,286
1
// TODO: Actually implement permissions
@Override public void handleIncoming(SoeUdpConnection connection, ClientIdMsg message) throws Exception { // Validate client version if (!message.getClientVersion().equals(requiredClientVersion)) { ErrorMessage error = new ErrorMessage("Login Error", "The client you are attempting to connect with does not match that required by the server.", false); connection.sendMessage(error); logger.info("Sending Client Error"); return; } SoeAccount account = accountService.validateSession(message.getToken()); if (account == null) { ErrorMessage error = new ErrorMessage("Error", "Invalid Session", false); connection.sendMessage(error); logger.info("Invalid Session: " + message.getToken()); return; } connection.setAccountId(account.getId()); connection.setAccountUsername(account.getUsername()); connection.addRole(ConnectionRole.AUTHENTICATED); // TODO: Actually implement permissions ClientPermissionsMessage cpm = new ClientPermissionsMessage(true, true, true, true); connection.sendMessage(cpm); }
IMPLEMENTATION
true
connection.setAccountUsername(account.getUsername()); connection.addRole(ConnectionRole.AUTHENTICATED); // TODO: Actually implement permissions ClientPermissionsMessage cpm = new ClientPermissionsMessage(true, true, true, true); connection.sendMessage(cpm);
SoeAccount account = accountService.validateSession(message.getToken()); if (account == null) { ErrorMessage error = new ErrorMessage("Error", "Invalid Session", false); connection.sendMessage(error); logger.info("Invalid Session: " + message.getToken()); return; } connection.setAccountId(account.getId()); connection.setAccountUsername(account.getUsername()); connection.addRole(ConnectionRole.AUTHENTICATED); // TODO: Actually implement permissions ClientPermissionsMessage cpm = new ClientPermissionsMessage(true, true, true, true); connection.sendMessage(cpm); }
@Override public void handleIncoming(SoeUdpConnection connection, ClientIdMsg message) throws Exception { // Validate client version if (!message.getClientVersion().equals(requiredClientVersion)) { ErrorMessage error = new ErrorMessage("Login Error", "The client you are attempting to connect with does not match that required by the server.", false); connection.sendMessage(error); logger.info("Sending Client Error"); return; } SoeAccount account = accountService.validateSession(message.getToken()); if (account == null) { ErrorMessage error = new ErrorMessage("Error", "Invalid Session", false); connection.sendMessage(error); logger.info("Invalid Session: " + message.getToken()); return; } connection.setAccountId(account.getId()); connection.setAccountUsername(account.getUsername()); connection.addRole(ConnectionRole.AUTHENTICATED); // TODO: Actually implement permissions ClientPermissionsMessage cpm = new ClientPermissionsMessage(true, true, true, true); connection.sendMessage(cpm); }
33,288
0
// if there is no pre-existing task, create a new one
@Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_CANCEL: _downTime.set(0); break; case MotionEvent.ACTION_DOWN: _downTime.set(System.currentTimeMillis()); _downX = event.getX(); _downY = event.getY(); if(_longClickTimer == null){ // if there is no pre-existing task, create a new one _longClickTimer = new AsyncTask<Void, Void, Boolean>(){ @Override protected Boolean doInBackground(Void... params) { try{ for(long i=0;i<Definitions.THRESHOLD_LONG_CLICK_MAX_DURATION;i+=INTERVAL_LONG_CLICK_CHECK){ Thread.sleep(INTERVAL_LONG_CLICK_CHECK); long downTime = _downTime.get(); if(downTime > 0 && System.currentTimeMillis()-downTime > Definitions.THRESHOLD_LONG_CLICK_MIN_DURATION){ return true; } } }catch(InterruptedException ex){ LogUtils.warn(CLASS_NAME, "doInBackground", ex.toString()); } return false; } @Override protected void onPostExecute(Boolean result) { if(result){ centerChart(); _downTime.set(0); } _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
NONSATD
true
_downX = event.getX(); _downY = event.getY(); if(_longClickTimer == null){ // if there is no pre-existing task, create a new one _longClickTimer = new AsyncTask<Void, Void, Boolean>(){ @Override
@Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_CANCEL: _downTime.set(0); break; case MotionEvent.ACTION_DOWN: _downTime.set(System.currentTimeMillis()); _downX = event.getX(); _downY = event.getY(); if(_longClickTimer == null){ // if there is no pre-existing task, create a new one _longClickTimer = new AsyncTask<Void, Void, Boolean>(){ @Override protected Boolean doInBackground(Void... params) { try{ for(long i=0;i<Definitions.THRESHOLD_LONG_CLICK_MAX_DURATION;i+=INTERVAL_LONG_CLICK_CHECK){ Thread.sleep(INTERVAL_LONG_CLICK_CHECK); long downTime = _downTime.get(); if(downTime > 0 && System.currentTimeMillis()-downTime > Definitions.THRESHOLD_LONG_CLICK_MIN_DURATION){ return true; }
@Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_CANCEL: _downTime.set(0); break; case MotionEvent.ACTION_DOWN: _downTime.set(System.currentTimeMillis()); _downX = event.getX(); _downY = event.getY(); if(_longClickTimer == null){ // if there is no pre-existing task, create a new one _longClickTimer = new AsyncTask<Void, Void, Boolean>(){ @Override protected Boolean doInBackground(Void... params) { try{ for(long i=0;i<Definitions.THRESHOLD_LONG_CLICK_MAX_DURATION;i+=INTERVAL_LONG_CLICK_CHECK){ Thread.sleep(INTERVAL_LONG_CLICK_CHECK); long downTime = _downTime.get(); if(downTime > 0 && System.currentTimeMillis()-downTime > Definitions.THRESHOLD_LONG_CLICK_MIN_DURATION){ return true; } } }catch(InterruptedException ex){ LogUtils.warn(CLASS_NAME, "doInBackground", ex.toString()); } return false; } @Override protected void onPostExecute(Boolean result) { if(result){ centerChart();
33,288
1
// new asyncTask
@Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_CANCEL: _downTime.set(0); break; case MotionEvent.ACTION_DOWN: _downTime.set(System.currentTimeMillis()); _downX = event.getX(); _downY = event.getY(); if(_longClickTimer == null){ // if there is no pre-existing task, create a new one _longClickTimer = new AsyncTask<Void, Void, Boolean>(){ @Override protected Boolean doInBackground(Void... params) { try{ for(long i=0;i<Definitions.THRESHOLD_LONG_CLICK_MAX_DURATION;i+=INTERVAL_LONG_CLICK_CHECK){ Thread.sleep(INTERVAL_LONG_CLICK_CHECK); long downTime = _downTime.get(); if(downTime > 0 && System.currentTimeMillis()-downTime > Definitions.THRESHOLD_LONG_CLICK_MIN_DURATION){ return true; } } }catch(InterruptedException ex){ LogUtils.warn(CLASS_NAME, "doInBackground", ex.toString()); } return false; } @Override protected void onPostExecute(Boolean result) { if(result){ centerChart(); _downTime.set(0); } _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
NONSATD
true
_longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); }
return false; } @Override protected void onPostExecute(Boolean result) { if(result){ centerChart(); _downTime.set(0); } _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint();
for(long i=0;i<Definitions.THRESHOLD_LONG_CLICK_MAX_DURATION;i+=INTERVAL_LONG_CLICK_CHECK){ Thread.sleep(INTERVAL_LONG_CLICK_CHECK); long downTime = _downTime.get(); if(downTime > 0 && System.currentTimeMillis()-downTime > Definitions.THRESHOLD_LONG_CLICK_MIN_DURATION){ return true; } } }catch(InterruptedException ex){ LogUtils.warn(CLASS_NAME, "doInBackground", ex.toString()); } return false; } @Override protected void onPostExecute(Boolean result) { if(result){ centerChart(); _downTime.set(0); } _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{
33,288
2
// if there was no selection or this is not the first series (point values)
@Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_CANCEL: _downTime.set(0); break; case MotionEvent.ACTION_DOWN: _downTime.set(System.currentTimeMillis()); _downX = event.getX(); _downY = event.getY(); if(_longClickTimer == null){ // if there is no pre-existing task, create a new one _longClickTimer = new AsyncTask<Void, Void, Boolean>(){ @Override protected Boolean doInBackground(Void... params) { try{ for(long i=0;i<Definitions.THRESHOLD_LONG_CLICK_MAX_DURATION;i+=INTERVAL_LONG_CLICK_CHECK){ Thread.sleep(INTERVAL_LONG_CLICK_CHECK); long downTime = _downTime.get(); if(downTime > 0 && System.currentTimeMillis()-downTime > Definitions.THRESHOLD_LONG_CLICK_MIN_DURATION){ return true; } } }catch(InterruptedException ex){ LogUtils.warn(CLASS_NAME, "doInBackground", ex.toString()); } return false; } @Override protected void onPostExecute(Boolean result) { if(result){ centerChart(); _downTime.set(0); } _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
NONSATD
true
if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{
_longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex();
} @Override protected void onPostExecute(Boolean result) { if(result){ centerChart(); _downTime.set(0); } _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls
33,288
3
//TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values
@Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_CANCEL: _downTime.set(0); break; case MotionEvent.ACTION_DOWN: _downTime.set(System.currentTimeMillis()); _downX = event.getX(); _downY = event.getY(); if(_longClickTimer == null){ // if there is no pre-existing task, create a new one _longClickTimer = new AsyncTask<Void, Void, Boolean>(){ @Override protected Boolean doInBackground(Void... params) { try{ for(long i=0;i<Definitions.THRESHOLD_LONG_CLICK_MAX_DURATION;i+=INTERVAL_LONG_CLICK_CHECK){ Thread.sleep(INTERVAL_LONG_CLICK_CHECK); long downTime = _downTime.get(); if(downTime > 0 && System.currentTimeMillis()-downTime > Definitions.THRESHOLD_LONG_CLICK_MIN_DURATION){ return true; } } }catch(InterruptedException ex){ LogUtils.warn(CLASS_NAME, "doInBackground", ex.toString()); } return false; } @Override protected void onPostExecute(Boolean result) { if(result){ centerChart(); _downTime.set(0); } _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
DEFECT
true
int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex();
case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break;
} _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
33,288
4
// ignore everything else
@Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_CANCEL: _downTime.set(0); break; case MotionEvent.ACTION_DOWN: _downTime.set(System.currentTimeMillis()); _downX = event.getX(); _downY = event.getY(); if(_longClickTimer == null){ // if there is no pre-existing task, create a new one _longClickTimer = new AsyncTask<Void, Void, Boolean>(){ @Override protected Boolean doInBackground(Void... params) { try{ for(long i=0;i<Definitions.THRESHOLD_LONG_CLICK_MAX_DURATION;i+=INTERVAL_LONG_CLICK_CHECK){ Thread.sleep(INTERVAL_LONG_CLICK_CHECK); long downTime = _downTime.get(); if(downTime > 0 && System.currentTimeMillis()-downTime > Definitions.THRESHOLD_LONG_CLICK_MIN_DURATION){ return true; } } }catch(InterruptedException ex){ LogUtils.warn(CLASS_NAME, "doInBackground", ex.toString()); } return false; } @Override protected void onPostExecute(Boolean result) { if(result){ centerChart(); _downTime.set(0); } _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
NONSATD
true
break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls
index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
33,288
5
// always return false so that we do not interfere with the graph pan/zoom controls
@Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_CANCEL: _downTime.set(0); break; case MotionEvent.ACTION_DOWN: _downTime.set(System.currentTimeMillis()); _downX = event.getX(); _downY = event.getY(); if(_longClickTimer == null){ // if there is no pre-existing task, create a new one _longClickTimer = new AsyncTask<Void, Void, Boolean>(){ @Override protected Boolean doInBackground(Void... params) { try{ for(long i=0;i<Definitions.THRESHOLD_LONG_CLICK_MAX_DURATION;i+=INTERVAL_LONG_CLICK_CHECK){ Thread.sleep(INTERVAL_LONG_CLICK_CHECK); long downTime = _downTime.get(); if(downTime > 0 && System.currentTimeMillis()-downTime > Definitions.THRESHOLD_LONG_CLICK_MIN_DURATION){ return true; } } }catch(InterruptedException ex){ LogUtils.warn(CLASS_NAME, "doInBackground", ex.toString()); } return false; } @Override protected void onPostExecute(Boolean result) { if(result){ centerChart(); _downTime.set(0); } _longClickTimer = null; } }; // new asyncTask _longClickTimer.execute(); } break; case MotionEvent.ACTION_MOVE: checkForMovement(event); break; case MotionEvent.ACTION_UP: long downTime = _downTime.getAndSet(0); if(downTime != 0 && (System.currentTimeMillis()-downTime) < Definitions.THRESHOLD_CLICK_MAX_DURATION && !checkForMovement(event)){ SeriesSelection selection = _viewChart.getCurrentSeriesAndPoint(); if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
NONSATD
true
break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
if(selection == null || selection.getSeriesIndex() != 0){ // if there was no selection or this is not the first series (point values) LogUtils.debug(CLASS_NAME, "onTouch", "No usable selection."); }else{ List<GaugeValue> values = _currentGauge.getValues(); int valueCount = values.size(); int index = 0; //TODO: this will break if the chart shows something else than the last getMaxGraphPoints() of values if(valueCount - _settings.getMaxGraphPoints() > 0){ index = valueCount - _settings.getMaxGraphPoints() + selection.getPointIndex(); }else{ index = selection.getPointIndex(); } _currentValue = _currentGauge.getValues().get(index); (new GaugeValueDialog()).show(GraphActivity.this.getSupportFragmentManager(), GaugeValueDialog.TAG); } } break; default: break; // ignore everything else } return false; // always return false so that we do not interfere with the graph pan/zoom controls }
521
0
// Plain test
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)");
521
1
// numeric field access
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access
int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)");
521
2
// string field access
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List
.put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")]
521
3
// List
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges
.build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases:
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')");
521
4
// Ranges
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps
client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()");
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" +
521
5
// Maps
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times
// Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)");
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")]
521
6
// Times
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections
// numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)");
int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")]
521
7
// GroovyCollections
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases:
// string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")]
.put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not.
521
8
// Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")]
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")]
// List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")]
.build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) {
521
9
// AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")]
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." +
assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")");
client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()");
521
10
// AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")]
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
"\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')");
// GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not.
// string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
521
11
// AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")]
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")");
// AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) {
assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
521
12
// AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")]
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")]
assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")]
internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) {
521
13
// AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")]
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not.
"\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
// Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
521
14
// test a directory we normally have access to, but the groovy script does not.
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :)
// AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
// GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
521
15
// TODO: figure out the necessary escaping for windows paths here :)
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
DESIGN
true
// test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read")
assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
// Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
521
16
// access denied ("java.io.FilePermission" ".../tempDir-00N" "read")
public void testEvilGroovyScripts() throws Exception { int nodes = randomIntBetween(1, 3); Settings nodeSettings = Settings.builder() .put("script.inline", true) .put("script.indexed", true) .build(); internalCluster().startNodesAsync(nodes, nodeSettings).get(); client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get(); client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get(); // Plain test assertSuccess(""); // numeric field access assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }"); // string field access assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }"); // List assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)"); // Ranges assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)"); // Maps assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)"); // Times assertSuccess("def t = Instant.now().getMillis()"); // GroovyCollections assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)"); // Fail cases: // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
NONSATD
true
// TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); }
assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")] assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)"); assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." + "\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)"); assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)"); // AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")] assertFailure("Eval.me('2 + 2')"); assertFailure("Eval.x(5, 'x + 2')"); // AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")] assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" + " f.setAccessible(true); f.get(\"fastTime\")"); // AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")] assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")"); // AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")] assertFailure("t = new Thread({ println 3 });"); // test a directory we normally have access to, but the groovy script does not. Path dir = createTempDir(); // TODO: figure out the necessary escaping for windows paths here :) if (!Constants.WINDOWS) { // access denied ("java.io.FilePermission" ".../tempDir-00N" "read") assertFailure("new File(\"" + dir + "\").exists()"); } }
33,289
0
/** * Runs the tests and reports results. */
@Override public void run(RunNotifier runNotifier) { runNotifier.fireTestRunStarted(topLevelDesc); for (SelfTest selfTest : selfTests) { for (SelfTestCase selfTestCase : selfTest.getSelfTestCases()) { Description currentDesc = createTestCaseDescription(selfTestCase); runNotifier.fireTestStarted(currentDesc); try { selfTest.runTest(selfTestCase); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | AssertionError e) { runNotifier.fireTestFailure(new Failure(currentDesc, e)); } runNotifier.fireTestFinished(currentDesc); } } // TODO: Fill in the Result instance appropriately. runNotifier.fireTestRunFinished(new Result()); }
NONSATD
true
@Override public void run(RunNotifier runNotifier) { runNotifier.fireTestRunStarted(topLevelDesc); for (SelfTest selfTest : selfTests) { for (SelfTestCase selfTestCase : selfTest.getSelfTestCases()) { Description currentDesc = createTestCaseDescription(selfTestCase); runNotifier.fireTestStarted(currentDesc); try { selfTest.runTest(selfTestCase); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | AssertionError e) { runNotifier.fireTestFailure(new Failure(currentDesc, e)); } runNotifier.fireTestFinished(currentDesc); } } // TODO: Fill in the Result instance appropriately. runNotifier.fireTestRunFinished(new Result()); }
@Override public void run(RunNotifier runNotifier) { runNotifier.fireTestRunStarted(topLevelDesc); for (SelfTest selfTest : selfTests) { for (SelfTestCase selfTestCase : selfTest.getSelfTestCases()) { Description currentDesc = createTestCaseDescription(selfTestCase); runNotifier.fireTestStarted(currentDesc); try { selfTest.runTest(selfTestCase); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | AssertionError e) { runNotifier.fireTestFailure(new Failure(currentDesc, e)); } runNotifier.fireTestFinished(currentDesc); } } // TODO: Fill in the Result instance appropriately. runNotifier.fireTestRunFinished(new Result()); }
@Override public void run(RunNotifier runNotifier) { runNotifier.fireTestRunStarted(topLevelDesc); for (SelfTest selfTest : selfTests) { for (SelfTestCase selfTestCase : selfTest.getSelfTestCases()) { Description currentDesc = createTestCaseDescription(selfTestCase); runNotifier.fireTestStarted(currentDesc); try { selfTest.runTest(selfTestCase); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | AssertionError e) { runNotifier.fireTestFailure(new Failure(currentDesc, e)); } runNotifier.fireTestFinished(currentDesc); } } // TODO: Fill in the Result instance appropriately. runNotifier.fireTestRunFinished(new Result()); }
33,289
1
// TODO: Fill in the Result instance appropriately.
@Override public void run(RunNotifier runNotifier) { runNotifier.fireTestRunStarted(topLevelDesc); for (SelfTest selfTest : selfTests) { for (SelfTestCase selfTestCase : selfTest.getSelfTestCases()) { Description currentDesc = createTestCaseDescription(selfTestCase); runNotifier.fireTestStarted(currentDesc); try { selfTest.runTest(selfTestCase); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | AssertionError e) { runNotifier.fireTestFailure(new Failure(currentDesc, e)); } runNotifier.fireTestFinished(currentDesc); } } // TODO: Fill in the Result instance appropriately. runNotifier.fireTestRunFinished(new Result()); }
IMPLEMENTATION
true
} } // TODO: Fill in the Result instance appropriately. runNotifier.fireTestRunFinished(new Result()); }
runNotifier.fireTestStarted(currentDesc); try { selfTest.runTest(selfTestCase); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | AssertionError e) { runNotifier.fireTestFailure(new Failure(currentDesc, e)); } runNotifier.fireTestFinished(currentDesc); } } // TODO: Fill in the Result instance appropriately. runNotifier.fireTestRunFinished(new Result()); }
@Override public void run(RunNotifier runNotifier) { runNotifier.fireTestRunStarted(topLevelDesc); for (SelfTest selfTest : selfTests) { for (SelfTestCase selfTestCase : selfTest.getSelfTestCases()) { Description currentDesc = createTestCaseDescription(selfTestCase); runNotifier.fireTestStarted(currentDesc); try { selfTest.runTest(selfTestCase); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | AssertionError e) { runNotifier.fireTestFailure(new Failure(currentDesc, e)); } runNotifier.fireTestFinished(currentDesc); } } // TODO: Fill in the Result instance appropriately. runNotifier.fireTestRunFinished(new Result()); }
25,102
0
// Need a method in the OWL API to get Annotation by URI...
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { // Need a method in the OWL API to get Annotation by URI... final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false); annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
IMPLEMENTATION
true
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { // Need a method in the OWL API to get Annotation by URI... final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false);
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { // Need a method in the OWL API to get Annotation by URI... final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false); annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else {
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { // Need a method in the OWL API to get Annotation by URI... final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false); annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); }
25,102
1
// for all other annotation axioms, just add them as they are
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { // Need a method in the OWL API to get Annotation by URI... final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false); annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
NONSATD
true
inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); }
.getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { // Need a method in the OWL API to get Annotation by URI... final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false); annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
25,102
2
// ensure inScheme is set. we need it, so set to default if missing
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { // Need a method in the OWL API to get Annotation by URI... final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false); annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
NONSATD
true
} }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory.
.map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId));
annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
25,102
3
// This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier.
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { // Need a method in the OWL API to get Annotation by URI... final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false); annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
DESIGN
true
getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":");
// for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
.getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
33,296
0
/* This really shouldn't happen */
private byte[] md5(String data) { try { return this.getMd5Digest().digest(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { /* This really shouldn't happen */ throw new RuntimeException(e); } }
DESIGN
true
return this.getMd5Digest().digest(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { /* This really shouldn't happen */ throw new RuntimeException(e); }
private byte[] md5(String data) { try { return this.getMd5Digest().digest(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { /* This really shouldn't happen */ throw new RuntimeException(e); } }
private byte[] md5(String data) { try { return this.getMd5Digest().digest(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { /* This really shouldn't happen */ throw new RuntimeException(e); } }
25,117
0
// ALM Specific Cleanup
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
NONSATD
true
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED;
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID);
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing }
25,117
1
// Should we wait for the interface to be unregistered?
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
DESIGN
true
_sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) {
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){
25,117
2
// Unregister app interface
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
NONSATD
true
// Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) {
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try {
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); }
25,117
3
// Wait for the app interface to be unregistered
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
NONSATD
true
} } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) {
firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } }
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); }