id int32 0 165k | repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,200 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/model/Policy.java | Policy.removePolicy | public boolean removePolicy(String sec, String ptype, List<String> rule) {
for (int i = 0; i < model.get(sec).get(ptype).policy.size(); i ++) {
List<String> r = model.get(sec).get(ptype).policy.get(i);
if (Util.arrayEquals(rule, r)) {
model.get(sec).get(ptype).policy.remove(i);
return true;
}
}
return false;
} | java | public boolean removePolicy(String sec, String ptype, List<String> rule) {
for (int i = 0; i < model.get(sec).get(ptype).policy.size(); i ++) {
List<String> r = model.get(sec).get(ptype).policy.get(i);
if (Util.arrayEquals(rule, r)) {
model.get(sec).get(ptype).policy.remove(i);
return true;
}
}
return false;
} | [
"public",
"boolean",
"removePolicy",
"(",
"String",
"sec",
",",
"String",
"ptype",
",",
"List",
"<",
"String",
">",
"rule",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"model",
".",
"get",
"(",
"sec",
")",
".",
"get",
"(",
"ptype",
")",
".",
"policy",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"List",
"<",
"String",
">",
"r",
"=",
"model",
".",
"get",
"(",
"sec",
")",
".",
"get",
"(",
"ptype",
")",
".",
"policy",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"Util",
".",
"arrayEquals",
"(",
"rule",
",",
"r",
")",
")",
"{",
"model",
".",
"get",
"(",
"sec",
")",
".",
"get",
"(",
"ptype",
")",
".",
"policy",
".",
"remove",
"(",
"i",
")",
";",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | removePolicy removes a policy rule from the model.
@param sec the section, "p" or "g".
@param ptype the policy type, "p", "p2", .. or "g", "g2", ..
@param rule the policy rule.
@return succeeds or not. | [
"removePolicy",
"removes",
"a",
"policy",
"rule",
"from",
"the",
"model",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L163-L173 |
27,201 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/model/Policy.java | Policy.getValuesForFieldInPolicy | public List<String> getValuesForFieldInPolicy(String sec, String ptype, int fieldIndex) {
List<String> values = new ArrayList<>();
for (List<String> rule : model.get(sec).get(ptype).policy) {
values.add(rule.get(fieldIndex));
}
Util.arrayRemoveDuplicates(values);
return values;
} | java | public List<String> getValuesForFieldInPolicy(String sec, String ptype, int fieldIndex) {
List<String> values = new ArrayList<>();
for (List<String> rule : model.get(sec).get(ptype).policy) {
values.add(rule.get(fieldIndex));
}
Util.arrayRemoveDuplicates(values);
return values;
} | [
"public",
"List",
"<",
"String",
">",
"getValuesForFieldInPolicy",
"(",
"String",
"sec",
",",
"String",
"ptype",
",",
"int",
"fieldIndex",
")",
"{",
"List",
"<",
"String",
">",
"values",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"List",
"<",
"String",
">",
"rule",
":",
"model",
".",
"get",
"(",
"sec",
")",
".",
"get",
"(",
"ptype",
")",
".",
"policy",
")",
"{",
"values",
".",
"add",
"(",
"rule",
".",
"get",
"(",
"fieldIndex",
")",
")",
";",
"}",
"Util",
".",
"arrayRemoveDuplicates",
"(",
"values",
")",
";",
"return",
"values",
";",
"}"
] | getValuesForFieldInPolicy gets all values for a field for all rules in a policy, duplicated values are removed.
@param sec the section, "p" or "g".
@param ptype the policy type, "p", "p2", .. or "g", "g2", ..
@param fieldIndex the policy rule's index.
@return the field values specified by fieldIndex. | [
"getValuesForFieldInPolicy",
"gets",
"all",
"values",
"for",
"a",
"field",
"for",
"all",
"rules",
"in",
"a",
"policy",
"duplicated",
"values",
"are",
"removed",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L218-L228 |
27,202 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/util/Util.java | Util.logPrintf | public static void logPrintf(String format, String... v) {
if (enableLog) {
String tmp = String.format(format, (Object[]) v);
logger.log(Level.INFO, tmp);
}
} | java | public static void logPrintf(String format, String... v) {
if (enableLog) {
String tmp = String.format(format, (Object[]) v);
logger.log(Level.INFO, tmp);
}
} | [
"public",
"static",
"void",
"logPrintf",
"(",
"String",
"format",
",",
"String",
"...",
"v",
")",
"{",
"if",
"(",
"enableLog",
")",
"{",
"String",
"tmp",
"=",
"String",
".",
"format",
"(",
"format",
",",
"(",
"Object",
"[",
"]",
")",
"v",
")",
";",
"logger",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
"tmp",
")",
";",
"}",
"}"
] | logPrintf prints the log with the format.
@param format the format of the log.
@param v the log. | [
"logPrintf",
"prints",
"the",
"log",
"with",
"the",
"format",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/util/Util.java#L47-L52 |
27,203 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/util/Util.java | Util.escapeAssertion | public static String escapeAssertion(String s) {
//Replace the first dot, because the string doesn't start with "m="
// and is not covered by the regex.
if (s.startsWith("r") || s.startsWith("p")) {
s = s.replaceFirst("\\.", "_");
}
String regex = "(\\|| |=|\\)|\\(|&|<|>|,|\\+|-|!|\\*|\\/)(r|p)\\.";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group().replace(".", "_") );
}
m.appendTail(sb);
return sb.toString();
} | java | public static String escapeAssertion(String s) {
//Replace the first dot, because the string doesn't start with "m="
// and is not covered by the regex.
if (s.startsWith("r") || s.startsWith("p")) {
s = s.replaceFirst("\\.", "_");
}
String regex = "(\\|| |=|\\)|\\(|&|<|>|,|\\+|-|!|\\*|\\/)(r|p)\\.";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group().replace(".", "_") );
}
m.appendTail(sb);
return sb.toString();
} | [
"public",
"static",
"String",
"escapeAssertion",
"(",
"String",
"s",
")",
"{",
"//Replace the first dot, because the string doesn't start with \"m=\"",
"// and is not covered by the regex.",
"if",
"(",
"s",
".",
"startsWith",
"(",
"\"r\"",
")",
"||",
"s",
".",
"startsWith",
"(",
"\"p\"",
")",
")",
"{",
"s",
"=",
"s",
".",
"replaceFirst",
"(",
"\"\\\\.\"",
",",
"\"_\"",
")",
";",
"}",
"String",
"regex",
"=",
"\"(\\\\|| |=|\\\\)|\\\\(|&|<|>|,|\\\\+|-|!|\\\\*|\\\\/)(r|p)\\\\.\"",
";",
"Pattern",
"p",
"=",
"Pattern",
".",
"compile",
"(",
"regex",
")",
";",
"Matcher",
"m",
"=",
"p",
".",
"matcher",
"(",
"s",
")",
";",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"while",
"(",
"m",
".",
"find",
"(",
")",
")",
"{",
"m",
".",
"appendReplacement",
"(",
"sb",
",",
"m",
".",
"group",
"(",
")",
".",
"replace",
"(",
"\".\"",
",",
"\"_\"",
")",
")",
";",
"}",
"m",
".",
"appendTail",
"(",
"sb",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | escapeAssertion escapes the dots in the assertion, because the expression evaluation doesn't support such variable names.
@param s the value of the matcher and effect assertions.
@return the escaped value. | [
"escapeAssertion",
"escapes",
"the",
"dots",
"in",
"the",
"assertion",
"because",
"the",
"expression",
"evaluation",
"doesn",
"t",
"support",
"such",
"variable",
"names",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/util/Util.java#L60-L77 |
27,204 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/util/Util.java | Util.arrayEquals | public static boolean arrayEquals(List<String> a, List<String> b) {
if (a == null) {
a = new ArrayList<>();
}
if (b == null) {
b = new ArrayList<>();
}
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); i ++) {
if (!a.get(i).equals(b.get(i))) {
return false;
}
}
return true;
} | java | public static boolean arrayEquals(List<String> a, List<String> b) {
if (a == null) {
a = new ArrayList<>();
}
if (b == null) {
b = new ArrayList<>();
}
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); i ++) {
if (!a.get(i).equals(b.get(i))) {
return false;
}
}
return true;
} | [
"public",
"static",
"boolean",
"arrayEquals",
"(",
"List",
"<",
"String",
">",
"a",
",",
"List",
"<",
"String",
">",
"b",
")",
"{",
"if",
"(",
"a",
"==",
"null",
")",
"{",
"a",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"if",
"(",
"b",
"==",
"null",
")",
"{",
"b",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"if",
"(",
"a",
".",
"size",
"(",
")",
"!=",
"b",
".",
"size",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"a",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"a",
".",
"get",
"(",
"i",
")",
".",
"equals",
"(",
"b",
".",
"get",
"(",
"i",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | arrayEquals determines whether two string arrays are identical.
@param a the first array.
@param b the second array.
@return whether a equals to b. | [
"arrayEquals",
"determines",
"whether",
"two",
"string",
"arrays",
"are",
"identical",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/util/Util.java#L100-L117 |
27,205 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/util/Util.java | Util.setEquals | public static boolean setEquals(List<String> a, List<String> b) {
if (a == null) {
a = new ArrayList<>();
}
if (b == null) {
b = new ArrayList<>();
}
if (a.size() != b.size()) {
return false;
}
Collections.sort(a);
Collections.sort(b);
for (int i = 0; i < a.size(); i ++) {
if (!a.get(i).equals(b.get(i))) {
return false;
}
}
return true;
} | java | public static boolean setEquals(List<String> a, List<String> b) {
if (a == null) {
a = new ArrayList<>();
}
if (b == null) {
b = new ArrayList<>();
}
if (a.size() != b.size()) {
return false;
}
Collections.sort(a);
Collections.sort(b);
for (int i = 0; i < a.size(); i ++) {
if (!a.get(i).equals(b.get(i))) {
return false;
}
}
return true;
} | [
"public",
"static",
"boolean",
"setEquals",
"(",
"List",
"<",
"String",
">",
"a",
",",
"List",
"<",
"String",
">",
"b",
")",
"{",
"if",
"(",
"a",
"==",
"null",
")",
"{",
"a",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"if",
"(",
"b",
"==",
"null",
")",
"{",
"b",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"if",
"(",
"a",
".",
"size",
"(",
")",
"!=",
"b",
".",
"size",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"Collections",
".",
"sort",
"(",
"a",
")",
";",
"Collections",
".",
"sort",
"(",
"b",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"a",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"a",
".",
"get",
"(",
"i",
")",
".",
"equals",
"(",
"b",
".",
"get",
"(",
"i",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | setEquals determines whether two string sets are identical.
@param a the first set.
@param b the second set.
@return whether a equals to b. | [
"setEquals",
"determines",
"whether",
"two",
"string",
"sets",
"are",
"identical",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/util/Util.java#L182-L202 |
27,206 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/InternalEnforcer.java | InternalEnforcer.addPolicy | boolean addPolicy(String sec, String ptype, List<String> rule) {
boolean ruleAdded = model.addPolicy(sec, ptype, rule);
if (!ruleAdded) {
return false;
}
if (adapter != null && autoSave) {
try {
adapter.addPolicy(sec, ptype, rule);
} catch (Error e) {
if (!e.getMessage().equals("not implemented")) {
throw e;
}
}
if (watcher != null) {
// error intentionally ignored
watcher.update();
}
}
return true;
} | java | boolean addPolicy(String sec, String ptype, List<String> rule) {
boolean ruleAdded = model.addPolicy(sec, ptype, rule);
if (!ruleAdded) {
return false;
}
if (adapter != null && autoSave) {
try {
adapter.addPolicy(sec, ptype, rule);
} catch (Error e) {
if (!e.getMessage().equals("not implemented")) {
throw e;
}
}
if (watcher != null) {
// error intentionally ignored
watcher.update();
}
}
return true;
} | [
"boolean",
"addPolicy",
"(",
"String",
"sec",
",",
"String",
"ptype",
",",
"List",
"<",
"String",
">",
"rule",
")",
"{",
"boolean",
"ruleAdded",
"=",
"model",
".",
"addPolicy",
"(",
"sec",
",",
"ptype",
",",
"rule",
")",
";",
"if",
"(",
"!",
"ruleAdded",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"adapter",
"!=",
"null",
"&&",
"autoSave",
")",
"{",
"try",
"{",
"adapter",
".",
"addPolicy",
"(",
"sec",
",",
"ptype",
",",
"rule",
")",
";",
"}",
"catch",
"(",
"Error",
"e",
")",
"{",
"if",
"(",
"!",
"e",
".",
"getMessage",
"(",
")",
".",
"equals",
"(",
"\"not implemented\"",
")",
")",
"{",
"throw",
"e",
";",
"}",
"}",
"if",
"(",
"watcher",
"!=",
"null",
")",
"{",
"// error intentionally ignored",
"watcher",
".",
"update",
"(",
")",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | addPolicy adds a rule to the current policy. | [
"addPolicy",
"adds",
"a",
"rule",
"to",
"the",
"current",
"policy",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/InternalEnforcer.java#L26-L48 |
27,207 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/InternalEnforcer.java | InternalEnforcer.removeFilteredPolicy | boolean removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
boolean ruleRemoved = model.removeFilteredPolicy(sec, ptype, fieldIndex, fieldValues);
if (!ruleRemoved) {
return false;
}
if (adapter != null && autoSave) {
try {
adapter.removeFilteredPolicy(sec, ptype, fieldIndex, fieldValues);
} catch (Error e) {
if (!e.getMessage().equals("not implemented")) {
throw e;
}
}
if (watcher != null) {
// error intentionally ignored
watcher.update();
}
}
return true;
} | java | boolean removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
boolean ruleRemoved = model.removeFilteredPolicy(sec, ptype, fieldIndex, fieldValues);
if (!ruleRemoved) {
return false;
}
if (adapter != null && autoSave) {
try {
adapter.removeFilteredPolicy(sec, ptype, fieldIndex, fieldValues);
} catch (Error e) {
if (!e.getMessage().equals("not implemented")) {
throw e;
}
}
if (watcher != null) {
// error intentionally ignored
watcher.update();
}
}
return true;
} | [
"boolean",
"removeFilteredPolicy",
"(",
"String",
"sec",
",",
"String",
"ptype",
",",
"int",
"fieldIndex",
",",
"String",
"...",
"fieldValues",
")",
"{",
"boolean",
"ruleRemoved",
"=",
"model",
".",
"removeFilteredPolicy",
"(",
"sec",
",",
"ptype",
",",
"fieldIndex",
",",
"fieldValues",
")",
";",
"if",
"(",
"!",
"ruleRemoved",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"adapter",
"!=",
"null",
"&&",
"autoSave",
")",
"{",
"try",
"{",
"adapter",
".",
"removeFilteredPolicy",
"(",
"sec",
",",
"ptype",
",",
"fieldIndex",
",",
"fieldValues",
")",
";",
"}",
"catch",
"(",
"Error",
"e",
")",
"{",
"if",
"(",
"!",
"e",
".",
"getMessage",
"(",
")",
".",
"equals",
"(",
"\"not implemented\"",
")",
")",
"{",
"throw",
"e",
";",
"}",
"}",
"if",
"(",
"watcher",
"!=",
"null",
")",
"{",
"// error intentionally ignored",
"watcher",
".",
"update",
"(",
")",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | removeFilteredPolicy removes rules based on field filters from the current policy. | [
"removeFilteredPolicy",
"removes",
"rules",
"based",
"on",
"field",
"filters",
"from",
"the",
"current",
"policy",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/InternalEnforcer.java#L80-L102 |
27,208 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java | FileAdapter.loadPolicy | @Override
public void loadPolicy(Model model) {
if (filePath.equals("")) {
// throw new Error("invalid file path, file path cannot be empty");
return;
}
loadPolicyFile(model, Helper::loadPolicyLine);
} | java | @Override
public void loadPolicy(Model model) {
if (filePath.equals("")) {
// throw new Error("invalid file path, file path cannot be empty");
return;
}
loadPolicyFile(model, Helper::loadPolicyLine);
} | [
"@",
"Override",
"public",
"void",
"loadPolicy",
"(",
"Model",
"model",
")",
"{",
"if",
"(",
"filePath",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"// throw new Error(\"invalid file path, file path cannot be empty\");",
"return",
";",
"}",
"loadPolicyFile",
"(",
"model",
",",
"Helper",
"::",
"loadPolicyLine",
")",
";",
"}"
] | loadPolicy loads all policy rules from the storage. | [
"loadPolicy",
"loads",
"all",
"policy",
"rules",
"from",
"the",
"storage",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java#L46-L54 |
27,209 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java | FileAdapter.savePolicy | @Override
public void savePolicy(Model model) {
if (filePath.equals("")) {
throw new Error("invalid file path, file path cannot be empty");
}
StringBuilder tmp = new StringBuilder();
for (Map.Entry<String, Assertion> entry : model.model.get("p").entrySet()) {
String ptype = entry.getKey();
Assertion ast = entry.getValue();
for (List<String> rule : ast.policy) {
tmp.append(ptype + ", ");
tmp.append(Util.arrayToString(rule));
tmp.append("\n");
}
}
for (Map.Entry<String, Assertion> entry : model.model.get("g").entrySet()) {
String ptype = entry.getKey();
Assertion ast = entry.getValue();
for (List<String> rule : ast.policy) {
tmp.append(ptype + ", ");
tmp.append(Util.arrayToString(rule));
tmp.append("\n");
}
}
savePolicyFile(tmp.toString().trim());
} | java | @Override
public void savePolicy(Model model) {
if (filePath.equals("")) {
throw new Error("invalid file path, file path cannot be empty");
}
StringBuilder tmp = new StringBuilder();
for (Map.Entry<String, Assertion> entry : model.model.get("p").entrySet()) {
String ptype = entry.getKey();
Assertion ast = entry.getValue();
for (List<String> rule : ast.policy) {
tmp.append(ptype + ", ");
tmp.append(Util.arrayToString(rule));
tmp.append("\n");
}
}
for (Map.Entry<String, Assertion> entry : model.model.get("g").entrySet()) {
String ptype = entry.getKey();
Assertion ast = entry.getValue();
for (List<String> rule : ast.policy) {
tmp.append(ptype + ", ");
tmp.append(Util.arrayToString(rule));
tmp.append("\n");
}
}
savePolicyFile(tmp.toString().trim());
} | [
"@",
"Override",
"public",
"void",
"savePolicy",
"(",
"Model",
"model",
")",
"{",
"if",
"(",
"filePath",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"invalid file path, file path cannot be empty\"",
")",
";",
"}",
"StringBuilder",
"tmp",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Assertion",
">",
"entry",
":",
"model",
".",
"model",
".",
"get",
"(",
"\"p\"",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"ptype",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"Assertion",
"ast",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"for",
"(",
"List",
"<",
"String",
">",
"rule",
":",
"ast",
".",
"policy",
")",
"{",
"tmp",
".",
"append",
"(",
"ptype",
"+",
"\", \"",
")",
";",
"tmp",
".",
"append",
"(",
"Util",
".",
"arrayToString",
"(",
"rule",
")",
")",
";",
"tmp",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"}",
"}",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Assertion",
">",
"entry",
":",
"model",
".",
"model",
".",
"get",
"(",
"\"g\"",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"ptype",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"Assertion",
"ast",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"for",
"(",
"List",
"<",
"String",
">",
"rule",
":",
"ast",
".",
"policy",
")",
"{",
"tmp",
".",
"append",
"(",
"ptype",
"+",
"\", \"",
")",
";",
"tmp",
".",
"append",
"(",
"Util",
".",
"arrayToString",
"(",
"rule",
")",
")",
";",
"tmp",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"}",
"}",
"savePolicyFile",
"(",
"tmp",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
")",
";",
"}"
] | savePolicy saves all policy rules to the storage. | [
"savePolicy",
"saves",
"all",
"policy",
"rules",
"to",
"the",
"storage",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java#L59-L90 |
27,210 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java | FileAdapter.addPolicy | @Override
public void addPolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
} | java | @Override
public void addPolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
} | [
"@",
"Override",
"public",
"void",
"addPolicy",
"(",
"String",
"sec",
",",
"String",
"ptype",
",",
"List",
"<",
"String",
">",
"rule",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"not implemented\"",
")",
";",
"}"
] | addPolicy adds a policy rule to the storage. | [
"addPolicy",
"adds",
"a",
"policy",
"rule",
"to",
"the",
"storage",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java#L132-L135 |
27,211 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java | FileAdapter.removePolicy | @Override
public void removePolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
} | java | @Override
public void removePolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
} | [
"@",
"Override",
"public",
"void",
"removePolicy",
"(",
"String",
"sec",
",",
"String",
"ptype",
",",
"List",
"<",
"String",
">",
"rule",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"not implemented\"",
")",
";",
"}"
] | removePolicy removes a policy rule from the storage. | [
"removePolicy",
"removes",
"a",
"policy",
"rule",
"from",
"the",
"storage",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java#L140-L143 |
27,212 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java | FileAdapter.removeFilteredPolicy | @Override
public void removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
throw new Error("not implemented");
} | java | @Override
public void removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
throw new Error("not implemented");
} | [
"@",
"Override",
"public",
"void",
"removeFilteredPolicy",
"(",
"String",
"sec",
",",
"String",
"ptype",
",",
"int",
"fieldIndex",
",",
"String",
"...",
"fieldValues",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"not implemented\"",
")",
";",
"}"
] | removeFilteredPolicy removes policy rules that match the filter from the storage. | [
"removeFilteredPolicy",
"removes",
"policy",
"rules",
"that",
"match",
"the",
"filter",
"from",
"the",
"storage",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java#L148-L151 |
27,213 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/model/FunctionMap.java | FunctionMap.loadFunctionMap | public static FunctionMap loadFunctionMap() {
FunctionMap fm = new FunctionMap();
fm.fm = new HashMap<>();
fm.addFunction("keyMatch", new KeyMatchFunc());
fm.addFunction("keyMatch2", new KeyMatch2Func());
fm.addFunction("regexMatch", new RegexMatchFunc());
fm.addFunction("ipMatch", new IPMatchFunc());
return fm;
} | java | public static FunctionMap loadFunctionMap() {
FunctionMap fm = new FunctionMap();
fm.fm = new HashMap<>();
fm.addFunction("keyMatch", new KeyMatchFunc());
fm.addFunction("keyMatch2", new KeyMatch2Func());
fm.addFunction("regexMatch", new RegexMatchFunc());
fm.addFunction("ipMatch", new IPMatchFunc());
return fm;
} | [
"public",
"static",
"FunctionMap",
"loadFunctionMap",
"(",
")",
"{",
"FunctionMap",
"fm",
"=",
"new",
"FunctionMap",
"(",
")",
";",
"fm",
".",
"fm",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"fm",
".",
"addFunction",
"(",
"\"keyMatch\"",
",",
"new",
"KeyMatchFunc",
"(",
")",
")",
";",
"fm",
".",
"addFunction",
"(",
"\"keyMatch2\"",
",",
"new",
"KeyMatch2Func",
"(",
")",
")",
";",
"fm",
".",
"addFunction",
"(",
"\"regexMatch\"",
",",
"new",
"RegexMatchFunc",
"(",
")",
")",
";",
"fm",
".",
"addFunction",
"(",
"\"ipMatch\"",
",",
"new",
"IPMatchFunc",
"(",
")",
")",
";",
"return",
"fm",
";",
"}"
] | loadFunctionMap loads an initial function map.
@return the constructor of FunctionMap. | [
"loadFunctionMap",
"loads",
"an",
"initial",
"function",
"map",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/FunctionMap.java#L50-L60 |
27,214 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/config/Config.java | Config.newConfig | public static Config newConfig(String confName) {
Config c = new Config();
c.parse(confName);
return c;
} | java | public static Config newConfig(String confName) {
Config c = new Config();
c.parse(confName);
return c;
} | [
"public",
"static",
"Config",
"newConfig",
"(",
"String",
"confName",
")",
"{",
"Config",
"c",
"=",
"new",
"Config",
"(",
")",
";",
"c",
".",
"parse",
"(",
"confName",
")",
";",
"return",
"c",
";",
"}"
] | newConfig create an empty configuration representation from file.
@param confName the path of the model file.
@return the constructor of Config. | [
"newConfig",
"create",
"an",
"empty",
"configuration",
"representation",
"from",
"file",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/config/Config.java#L45-L49 |
27,215 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/config/Config.java | Config.newConfigFromText | public static Config newConfigFromText(String text) {
Config c = new Config();
c.parseBuffer(new BufferedReader(new StringReader(text)));
return c;
} | java | public static Config newConfigFromText(String text) {
Config c = new Config();
c.parseBuffer(new BufferedReader(new StringReader(text)));
return c;
} | [
"public",
"static",
"Config",
"newConfigFromText",
"(",
"String",
"text",
")",
"{",
"Config",
"c",
"=",
"new",
"Config",
"(",
")",
";",
"c",
".",
"parseBuffer",
"(",
"new",
"BufferedReader",
"(",
"new",
"StringReader",
"(",
"text",
")",
")",
")",
";",
"return",
"c",
";",
"}"
] | newConfigFromText create an empty configuration representation from text.
@param text the model text.
@return the constructor of Config. | [
"newConfigFromText",
"create",
"an",
"empty",
"configuration",
"representation",
"from",
"text",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/config/Config.java#L57-L61 |
27,216 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/model/Model.java | Model.addDef | public boolean addDef(String sec, String key, String value) {
Assertion ast = new Assertion();
ast.key = key;
ast.value = value;
if (ast.value.equals("")) {
return false;
}
if (sec.equals("r") || sec.equals("p")) {
ast.tokens = ast.value.split(", ");
for (int i = 0; i < ast.tokens.length; i ++) {
ast.tokens[i] = key + "_" + ast.tokens[i];
}
} else {
ast.value = Util.removeComments(Util.escapeAssertion(ast.value));
}
if (!model.containsKey(sec)) {
model.put(sec, new HashMap<>());
}
model.get(sec).put(key, ast);
return true;
} | java | public boolean addDef(String sec, String key, String value) {
Assertion ast = new Assertion();
ast.key = key;
ast.value = value;
if (ast.value.equals("")) {
return false;
}
if (sec.equals("r") || sec.equals("p")) {
ast.tokens = ast.value.split(", ");
for (int i = 0; i < ast.tokens.length; i ++) {
ast.tokens[i] = key + "_" + ast.tokens[i];
}
} else {
ast.value = Util.removeComments(Util.escapeAssertion(ast.value));
}
if (!model.containsKey(sec)) {
model.put(sec, new HashMap<>());
}
model.get(sec).put(key, ast);
return true;
} | [
"public",
"boolean",
"addDef",
"(",
"String",
"sec",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"Assertion",
"ast",
"=",
"new",
"Assertion",
"(",
")",
";",
"ast",
".",
"key",
"=",
"key",
";",
"ast",
".",
"value",
"=",
"value",
";",
"if",
"(",
"ast",
".",
"value",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"sec",
".",
"equals",
"(",
"\"r\"",
")",
"||",
"sec",
".",
"equals",
"(",
"\"p\"",
")",
")",
"{",
"ast",
".",
"tokens",
"=",
"ast",
".",
"value",
".",
"split",
"(",
"\", \"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"ast",
".",
"tokens",
".",
"length",
";",
"i",
"++",
")",
"{",
"ast",
".",
"tokens",
"[",
"i",
"]",
"=",
"key",
"+",
"\"_\"",
"+",
"ast",
".",
"tokens",
"[",
"i",
"]",
";",
"}",
"}",
"else",
"{",
"ast",
".",
"value",
"=",
"Util",
".",
"removeComments",
"(",
"Util",
".",
"escapeAssertion",
"(",
"ast",
".",
"value",
")",
")",
";",
"}",
"if",
"(",
"!",
"model",
".",
"containsKey",
"(",
"sec",
")",
")",
"{",
"model",
".",
"put",
"(",
"sec",
",",
"new",
"HashMap",
"<>",
"(",
")",
")",
";",
"}",
"model",
".",
"get",
"(",
"sec",
")",
".",
"put",
"(",
"key",
",",
"ast",
")",
";",
"return",
"true",
";",
"}"
] | addDef adds an assertion to the model.
@param sec the section, "p" or "g".
@param key the policy type, "p", "p2", .. or "g", "g2", ..
@param value the policy rule, separated by ", ".
@return succeeds or not. | [
"addDef",
"adds",
"an",
"assertion",
"to",
"the",
"model",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Model.java#L57-L81 |
27,217 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/model/Model.java | Model.loadModel | public void loadModel(String path) {
Config cfg = Config.newConfig(path);
loadSection(this, cfg, "r");
loadSection(this, cfg, "p");
loadSection(this, cfg, "e");
loadSection(this, cfg, "m");
loadSection(this, cfg, "g");
} | java | public void loadModel(String path) {
Config cfg = Config.newConfig(path);
loadSection(this, cfg, "r");
loadSection(this, cfg, "p");
loadSection(this, cfg, "e");
loadSection(this, cfg, "m");
loadSection(this, cfg, "g");
} | [
"public",
"void",
"loadModel",
"(",
"String",
"path",
")",
"{",
"Config",
"cfg",
"=",
"Config",
".",
"newConfig",
"(",
"path",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"r\"",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"p\"",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"e\"",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"m\"",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"g\"",
")",
";",
"}"
] | loadModel loads the model from model CONF file.
@param path the path of the model file. | [
"loadModel",
"loads",
"the",
"model",
"from",
"model",
"CONF",
"file",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Model.java#L107-L116 |
27,218 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/model/Model.java | Model.loadModelFromText | public void loadModelFromText(String text) {
Config cfg = Config.newConfigFromText(text);
loadSection(this, cfg, "r");
loadSection(this, cfg, "p");
loadSection(this, cfg, "e");
loadSection(this, cfg, "m");
loadSection(this, cfg, "g");
} | java | public void loadModelFromText(String text) {
Config cfg = Config.newConfigFromText(text);
loadSection(this, cfg, "r");
loadSection(this, cfg, "p");
loadSection(this, cfg, "e");
loadSection(this, cfg, "m");
loadSection(this, cfg, "g");
} | [
"public",
"void",
"loadModelFromText",
"(",
"String",
"text",
")",
"{",
"Config",
"cfg",
"=",
"Config",
".",
"newConfigFromText",
"(",
"text",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"r\"",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"p\"",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"e\"",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"m\"",
")",
";",
"loadSection",
"(",
"this",
",",
"cfg",
",",
"\"g\"",
")",
";",
"}"
] | loadModelFromText loads the model from the text.
@param text the model text. | [
"loadModelFromText",
"loads",
"the",
"model",
"from",
"the",
"text",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Model.java#L123-L132 |
27,219 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/model/Model.java | Model.printModel | public void printModel() {
Util.logPrint("Model:");
for (Map.Entry<String, Map<String, Assertion>> entry : model.entrySet()) {
for (Map.Entry<String, Assertion> entry2 : entry.getValue().entrySet()) {
Util.logPrintf("%s.%s: %s", entry.getKey(), entry2.getKey(), entry2.getValue().value);
}
}
} | java | public void printModel() {
Util.logPrint("Model:");
for (Map.Entry<String, Map<String, Assertion>> entry : model.entrySet()) {
for (Map.Entry<String, Assertion> entry2 : entry.getValue().entrySet()) {
Util.logPrintf("%s.%s: %s", entry.getKey(), entry2.getKey(), entry2.getValue().value);
}
}
} | [
"public",
"void",
"printModel",
"(",
")",
"{",
"Util",
".",
"logPrint",
"(",
"\"Model:\"",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Map",
"<",
"String",
",",
"Assertion",
">",
">",
"entry",
":",
"model",
".",
"entrySet",
"(",
")",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Assertion",
">",
"entry2",
":",
"entry",
".",
"getValue",
"(",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"Util",
".",
"logPrintf",
"(",
"\"%s.%s: %s\"",
",",
"entry",
".",
"getKey",
"(",
")",
",",
"entry2",
".",
"getKey",
"(",
")",
",",
"entry2",
".",
"getValue",
"(",
")",
".",
"value",
")",
";",
"}",
"}",
"}"
] | printModel prints the model to the log. | [
"printModel",
"prints",
"the",
"model",
"to",
"the",
"log",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Model.java#L137-L144 |
27,220 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/effect/DefaultEffector.java | DefaultEffector.mergeEffects | public boolean mergeEffects(String expr, Effect[] effects, float[] results) {
boolean result;
if (expr.equals("some(where (p_eft == allow))")) {
result = false;
for (Effect eft : effects) {
if (eft == Effect.Allow) {
result = true;
break;
}
}
} else if (expr.equals("!some(where (p_eft == deny))")) {
result = true;
for (Effect eft : effects) {
if (eft == Effect.Deny) {
result = false;
break;
}
}
} else if (expr.equals("some(where (p_eft == allow)) && !some(where (p_eft == deny))")) {
result = false;
for (Effect eft : effects) {
if (eft == Effect.Allow) {
result = true;
} else if (eft == Effect.Deny) {
result = false;
break;
}
}
} else if (expr.equals("priority(p_eft) || deny")) {
result = false;
for (Effect eft : effects) {
if (eft != Effect.Indeterminate) {
if (eft == Effect.Allow) {
result = true;
} else {
result = false;
}
break;
}
}
} else {
throw new Error("unsupported effect");
}
return result;
} | java | public boolean mergeEffects(String expr, Effect[] effects, float[] results) {
boolean result;
if (expr.equals("some(where (p_eft == allow))")) {
result = false;
for (Effect eft : effects) {
if (eft == Effect.Allow) {
result = true;
break;
}
}
} else if (expr.equals("!some(where (p_eft == deny))")) {
result = true;
for (Effect eft : effects) {
if (eft == Effect.Deny) {
result = false;
break;
}
}
} else if (expr.equals("some(where (p_eft == allow)) && !some(where (p_eft == deny))")) {
result = false;
for (Effect eft : effects) {
if (eft == Effect.Allow) {
result = true;
} else if (eft == Effect.Deny) {
result = false;
break;
}
}
} else if (expr.equals("priority(p_eft) || deny")) {
result = false;
for (Effect eft : effects) {
if (eft != Effect.Indeterminate) {
if (eft == Effect.Allow) {
result = true;
} else {
result = false;
}
break;
}
}
} else {
throw new Error("unsupported effect");
}
return result;
} | [
"public",
"boolean",
"mergeEffects",
"(",
"String",
"expr",
",",
"Effect",
"[",
"]",
"effects",
",",
"float",
"[",
"]",
"results",
")",
"{",
"boolean",
"result",
";",
"if",
"(",
"expr",
".",
"equals",
"(",
"\"some(where (p_eft == allow))\"",
")",
")",
"{",
"result",
"=",
"false",
";",
"for",
"(",
"Effect",
"eft",
":",
"effects",
")",
"{",
"if",
"(",
"eft",
"==",
"Effect",
".",
"Allow",
")",
"{",
"result",
"=",
"true",
";",
"break",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"expr",
".",
"equals",
"(",
"\"!some(where (p_eft == deny))\"",
")",
")",
"{",
"result",
"=",
"true",
";",
"for",
"(",
"Effect",
"eft",
":",
"effects",
")",
"{",
"if",
"(",
"eft",
"==",
"Effect",
".",
"Deny",
")",
"{",
"result",
"=",
"false",
";",
"break",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"expr",
".",
"equals",
"(",
"\"some(where (p_eft == allow)) && !some(where (p_eft == deny))\"",
")",
")",
"{",
"result",
"=",
"false",
";",
"for",
"(",
"Effect",
"eft",
":",
"effects",
")",
"{",
"if",
"(",
"eft",
"==",
"Effect",
".",
"Allow",
")",
"{",
"result",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"eft",
"==",
"Effect",
".",
"Deny",
")",
"{",
"result",
"=",
"false",
";",
"break",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"expr",
".",
"equals",
"(",
"\"priority(p_eft) || deny\"",
")",
")",
"{",
"result",
"=",
"false",
";",
"for",
"(",
"Effect",
"eft",
":",
"effects",
")",
"{",
"if",
"(",
"eft",
"!=",
"Effect",
".",
"Indeterminate",
")",
"{",
"if",
"(",
"eft",
"==",
"Effect",
".",
"Allow",
")",
"{",
"result",
"=",
"true",
";",
"}",
"else",
"{",
"result",
"=",
"false",
";",
"}",
"break",
";",
"}",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"unsupported effect\"",
")",
";",
"}",
"return",
"result",
";",
"}"
] | mergeEffects merges all matching results collected by the enforcer into a single decision. | [
"mergeEffects",
"merges",
"all",
"matching",
"results",
"collected",
"by",
"the",
"enforcer",
"into",
"a",
"single",
"decision",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/effect/DefaultEffector.java#L30-L75 |
27,221 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java | ManagementEnforcer.getFilteredPolicy | public List<List<String>> getFilteredPolicy(int fieldIndex, String... fieldValues) {
return getFilteredNamedPolicy("p", fieldIndex, fieldValues);
} | java | public List<List<String>> getFilteredPolicy(int fieldIndex, String... fieldValues) {
return getFilteredNamedPolicy("p", fieldIndex, fieldValues);
} | [
"public",
"List",
"<",
"List",
"<",
"String",
">",
">",
"getFilteredPolicy",
"(",
"int",
"fieldIndex",
",",
"String",
"...",
"fieldValues",
")",
"{",
"return",
"getFilteredNamedPolicy",
"(",
"\"p\"",
",",
"fieldIndex",
",",
"fieldValues",
")",
";",
"}"
] | getFilteredPolicy gets all the authorization rules in the policy, field filters can be specified.
@param fieldIndex the policy rule's start index to be matched.
@param fieldValues the field values to be matched, value ""
means not to match this field.
@return the filtered "p" policy rules. | [
"getFilteredPolicy",
"gets",
"all",
"the",
"authorization",
"rules",
"in",
"the",
"policy",
"field",
"filters",
"can",
"be",
"specified",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L143-L145 |
27,222 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java | ManagementEnforcer.getFilteredNamedPolicy | public List<List<String>> getFilteredNamedPolicy(String ptype, int fieldIndex, String... fieldValues) {
return model.getFilteredPolicy("p", ptype, fieldIndex, fieldValues);
} | java | public List<List<String>> getFilteredNamedPolicy(String ptype, int fieldIndex, String... fieldValues) {
return model.getFilteredPolicy("p", ptype, fieldIndex, fieldValues);
} | [
"public",
"List",
"<",
"List",
"<",
"String",
">",
">",
"getFilteredNamedPolicy",
"(",
"String",
"ptype",
",",
"int",
"fieldIndex",
",",
"String",
"...",
"fieldValues",
")",
"{",
"return",
"model",
".",
"getFilteredPolicy",
"(",
"\"p\"",
",",
"ptype",
",",
"fieldIndex",
",",
"fieldValues",
")",
";",
"}"
] | getFilteredNamedPolicy gets all the authorization rules in the named policy, field filters can be specified.
@param ptype the policy type, can be "p", "p2", "p3", ..
@param fieldIndex the policy rule's start index to be matched.
@param fieldValues the field values to be matched, value ""
means not to match this field.
@return the filtered "p" policy rules of the specified ptype. | [
"getFilteredNamedPolicy",
"gets",
"all",
"the",
"authorization",
"rules",
"in",
"the",
"named",
"policy",
"field",
"filters",
"can",
"be",
"specified",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L166-L168 |
27,223 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java | ManagementEnforcer.getFilteredGroupingPolicy | public List<List<String>> getFilteredGroupingPolicy(int fieldIndex, String... fieldValues) {
return getFilteredNamedGroupingPolicy("g", fieldIndex, fieldValues);
} | java | public List<List<String>> getFilteredGroupingPolicy(int fieldIndex, String... fieldValues) {
return getFilteredNamedGroupingPolicy("g", fieldIndex, fieldValues);
} | [
"public",
"List",
"<",
"List",
"<",
"String",
">",
">",
"getFilteredGroupingPolicy",
"(",
"int",
"fieldIndex",
",",
"String",
"...",
"fieldValues",
")",
"{",
"return",
"getFilteredNamedGroupingPolicy",
"(",
"\"g\"",
",",
"fieldIndex",
",",
"fieldValues",
")",
";",
"}"
] | getFilteredGroupingPolicy gets all the role inheritance rules in the policy, field filters can be specified.
@param fieldIndex the policy rule's start index to be matched.
@param fieldValues the field values to be matched, value ""
means not to match this field.
@return the filtered "g" policy rules. | [
"getFilteredGroupingPolicy",
"gets",
"all",
"the",
"role",
"inheritance",
"rules",
"in",
"the",
"policy",
"field",
"filters",
"can",
"be",
"specified",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L187-L189 |
27,224 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java | ManagementEnforcer.getFilteredNamedGroupingPolicy | public List<List<String>> getFilteredNamedGroupingPolicy(String ptype, int fieldIndex, String... fieldValues) {
return model.getFilteredPolicy("g", ptype, fieldIndex, fieldValues);
} | java | public List<List<String>> getFilteredNamedGroupingPolicy(String ptype, int fieldIndex, String... fieldValues) {
return model.getFilteredPolicy("g", ptype, fieldIndex, fieldValues);
} | [
"public",
"List",
"<",
"List",
"<",
"String",
">",
">",
"getFilteredNamedGroupingPolicy",
"(",
"String",
"ptype",
",",
"int",
"fieldIndex",
",",
"String",
"...",
"fieldValues",
")",
"{",
"return",
"model",
".",
"getFilteredPolicy",
"(",
"\"g\"",
",",
"ptype",
",",
"fieldIndex",
",",
"fieldValues",
")",
";",
"}"
] | getFilteredNamedGroupingPolicy gets all the role inheritance rules in the policy, field filters can be specified.
@param ptype the policy type, can be "g", "g2", "g3", ..
@param fieldIndex the policy rule's start index to be matched.
@param fieldValues the field values to be matched, value ""
means not to match this field.
@return the filtered "g" policy rules of the specified ptype. | [
"getFilteredNamedGroupingPolicy",
"gets",
"all",
"the",
"role",
"inheritance",
"rules",
"in",
"the",
"policy",
"field",
"filters",
"can",
"be",
"specified",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L210-L212 |
27,225 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java | ManagementEnforcer.addNamedPolicy | public boolean addNamedPolicy(String ptype, String... params) {
return addNamedPolicy(ptype, Arrays.asList(params));
} | java | public boolean addNamedPolicy(String ptype, String... params) {
return addNamedPolicy(ptype, Arrays.asList(params));
} | [
"public",
"boolean",
"addNamedPolicy",
"(",
"String",
"ptype",
",",
"String",
"...",
"params",
")",
"{",
"return",
"addNamedPolicy",
"(",
"ptype",
",",
"Arrays",
".",
"asList",
"(",
"params",
")",
")",
";",
"}"
] | AddNamedPolicy adds an authorization rule to the current named policy.
If the rule already exists, the function returns false and the rule will not be added.
Otherwise the function returns true by adding the new rule.
@param ptype the policy type, can be "p", "p2", "p3", ..
@param params the "p" policy rule.
@return succeeds or not. | [
"AddNamedPolicy",
"adds",
"an",
"authorization",
"rule",
"to",
"the",
"current",
"named",
"policy",
".",
"If",
"the",
"rule",
"already",
"exists",
"the",
"function",
"returns",
"false",
"and",
"the",
"rule",
"will",
"not",
"be",
"added",
".",
"Otherwise",
"the",
"function",
"returns",
"true",
"by",
"adding",
"the",
"new",
"rule",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L302-L304 |
27,226 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java | ManagementEnforcer.removeNamedPolicy | public boolean removeNamedPolicy(String ptype, String... params) {
return removeNamedPolicy(ptype, Arrays.asList(params));
} | java | public boolean removeNamedPolicy(String ptype, String... params) {
return removeNamedPolicy(ptype, Arrays.asList(params));
} | [
"public",
"boolean",
"removeNamedPolicy",
"(",
"String",
"ptype",
",",
"String",
"...",
"params",
")",
"{",
"return",
"removeNamedPolicy",
"(",
"ptype",
",",
"Arrays",
".",
"asList",
"(",
"params",
")",
")",
";",
"}"
] | removeNamedPolicy removes an authorization rule from the current named policy.
@param ptype the policy type, can be "p", "p2", "p3", ..
@param params the "p" policy rule.
@return succeeds or not. | [
"removeNamedPolicy",
"removes",
"an",
"authorization",
"rule",
"from",
"the",
"current",
"named",
"policy",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L356-L358 |
27,227 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java | ManagementEnforcer.removeFilteredNamedPolicy | public boolean removeFilteredNamedPolicy(String ptype, int fieldIndex, String... fieldValues) {
return removeFilteredPolicy("p", ptype, fieldIndex, fieldValues);
} | java | public boolean removeFilteredNamedPolicy(String ptype, int fieldIndex, String... fieldValues) {
return removeFilteredPolicy("p", ptype, fieldIndex, fieldValues);
} | [
"public",
"boolean",
"removeFilteredNamedPolicy",
"(",
"String",
"ptype",
",",
"int",
"fieldIndex",
",",
"String",
"...",
"fieldValues",
")",
"{",
"return",
"removeFilteredPolicy",
"(",
"\"p\"",
",",
"ptype",
",",
"fieldIndex",
",",
"fieldValues",
")",
";",
"}"
] | removeFilteredNamedPolicy removes an authorization rule from the current named policy, field filters can be specified.
@param ptype the policy type, can be "p", "p2", "p3", ..
@param fieldIndex the policy rule's start index to be matched.
@param fieldValues the field values to be matched, value ""
means not to match this field.
@return succeeds or not. | [
"removeFilteredNamedPolicy",
"removes",
"an",
"authorization",
"rule",
"from",
"the",
"current",
"named",
"policy",
"field",
"filters",
"can",
"be",
"specified",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L369-L371 |
27,228 | casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java | ManagementEnforcer.removeFilteredNamedGroupingPolicy | public boolean removeFilteredNamedGroupingPolicy(String ptype, int fieldIndex, String... fieldValues) {
boolean ruleRemoved = removeFilteredPolicy("g", ptype, fieldIndex, fieldValues);
if (autoBuildRoleLinks) {
buildRoleLinks();
}
return ruleRemoved;
} | java | public boolean removeFilteredNamedGroupingPolicy(String ptype, int fieldIndex, String... fieldValues) {
boolean ruleRemoved = removeFilteredPolicy("g", ptype, fieldIndex, fieldValues);
if (autoBuildRoleLinks) {
buildRoleLinks();
}
return ruleRemoved;
} | [
"public",
"boolean",
"removeFilteredNamedGroupingPolicy",
"(",
"String",
"ptype",
",",
"int",
"fieldIndex",
",",
"String",
"...",
"fieldValues",
")",
"{",
"boolean",
"ruleRemoved",
"=",
"removeFilteredPolicy",
"(",
"\"g\"",
",",
"ptype",
",",
"fieldIndex",
",",
"fieldValues",
")",
";",
"if",
"(",
"autoBuildRoleLinks",
")",
"{",
"buildRoleLinks",
"(",
")",
";",
"}",
"return",
"ruleRemoved",
";",
"}"
] | removeFilteredNamedGroupingPolicy removes a role inheritance rule from the current named policy, field filters can be specified.
@param ptype the policy type, can be "g", "g2", "g3", ..
@param fieldIndex the policy rule's start index to be matched.
@param fieldValues the field values to be matched, value ""
means not to match this field.
@return succeeds or not. | [
"removeFilteredNamedGroupingPolicy",
"removes",
"a",
"role",
"inheritance",
"rule",
"from",
"the",
"current",
"named",
"policy",
"field",
"filters",
"can",
"be",
"specified",
"."
] | b46d7a756b6c39cdb17e0600607e5fcdc66edd11 | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L538-L545 |
27,229 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/NodeInterval.java | NodeInterval.build | public void build(final BuildNodeCallback callback) {
Preconditions.checkNotNull(callback);
if (leftChild == null) {
callback.onLastNode(this);
return;
}
LocalDate curDate = start;
NodeInterval curChild = leftChild;
while (curChild != null) {
if (curChild.getStart().compareTo(curDate) > 0) {
callback.onMissingInterval(this, curDate, curChild.getStart());
}
curChild.build(callback);
// Note that skip to child endDate, meaning that we always consider the child [start end]
curDate = curChild.getEnd();
curChild = curChild.getRightSibling();
}
// Finally if there is a hole at the end, we build the missing piece from ourselves
if (curDate.compareTo(end) < 0) {
callback.onMissingInterval(this, curDate, end);
}
return;
} | java | public void build(final BuildNodeCallback callback) {
Preconditions.checkNotNull(callback);
if (leftChild == null) {
callback.onLastNode(this);
return;
}
LocalDate curDate = start;
NodeInterval curChild = leftChild;
while (curChild != null) {
if (curChild.getStart().compareTo(curDate) > 0) {
callback.onMissingInterval(this, curDate, curChild.getStart());
}
curChild.build(callback);
// Note that skip to child endDate, meaning that we always consider the child [start end]
curDate = curChild.getEnd();
curChild = curChild.getRightSibling();
}
// Finally if there is a hole at the end, we build the missing piece from ourselves
if (curDate.compareTo(end) < 0) {
callback.onMissingInterval(this, curDate, end);
}
return;
} | [
"public",
"void",
"build",
"(",
"final",
"BuildNodeCallback",
"callback",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"callback",
")",
";",
"if",
"(",
"leftChild",
"==",
"null",
")",
"{",
"callback",
".",
"onLastNode",
"(",
"this",
")",
";",
"return",
";",
"}",
"LocalDate",
"curDate",
"=",
"start",
";",
"NodeInterval",
"curChild",
"=",
"leftChild",
";",
"while",
"(",
"curChild",
"!=",
"null",
")",
"{",
"if",
"(",
"curChild",
".",
"getStart",
"(",
")",
".",
"compareTo",
"(",
"curDate",
")",
">",
"0",
")",
"{",
"callback",
".",
"onMissingInterval",
"(",
"this",
",",
"curDate",
",",
"curChild",
".",
"getStart",
"(",
")",
")",
";",
"}",
"curChild",
".",
"build",
"(",
"callback",
")",
";",
"// Note that skip to child endDate, meaning that we always consider the child [start end]",
"curDate",
"=",
"curChild",
".",
"getEnd",
"(",
")",
";",
"curChild",
"=",
"curChild",
".",
"getRightSibling",
"(",
")",
";",
"}",
"// Finally if there is a hole at the end, we build the missing piece from ourselves",
"if",
"(",
"curDate",
".",
"compareTo",
"(",
"end",
")",
"<",
"0",
")",
"{",
"callback",
".",
"onMissingInterval",
"(",
"this",
",",
"curDate",
",",
"end",
")",
";",
"}",
"return",
";",
"}"
] | Build the tree by calling the callback on the last node in the tree or remaining part with no children.
@param callback the callback which perform the build logic.
@return whether or not the parent NodeInterval should ignore the period covered by the child (NodeInterval) | [
"Build",
"the",
"tree",
"by",
"calling",
"the",
"callback",
"on",
"the",
"last",
"node",
"in",
"the",
"tree",
"or",
"remaining",
"part",
"with",
"no",
"children",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/NodeInterval.java#L54-L80 |
27,230 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/NodeInterval.java | NodeInterval.addNode | public boolean addNode(final NodeInterval newNode, final AddNodeCallback callback) {
Preconditions.checkNotNull(newNode);
Preconditions.checkNotNull(callback);
if (!isRoot() && newNode.getStart().compareTo(start) == 0 && newNode.getEnd().compareTo(end) == 0) {
return callback.onExistingNode(this);
}
computeRootInterval(newNode);
newNode.parent = this;
if (leftChild == null) {
if (callback.shouldInsertNode(this)) {
leftChild = newNode;
return true;
} else {
return false;
}
}
NodeInterval prevChild = null;
NodeInterval curChild = leftChild;
while (curChild != null) {
if (curChild.isItemContained(newNode)) {
return curChild.addNode(newNode, callback);
}
if (curChild.isItemOverlap(newNode)) {
if (rebalance(newNode)) {
return callback.shouldInsertNode(this);
}
}
if (newNode.getStart().compareTo(curChild.getStart()) < 0) {
Preconditions.checkState(newNode.getEnd().compareTo(end) <= 0);
if (callback.shouldInsertNode(this)) {
newNode.rightSibling = curChild;
if (prevChild == null) {
leftChild = newNode;
} else {
prevChild.rightSibling = newNode;
}
return true;
} else {
return false;
}
}
prevChild = curChild;
curChild = curChild.rightSibling;
}
if (callback.shouldInsertNode(this)) {
prevChild.rightSibling = newNode;
return true;
} else {
return false;
}
} | java | public boolean addNode(final NodeInterval newNode, final AddNodeCallback callback) {
Preconditions.checkNotNull(newNode);
Preconditions.checkNotNull(callback);
if (!isRoot() && newNode.getStart().compareTo(start) == 0 && newNode.getEnd().compareTo(end) == 0) {
return callback.onExistingNode(this);
}
computeRootInterval(newNode);
newNode.parent = this;
if (leftChild == null) {
if (callback.shouldInsertNode(this)) {
leftChild = newNode;
return true;
} else {
return false;
}
}
NodeInterval prevChild = null;
NodeInterval curChild = leftChild;
while (curChild != null) {
if (curChild.isItemContained(newNode)) {
return curChild.addNode(newNode, callback);
}
if (curChild.isItemOverlap(newNode)) {
if (rebalance(newNode)) {
return callback.shouldInsertNode(this);
}
}
if (newNode.getStart().compareTo(curChild.getStart()) < 0) {
Preconditions.checkState(newNode.getEnd().compareTo(end) <= 0);
if (callback.shouldInsertNode(this)) {
newNode.rightSibling = curChild;
if (prevChild == null) {
leftChild = newNode;
} else {
prevChild.rightSibling = newNode;
}
return true;
} else {
return false;
}
}
prevChild = curChild;
curChild = curChild.rightSibling;
}
if (callback.shouldInsertNode(this)) {
prevChild.rightSibling = newNode;
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"addNode",
"(",
"final",
"NodeInterval",
"newNode",
",",
"final",
"AddNodeCallback",
"callback",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"newNode",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"callback",
")",
";",
"if",
"(",
"!",
"isRoot",
"(",
")",
"&&",
"newNode",
".",
"getStart",
"(",
")",
".",
"compareTo",
"(",
"start",
")",
"==",
"0",
"&&",
"newNode",
".",
"getEnd",
"(",
")",
".",
"compareTo",
"(",
"end",
")",
"==",
"0",
")",
"{",
"return",
"callback",
".",
"onExistingNode",
"(",
"this",
")",
";",
"}",
"computeRootInterval",
"(",
"newNode",
")",
";",
"newNode",
".",
"parent",
"=",
"this",
";",
"if",
"(",
"leftChild",
"==",
"null",
")",
"{",
"if",
"(",
"callback",
".",
"shouldInsertNode",
"(",
"this",
")",
")",
"{",
"leftChild",
"=",
"newNode",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"NodeInterval",
"prevChild",
"=",
"null",
";",
"NodeInterval",
"curChild",
"=",
"leftChild",
";",
"while",
"(",
"curChild",
"!=",
"null",
")",
"{",
"if",
"(",
"curChild",
".",
"isItemContained",
"(",
"newNode",
")",
")",
"{",
"return",
"curChild",
".",
"addNode",
"(",
"newNode",
",",
"callback",
")",
";",
"}",
"if",
"(",
"curChild",
".",
"isItemOverlap",
"(",
"newNode",
")",
")",
"{",
"if",
"(",
"rebalance",
"(",
"newNode",
")",
")",
"{",
"return",
"callback",
".",
"shouldInsertNode",
"(",
"this",
")",
";",
"}",
"}",
"if",
"(",
"newNode",
".",
"getStart",
"(",
")",
".",
"compareTo",
"(",
"curChild",
".",
"getStart",
"(",
")",
")",
"<",
"0",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"newNode",
".",
"getEnd",
"(",
")",
".",
"compareTo",
"(",
"end",
")",
"<=",
"0",
")",
";",
"if",
"(",
"callback",
".",
"shouldInsertNode",
"(",
"this",
")",
")",
"{",
"newNode",
".",
"rightSibling",
"=",
"curChild",
";",
"if",
"(",
"prevChild",
"==",
"null",
")",
"{",
"leftChild",
"=",
"newNode",
";",
"}",
"else",
"{",
"prevChild",
".",
"rightSibling",
"=",
"newNode",
";",
"}",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"prevChild",
"=",
"curChild",
";",
"curChild",
"=",
"curChild",
".",
"rightSibling",
";",
"}",
"if",
"(",
"callback",
".",
"shouldInsertNode",
"(",
"this",
")",
")",
"{",
"prevChild",
".",
"rightSibling",
"=",
"newNode",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Add a new node in the tree.
@param newNode the node to be added
@param callback the callback that will allow to specify insertion and return behavior.
@return true if node was inserted. Note that this is driven by the callback, this method is generic
and specific behavior can be tuned through specific callbacks. | [
"Add",
"a",
"new",
"node",
"in",
"the",
"tree",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/NodeInterval.java#L90-L150 |
27,231 | killbill/killbill | util/src/main/java/org/killbill/billing/util/PluginProperties.java | PluginProperties.toMap | public static Map<String, Object> toMap(final Iterable<PluginProperty>... propertiesLists) {
final Map<String, Object> mergedProperties = new HashMap<String, Object>();
for (final Iterable<PluginProperty> propertiesList : propertiesLists) {
if(propertiesList != null) {
for (final PluginProperty pluginProperty : propertiesList) {
if (pluginProperty != null && pluginProperty.getKey() != null) {
mergedProperties.put(pluginProperty.getKey(), pluginProperty.getValue());
}
}
}
}
return mergedProperties;
} | java | public static Map<String, Object> toMap(final Iterable<PluginProperty>... propertiesLists) {
final Map<String, Object> mergedProperties = new HashMap<String, Object>();
for (final Iterable<PluginProperty> propertiesList : propertiesLists) {
if(propertiesList != null) {
for (final PluginProperty pluginProperty : propertiesList) {
if (pluginProperty != null && pluginProperty.getKey() != null) {
mergedProperties.put(pluginProperty.getKey(), pluginProperty.getValue());
}
}
}
}
return mergedProperties;
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"toMap",
"(",
"final",
"Iterable",
"<",
"PluginProperty",
">",
"...",
"propertiesLists",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"mergedProperties",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"for",
"(",
"final",
"Iterable",
"<",
"PluginProperty",
">",
"propertiesList",
":",
"propertiesLists",
")",
"{",
"if",
"(",
"propertiesList",
"!=",
"null",
")",
"{",
"for",
"(",
"final",
"PluginProperty",
"pluginProperty",
":",
"propertiesList",
")",
"{",
"if",
"(",
"pluginProperty",
"!=",
"null",
"&&",
"pluginProperty",
".",
"getKey",
"(",
")",
"!=",
"null",
")",
"{",
"mergedProperties",
".",
"put",
"(",
"pluginProperty",
".",
"getKey",
"(",
")",
",",
"pluginProperty",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"}",
"}",
"return",
"mergedProperties",
";",
"}"
] | Last one has precedence | [
"Last",
"one",
"has",
"precedence"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/PluginProperties.java#L38-L50 |
27,232 | killbill/killbill | util/src/main/java/org/killbill/billing/util/entity/dao/EntitySqlDaoWrapperInvocationHandler.java | EntitySqlDaoWrapperInvocationHandler.errorDuringTransaction | private void errorDuringTransaction(final Throwable t, final Method method, final String extraErrorMessage) throws Throwable {
final StringBuilder errorMessageBuilder = new StringBuilder("Error during transaction for sql entity {} and method {}");
if (t instanceof SQLException) {
final SQLException sqlException = (SQLException) t;
errorMessageBuilder.append(" [SQL DefaultState: ")
.append(sqlException.getSQLState())
.append(", Vendor Error Code: ")
.append(sqlException.getErrorCode())
.append("]");
}
if (extraErrorMessage != null) {
// This is usually the SQL statement
errorMessageBuilder.append("\n").append(extraErrorMessage);
}
logger.warn(errorMessageBuilder.toString(), sqlDaoClass, method.getName());
// This is to avoid throwing an exception wrapped in an UndeclaredThrowableException
if (!(t instanceof RuntimeException)) {
throw new RuntimeException(t);
} else {
throw t;
}
} | java | private void errorDuringTransaction(final Throwable t, final Method method, final String extraErrorMessage) throws Throwable {
final StringBuilder errorMessageBuilder = new StringBuilder("Error during transaction for sql entity {} and method {}");
if (t instanceof SQLException) {
final SQLException sqlException = (SQLException) t;
errorMessageBuilder.append(" [SQL DefaultState: ")
.append(sqlException.getSQLState())
.append(", Vendor Error Code: ")
.append(sqlException.getErrorCode())
.append("]");
}
if (extraErrorMessage != null) {
// This is usually the SQL statement
errorMessageBuilder.append("\n").append(extraErrorMessage);
}
logger.warn(errorMessageBuilder.toString(), sqlDaoClass, method.getName());
// This is to avoid throwing an exception wrapped in an UndeclaredThrowableException
if (!(t instanceof RuntimeException)) {
throw new RuntimeException(t);
} else {
throw t;
}
} | [
"private",
"void",
"errorDuringTransaction",
"(",
"final",
"Throwable",
"t",
",",
"final",
"Method",
"method",
",",
"final",
"String",
"extraErrorMessage",
")",
"throws",
"Throwable",
"{",
"final",
"StringBuilder",
"errorMessageBuilder",
"=",
"new",
"StringBuilder",
"(",
"\"Error during transaction for sql entity {} and method {}\"",
")",
";",
"if",
"(",
"t",
"instanceof",
"SQLException",
")",
"{",
"final",
"SQLException",
"sqlException",
"=",
"(",
"SQLException",
")",
"t",
";",
"errorMessageBuilder",
".",
"append",
"(",
"\" [SQL DefaultState: \"",
")",
".",
"append",
"(",
"sqlException",
".",
"getSQLState",
"(",
")",
")",
".",
"append",
"(",
"\", Vendor Error Code: \"",
")",
".",
"append",
"(",
"sqlException",
".",
"getErrorCode",
"(",
")",
")",
".",
"append",
"(",
"\"]\"",
")",
";",
"}",
"if",
"(",
"extraErrorMessage",
"!=",
"null",
")",
"{",
"// This is usually the SQL statement",
"errorMessageBuilder",
".",
"append",
"(",
"\"\\n\"",
")",
".",
"append",
"(",
"extraErrorMessage",
")",
";",
"}",
"logger",
".",
"warn",
"(",
"errorMessageBuilder",
".",
"toString",
"(",
")",
",",
"sqlDaoClass",
",",
"method",
".",
"getName",
"(",
")",
")",
";",
"// This is to avoid throwing an exception wrapped in an UndeclaredThrowableException",
"if",
"(",
"!",
"(",
"t",
"instanceof",
"RuntimeException",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"t",
")",
";",
"}",
"else",
"{",
"throw",
"t",
";",
"}",
"}"
] | Nice method name to ease debugging while looking at log files | [
"Nice",
"method",
"name",
"to",
"ease",
"debugging",
"while",
"looking",
"at",
"log",
"files"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/entity/dao/EntitySqlDaoWrapperInvocationHandler.java#L162-L184 |
27,233 | killbill/killbill | entitlement/src/main/java/org/killbill/billing/entitlement/dao/ProxyBlockingStateDao.java | ProxyBlockingStateDao.sortedCopy | public static List<BlockingState> sortedCopy(final Iterable<BlockingState> blockingStates) {
final List<BlockingState> blockingStatesSomewhatSorted = Ordering.<BlockingState>natural().immutableSortedCopy(blockingStates);
final List<BlockingState> result = new LinkedList<BlockingState>();
// Make sure same-day transitions are always returned in the same order depending on their attributes
final Iterator<BlockingState> iterator = blockingStatesSomewhatSorted.iterator();
BlockingState prev = null;
while (iterator.hasNext()) {
final BlockingState current = iterator.next();
if (iterator.hasNext()) {
final BlockingState next = iterator.next();
if (prev != null &&
current.getEffectiveDate().equals(next.getEffectiveDate()) &&
current.getBlockedId().equals(next.getBlockedId()) &&
!current.getService().equals(next.getService())) {
// Same date, same blockable id, different services (for same-service events, trust the total ordering)
// Make sure block billing transitions are respected first
BlockingState prevCandidate = insertTiedBlockingStatesInTheRightOrder(result, current, next, prev.isBlockBilling(), current.isBlockBilling(), next.isBlockBilling());
if (prevCandidate == null) {
// Then respect block entitlement transitions
prevCandidate = insertTiedBlockingStatesInTheRightOrder(result, current, next, prev.isBlockEntitlement(), current.isBlockEntitlement(), next.isBlockEntitlement());
if (prevCandidate == null) {
// And finally block changes transitions
prevCandidate = insertTiedBlockingStatesInTheRightOrder(result, current, next, prev.isBlockChange(), current.isBlockChange(), next.isBlockChange());
if (prevCandidate == null) {
// Trust the current sorting
result.add(current);
result.add(next);
prev = next;
} else {
prev = prevCandidate;
}
} else {
prev = prevCandidate;
}
} else {
prev = prevCandidate;
}
} else {
result.add(current);
result.add(next);
prev = next;
}
} else {
// End of the list
result.add(current);
}
}
return result;
} | java | public static List<BlockingState> sortedCopy(final Iterable<BlockingState> blockingStates) {
final List<BlockingState> blockingStatesSomewhatSorted = Ordering.<BlockingState>natural().immutableSortedCopy(blockingStates);
final List<BlockingState> result = new LinkedList<BlockingState>();
// Make sure same-day transitions are always returned in the same order depending on their attributes
final Iterator<BlockingState> iterator = blockingStatesSomewhatSorted.iterator();
BlockingState prev = null;
while (iterator.hasNext()) {
final BlockingState current = iterator.next();
if (iterator.hasNext()) {
final BlockingState next = iterator.next();
if (prev != null &&
current.getEffectiveDate().equals(next.getEffectiveDate()) &&
current.getBlockedId().equals(next.getBlockedId()) &&
!current.getService().equals(next.getService())) {
// Same date, same blockable id, different services (for same-service events, trust the total ordering)
// Make sure block billing transitions are respected first
BlockingState prevCandidate = insertTiedBlockingStatesInTheRightOrder(result, current, next, prev.isBlockBilling(), current.isBlockBilling(), next.isBlockBilling());
if (prevCandidate == null) {
// Then respect block entitlement transitions
prevCandidate = insertTiedBlockingStatesInTheRightOrder(result, current, next, prev.isBlockEntitlement(), current.isBlockEntitlement(), next.isBlockEntitlement());
if (prevCandidate == null) {
// And finally block changes transitions
prevCandidate = insertTiedBlockingStatesInTheRightOrder(result, current, next, prev.isBlockChange(), current.isBlockChange(), next.isBlockChange());
if (prevCandidate == null) {
// Trust the current sorting
result.add(current);
result.add(next);
prev = next;
} else {
prev = prevCandidate;
}
} else {
prev = prevCandidate;
}
} else {
prev = prevCandidate;
}
} else {
result.add(current);
result.add(next);
prev = next;
}
} else {
// End of the list
result.add(current);
}
}
return result;
} | [
"public",
"static",
"List",
"<",
"BlockingState",
">",
"sortedCopy",
"(",
"final",
"Iterable",
"<",
"BlockingState",
">",
"blockingStates",
")",
"{",
"final",
"List",
"<",
"BlockingState",
">",
"blockingStatesSomewhatSorted",
"=",
"Ordering",
".",
"<",
"BlockingState",
">",
"natural",
"(",
")",
".",
"immutableSortedCopy",
"(",
"blockingStates",
")",
";",
"final",
"List",
"<",
"BlockingState",
">",
"result",
"=",
"new",
"LinkedList",
"<",
"BlockingState",
">",
"(",
")",
";",
"// Make sure same-day transitions are always returned in the same order depending on their attributes",
"final",
"Iterator",
"<",
"BlockingState",
">",
"iterator",
"=",
"blockingStatesSomewhatSorted",
".",
"iterator",
"(",
")",
";",
"BlockingState",
"prev",
"=",
"null",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"BlockingState",
"current",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"BlockingState",
"next",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"prev",
"!=",
"null",
"&&",
"current",
".",
"getEffectiveDate",
"(",
")",
".",
"equals",
"(",
"next",
".",
"getEffectiveDate",
"(",
")",
")",
"&&",
"current",
".",
"getBlockedId",
"(",
")",
".",
"equals",
"(",
"next",
".",
"getBlockedId",
"(",
")",
")",
"&&",
"!",
"current",
".",
"getService",
"(",
")",
".",
"equals",
"(",
"next",
".",
"getService",
"(",
")",
")",
")",
"{",
"// Same date, same blockable id, different services (for same-service events, trust the total ordering)",
"// Make sure block billing transitions are respected first",
"BlockingState",
"prevCandidate",
"=",
"insertTiedBlockingStatesInTheRightOrder",
"(",
"result",
",",
"current",
",",
"next",
",",
"prev",
".",
"isBlockBilling",
"(",
")",
",",
"current",
".",
"isBlockBilling",
"(",
")",
",",
"next",
".",
"isBlockBilling",
"(",
")",
")",
";",
"if",
"(",
"prevCandidate",
"==",
"null",
")",
"{",
"// Then respect block entitlement transitions",
"prevCandidate",
"=",
"insertTiedBlockingStatesInTheRightOrder",
"(",
"result",
",",
"current",
",",
"next",
",",
"prev",
".",
"isBlockEntitlement",
"(",
")",
",",
"current",
".",
"isBlockEntitlement",
"(",
")",
",",
"next",
".",
"isBlockEntitlement",
"(",
")",
")",
";",
"if",
"(",
"prevCandidate",
"==",
"null",
")",
"{",
"// And finally block changes transitions",
"prevCandidate",
"=",
"insertTiedBlockingStatesInTheRightOrder",
"(",
"result",
",",
"current",
",",
"next",
",",
"prev",
".",
"isBlockChange",
"(",
")",
",",
"current",
".",
"isBlockChange",
"(",
")",
",",
"next",
".",
"isBlockChange",
"(",
")",
")",
";",
"if",
"(",
"prevCandidate",
"==",
"null",
")",
"{",
"// Trust the current sorting",
"result",
".",
"add",
"(",
"current",
")",
";",
"result",
".",
"add",
"(",
"next",
")",
";",
"prev",
"=",
"next",
";",
"}",
"else",
"{",
"prev",
"=",
"prevCandidate",
";",
"}",
"}",
"else",
"{",
"prev",
"=",
"prevCandidate",
";",
"}",
"}",
"else",
"{",
"prev",
"=",
"prevCandidate",
";",
"}",
"}",
"else",
"{",
"result",
".",
"add",
"(",
"current",
")",
";",
"result",
".",
"add",
"(",
"next",
")",
";",
"prev",
"=",
"next",
";",
"}",
"}",
"else",
"{",
"// End of the list",
"result",
".",
"add",
"(",
"current",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Ordering is critical here, especially for Junction | [
"Ordering",
"is",
"critical",
"here",
"especially",
"for",
"Junction"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/entitlement/src/main/java/org/killbill/billing/entitlement/dao/ProxyBlockingStateDao.java#L74-L126 |
27,234 | killbill/killbill | entitlement/src/main/java/org/killbill/billing/entitlement/dao/ProxyBlockingStateDao.java | ProxyBlockingStateDao.addBlockingStatesNotOnDisk | protected List<BlockingState> addBlockingStatesNotOnDisk(@Nullable final UUID blockableId,
@Nullable final BlockingStateType blockingStateType,
final Collection<BlockingState> blockingStatesOnDiskCopy,
final Iterable<SubscriptionBase> baseSubscriptionsToConsider,
final Iterable<EventsStream> eventsStreams) {
// Compute the blocking states not on disk for all base subscriptions
final DateTime now = clock.getUTCNow();
for (final SubscriptionBase baseSubscription : baseSubscriptionsToConsider) {
final EventsStream eventsStream = Iterables.<EventsStream>find(eventsStreams,
new Predicate<EventsStream>() {
@Override
public boolean apply(final EventsStream input) {
return input.getSubscriptionBase().getId().equals(baseSubscription.getId());
}
});
// First, check to see if the base entitlement is cancelled
final Collection<BlockingState> blockingStatesNotOnDisk = eventsStream.computeAddonsBlockingStatesForFutureSubscriptionBaseEvents();
// Inject the extra blocking states into the stream if needed
for (final BlockingState blockingState : blockingStatesNotOnDisk) {
// If this entitlement is actually already cancelled, add the cancellation event we computed
// only if it's prior to the blocking state on disk (e.g. add-on future cancelled but base plan cancelled earlier).
BlockingState cancellationBlockingStateOnDisk = null;
boolean overrideCancellationBlockingStateOnDisk = false;
if (isEntitlementCancellationBlockingState(blockingState)) {
cancellationBlockingStateOnDisk = findEntitlementCancellationBlockingState(blockingState.getBlockedId(), blockingStatesOnDiskCopy);
overrideCancellationBlockingStateOnDisk = cancellationBlockingStateOnDisk != null && blockingState.getEffectiveDate().isBefore(cancellationBlockingStateOnDisk.getEffectiveDate());
}
if ((
blockingStateType == null ||
// In case we're coming from OptimizedProxyBlockingStateDao, make sure we don't add
// blocking states for other add-ons on that base subscription
(BlockingStateType.SUBSCRIPTION.equals(blockingStateType) && blockingState.getBlockedId().equals(blockableId))
) && (
cancellationBlockingStateOnDisk == null || overrideCancellationBlockingStateOnDisk
)) {
final BlockingStateModelDao blockingStateModelDao = new BlockingStateModelDao(blockingState, now, now);
blockingStatesOnDiskCopy.add(BlockingStateModelDao.toBlockingState(blockingStateModelDao));
if (overrideCancellationBlockingStateOnDisk) {
blockingStatesOnDiskCopy.remove(cancellationBlockingStateOnDisk);
}
}
}
}
// Return the sorted list
return sortedCopy(blockingStatesOnDiskCopy);
} | java | protected List<BlockingState> addBlockingStatesNotOnDisk(@Nullable final UUID blockableId,
@Nullable final BlockingStateType blockingStateType,
final Collection<BlockingState> blockingStatesOnDiskCopy,
final Iterable<SubscriptionBase> baseSubscriptionsToConsider,
final Iterable<EventsStream> eventsStreams) {
// Compute the blocking states not on disk for all base subscriptions
final DateTime now = clock.getUTCNow();
for (final SubscriptionBase baseSubscription : baseSubscriptionsToConsider) {
final EventsStream eventsStream = Iterables.<EventsStream>find(eventsStreams,
new Predicate<EventsStream>() {
@Override
public boolean apply(final EventsStream input) {
return input.getSubscriptionBase().getId().equals(baseSubscription.getId());
}
});
// First, check to see if the base entitlement is cancelled
final Collection<BlockingState> blockingStatesNotOnDisk = eventsStream.computeAddonsBlockingStatesForFutureSubscriptionBaseEvents();
// Inject the extra blocking states into the stream if needed
for (final BlockingState blockingState : blockingStatesNotOnDisk) {
// If this entitlement is actually already cancelled, add the cancellation event we computed
// only if it's prior to the blocking state on disk (e.g. add-on future cancelled but base plan cancelled earlier).
BlockingState cancellationBlockingStateOnDisk = null;
boolean overrideCancellationBlockingStateOnDisk = false;
if (isEntitlementCancellationBlockingState(blockingState)) {
cancellationBlockingStateOnDisk = findEntitlementCancellationBlockingState(blockingState.getBlockedId(), blockingStatesOnDiskCopy);
overrideCancellationBlockingStateOnDisk = cancellationBlockingStateOnDisk != null && blockingState.getEffectiveDate().isBefore(cancellationBlockingStateOnDisk.getEffectiveDate());
}
if ((
blockingStateType == null ||
// In case we're coming from OptimizedProxyBlockingStateDao, make sure we don't add
// blocking states for other add-ons on that base subscription
(BlockingStateType.SUBSCRIPTION.equals(blockingStateType) && blockingState.getBlockedId().equals(blockableId))
) && (
cancellationBlockingStateOnDisk == null || overrideCancellationBlockingStateOnDisk
)) {
final BlockingStateModelDao blockingStateModelDao = new BlockingStateModelDao(blockingState, now, now);
blockingStatesOnDiskCopy.add(BlockingStateModelDao.toBlockingState(blockingStateModelDao));
if (overrideCancellationBlockingStateOnDisk) {
blockingStatesOnDiskCopy.remove(cancellationBlockingStateOnDisk);
}
}
}
}
// Return the sorted list
return sortedCopy(blockingStatesOnDiskCopy);
} | [
"protected",
"List",
"<",
"BlockingState",
">",
"addBlockingStatesNotOnDisk",
"(",
"@",
"Nullable",
"final",
"UUID",
"blockableId",
",",
"@",
"Nullable",
"final",
"BlockingStateType",
"blockingStateType",
",",
"final",
"Collection",
"<",
"BlockingState",
">",
"blockingStatesOnDiskCopy",
",",
"final",
"Iterable",
"<",
"SubscriptionBase",
">",
"baseSubscriptionsToConsider",
",",
"final",
"Iterable",
"<",
"EventsStream",
">",
"eventsStreams",
")",
"{",
"// Compute the blocking states not on disk for all base subscriptions",
"final",
"DateTime",
"now",
"=",
"clock",
".",
"getUTCNow",
"(",
")",
";",
"for",
"(",
"final",
"SubscriptionBase",
"baseSubscription",
":",
"baseSubscriptionsToConsider",
")",
"{",
"final",
"EventsStream",
"eventsStream",
"=",
"Iterables",
".",
"<",
"EventsStream",
">",
"find",
"(",
"eventsStreams",
",",
"new",
"Predicate",
"<",
"EventsStream",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"final",
"EventsStream",
"input",
")",
"{",
"return",
"input",
".",
"getSubscriptionBase",
"(",
")",
".",
"getId",
"(",
")",
".",
"equals",
"(",
"baseSubscription",
".",
"getId",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"// First, check to see if the base entitlement is cancelled",
"final",
"Collection",
"<",
"BlockingState",
">",
"blockingStatesNotOnDisk",
"=",
"eventsStream",
".",
"computeAddonsBlockingStatesForFutureSubscriptionBaseEvents",
"(",
")",
";",
"// Inject the extra blocking states into the stream if needed",
"for",
"(",
"final",
"BlockingState",
"blockingState",
":",
"blockingStatesNotOnDisk",
")",
"{",
"// If this entitlement is actually already cancelled, add the cancellation event we computed",
"// only if it's prior to the blocking state on disk (e.g. add-on future cancelled but base plan cancelled earlier).",
"BlockingState",
"cancellationBlockingStateOnDisk",
"=",
"null",
";",
"boolean",
"overrideCancellationBlockingStateOnDisk",
"=",
"false",
";",
"if",
"(",
"isEntitlementCancellationBlockingState",
"(",
"blockingState",
")",
")",
"{",
"cancellationBlockingStateOnDisk",
"=",
"findEntitlementCancellationBlockingState",
"(",
"blockingState",
".",
"getBlockedId",
"(",
")",
",",
"blockingStatesOnDiskCopy",
")",
";",
"overrideCancellationBlockingStateOnDisk",
"=",
"cancellationBlockingStateOnDisk",
"!=",
"null",
"&&",
"blockingState",
".",
"getEffectiveDate",
"(",
")",
".",
"isBefore",
"(",
"cancellationBlockingStateOnDisk",
".",
"getEffectiveDate",
"(",
")",
")",
";",
"}",
"if",
"(",
"(",
"blockingStateType",
"==",
"null",
"||",
"// In case we're coming from OptimizedProxyBlockingStateDao, make sure we don't add",
"// blocking states for other add-ons on that base subscription",
"(",
"BlockingStateType",
".",
"SUBSCRIPTION",
".",
"equals",
"(",
"blockingStateType",
")",
"&&",
"blockingState",
".",
"getBlockedId",
"(",
")",
".",
"equals",
"(",
"blockableId",
")",
")",
")",
"&&",
"(",
"cancellationBlockingStateOnDisk",
"==",
"null",
"||",
"overrideCancellationBlockingStateOnDisk",
")",
")",
"{",
"final",
"BlockingStateModelDao",
"blockingStateModelDao",
"=",
"new",
"BlockingStateModelDao",
"(",
"blockingState",
",",
"now",
",",
"now",
")",
";",
"blockingStatesOnDiskCopy",
".",
"add",
"(",
"BlockingStateModelDao",
".",
"toBlockingState",
"(",
"blockingStateModelDao",
")",
")",
";",
"if",
"(",
"overrideCancellationBlockingStateOnDisk",
")",
"{",
"blockingStatesOnDiskCopy",
".",
"remove",
"(",
"cancellationBlockingStateOnDisk",
")",
";",
"}",
"}",
"}",
"}",
"// Return the sorted list",
"return",
"sortedCopy",
"(",
"blockingStatesOnDiskCopy",
")",
";",
"}"
] | Special signature for OptimizedProxyBlockingStateDao | [
"Special",
"signature",
"for",
"OptimizedProxyBlockingStateDao"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/entitlement/src/main/java/org/killbill/billing/entitlement/dao/ProxyBlockingStateDao.java#L285-L335 |
27,235 | killbill/killbill | util/src/main/java/org/killbill/billing/util/audit/DefaultAccountAuditLogsForObjectType.java | DefaultAccountAuditLogsForObjectType.initializeIfNeeded | void initializeIfNeeded(final UUID objectId) {
if (auditLogsCache.get(objectId) == null) {
auditLogsCache.put(objectId, new LinkedList<AuditLog>());
}
} | java | void initializeIfNeeded(final UUID objectId) {
if (auditLogsCache.get(objectId) == null) {
auditLogsCache.put(objectId, new LinkedList<AuditLog>());
}
} | [
"void",
"initializeIfNeeded",
"(",
"final",
"UUID",
"objectId",
")",
"{",
"if",
"(",
"auditLogsCache",
".",
"get",
"(",
"objectId",
")",
"==",
"null",
")",
"{",
"auditLogsCache",
".",
"put",
"(",
"objectId",
",",
"new",
"LinkedList",
"<",
"AuditLog",
">",
"(",
")",
")",
";",
"}",
"}"
] | Used by DefaultAccountAuditLogs | [
"Used",
"by",
"DefaultAccountAuditLogs"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/audit/DefaultAccountAuditLogsForObjectType.java#L52-L56 |
27,236 | killbill/killbill | junction/src/main/java/org/killbill/billing/junction/plumbing/billing/DisabledDuration.java | DisabledDuration.compareTo | @Override
public int compareTo(final DisabledDuration o) {
int result = start.compareTo(o.getStart());
if (result == 0) {
if (end == null && o.getEnd() == null) {
result = 0;
} else if (end != null && o.getEnd() != null) {
result = end.compareTo(o.getEnd());
} else if (o.getEnd() == null) {
return -1;
} else {
return 1;
}
}
return result;
} | java | @Override
public int compareTo(final DisabledDuration o) {
int result = start.compareTo(o.getStart());
if (result == 0) {
if (end == null && o.getEnd() == null) {
result = 0;
} else if (end != null && o.getEnd() != null) {
result = end.compareTo(o.getEnd());
} else if (o.getEnd() == null) {
return -1;
} else {
return 1;
}
}
return result;
} | [
"@",
"Override",
"public",
"int",
"compareTo",
"(",
"final",
"DisabledDuration",
"o",
")",
"{",
"int",
"result",
"=",
"start",
".",
"compareTo",
"(",
"o",
".",
"getStart",
"(",
")",
")",
";",
"if",
"(",
"result",
"==",
"0",
")",
"{",
"if",
"(",
"end",
"==",
"null",
"&&",
"o",
".",
"getEnd",
"(",
")",
"==",
"null",
")",
"{",
"result",
"=",
"0",
";",
"}",
"else",
"if",
"(",
"end",
"!=",
"null",
"&&",
"o",
".",
"getEnd",
"(",
")",
"!=",
"null",
")",
"{",
"result",
"=",
"end",
".",
"compareTo",
"(",
"o",
".",
"getEnd",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"o",
".",
"getEnd",
"(",
")",
"==",
"null",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"{",
"return",
"1",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Order by start date first and then end date | [
"Order",
"by",
"start",
"date",
"first",
"and",
"then",
"end",
"date"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/junction/src/main/java/org/killbill/billing/junction/plumbing/billing/DisabledDuration.java#L47-L62 |
27,237 | killbill/killbill | util/src/main/java/org/killbill/billing/util/glue/KillBillShiroAopModule.java | KillBillShiroAopModule.bindShiroInterceptorWithHierarchy | protected final void bindShiroInterceptorWithHierarchy(final AnnotationMethodInterceptor methodInterceptor) {
bindInterceptor(Matchers.any(),
new AbstractMatcher<Method>() {
public boolean matches(final Method method) {
final Class<? extends Annotation> annotation = methodInterceptor.getHandler().getAnnotationClass();
return resolver.getAnnotationFromMethod(method, annotation) != null;
}
},
new AopAllianceMethodInterceptorAdapter(methodInterceptor));
} | java | protected final void bindShiroInterceptorWithHierarchy(final AnnotationMethodInterceptor methodInterceptor) {
bindInterceptor(Matchers.any(),
new AbstractMatcher<Method>() {
public boolean matches(final Method method) {
final Class<? extends Annotation> annotation = methodInterceptor.getHandler().getAnnotationClass();
return resolver.getAnnotationFromMethod(method, annotation) != null;
}
},
new AopAllianceMethodInterceptorAdapter(methodInterceptor));
} | [
"protected",
"final",
"void",
"bindShiroInterceptorWithHierarchy",
"(",
"final",
"AnnotationMethodInterceptor",
"methodInterceptor",
")",
"{",
"bindInterceptor",
"(",
"Matchers",
".",
"any",
"(",
")",
",",
"new",
"AbstractMatcher",
"<",
"Method",
">",
"(",
")",
"{",
"public",
"boolean",
"matches",
"(",
"final",
"Method",
"method",
")",
"{",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotation",
"=",
"methodInterceptor",
".",
"getHandler",
"(",
")",
".",
"getAnnotationClass",
"(",
")",
";",
"return",
"resolver",
".",
"getAnnotationFromMethod",
"(",
"method",
",",
"annotation",
")",
"!=",
"null",
";",
"}",
"}",
",",
"new",
"AopAllianceMethodInterceptorAdapter",
"(",
"methodInterceptor",
")",
")",
";",
"}"
] | Similar to bindShiroInterceptor but will look for annotations in the class hierarchy | [
"Similar",
"to",
"bindShiroInterceptor",
"but",
"will",
"look",
"for",
"annotations",
"in",
"the",
"class",
"hierarchy"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/glue/KillBillShiroAopModule.java#L61-L70 |
27,238 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsNodeInterval.java | ItemsNodeInterval.addExistingItem | public void addExistingItem(final ItemsNodeInterval newNode) {
Preconditions.checkState(newNode.getItems().size() == 1, "Invalid node=%s", newNode);
final Item item = newNode.getItems().get(0);
addNode(newNode,
new AddNodeCallback() {
@Override
public boolean onExistingNode(final NodeInterval existingNode) {
final ItemsInterval existingOrNewNodeItems = ((ItemsNodeInterval) existingNode).getItemsInterval();
existingOrNewNodeItems.add(item);
// There is no new node added but instead we just populated the list of items for the already existing node
return false;
}
@Override
public boolean shouldInsertNode(final NodeInterval insertionNode) {
// Always want to insert node in the tree when we find the right place.
return true;
}
});
} | java | public void addExistingItem(final ItemsNodeInterval newNode) {
Preconditions.checkState(newNode.getItems().size() == 1, "Invalid node=%s", newNode);
final Item item = newNode.getItems().get(0);
addNode(newNode,
new AddNodeCallback() {
@Override
public boolean onExistingNode(final NodeInterval existingNode) {
final ItemsInterval existingOrNewNodeItems = ((ItemsNodeInterval) existingNode).getItemsInterval();
existingOrNewNodeItems.add(item);
// There is no new node added but instead we just populated the list of items for the already existing node
return false;
}
@Override
public boolean shouldInsertNode(final NodeInterval insertionNode) {
// Always want to insert node in the tree when we find the right place.
return true;
}
});
} | [
"public",
"void",
"addExistingItem",
"(",
"final",
"ItemsNodeInterval",
"newNode",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"newNode",
".",
"getItems",
"(",
")",
".",
"size",
"(",
")",
"==",
"1",
",",
"\"Invalid node=%s\"",
",",
"newNode",
")",
";",
"final",
"Item",
"item",
"=",
"newNode",
".",
"getItems",
"(",
")",
".",
"get",
"(",
"0",
")",
";",
"addNode",
"(",
"newNode",
",",
"new",
"AddNodeCallback",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"onExistingNode",
"(",
"final",
"NodeInterval",
"existingNode",
")",
"{",
"final",
"ItemsInterval",
"existingOrNewNodeItems",
"=",
"(",
"(",
"ItemsNodeInterval",
")",
"existingNode",
")",
".",
"getItemsInterval",
"(",
")",
";",
"existingOrNewNodeItems",
".",
"add",
"(",
"item",
")",
";",
"// There is no new node added but instead we just populated the list of items for the already existing node",
"return",
"false",
";",
"}",
"@",
"Override",
"public",
"boolean",
"shouldInsertNode",
"(",
"final",
"NodeInterval",
"insertionNode",
")",
"{",
"// Always want to insert node in the tree when we find the right place.",
"return",
"true",
";",
"}",
"}",
")",
";",
"}"
] | Add existing item into the tree
@param newNode an existing item | [
"Add",
"existing",
"item",
"into",
"the",
"tree"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsNodeInterval.java#L73-L93 |
27,239 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsNodeInterval.java | ItemsNodeInterval.addAdjustment | public Item addAdjustment(final InvoiceItem item, final UUID targetInvoiceId) {
final UUID targetId = item.getLinkedItemId();
final NodeInterval node = findNode(new SearchCallback() {
@Override
public boolean isMatch(final NodeInterval curNode) {
return ((ItemsNodeInterval) curNode).getItemsInterval().findItem(targetId) != null;
}
});
Preconditions.checkNotNull(node, "Unable to find item interval for id='%s', tree=%s", targetId, this);
final ItemsInterval targetItemsInterval = ((ItemsNodeInterval) node).getItemsInterval();
final Item targetItem = targetItemsInterval.findItem(targetId);
Preconditions.checkNotNull(targetItem, "Unable to find item with id='%s', itemsInterval=%s", targetId, targetItemsInterval);
final BigDecimal adjustmentAmount = item.getAmount().negate();
if (targetItem.getAmount().compareTo(adjustmentAmount) == 0) {
// Full item adjustment - treat it like a repair
addExistingItem(new ItemsNodeInterval(this, new Item(item, targetItem.getStartDate(), targetItem.getEndDate(), targetInvoiceId, ItemAction.CANCEL)));
return targetItem;
} else {
targetItem.incrementAdjustedAmount(adjustmentAmount);
return null;
}
} | java | public Item addAdjustment(final InvoiceItem item, final UUID targetInvoiceId) {
final UUID targetId = item.getLinkedItemId();
final NodeInterval node = findNode(new SearchCallback() {
@Override
public boolean isMatch(final NodeInterval curNode) {
return ((ItemsNodeInterval) curNode).getItemsInterval().findItem(targetId) != null;
}
});
Preconditions.checkNotNull(node, "Unable to find item interval for id='%s', tree=%s", targetId, this);
final ItemsInterval targetItemsInterval = ((ItemsNodeInterval) node).getItemsInterval();
final Item targetItem = targetItemsInterval.findItem(targetId);
Preconditions.checkNotNull(targetItem, "Unable to find item with id='%s', itemsInterval=%s", targetId, targetItemsInterval);
final BigDecimal adjustmentAmount = item.getAmount().negate();
if (targetItem.getAmount().compareTo(adjustmentAmount) == 0) {
// Full item adjustment - treat it like a repair
addExistingItem(new ItemsNodeInterval(this, new Item(item, targetItem.getStartDate(), targetItem.getEndDate(), targetInvoiceId, ItemAction.CANCEL)));
return targetItem;
} else {
targetItem.incrementAdjustedAmount(adjustmentAmount);
return null;
}
} | [
"public",
"Item",
"addAdjustment",
"(",
"final",
"InvoiceItem",
"item",
",",
"final",
"UUID",
"targetInvoiceId",
")",
"{",
"final",
"UUID",
"targetId",
"=",
"item",
".",
"getLinkedItemId",
"(",
")",
";",
"final",
"NodeInterval",
"node",
"=",
"findNode",
"(",
"new",
"SearchCallback",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"isMatch",
"(",
"final",
"NodeInterval",
"curNode",
")",
"{",
"return",
"(",
"(",
"ItemsNodeInterval",
")",
"curNode",
")",
".",
"getItemsInterval",
"(",
")",
".",
"findItem",
"(",
"targetId",
")",
"!=",
"null",
";",
"}",
"}",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"node",
",",
"\"Unable to find item interval for id='%s', tree=%s\"",
",",
"targetId",
",",
"this",
")",
";",
"final",
"ItemsInterval",
"targetItemsInterval",
"=",
"(",
"(",
"ItemsNodeInterval",
")",
"node",
")",
".",
"getItemsInterval",
"(",
")",
";",
"final",
"Item",
"targetItem",
"=",
"targetItemsInterval",
".",
"findItem",
"(",
"targetId",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"targetItem",
",",
"\"Unable to find item with id='%s', itemsInterval=%s\"",
",",
"targetId",
",",
"targetItemsInterval",
")",
";",
"final",
"BigDecimal",
"adjustmentAmount",
"=",
"item",
".",
"getAmount",
"(",
")",
".",
"negate",
"(",
")",
";",
"if",
"(",
"targetItem",
".",
"getAmount",
"(",
")",
".",
"compareTo",
"(",
"adjustmentAmount",
")",
"==",
"0",
")",
"{",
"// Full item adjustment - treat it like a repair",
"addExistingItem",
"(",
"new",
"ItemsNodeInterval",
"(",
"this",
",",
"new",
"Item",
"(",
"item",
",",
"targetItem",
".",
"getStartDate",
"(",
")",
",",
"targetItem",
".",
"getEndDate",
"(",
")",
",",
"targetInvoiceId",
",",
"ItemAction",
".",
"CANCEL",
")",
")",
")",
";",
"return",
"targetItem",
";",
"}",
"else",
"{",
"targetItem",
".",
"incrementAdjustedAmount",
"(",
"adjustmentAmount",
")",
";",
"return",
"null",
";",
"}",
"}"
] | Add the adjustment amount on the item specified by the targetId.
@return linked item if fully adjusted, null otherwise | [
"Add",
"the",
"adjustment",
"amount",
"on",
"the",
"item",
"specified",
"by",
"the",
"targetId",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsNodeInterval.java#L203-L227 |
27,240 | killbill/killbill | catalog/src/main/java/org/killbill/billing/catalog/DefaultVersionedCatalog.java | DefaultVersionedCatalog.getStaticCatalog | private StaticCatalog getStaticCatalog(final PlanSpecifier spec, final DateTime requestedDate, final DateTime subscriptionChangePlanDate) throws CatalogApiException {
final CatalogPlanEntry entry = findCatalogPlanEntry(new PlanRequestWrapper(spec), requestedDate, subscriptionChangePlanDate);
return entry.getStaticCatalog();
} | java | private StaticCatalog getStaticCatalog(final PlanSpecifier spec, final DateTime requestedDate, final DateTime subscriptionChangePlanDate) throws CatalogApiException {
final CatalogPlanEntry entry = findCatalogPlanEntry(new PlanRequestWrapper(spec), requestedDate, subscriptionChangePlanDate);
return entry.getStaticCatalog();
} | [
"private",
"StaticCatalog",
"getStaticCatalog",
"(",
"final",
"PlanSpecifier",
"spec",
",",
"final",
"DateTime",
"requestedDate",
",",
"final",
"DateTime",
"subscriptionChangePlanDate",
")",
"throws",
"CatalogApiException",
"{",
"final",
"CatalogPlanEntry",
"entry",
"=",
"findCatalogPlanEntry",
"(",
"new",
"PlanRequestWrapper",
"(",
"spec",
")",
",",
"requestedDate",
",",
"subscriptionChangePlanDate",
")",
";",
"return",
"entry",
".",
"getStaticCatalog",
"(",
")",
";",
"}"
] | Note that the PlanSpecifier billing period must refer here to the recurring phase one when a plan name isn't specified | [
"Note",
"that",
"the",
"PlanSpecifier",
"billing",
"period",
"must",
"refer",
"here",
"to",
"the",
"recurring",
"phase",
"one",
"when",
"a",
"plan",
"name",
"isn",
"t",
"specified"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/catalog/src/main/java/org/killbill/billing/catalog/DefaultVersionedCatalog.java#L327-L330 |
27,241 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/dao/CBADao.java | CBADao.computeCBAComplexity | public InvoiceItemModelDao computeCBAComplexity(final InvoiceModelDao invoice,
@Nullable final BigDecimal accountCBAOrNull,
@Nullable final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory,
final InternalCallContext context) throws EntityPersistenceException, InvoiceApiException {
final BigDecimal balance = getInvoiceBalance(invoice);
if (balance.compareTo(BigDecimal.ZERO) < 0) {
// Current balance is negative, we need to generate a credit (positive CBA amount)
return buildCBAItem(invoice, balance, context);
} else if (balance.compareTo(BigDecimal.ZERO) > 0 && invoice.getStatus() == InvoiceStatus.COMMITTED && !invoice.isWrittenOff()) {
// Current balance is positive and the invoice is COMMITTED, we need to use some of the existing if available (negative CBA amount)
// PERF: in some codepaths, the CBA maybe have already been computed
BigDecimal accountCBA = accountCBAOrNull;
if (accountCBAOrNull == null) {
accountCBA = getAccountCBAFromTransaction(entitySqlDaoWrapperFactory, context);
}
if (accountCBA.compareTo(BigDecimal.ZERO) <= 0) {
return null;
}
final BigDecimal positiveCreditAmount = accountCBA.compareTo(balance) > 0 ? balance : accountCBA;
return buildCBAItem(invoice, positiveCreditAmount, context);
} else {
// 0 balance, nothing to do.
return null;
}
} | java | public InvoiceItemModelDao computeCBAComplexity(final InvoiceModelDao invoice,
@Nullable final BigDecimal accountCBAOrNull,
@Nullable final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory,
final InternalCallContext context) throws EntityPersistenceException, InvoiceApiException {
final BigDecimal balance = getInvoiceBalance(invoice);
if (balance.compareTo(BigDecimal.ZERO) < 0) {
// Current balance is negative, we need to generate a credit (positive CBA amount)
return buildCBAItem(invoice, balance, context);
} else if (balance.compareTo(BigDecimal.ZERO) > 0 && invoice.getStatus() == InvoiceStatus.COMMITTED && !invoice.isWrittenOff()) {
// Current balance is positive and the invoice is COMMITTED, we need to use some of the existing if available (negative CBA amount)
// PERF: in some codepaths, the CBA maybe have already been computed
BigDecimal accountCBA = accountCBAOrNull;
if (accountCBAOrNull == null) {
accountCBA = getAccountCBAFromTransaction(entitySqlDaoWrapperFactory, context);
}
if (accountCBA.compareTo(BigDecimal.ZERO) <= 0) {
return null;
}
final BigDecimal positiveCreditAmount = accountCBA.compareTo(balance) > 0 ? balance : accountCBA;
return buildCBAItem(invoice, positiveCreditAmount, context);
} else {
// 0 balance, nothing to do.
return null;
}
} | [
"public",
"InvoiceItemModelDao",
"computeCBAComplexity",
"(",
"final",
"InvoiceModelDao",
"invoice",
",",
"@",
"Nullable",
"final",
"BigDecimal",
"accountCBAOrNull",
",",
"@",
"Nullable",
"final",
"EntitySqlDaoWrapperFactory",
"entitySqlDaoWrapperFactory",
",",
"final",
"InternalCallContext",
"context",
")",
"throws",
"EntityPersistenceException",
",",
"InvoiceApiException",
"{",
"final",
"BigDecimal",
"balance",
"=",
"getInvoiceBalance",
"(",
"invoice",
")",
";",
"if",
"(",
"balance",
".",
"compareTo",
"(",
"BigDecimal",
".",
"ZERO",
")",
"<",
"0",
")",
"{",
"// Current balance is negative, we need to generate a credit (positive CBA amount)",
"return",
"buildCBAItem",
"(",
"invoice",
",",
"balance",
",",
"context",
")",
";",
"}",
"else",
"if",
"(",
"balance",
".",
"compareTo",
"(",
"BigDecimal",
".",
"ZERO",
")",
">",
"0",
"&&",
"invoice",
".",
"getStatus",
"(",
")",
"==",
"InvoiceStatus",
".",
"COMMITTED",
"&&",
"!",
"invoice",
".",
"isWrittenOff",
"(",
")",
")",
"{",
"// Current balance is positive and the invoice is COMMITTED, we need to use some of the existing if available (negative CBA amount)",
"// PERF: in some codepaths, the CBA maybe have already been computed",
"BigDecimal",
"accountCBA",
"=",
"accountCBAOrNull",
";",
"if",
"(",
"accountCBAOrNull",
"==",
"null",
")",
"{",
"accountCBA",
"=",
"getAccountCBAFromTransaction",
"(",
"entitySqlDaoWrapperFactory",
",",
"context",
")",
";",
"}",
"if",
"(",
"accountCBA",
".",
"compareTo",
"(",
"BigDecimal",
".",
"ZERO",
")",
"<=",
"0",
")",
"{",
"return",
"null",
";",
"}",
"final",
"BigDecimal",
"positiveCreditAmount",
"=",
"accountCBA",
".",
"compareTo",
"(",
"balance",
")",
">",
"0",
"?",
"balance",
":",
"accountCBA",
";",
"return",
"buildCBAItem",
"(",
"invoice",
",",
"positiveCreditAmount",
",",
"context",
")",
";",
"}",
"else",
"{",
"// 0 balance, nothing to do.",
"return",
"null",
";",
"}",
"}"
] | We expect a clean up to date invoice, with all the items except the cba, that we will compute in that method | [
"We",
"expect",
"a",
"clean",
"up",
"to",
"date",
"invoice",
"with",
"all",
"the",
"items",
"except",
"the",
"cba",
"that",
"we",
"will",
"compute",
"in",
"that",
"method"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/dao/CBADao.java#L58-L84 |
27,242 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/dao/CBADao.java | CBADao.useExistingCBAFromTransaction | private void useExistingCBAFromTransaction(final BigDecimal accountCBA,
final List<Tag> invoicesTags,
final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory,
final InternalCallContext context) throws InvoiceApiException, EntityPersistenceException {
if (accountCBA.compareTo(BigDecimal.ZERO) <= 0) {
return;
}
// PERF: Computing the invoice balance is difficult to do in the DB, so we effectively need to retrieve all invoices on the account and filter the unpaid ones in memory.
// This should be infrequent though because of the account CBA check above.
final List<InvoiceModelDao> allInvoices = invoiceDaoHelper.getAllInvoicesByAccountFromTransaction(false, invoicesTags, entitySqlDaoWrapperFactory, context);
final List<InvoiceModelDao> unpaidInvoices = invoiceDaoHelper.getUnpaidInvoicesByAccountFromTransaction(allInvoices, null);
// We order the same os BillingStateCalculator-- should really share the comparator
final List<InvoiceModelDao> orderedUnpaidInvoices = Ordering.from(new Comparator<InvoiceModelDao>() {
@Override
public int compare(final InvoiceModelDao i1, final InvoiceModelDao i2) {
return i1.getInvoiceDate().compareTo(i2.getInvoiceDate());
}
}).immutableSortedCopy(unpaidInvoices);
BigDecimal remainingAccountCBA = accountCBA;
for (final InvoiceModelDao unpaidInvoice : orderedUnpaidInvoices) {
remainingAccountCBA = computeCBAComplexityAndCreateCBAItem(remainingAccountCBA, unpaidInvoice, entitySqlDaoWrapperFactory, context);
if (remainingAccountCBA.compareTo(BigDecimal.ZERO) <= 0) {
break;
}
}
} | java | private void useExistingCBAFromTransaction(final BigDecimal accountCBA,
final List<Tag> invoicesTags,
final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory,
final InternalCallContext context) throws InvoiceApiException, EntityPersistenceException {
if (accountCBA.compareTo(BigDecimal.ZERO) <= 0) {
return;
}
// PERF: Computing the invoice balance is difficult to do in the DB, so we effectively need to retrieve all invoices on the account and filter the unpaid ones in memory.
// This should be infrequent though because of the account CBA check above.
final List<InvoiceModelDao> allInvoices = invoiceDaoHelper.getAllInvoicesByAccountFromTransaction(false, invoicesTags, entitySqlDaoWrapperFactory, context);
final List<InvoiceModelDao> unpaidInvoices = invoiceDaoHelper.getUnpaidInvoicesByAccountFromTransaction(allInvoices, null);
// We order the same os BillingStateCalculator-- should really share the comparator
final List<InvoiceModelDao> orderedUnpaidInvoices = Ordering.from(new Comparator<InvoiceModelDao>() {
@Override
public int compare(final InvoiceModelDao i1, final InvoiceModelDao i2) {
return i1.getInvoiceDate().compareTo(i2.getInvoiceDate());
}
}).immutableSortedCopy(unpaidInvoices);
BigDecimal remainingAccountCBA = accountCBA;
for (final InvoiceModelDao unpaidInvoice : orderedUnpaidInvoices) {
remainingAccountCBA = computeCBAComplexityAndCreateCBAItem(remainingAccountCBA, unpaidInvoice, entitySqlDaoWrapperFactory, context);
if (remainingAccountCBA.compareTo(BigDecimal.ZERO) <= 0) {
break;
}
}
} | [
"private",
"void",
"useExistingCBAFromTransaction",
"(",
"final",
"BigDecimal",
"accountCBA",
",",
"final",
"List",
"<",
"Tag",
">",
"invoicesTags",
",",
"final",
"EntitySqlDaoWrapperFactory",
"entitySqlDaoWrapperFactory",
",",
"final",
"InternalCallContext",
"context",
")",
"throws",
"InvoiceApiException",
",",
"EntityPersistenceException",
"{",
"if",
"(",
"accountCBA",
".",
"compareTo",
"(",
"BigDecimal",
".",
"ZERO",
")",
"<=",
"0",
")",
"{",
"return",
";",
"}",
"// PERF: Computing the invoice balance is difficult to do in the DB, so we effectively need to retrieve all invoices on the account and filter the unpaid ones in memory.",
"// This should be infrequent though because of the account CBA check above.",
"final",
"List",
"<",
"InvoiceModelDao",
">",
"allInvoices",
"=",
"invoiceDaoHelper",
".",
"getAllInvoicesByAccountFromTransaction",
"(",
"false",
",",
"invoicesTags",
",",
"entitySqlDaoWrapperFactory",
",",
"context",
")",
";",
"final",
"List",
"<",
"InvoiceModelDao",
">",
"unpaidInvoices",
"=",
"invoiceDaoHelper",
".",
"getUnpaidInvoicesByAccountFromTransaction",
"(",
"allInvoices",
",",
"null",
")",
";",
"// We order the same os BillingStateCalculator-- should really share the comparator",
"final",
"List",
"<",
"InvoiceModelDao",
">",
"orderedUnpaidInvoices",
"=",
"Ordering",
".",
"from",
"(",
"new",
"Comparator",
"<",
"InvoiceModelDao",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"compare",
"(",
"final",
"InvoiceModelDao",
"i1",
",",
"final",
"InvoiceModelDao",
"i2",
")",
"{",
"return",
"i1",
".",
"getInvoiceDate",
"(",
")",
".",
"compareTo",
"(",
"i2",
".",
"getInvoiceDate",
"(",
")",
")",
";",
"}",
"}",
")",
".",
"immutableSortedCopy",
"(",
"unpaidInvoices",
")",
";",
"BigDecimal",
"remainingAccountCBA",
"=",
"accountCBA",
";",
"for",
"(",
"final",
"InvoiceModelDao",
"unpaidInvoice",
":",
"orderedUnpaidInvoices",
")",
"{",
"remainingAccountCBA",
"=",
"computeCBAComplexityAndCreateCBAItem",
"(",
"remainingAccountCBA",
",",
"unpaidInvoice",
",",
"entitySqlDaoWrapperFactory",
",",
"context",
")",
";",
"if",
"(",
"remainingAccountCBA",
".",
"compareTo",
"(",
"BigDecimal",
".",
"ZERO",
")",
"<=",
"0",
")",
"{",
"break",
";",
"}",
"}",
"}"
] | Distribute account CBA across all COMMITTED unpaid invoices | [
"Distribute",
"account",
"CBA",
"across",
"all",
"COMMITTED",
"unpaid",
"invoices"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/dao/CBADao.java#L147-L174 |
27,243 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/dao/CBADao.java | CBADao.computeCBAComplexityAndCreateCBAItem | private BigDecimal computeCBAComplexityAndCreateCBAItem(final BigDecimal accountCBA,
final InvoiceModelDao invoice,
final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory,
final InternalCallContext context) throws EntityPersistenceException, InvoiceApiException {
final InvoiceItemModelDao cbaItem = computeCBAComplexity(invoice, accountCBA, entitySqlDaoWrapperFactory, context);
if (cbaItem != null) {
createCBAItem(invoice, cbaItem, entitySqlDaoWrapperFactory, context);
return accountCBA.add(cbaItem.getAmount());
} else {
return accountCBA;
}
} | java | private BigDecimal computeCBAComplexityAndCreateCBAItem(final BigDecimal accountCBA,
final InvoiceModelDao invoice,
final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory,
final InternalCallContext context) throws EntityPersistenceException, InvoiceApiException {
final InvoiceItemModelDao cbaItem = computeCBAComplexity(invoice, accountCBA, entitySqlDaoWrapperFactory, context);
if (cbaItem != null) {
createCBAItem(invoice, cbaItem, entitySqlDaoWrapperFactory, context);
return accountCBA.add(cbaItem.getAmount());
} else {
return accountCBA;
}
} | [
"private",
"BigDecimal",
"computeCBAComplexityAndCreateCBAItem",
"(",
"final",
"BigDecimal",
"accountCBA",
",",
"final",
"InvoiceModelDao",
"invoice",
",",
"final",
"EntitySqlDaoWrapperFactory",
"entitySqlDaoWrapperFactory",
",",
"final",
"InternalCallContext",
"context",
")",
"throws",
"EntityPersistenceException",
",",
"InvoiceApiException",
"{",
"final",
"InvoiceItemModelDao",
"cbaItem",
"=",
"computeCBAComplexity",
"(",
"invoice",
",",
"accountCBA",
",",
"entitySqlDaoWrapperFactory",
",",
"context",
")",
";",
"if",
"(",
"cbaItem",
"!=",
"null",
")",
"{",
"createCBAItem",
"(",
"invoice",
",",
"cbaItem",
",",
"entitySqlDaoWrapperFactory",
",",
"context",
")",
";",
"return",
"accountCBA",
".",
"add",
"(",
"cbaItem",
".",
"getAmount",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"accountCBA",
";",
"}",
"}"
] | Return the updated account CBA | [
"Return",
"the",
"updated",
"account",
"CBA"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/dao/CBADao.java#L177-L188 |
27,244 | killbill/killbill | util/src/main/java/org/killbill/billing/util/validation/ValidationManager.java | ValidationManager.loadSchemaInformation | public void loadSchemaInformation(final String schemaName) {
columnInfoMap.clear();
// get schema information and map it to columnInfo
final List<DefaultColumnInfo> columnInfoList = dao.getColumnInfoList(schemaName);
for (final DefaultColumnInfo columnInfo : columnInfoList) {
final String tableName = columnInfo.getTableName();
if (!columnInfoMap.containsKey(tableName)) {
columnInfoMap.put(tableName, new HashMap<String, DefaultColumnInfo>());
}
columnInfoMap.get(tableName).put(columnInfo.getColumnName(), columnInfo);
}
} | java | public void loadSchemaInformation(final String schemaName) {
columnInfoMap.clear();
// get schema information and map it to columnInfo
final List<DefaultColumnInfo> columnInfoList = dao.getColumnInfoList(schemaName);
for (final DefaultColumnInfo columnInfo : columnInfoList) {
final String tableName = columnInfo.getTableName();
if (!columnInfoMap.containsKey(tableName)) {
columnInfoMap.put(tableName, new HashMap<String, DefaultColumnInfo>());
}
columnInfoMap.get(tableName).put(columnInfo.getColumnName(), columnInfo);
}
} | [
"public",
"void",
"loadSchemaInformation",
"(",
"final",
"String",
"schemaName",
")",
"{",
"columnInfoMap",
".",
"clear",
"(",
")",
";",
"// get schema information and map it to columnInfo",
"final",
"List",
"<",
"DefaultColumnInfo",
">",
"columnInfoList",
"=",
"dao",
".",
"getColumnInfoList",
"(",
"schemaName",
")",
";",
"for",
"(",
"final",
"DefaultColumnInfo",
"columnInfo",
":",
"columnInfoList",
")",
"{",
"final",
"String",
"tableName",
"=",
"columnInfo",
".",
"getTableName",
"(",
")",
";",
"if",
"(",
"!",
"columnInfoMap",
".",
"containsKey",
"(",
"tableName",
")",
")",
"{",
"columnInfoMap",
".",
"put",
"(",
"tableName",
",",
"new",
"HashMap",
"<",
"String",
",",
"DefaultColumnInfo",
">",
"(",
")",
")",
";",
"}",
"columnInfoMap",
".",
"get",
"(",
"tableName",
")",
".",
"put",
"(",
"columnInfo",
".",
"getColumnName",
"(",
")",
",",
"columnInfo",
")",
";",
"}",
"}"
] | replaces existing schema information with the information for the specified schema | [
"replaces",
"existing",
"schema",
"information",
"with",
"the",
"information",
"for",
"the",
"specified",
"schema"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/validation/ValidationManager.java#L45-L59 |
27,245 | killbill/killbill | catalog/src/main/java/org/killbill/billing/catalog/CatalogSafetyInitializer.java | CatalogSafetyInitializer.initializeNonRequiredFields | private static LinkedList<Field> initializeNonRequiredFields(final Class<?> aClass) {
final LinkedList<Field> result = new LinkedList();
final Field[] fields = aClass.getDeclaredFields();
for (final Field f : fields) {
if (f.getType().isArray()) {
final XmlElementWrapper xmlElementWrapper = f.getAnnotation(XmlElementWrapper.class);
if (xmlElementWrapper != null) {
if (!xmlElementWrapper.required()) {
result.add(f);
}
} else {
final XmlElement xmlElement = f.getAnnotation(XmlElement.class);
if (xmlElement != null && !xmlElement.required()) {
result.add(f);
}
}
} else if (!f.getType().isPrimitive()) {
if (f.getType().isEnum()) {
if (FixedType.class.equals(f.getType())) {
result.add(f);
} else if (BlockType.class.equals(f.getType())) {
result.add(f);
} else if (TierBlockPolicy.class.equals(f.getType())) {
result.add(f);
}
} else if (Integer.class.equals(f.getType())) {
result.add(f);
} else if (Double.class.equals(f.getType())) {
result.add(f);
}
}
}
return result;
} | java | private static LinkedList<Field> initializeNonRequiredFields(final Class<?> aClass) {
final LinkedList<Field> result = new LinkedList();
final Field[] fields = aClass.getDeclaredFields();
for (final Field f : fields) {
if (f.getType().isArray()) {
final XmlElementWrapper xmlElementWrapper = f.getAnnotation(XmlElementWrapper.class);
if (xmlElementWrapper != null) {
if (!xmlElementWrapper.required()) {
result.add(f);
}
} else {
final XmlElement xmlElement = f.getAnnotation(XmlElement.class);
if (xmlElement != null && !xmlElement.required()) {
result.add(f);
}
}
} else if (!f.getType().isPrimitive()) {
if (f.getType().isEnum()) {
if (FixedType.class.equals(f.getType())) {
result.add(f);
} else if (BlockType.class.equals(f.getType())) {
result.add(f);
} else if (TierBlockPolicy.class.equals(f.getType())) {
result.add(f);
}
} else if (Integer.class.equals(f.getType())) {
result.add(f);
} else if (Double.class.equals(f.getType())) {
result.add(f);
}
}
}
return result;
} | [
"private",
"static",
"LinkedList",
"<",
"Field",
">",
"initializeNonRequiredFields",
"(",
"final",
"Class",
"<",
"?",
">",
"aClass",
")",
"{",
"final",
"LinkedList",
"<",
"Field",
">",
"result",
"=",
"new",
"LinkedList",
"(",
")",
";",
"final",
"Field",
"[",
"]",
"fields",
"=",
"aClass",
".",
"getDeclaredFields",
"(",
")",
";",
"for",
"(",
"final",
"Field",
"f",
":",
"fields",
")",
"{",
"if",
"(",
"f",
".",
"getType",
"(",
")",
".",
"isArray",
"(",
")",
")",
"{",
"final",
"XmlElementWrapper",
"xmlElementWrapper",
"=",
"f",
".",
"getAnnotation",
"(",
"XmlElementWrapper",
".",
"class",
")",
";",
"if",
"(",
"xmlElementWrapper",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"xmlElementWrapper",
".",
"required",
"(",
")",
")",
"{",
"result",
".",
"add",
"(",
"f",
")",
";",
"}",
"}",
"else",
"{",
"final",
"XmlElement",
"xmlElement",
"=",
"f",
".",
"getAnnotation",
"(",
"XmlElement",
".",
"class",
")",
";",
"if",
"(",
"xmlElement",
"!=",
"null",
"&&",
"!",
"xmlElement",
".",
"required",
"(",
")",
")",
"{",
"result",
".",
"add",
"(",
"f",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"!",
"f",
".",
"getType",
"(",
")",
".",
"isPrimitive",
"(",
")",
")",
"{",
"if",
"(",
"f",
".",
"getType",
"(",
")",
".",
"isEnum",
"(",
")",
")",
"{",
"if",
"(",
"FixedType",
".",
"class",
".",
"equals",
"(",
"f",
".",
"getType",
"(",
")",
")",
")",
"{",
"result",
".",
"add",
"(",
"f",
")",
";",
"}",
"else",
"if",
"(",
"BlockType",
".",
"class",
".",
"equals",
"(",
"f",
".",
"getType",
"(",
")",
")",
")",
"{",
"result",
".",
"add",
"(",
"f",
")",
";",
"}",
"else",
"if",
"(",
"TierBlockPolicy",
".",
"class",
".",
"equals",
"(",
"f",
".",
"getType",
"(",
")",
")",
")",
"{",
"result",
".",
"add",
"(",
"f",
")",
";",
"}",
"}",
"else",
"if",
"(",
"Integer",
".",
"class",
".",
"equals",
"(",
"f",
".",
"getType",
"(",
")",
")",
")",
"{",
"result",
".",
"add",
"(",
"f",
")",
";",
"}",
"else",
"if",
"(",
"Double",
".",
"class",
".",
"equals",
"(",
"f",
".",
"getType",
"(",
")",
")",
")",
"{",
"result",
".",
"add",
"(",
"f",
")",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | For each type of catalog object we keep the 'Field' associated to non required attribute fields | [
"For",
"each",
"type",
"of",
"catalog",
"object",
"we",
"keep",
"the",
"Field",
"associated",
"to",
"non",
"required",
"attribute",
"fields"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/catalog/src/main/java/org/killbill/billing/catalog/CatalogSafetyInitializer.java#L80-L114 |
27,246 | killbill/killbill | subscription/src/main/java/org/killbill/billing/subscription/api/svcs/DefaultSubscriptionInternalApi.java | DefaultSubscriptionInternalApi.getDefaultSubscriptionBase | private DefaultSubscriptionBase getDefaultSubscriptionBase(final Entity subscriptionBase, final Catalog catalog, final InternalTenantContext context) throws CatalogApiException {
if (subscriptionBase instanceof DefaultSubscriptionBase) {
return (DefaultSubscriptionBase) subscriptionBase;
} else {
// Safe cast, see above
return (DefaultSubscriptionBase) dao.getSubscriptionFromId(subscriptionBase.getId(), catalog, context);
}
} | java | private DefaultSubscriptionBase getDefaultSubscriptionBase(final Entity subscriptionBase, final Catalog catalog, final InternalTenantContext context) throws CatalogApiException {
if (subscriptionBase instanceof DefaultSubscriptionBase) {
return (DefaultSubscriptionBase) subscriptionBase;
} else {
// Safe cast, see above
return (DefaultSubscriptionBase) dao.getSubscriptionFromId(subscriptionBase.getId(), catalog, context);
}
} | [
"private",
"DefaultSubscriptionBase",
"getDefaultSubscriptionBase",
"(",
"final",
"Entity",
"subscriptionBase",
",",
"final",
"Catalog",
"catalog",
",",
"final",
"InternalTenantContext",
"context",
")",
"throws",
"CatalogApiException",
"{",
"if",
"(",
"subscriptionBase",
"instanceof",
"DefaultSubscriptionBase",
")",
"{",
"return",
"(",
"DefaultSubscriptionBase",
")",
"subscriptionBase",
";",
"}",
"else",
"{",
"// Safe cast, see above",
"return",
"(",
"DefaultSubscriptionBase",
")",
"dao",
".",
"getSubscriptionFromId",
"(",
"subscriptionBase",
".",
"getId",
"(",
")",
",",
"catalog",
",",
"context",
")",
";",
"}",
"}"
] | For forward-compatibility | [
"For",
"forward",
"-",
"compatibility"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/subscription/src/main/java/org/killbill/billing/subscription/api/svcs/DefaultSubscriptionInternalApi.java#L553-L560 |
27,247 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java | DefaultInvoiceFormatter.getFormattedAmountByLocaleAndInvoiceCurrency | private String getFormattedAmountByLocaleAndInvoiceCurrency(final BigDecimal amount) {
final String invoiceCurrencyCode = invoice.getCurrency().toString();
final CurrencyUnit currencyUnit = CurrencyUnit.of(invoiceCurrencyCode);
final DecimalFormat numberFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale);
final DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols();
dfs.setInternationalCurrencySymbol(currencyUnit.getCurrencyCode());
try {
Currency currency = Currency.fromCode(invoiceCurrencyCode);
dfs.setCurrencySymbol(currency.getSymbol());
} catch (final IllegalArgumentException e) {
dfs.setCurrencySymbol(currencyUnit.getSymbol(locale));
}
numberFormatter.setDecimalFormatSymbols(dfs);
numberFormatter.setMinimumFractionDigits(currencyUnit.getDefaultFractionDigits());
numberFormatter.setMaximumFractionDigits(currencyUnit.getDefaultFractionDigits());
return numberFormatter.format(amount.doubleValue());
} | java | private String getFormattedAmountByLocaleAndInvoiceCurrency(final BigDecimal amount) {
final String invoiceCurrencyCode = invoice.getCurrency().toString();
final CurrencyUnit currencyUnit = CurrencyUnit.of(invoiceCurrencyCode);
final DecimalFormat numberFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale);
final DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols();
dfs.setInternationalCurrencySymbol(currencyUnit.getCurrencyCode());
try {
Currency currency = Currency.fromCode(invoiceCurrencyCode);
dfs.setCurrencySymbol(currency.getSymbol());
} catch (final IllegalArgumentException e) {
dfs.setCurrencySymbol(currencyUnit.getSymbol(locale));
}
numberFormatter.setDecimalFormatSymbols(dfs);
numberFormatter.setMinimumFractionDigits(currencyUnit.getDefaultFractionDigits());
numberFormatter.setMaximumFractionDigits(currencyUnit.getDefaultFractionDigits());
return numberFormatter.format(amount.doubleValue());
} | [
"private",
"String",
"getFormattedAmountByLocaleAndInvoiceCurrency",
"(",
"final",
"BigDecimal",
"amount",
")",
"{",
"final",
"String",
"invoiceCurrencyCode",
"=",
"invoice",
".",
"getCurrency",
"(",
")",
".",
"toString",
"(",
")",
";",
"final",
"CurrencyUnit",
"currencyUnit",
"=",
"CurrencyUnit",
".",
"of",
"(",
"invoiceCurrencyCode",
")",
";",
"final",
"DecimalFormat",
"numberFormatter",
"=",
"(",
"DecimalFormat",
")",
"DecimalFormat",
".",
"getCurrencyInstance",
"(",
"locale",
")",
";",
"final",
"DecimalFormatSymbols",
"dfs",
"=",
"numberFormatter",
".",
"getDecimalFormatSymbols",
"(",
")",
";",
"dfs",
".",
"setInternationalCurrencySymbol",
"(",
"currencyUnit",
".",
"getCurrencyCode",
"(",
")",
")",
";",
"try",
"{",
"Currency",
"currency",
"=",
"Currency",
".",
"fromCode",
"(",
"invoiceCurrencyCode",
")",
";",
"dfs",
".",
"setCurrencySymbol",
"(",
"currency",
".",
"getSymbol",
"(",
")",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalArgumentException",
"e",
")",
"{",
"dfs",
".",
"setCurrencySymbol",
"(",
"currencyUnit",
".",
"getSymbol",
"(",
"locale",
")",
")",
";",
"}",
"numberFormatter",
".",
"setDecimalFormatSymbols",
"(",
"dfs",
")",
";",
"numberFormatter",
".",
"setMinimumFractionDigits",
"(",
"currencyUnit",
".",
"getDefaultFractionDigits",
"(",
")",
")",
";",
"numberFormatter",
".",
"setMaximumFractionDigits",
"(",
"currencyUnit",
".",
"getDefaultFractionDigits",
"(",
")",
")",
";",
"return",
"numberFormatter",
".",
"format",
"(",
"amount",
".",
"doubleValue",
"(",
")",
")",
";",
"}"
] | Returns the formatted amount with the correct currency symbol that is get from the invoice currency. | [
"Returns",
"the",
"formatted",
"amount",
"with",
"the",
"correct",
"currency",
"symbol",
"that",
"is",
"get",
"from",
"the",
"invoice",
"currency",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java#L231-L251 |
27,248 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/SubscriptionItemTree.java | SubscriptionItemTree.addItem | public void addItem(final InvoiceItem invoiceItem) {
Preconditions.checkState(!isBuilt, "Tree already built, unable to add new invoiceItem=%s", invoiceItem);
switch (invoiceItem.getInvoiceItemType()) {
case RECURRING:
if (invoiceItem.getAmount().compareTo(BigDecimal.ZERO) == 0) {
// Nothing to repair -- https://github.com/killbill/killbill/issues/783
existingIgnoredItems.add(invoiceItem);
} else {
root.addExistingItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.ADD)));
}
break;
case REPAIR_ADJ:
root.addExistingItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.CANCEL)));
break;
case FIXED:
existingIgnoredItems.add(invoiceItem);
break;
case ITEM_ADJ:
pendingItemAdj.add(invoiceItem);
break;
default:
break;
}
} | java | public void addItem(final InvoiceItem invoiceItem) {
Preconditions.checkState(!isBuilt, "Tree already built, unable to add new invoiceItem=%s", invoiceItem);
switch (invoiceItem.getInvoiceItemType()) {
case RECURRING:
if (invoiceItem.getAmount().compareTo(BigDecimal.ZERO) == 0) {
// Nothing to repair -- https://github.com/killbill/killbill/issues/783
existingIgnoredItems.add(invoiceItem);
} else {
root.addExistingItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.ADD)));
}
break;
case REPAIR_ADJ:
root.addExistingItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.CANCEL)));
break;
case FIXED:
existingIgnoredItems.add(invoiceItem);
break;
case ITEM_ADJ:
pendingItemAdj.add(invoiceItem);
break;
default:
break;
}
} | [
"public",
"void",
"addItem",
"(",
"final",
"InvoiceItem",
"invoiceItem",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"!",
"isBuilt",
",",
"\"Tree already built, unable to add new invoiceItem=%s\"",
",",
"invoiceItem",
")",
";",
"switch",
"(",
"invoiceItem",
".",
"getInvoiceItemType",
"(",
")",
")",
"{",
"case",
"RECURRING",
":",
"if",
"(",
"invoiceItem",
".",
"getAmount",
"(",
")",
".",
"compareTo",
"(",
"BigDecimal",
".",
"ZERO",
")",
"==",
"0",
")",
"{",
"// Nothing to repair -- https://github.com/killbill/killbill/issues/783",
"existingIgnoredItems",
".",
"add",
"(",
"invoiceItem",
")",
";",
"}",
"else",
"{",
"root",
".",
"addExistingItem",
"(",
"new",
"ItemsNodeInterval",
"(",
"root",
",",
"new",
"Item",
"(",
"invoiceItem",
",",
"targetInvoiceId",
",",
"ItemAction",
".",
"ADD",
")",
")",
")",
";",
"}",
"break",
";",
"case",
"REPAIR_ADJ",
":",
"root",
".",
"addExistingItem",
"(",
"new",
"ItemsNodeInterval",
"(",
"root",
",",
"new",
"Item",
"(",
"invoiceItem",
",",
"targetInvoiceId",
",",
"ItemAction",
".",
"CANCEL",
")",
")",
")",
";",
"break",
";",
"case",
"FIXED",
":",
"existingIgnoredItems",
".",
"add",
"(",
"invoiceItem",
")",
";",
"break",
";",
"case",
"ITEM_ADJ",
":",
"pendingItemAdj",
".",
"add",
"(",
"invoiceItem",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}"
] | Add an existing item in the tree. A new node is inserted or an existing one updated, if one for the same period already exists.
@param invoiceItem new existing invoice item on disk. | [
"Add",
"an",
"existing",
"item",
"in",
"the",
"tree",
".",
"A",
"new",
"node",
"is",
"inserted",
"or",
"an",
"existing",
"one",
"updated",
"if",
"one",
"for",
"the",
"same",
"period",
"already",
"exists",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/SubscriptionItemTree.java#L90-L118 |
27,249 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/SubscriptionItemTree.java | SubscriptionItemTree.build | public void build() {
Preconditions.checkState(!isBuilt);
for (final InvoiceItem item : pendingItemAdj) {
// If the linked item was ignored, ignore this adjustment too
final InvoiceItem ignoredLinkedItem = Iterables.tryFind(existingIgnoredItems, new Predicate<InvoiceItem>() {
@Override
public boolean apply(final InvoiceItem input) {
return input.getId().equals(item.getLinkedItemId());
}
}).orNull();
if (ignoredLinkedItem == null) {
final Item fullyAdjustedItem = root.addAdjustment(item, targetInvoiceId);
if (fullyAdjustedItem != null) {
existingFullyAdjustedItems.add(fullyAdjustedItem);
}
}
}
pendingItemAdj.clear();
root.buildForExistingItems(items, targetInvoiceId);
isBuilt = true;
} | java | public void build() {
Preconditions.checkState(!isBuilt);
for (final InvoiceItem item : pendingItemAdj) {
// If the linked item was ignored, ignore this adjustment too
final InvoiceItem ignoredLinkedItem = Iterables.tryFind(existingIgnoredItems, new Predicate<InvoiceItem>() {
@Override
public boolean apply(final InvoiceItem input) {
return input.getId().equals(item.getLinkedItemId());
}
}).orNull();
if (ignoredLinkedItem == null) {
final Item fullyAdjustedItem = root.addAdjustment(item, targetInvoiceId);
if (fullyAdjustedItem != null) {
existingFullyAdjustedItems.add(fullyAdjustedItem);
}
}
}
pendingItemAdj.clear();
root.buildForExistingItems(items, targetInvoiceId);
isBuilt = true;
} | [
"public",
"void",
"build",
"(",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"!",
"isBuilt",
")",
";",
"for",
"(",
"final",
"InvoiceItem",
"item",
":",
"pendingItemAdj",
")",
"{",
"// If the linked item was ignored, ignore this adjustment too",
"final",
"InvoiceItem",
"ignoredLinkedItem",
"=",
"Iterables",
".",
"tryFind",
"(",
"existingIgnoredItems",
",",
"new",
"Predicate",
"<",
"InvoiceItem",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"final",
"InvoiceItem",
"input",
")",
"{",
"return",
"input",
".",
"getId",
"(",
")",
".",
"equals",
"(",
"item",
".",
"getLinkedItemId",
"(",
")",
")",
";",
"}",
"}",
")",
".",
"orNull",
"(",
")",
";",
"if",
"(",
"ignoredLinkedItem",
"==",
"null",
")",
"{",
"final",
"Item",
"fullyAdjustedItem",
"=",
"root",
".",
"addAdjustment",
"(",
"item",
",",
"targetInvoiceId",
")",
";",
"if",
"(",
"fullyAdjustedItem",
"!=",
"null",
")",
"{",
"existingFullyAdjustedItems",
".",
"add",
"(",
"fullyAdjustedItem",
")",
";",
"}",
"}",
"}",
"pendingItemAdj",
".",
"clear",
"(",
")",
";",
"root",
".",
"buildForExistingItems",
"(",
"items",
",",
"targetInvoiceId",
")",
";",
"isBuilt",
"=",
"true",
";",
"}"
] | Build the tree and process adjustments | [
"Build",
"the",
"tree",
"and",
"process",
"adjustments"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/SubscriptionItemTree.java#L123-L145 |
27,250 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/SubscriptionItemTree.java | SubscriptionItemTree.mergeProposedItem | public void mergeProposedItem(final InvoiceItem invoiceItem) {
Preconditions.checkState(!isBuilt, "Tree already built, unable to add new invoiceItem=%s", invoiceItem);
// Check if it was an existing item ignored for tree purposes (e.g. FIXED or $0 RECURRING, both of which aren't repaired)
final InvoiceItem existingItem = Iterables.tryFind(existingIgnoredItems, new Predicate<InvoiceItem>() {
@Override
public boolean apply(final InvoiceItem input) {
return input.matches(invoiceItem);
}
}).orNull();
if (existingItem != null) {
return;
}
switch (invoiceItem.getInvoiceItemType()) {
case RECURRING:
// merged means we've either matched the proposed to an existing, or triggered a repair
final boolean merged = root.addProposedItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.ADD)));
if (!merged) {
items.add(new Item(invoiceItem, targetInvoiceId, ItemAction.ADD));
}
break;
case FIXED:
remainingIgnoredItems.add(invoiceItem);
break;
default:
Preconditions.checkState(false, "Unexpected proposed item " + invoiceItem);
}
} | java | public void mergeProposedItem(final InvoiceItem invoiceItem) {
Preconditions.checkState(!isBuilt, "Tree already built, unable to add new invoiceItem=%s", invoiceItem);
// Check if it was an existing item ignored for tree purposes (e.g. FIXED or $0 RECURRING, both of which aren't repaired)
final InvoiceItem existingItem = Iterables.tryFind(existingIgnoredItems, new Predicate<InvoiceItem>() {
@Override
public boolean apply(final InvoiceItem input) {
return input.matches(invoiceItem);
}
}).orNull();
if (existingItem != null) {
return;
}
switch (invoiceItem.getInvoiceItemType()) {
case RECURRING:
// merged means we've either matched the proposed to an existing, or triggered a repair
final boolean merged = root.addProposedItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.ADD)));
if (!merged) {
items.add(new Item(invoiceItem, targetInvoiceId, ItemAction.ADD));
}
break;
case FIXED:
remainingIgnoredItems.add(invoiceItem);
break;
default:
Preconditions.checkState(false, "Unexpected proposed item " + invoiceItem);
}
} | [
"public",
"void",
"mergeProposedItem",
"(",
"final",
"InvoiceItem",
"invoiceItem",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"!",
"isBuilt",
",",
"\"Tree already built, unable to add new invoiceItem=%s\"",
",",
"invoiceItem",
")",
";",
"// Check if it was an existing item ignored for tree purposes (e.g. FIXED or $0 RECURRING, both of which aren't repaired)",
"final",
"InvoiceItem",
"existingItem",
"=",
"Iterables",
".",
"tryFind",
"(",
"existingIgnoredItems",
",",
"new",
"Predicate",
"<",
"InvoiceItem",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"final",
"InvoiceItem",
"input",
")",
"{",
"return",
"input",
".",
"matches",
"(",
"invoiceItem",
")",
";",
"}",
"}",
")",
".",
"orNull",
"(",
")",
";",
"if",
"(",
"existingItem",
"!=",
"null",
")",
"{",
"return",
";",
"}",
"switch",
"(",
"invoiceItem",
".",
"getInvoiceItemType",
"(",
")",
")",
"{",
"case",
"RECURRING",
":",
"// merged means we've either matched the proposed to an existing, or triggered a repair",
"final",
"boolean",
"merged",
"=",
"root",
".",
"addProposedItem",
"(",
"new",
"ItemsNodeInterval",
"(",
"root",
",",
"new",
"Item",
"(",
"invoiceItem",
",",
"targetInvoiceId",
",",
"ItemAction",
".",
"ADD",
")",
")",
")",
";",
"if",
"(",
"!",
"merged",
")",
"{",
"items",
".",
"add",
"(",
"new",
"Item",
"(",
"invoiceItem",
",",
"targetInvoiceId",
",",
"ItemAction",
".",
"ADD",
")",
")",
";",
"}",
"break",
";",
"case",
"FIXED",
":",
"remainingIgnoredItems",
".",
"add",
"(",
"invoiceItem",
")",
";",
"break",
";",
"default",
":",
"Preconditions",
".",
"checkState",
"(",
"false",
",",
"\"Unexpected proposed item \"",
"+",
"invoiceItem",
")",
";",
"}",
"}"
] | Merge a new proposed item in the tree.
@param invoiceItem new proposed item that should be merged in the existing tree | [
"Merge",
"a",
"new",
"proposed",
"item",
"in",
"the",
"tree",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/SubscriptionItemTree.java#L173-L203 |
27,251 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/SubscriptionItemTree.java | SubscriptionItemTree.buildForMerge | public void buildForMerge() {
Preconditions.checkState(!isBuilt, "Tree already built");
root.mergeExistingAndProposed(items, targetInvoiceId);
isBuilt = true;
isMerged = true;
} | java | public void buildForMerge() {
Preconditions.checkState(!isBuilt, "Tree already built");
root.mergeExistingAndProposed(items, targetInvoiceId);
isBuilt = true;
isMerged = true;
} | [
"public",
"void",
"buildForMerge",
"(",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"!",
"isBuilt",
",",
"\"Tree already built\"",
")",
";",
"root",
".",
"mergeExistingAndProposed",
"(",
"items",
",",
"targetInvoiceId",
")",
";",
"isBuilt",
"=",
"true",
";",
"isMerged",
"=",
"true",
";",
"}"
] | Build tree post merge | [
"Build",
"tree",
"post",
"merge"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/SubscriptionItemTree.java#L206-L211 |
27,252 | killbill/killbill | entitlement/src/main/java/org/killbill/billing/entitlement/engine/core/EventsStreamBuilder.java | EventsStreamBuilder.buildForEntitlement | public EventsStream buildForEntitlement(final Collection<BlockingState> blockingStatesForAccount,
final ImmutableAccountData account,
final SubscriptionBaseBundle bundle,
final SubscriptionBase baseSubscription,
final Collection<SubscriptionBase> allSubscriptionsForBundle,
final int accountBCD,
final Catalog catalog,
final InternalTenantContext internalTenantContext) throws EntitlementApiException {
final Map<UUID, Integer> bcdCache = new HashMap<UUID, Integer>();
return buildForEntitlement(blockingStatesForAccount, account, bundle, baseSubscription, baseSubscription, allSubscriptionsForBundle, accountBCD, bcdCache, catalog, internalTenantContext);
} | java | public EventsStream buildForEntitlement(final Collection<BlockingState> blockingStatesForAccount,
final ImmutableAccountData account,
final SubscriptionBaseBundle bundle,
final SubscriptionBase baseSubscription,
final Collection<SubscriptionBase> allSubscriptionsForBundle,
final int accountBCD,
final Catalog catalog,
final InternalTenantContext internalTenantContext) throws EntitlementApiException {
final Map<UUID, Integer> bcdCache = new HashMap<UUID, Integer>();
return buildForEntitlement(blockingStatesForAccount, account, bundle, baseSubscription, baseSubscription, allSubscriptionsForBundle, accountBCD, bcdCache, catalog, internalTenantContext);
} | [
"public",
"EventsStream",
"buildForEntitlement",
"(",
"final",
"Collection",
"<",
"BlockingState",
">",
"blockingStatesForAccount",
",",
"final",
"ImmutableAccountData",
"account",
",",
"final",
"SubscriptionBaseBundle",
"bundle",
",",
"final",
"SubscriptionBase",
"baseSubscription",
",",
"final",
"Collection",
"<",
"SubscriptionBase",
">",
"allSubscriptionsForBundle",
",",
"final",
"int",
"accountBCD",
",",
"final",
"Catalog",
"catalog",
",",
"final",
"InternalTenantContext",
"internalTenantContext",
")",
"throws",
"EntitlementApiException",
"{",
"final",
"Map",
"<",
"UUID",
",",
"Integer",
">",
"bcdCache",
"=",
"new",
"HashMap",
"<",
"UUID",
",",
"Integer",
">",
"(",
")",
";",
"return",
"buildForEntitlement",
"(",
"blockingStatesForAccount",
",",
"account",
",",
"bundle",
",",
"baseSubscription",
",",
"baseSubscription",
",",
"allSubscriptionsForBundle",
",",
"accountBCD",
",",
"bcdCache",
",",
"catalog",
",",
"internalTenantContext",
")",
";",
"}"
] | Special signature for OptimizedProxyBlockingStateDao to save some DAO calls | [
"Special",
"signature",
"for",
"OptimizedProxyBlockingStateDao",
"to",
"save",
"some",
"DAO",
"calls"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/entitlement/src/main/java/org/killbill/billing/entitlement/engine/core/EventsStreamBuilder.java#L313-L323 |
27,253 | killbill/killbill | jaxrs/src/main/java/org/killbill/billing/jaxrs/util/Context.java | Context.getOrCreateUserToken | public static UUID getOrCreateUserToken() {
UUID userToken;
if (Request.getPerThreadRequestData().getRequestId() != null) {
try {
userToken = UUID.fromString(Request.getPerThreadRequestData().getRequestId());
} catch (final IllegalArgumentException ignored) {
userToken = UUIDs.randomUUID();
}
} else {
userToken = UUIDs.randomUUID();
}
return userToken;
} | java | public static UUID getOrCreateUserToken() {
UUID userToken;
if (Request.getPerThreadRequestData().getRequestId() != null) {
try {
userToken = UUID.fromString(Request.getPerThreadRequestData().getRequestId());
} catch (final IllegalArgumentException ignored) {
userToken = UUIDs.randomUUID();
}
} else {
userToken = UUIDs.randomUUID();
}
return userToken;
} | [
"public",
"static",
"UUID",
"getOrCreateUserToken",
"(",
")",
"{",
"UUID",
"userToken",
";",
"if",
"(",
"Request",
".",
"getPerThreadRequestData",
"(",
")",
".",
"getRequestId",
"(",
")",
"!=",
"null",
")",
"{",
"try",
"{",
"userToken",
"=",
"UUID",
".",
"fromString",
"(",
"Request",
".",
"getPerThreadRequestData",
"(",
")",
".",
"getRequestId",
"(",
")",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalArgumentException",
"ignored",
")",
"{",
"userToken",
"=",
"UUIDs",
".",
"randomUUID",
"(",
")",
";",
"}",
"}",
"else",
"{",
"userToken",
"=",
"UUIDs",
".",
"randomUUID",
"(",
")",
";",
"}",
"return",
"userToken",
";",
"}"
] | Use REQUEST_ID_HEADER if this is provided and looks like a UUID, if not allocate a random one. | [
"Use",
"REQUEST_ID_HEADER",
"if",
"this",
"is",
"provided",
"and",
"looks",
"like",
"a",
"UUID",
"if",
"not",
"allocate",
"a",
"random",
"one",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/Context.java#L97-L109 |
27,254 | killbill/killbill | junction/src/main/java/org/killbill/billing/junction/plumbing/billing/BlockingCalculator.java | BlockingCalculator.createBlockingDurations | protected List<DisabledDuration> createBlockingDurations(final Iterable<BlockingState> inputBundleEvents) {
final List<DisabledDuration> result = new ArrayList<DisabledDuration>();
final Set<String> services = ImmutableSet.copyOf(Iterables.transform(inputBundleEvents, new Function<BlockingState, String>() {
@Override
public String apply(final BlockingState input) {
return input.getService();
}
}));
final Map<String, BlockingStateService> svcBlockedMap = new HashMap<String, BlockingStateService>();
for (String svc : services) {
svcBlockedMap.put(svc, new BlockingStateService());
}
for (final BlockingState e : inputBundleEvents) {
svcBlockedMap.get(e.getService()).addBlockingState(e);
}
final Iterable<DisabledDuration> unorderedDisabledDuration = Iterables.concat(Iterables.transform(svcBlockedMap.values(), new Function<BlockingStateService, List<DisabledDuration>>() {
@Override
public List<DisabledDuration> apply(final BlockingStateService input) {
return input.build();
}
}));
final List<DisabledDuration> sortedDisabledDuration = Ordering.natural().sortedCopy(unorderedDisabledDuration);
DisabledDuration prevDuration = null;
for (DisabledDuration d : sortedDisabledDuration) {
// isDisjoint
if (prevDuration == null) {
prevDuration = d;
} else {
if (prevDuration.isDisjoint(d)) {
result.add(prevDuration);
prevDuration = d;
} else {
prevDuration = DisabledDuration.mergeDuration(prevDuration, d);
}
}
}
if (prevDuration != null) {
result.add(prevDuration);
}
return result;
} | java | protected List<DisabledDuration> createBlockingDurations(final Iterable<BlockingState> inputBundleEvents) {
final List<DisabledDuration> result = new ArrayList<DisabledDuration>();
final Set<String> services = ImmutableSet.copyOf(Iterables.transform(inputBundleEvents, new Function<BlockingState, String>() {
@Override
public String apply(final BlockingState input) {
return input.getService();
}
}));
final Map<String, BlockingStateService> svcBlockedMap = new HashMap<String, BlockingStateService>();
for (String svc : services) {
svcBlockedMap.put(svc, new BlockingStateService());
}
for (final BlockingState e : inputBundleEvents) {
svcBlockedMap.get(e.getService()).addBlockingState(e);
}
final Iterable<DisabledDuration> unorderedDisabledDuration = Iterables.concat(Iterables.transform(svcBlockedMap.values(), new Function<BlockingStateService, List<DisabledDuration>>() {
@Override
public List<DisabledDuration> apply(final BlockingStateService input) {
return input.build();
}
}));
final List<DisabledDuration> sortedDisabledDuration = Ordering.natural().sortedCopy(unorderedDisabledDuration);
DisabledDuration prevDuration = null;
for (DisabledDuration d : sortedDisabledDuration) {
// isDisjoint
if (prevDuration == null) {
prevDuration = d;
} else {
if (prevDuration.isDisjoint(d)) {
result.add(prevDuration);
prevDuration = d;
} else {
prevDuration = DisabledDuration.mergeDuration(prevDuration, d);
}
}
}
if (prevDuration != null) {
result.add(prevDuration);
}
return result;
} | [
"protected",
"List",
"<",
"DisabledDuration",
">",
"createBlockingDurations",
"(",
"final",
"Iterable",
"<",
"BlockingState",
">",
"inputBundleEvents",
")",
"{",
"final",
"List",
"<",
"DisabledDuration",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"DisabledDuration",
">",
"(",
")",
";",
"final",
"Set",
"<",
"String",
">",
"services",
"=",
"ImmutableSet",
".",
"copyOf",
"(",
"Iterables",
".",
"transform",
"(",
"inputBundleEvents",
",",
"new",
"Function",
"<",
"BlockingState",
",",
"String",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"String",
"apply",
"(",
"final",
"BlockingState",
"input",
")",
"{",
"return",
"input",
".",
"getService",
"(",
")",
";",
"}",
"}",
")",
")",
";",
"final",
"Map",
"<",
"String",
",",
"BlockingStateService",
">",
"svcBlockedMap",
"=",
"new",
"HashMap",
"<",
"String",
",",
"BlockingStateService",
">",
"(",
")",
";",
"for",
"(",
"String",
"svc",
":",
"services",
")",
"{",
"svcBlockedMap",
".",
"put",
"(",
"svc",
",",
"new",
"BlockingStateService",
"(",
")",
")",
";",
"}",
"for",
"(",
"final",
"BlockingState",
"e",
":",
"inputBundleEvents",
")",
"{",
"svcBlockedMap",
".",
"get",
"(",
"e",
".",
"getService",
"(",
")",
")",
".",
"addBlockingState",
"(",
"e",
")",
";",
"}",
"final",
"Iterable",
"<",
"DisabledDuration",
">",
"unorderedDisabledDuration",
"=",
"Iterables",
".",
"concat",
"(",
"Iterables",
".",
"transform",
"(",
"svcBlockedMap",
".",
"values",
"(",
")",
",",
"new",
"Function",
"<",
"BlockingStateService",
",",
"List",
"<",
"DisabledDuration",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"List",
"<",
"DisabledDuration",
">",
"apply",
"(",
"final",
"BlockingStateService",
"input",
")",
"{",
"return",
"input",
".",
"build",
"(",
")",
";",
"}",
"}",
")",
")",
";",
"final",
"List",
"<",
"DisabledDuration",
">",
"sortedDisabledDuration",
"=",
"Ordering",
".",
"natural",
"(",
")",
".",
"sortedCopy",
"(",
"unorderedDisabledDuration",
")",
";",
"DisabledDuration",
"prevDuration",
"=",
"null",
";",
"for",
"(",
"DisabledDuration",
"d",
":",
"sortedDisabledDuration",
")",
"{",
"// isDisjoint",
"if",
"(",
"prevDuration",
"==",
"null",
")",
"{",
"prevDuration",
"=",
"d",
";",
"}",
"else",
"{",
"if",
"(",
"prevDuration",
".",
"isDisjoint",
"(",
"d",
")",
")",
"{",
"result",
".",
"add",
"(",
"prevDuration",
")",
";",
"prevDuration",
"=",
"d",
";",
"}",
"else",
"{",
"prevDuration",
"=",
"DisabledDuration",
".",
"mergeDuration",
"(",
"prevDuration",
",",
"d",
")",
";",
"}",
"}",
"}",
"if",
"(",
"prevDuration",
"!=",
"null",
")",
"{",
"result",
".",
"add",
"(",
"prevDuration",
")",
";",
"}",
"return",
"result",
";",
"}"
] | In ascending order | [
"In",
"ascending",
"order"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/junction/src/main/java/org/killbill/billing/junction/plumbing/billing/BlockingCalculator.java#L302-L350 |
27,255 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/AccountItemTree.java | AccountItemTree.build | public void build() {
Preconditions.checkState(!isBuilt);
if (pendingItemAdj.size() > 0) {
for (InvoiceItem item : pendingItemAdj) {
addExistingItem(item, true);
}
pendingItemAdj.clear();
}
for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
tree.build();
}
isBuilt = true;
} | java | public void build() {
Preconditions.checkState(!isBuilt);
if (pendingItemAdj.size() > 0) {
for (InvoiceItem item : pendingItemAdj) {
addExistingItem(item, true);
}
pendingItemAdj.clear();
}
for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
tree.build();
}
isBuilt = true;
} | [
"public",
"void",
"build",
"(",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"!",
"isBuilt",
")",
";",
"if",
"(",
"pendingItemAdj",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"for",
"(",
"InvoiceItem",
"item",
":",
"pendingItemAdj",
")",
"{",
"addExistingItem",
"(",
"item",
",",
"true",
")",
";",
"}",
"pendingItemAdj",
".",
"clear",
"(",
")",
";",
"}",
"for",
"(",
"SubscriptionItemTree",
"tree",
":",
"subscriptionItemTree",
".",
"values",
"(",
")",
")",
"{",
"tree",
".",
"build",
"(",
")",
";",
"}",
"isBuilt",
"=",
"true",
";",
"}"
] | build the subscription trees after they have been populated with existing items on disk | [
"build",
"the",
"subscription",
"trees",
"after",
"they",
"have",
"been",
"populated",
"with",
"existing",
"items",
"on",
"disk"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/AccountItemTree.java#L72-L85 |
27,256 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/AccountItemTree.java | AccountItemTree.mergeWithProposedItems | public void mergeWithProposedItems(final List<InvoiceItem> proposedItems) {
build();
for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
tree.flatten(true);
}
for (InvoiceItem item : proposedItems) {
final UUID subscriptionId = getSubscriptionId(item, null);
SubscriptionItemTree tree = subscriptionItemTree.get(subscriptionId);
if (tree == null) {
tree = new SubscriptionItemTree(subscriptionId, targetInvoiceId);
subscriptionItemTree.put(subscriptionId, tree);
}
tree.mergeProposedItem(item);
}
for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
tree.buildForMerge();
}
} | java | public void mergeWithProposedItems(final List<InvoiceItem> proposedItems) {
build();
for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
tree.flatten(true);
}
for (InvoiceItem item : proposedItems) {
final UUID subscriptionId = getSubscriptionId(item, null);
SubscriptionItemTree tree = subscriptionItemTree.get(subscriptionId);
if (tree == null) {
tree = new SubscriptionItemTree(subscriptionId, targetInvoiceId);
subscriptionItemTree.put(subscriptionId, tree);
}
tree.mergeProposedItem(item);
}
for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
tree.buildForMerge();
}
} | [
"public",
"void",
"mergeWithProposedItems",
"(",
"final",
"List",
"<",
"InvoiceItem",
">",
"proposedItems",
")",
"{",
"build",
"(",
")",
";",
"for",
"(",
"SubscriptionItemTree",
"tree",
":",
"subscriptionItemTree",
".",
"values",
"(",
")",
")",
"{",
"tree",
".",
"flatten",
"(",
"true",
")",
";",
"}",
"for",
"(",
"InvoiceItem",
"item",
":",
"proposedItems",
")",
"{",
"final",
"UUID",
"subscriptionId",
"=",
"getSubscriptionId",
"(",
"item",
",",
"null",
")",
";",
"SubscriptionItemTree",
"tree",
"=",
"subscriptionItemTree",
".",
"get",
"(",
"subscriptionId",
")",
";",
"if",
"(",
"tree",
"==",
"null",
")",
"{",
"tree",
"=",
"new",
"SubscriptionItemTree",
"(",
"subscriptionId",
",",
"targetInvoiceId",
")",
";",
"subscriptionItemTree",
".",
"put",
"(",
"subscriptionId",
",",
"tree",
")",
";",
"}",
"tree",
".",
"mergeProposedItem",
"(",
"item",
")",
";",
"}",
"for",
"(",
"SubscriptionItemTree",
"tree",
":",
"subscriptionItemTree",
".",
"values",
"(",
")",
")",
"{",
"tree",
".",
"buildForMerge",
"(",
")",
";",
"}",
"}"
] | Rebuild the new tree by merging current on-disk existing view with new proposed list.
@param proposedItems list of proposed item that should be merged with current existing view | [
"Rebuild",
"the",
"new",
"tree",
"by",
"merging",
"current",
"on",
"-",
"disk",
"existing",
"view",
"with",
"new",
"proposed",
"list",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/AccountItemTree.java#L154-L174 |
27,257 | killbill/killbill | util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java | InternalCallContextFactory.createInternalTenantContext | public InternalTenantContext createInternalTenantContext(final UUID objectId, final ObjectType objectType, final TenantContext context) {
// The callcontext may come from a user API - for security, check we're not doing cross-tenants operations
//final Long tenantRecordIdFromObject = retrieveTenantRecordIdFromObject(objectId, objectType);
//final Long tenantRecordIdFromContext = getTenantRecordIdSafe(callcontext);
//Preconditions.checkState(tenantRecordIdFromContext.equals(tenantRecordIdFromObject),
// "tenant of the pointed object (%s) and the callcontext (%s) don't match!", tenantRecordIdFromObject, tenantRecordIdFromContext);
final Long tenantRecordId = getTenantRecordIdSafe(context);
final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, context);
return createInternalTenantContext(tenantRecordId, accountRecordId);
} | java | public InternalTenantContext createInternalTenantContext(final UUID objectId, final ObjectType objectType, final TenantContext context) {
// The callcontext may come from a user API - for security, check we're not doing cross-tenants operations
//final Long tenantRecordIdFromObject = retrieveTenantRecordIdFromObject(objectId, objectType);
//final Long tenantRecordIdFromContext = getTenantRecordIdSafe(callcontext);
//Preconditions.checkState(tenantRecordIdFromContext.equals(tenantRecordIdFromObject),
// "tenant of the pointed object (%s) and the callcontext (%s) don't match!", tenantRecordIdFromObject, tenantRecordIdFromContext);
final Long tenantRecordId = getTenantRecordIdSafe(context);
final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, context);
return createInternalTenantContext(tenantRecordId, accountRecordId);
} | [
"public",
"InternalTenantContext",
"createInternalTenantContext",
"(",
"final",
"UUID",
"objectId",
",",
"final",
"ObjectType",
"objectType",
",",
"final",
"TenantContext",
"context",
")",
"{",
"// The callcontext may come from a user API - for security, check we're not doing cross-tenants operations",
"//final Long tenantRecordIdFromObject = retrieveTenantRecordIdFromObject(objectId, objectType);",
"//final Long tenantRecordIdFromContext = getTenantRecordIdSafe(callcontext);",
"//Preconditions.checkState(tenantRecordIdFromContext.equals(tenantRecordIdFromObject),",
"// \"tenant of the pointed object (%s) and the callcontext (%s) don't match!\", tenantRecordIdFromObject, tenantRecordIdFromContext);",
"final",
"Long",
"tenantRecordId",
"=",
"getTenantRecordIdSafe",
"(",
"context",
")",
";",
"final",
"Long",
"accountRecordId",
"=",
"getAccountRecordIdSafe",
"(",
"objectId",
",",
"objectType",
",",
"context",
")",
";",
"return",
"createInternalTenantContext",
"(",
"tenantRecordId",
",",
"accountRecordId",
")",
";",
"}"
] | Crate an internal tenant callcontext from a tenant callcontext, and retrieving the account_record_id from another table
@param objectId the id of the row in the table pointed by object type where to look for account_record_id
@param objectType the object type pointed by this objectId
@param context original tenant callcontext
@return internal tenant callcontext from callcontext, with a non null account_record_id (if found) | [
"Crate",
"an",
"internal",
"tenant",
"callcontext",
"from",
"a",
"tenant",
"callcontext",
"and",
"retrieving",
"the",
"account_record_id",
"from",
"another",
"table"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java#L138-L147 |
27,258 | killbill/killbill | util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java | InternalCallContextFactory.createInternalTenantContext | public InternalTenantContext createInternalTenantContext(final Long tenantRecordId, @Nullable final Long accountRecordId) {
populateMDCContext(null, accountRecordId, tenantRecordId);
if (accountRecordId == null) {
return new InternalTenantContext(tenantRecordId);
} else {
final ImmutableAccountData immutableAccountData = getImmutableAccountData(accountRecordId, tenantRecordId);
final DateTimeZone fixedOffsetTimeZone = immutableAccountData.getFixedOffsetTimeZone();
final DateTime referenceTime = immutableAccountData.getReferenceTime();
return new InternalTenantContext(tenantRecordId, accountRecordId, fixedOffsetTimeZone, referenceTime);
}
} | java | public InternalTenantContext createInternalTenantContext(final Long tenantRecordId, @Nullable final Long accountRecordId) {
populateMDCContext(null, accountRecordId, tenantRecordId);
if (accountRecordId == null) {
return new InternalTenantContext(tenantRecordId);
} else {
final ImmutableAccountData immutableAccountData = getImmutableAccountData(accountRecordId, tenantRecordId);
final DateTimeZone fixedOffsetTimeZone = immutableAccountData.getFixedOffsetTimeZone();
final DateTime referenceTime = immutableAccountData.getReferenceTime();
return new InternalTenantContext(tenantRecordId, accountRecordId, fixedOffsetTimeZone, referenceTime);
}
} | [
"public",
"InternalTenantContext",
"createInternalTenantContext",
"(",
"final",
"Long",
"tenantRecordId",
",",
"@",
"Nullable",
"final",
"Long",
"accountRecordId",
")",
"{",
"populateMDCContext",
"(",
"null",
",",
"accountRecordId",
",",
"tenantRecordId",
")",
";",
"if",
"(",
"accountRecordId",
"==",
"null",
")",
"{",
"return",
"new",
"InternalTenantContext",
"(",
"tenantRecordId",
")",
";",
"}",
"else",
"{",
"final",
"ImmutableAccountData",
"immutableAccountData",
"=",
"getImmutableAccountData",
"(",
"accountRecordId",
",",
"tenantRecordId",
")",
";",
"final",
"DateTimeZone",
"fixedOffsetTimeZone",
"=",
"immutableAccountData",
".",
"getFixedOffsetTimeZone",
"(",
")",
";",
"final",
"DateTime",
"referenceTime",
"=",
"immutableAccountData",
".",
"getReferenceTime",
"(",
")",
";",
"return",
"new",
"InternalTenantContext",
"(",
"tenantRecordId",
",",
"accountRecordId",
",",
"fixedOffsetTimeZone",
",",
"referenceTime",
")",
";",
"}",
"}"
] | Create an internal tenant callcontext
@param tenantRecordId tenant_record_id (cannot be null)
@param accountRecordId account_record_id (cannot be null for INSERT operations)
@return internal tenant callcontext | [
"Create",
"an",
"internal",
"tenant",
"callcontext"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java#L156-L167 |
27,259 | killbill/killbill | util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java | InternalCallContextFactory.createInternalCallContext | public InternalCallContext createInternalCallContext(final UUID objectId, final ObjectType objectType, final CallContext context) {
// The callcontext may come from a user API - for security, check we're not doing cross-tenants operations
//final Long tenantRecordIdFromObject = retrieveTenantRecordIdFromObject(objectId, objectType);
//final Long tenantRecordIdFromContext = getTenantRecordIdSafe(callcontext);
//Preconditions.checkState(tenantRecordIdFromContext.equals(tenantRecordIdFromObject),
// "tenant of the pointed object (%s) and the callcontext (%s) don't match!", tenantRecordIdFromObject, tenantRecordIdFromContext);
final Long tenantRecordId = getTenantRecordIdSafe(context);
final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, context);
return createInternalCallContext(tenantRecordId,
accountRecordId,
context.getUserName(),
context.getCallOrigin(),
context.getUserType(),
context.getUserToken(),
context.getReasonCode(),
context.getComments(),
context.getCreatedDate(),
context.getUpdatedDate());
} | java | public InternalCallContext createInternalCallContext(final UUID objectId, final ObjectType objectType, final CallContext context) {
// The callcontext may come from a user API - for security, check we're not doing cross-tenants operations
//final Long tenantRecordIdFromObject = retrieveTenantRecordIdFromObject(objectId, objectType);
//final Long tenantRecordIdFromContext = getTenantRecordIdSafe(callcontext);
//Preconditions.checkState(tenantRecordIdFromContext.equals(tenantRecordIdFromObject),
// "tenant of the pointed object (%s) and the callcontext (%s) don't match!", tenantRecordIdFromObject, tenantRecordIdFromContext);
final Long tenantRecordId = getTenantRecordIdSafe(context);
final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, context);
return createInternalCallContext(tenantRecordId,
accountRecordId,
context.getUserName(),
context.getCallOrigin(),
context.getUserType(),
context.getUserToken(),
context.getReasonCode(),
context.getComments(),
context.getCreatedDate(),
context.getUpdatedDate());
} | [
"public",
"InternalCallContext",
"createInternalCallContext",
"(",
"final",
"UUID",
"objectId",
",",
"final",
"ObjectType",
"objectType",
",",
"final",
"CallContext",
"context",
")",
"{",
"// The callcontext may come from a user API - for security, check we're not doing cross-tenants operations",
"//final Long tenantRecordIdFromObject = retrieveTenantRecordIdFromObject(objectId, objectType);",
"//final Long tenantRecordIdFromContext = getTenantRecordIdSafe(callcontext);",
"//Preconditions.checkState(tenantRecordIdFromContext.equals(tenantRecordIdFromObject),",
"// \"tenant of the pointed object (%s) and the callcontext (%s) don't match!\", tenantRecordIdFromObject, tenantRecordIdFromContext);",
"final",
"Long",
"tenantRecordId",
"=",
"getTenantRecordIdSafe",
"(",
"context",
")",
";",
"final",
"Long",
"accountRecordId",
"=",
"getAccountRecordIdSafe",
"(",
"objectId",
",",
"objectType",
",",
"context",
")",
";",
"return",
"createInternalCallContext",
"(",
"tenantRecordId",
",",
"accountRecordId",
",",
"context",
".",
"getUserName",
"(",
")",
",",
"context",
".",
"getCallOrigin",
"(",
")",
",",
"context",
".",
"getUserType",
"(",
")",
",",
"context",
".",
"getUserToken",
"(",
")",
",",
"context",
".",
"getReasonCode",
"(",
")",
",",
"context",
".",
"getComments",
"(",
")",
",",
"context",
".",
"getCreatedDate",
"(",
")",
",",
"context",
".",
"getUpdatedDate",
"(",
")",
")",
";",
"}"
] | Create an internal call callcontext from a call callcontext, and retrieving the account_record_id from another table
@param objectId the id of the row in the table pointed by object type where to look for account_record_id
@param objectType the object type pointed by this objectId
@param context original call callcontext
@return internal call callcontext from callcontext, with a non null account_record_id (if found) | [
"Create",
"an",
"internal",
"call",
"callcontext",
"from",
"a",
"call",
"callcontext",
"and",
"retrieving",
"the",
"account_record_id",
"from",
"another",
"table"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java#L194-L213 |
27,260 | killbill/killbill | util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java | InternalCallContextFactory.createInternalCallContext | public InternalCallContext createInternalCallContext(final UUID objectId, final ObjectType objectType, final String userName,
final CallOrigin callOrigin, final UserType userType, @Nullable final UUID userToken, final Long tenantRecordId) {
final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, tenantRecordId);
return createInternalCallContext(tenantRecordId, accountRecordId, userName, callOrigin, userType, userToken, null, null, null, null);
} | java | public InternalCallContext createInternalCallContext(final UUID objectId, final ObjectType objectType, final String userName,
final CallOrigin callOrigin, final UserType userType, @Nullable final UUID userToken, final Long tenantRecordId) {
final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, tenantRecordId);
return createInternalCallContext(tenantRecordId, accountRecordId, userName, callOrigin, userType, userToken, null, null, null, null);
} | [
"public",
"InternalCallContext",
"createInternalCallContext",
"(",
"final",
"UUID",
"objectId",
",",
"final",
"ObjectType",
"objectType",
",",
"final",
"String",
"userName",
",",
"final",
"CallOrigin",
"callOrigin",
",",
"final",
"UserType",
"userType",
",",
"@",
"Nullable",
"final",
"UUID",
"userToken",
",",
"final",
"Long",
"tenantRecordId",
")",
"{",
"final",
"Long",
"accountRecordId",
"=",
"getAccountRecordIdSafe",
"(",
"objectId",
",",
"objectType",
",",
"tenantRecordId",
")",
";",
"return",
"createInternalCallContext",
"(",
"tenantRecordId",
",",
"accountRecordId",
",",
"userName",
",",
"callOrigin",
",",
"userType",
",",
"userToken",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"}"
] | Used by the payment retry service | [
"Used",
"by",
"the",
"payment",
"retry",
"service"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java#L216-L220 |
27,261 | killbill/killbill | util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java | InternalCallContextFactory.getAccountId | public UUID getAccountId(final UUID objectId, final ObjectType objectType, final TenantContext context) {
final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, context);
if (accountRecordId != null) {
return nonEntityDao.retrieveIdFromObject(accountRecordId, ObjectType.ACCOUNT, objectIdCacheController);
} else {
return null;
}
} | java | public UUID getAccountId(final UUID objectId, final ObjectType objectType, final TenantContext context) {
final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, context);
if (accountRecordId != null) {
return nonEntityDao.retrieveIdFromObject(accountRecordId, ObjectType.ACCOUNT, objectIdCacheController);
} else {
return null;
}
} | [
"public",
"UUID",
"getAccountId",
"(",
"final",
"UUID",
"objectId",
",",
"final",
"ObjectType",
"objectType",
",",
"final",
"TenantContext",
"context",
")",
"{",
"final",
"Long",
"accountRecordId",
"=",
"getAccountRecordIdSafe",
"(",
"objectId",
",",
"objectType",
",",
"context",
")",
";",
"if",
"(",
"accountRecordId",
"!=",
"null",
")",
"{",
"return",
"nonEntityDao",
".",
"retrieveIdFromObject",
"(",
"accountRecordId",
",",
"ObjectType",
".",
"ACCOUNT",
",",
"objectIdCacheController",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | Safe method to retrieve the account id from any object | [
"Safe",
"method",
"to",
"retrieve",
"the",
"account",
"id",
"from",
"any",
"object"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java#L344-L351 |
27,262 | killbill/killbill | entitlement/src/main/java/org/killbill/billing/entitlement/api/SubscriptionEventOrdering.java | SubscriptionEventOrdering.computeSubscriptionBaseEvents | private LinkedList<SubscriptionEvent> computeSubscriptionBaseEvents(final Iterable<Entitlement> entitlements, final InternalTenantContext internalTenantContext) {
final LinkedList<SubscriptionEvent> result = new LinkedList<SubscriptionEvent>();
for (final Entitlement cur : entitlements) {
Preconditions.checkState(cur instanceof DefaultEntitlement, "Entitlement %s is not a DefaultEntitlement", cur);
final SubscriptionBase base = ((DefaultEntitlement) cur).getSubscriptionBase();
final List<SubscriptionBaseTransition> baseTransitions = base.getAllTransitions();
for (final SubscriptionBaseTransition tr : baseTransitions) {
final List<SubscriptionEventType> eventTypes = toEventTypes(tr.getTransitionType());
for (final SubscriptionEventType eventType : eventTypes) {
final SubscriptionEvent event = toSubscriptionEvent(tr, eventType, internalTenantContext);
insertSubscriptionEvent(event, result);
}
}
}
return result;
} | java | private LinkedList<SubscriptionEvent> computeSubscriptionBaseEvents(final Iterable<Entitlement> entitlements, final InternalTenantContext internalTenantContext) {
final LinkedList<SubscriptionEvent> result = new LinkedList<SubscriptionEvent>();
for (final Entitlement cur : entitlements) {
Preconditions.checkState(cur instanceof DefaultEntitlement, "Entitlement %s is not a DefaultEntitlement", cur);
final SubscriptionBase base = ((DefaultEntitlement) cur).getSubscriptionBase();
final List<SubscriptionBaseTransition> baseTransitions = base.getAllTransitions();
for (final SubscriptionBaseTransition tr : baseTransitions) {
final List<SubscriptionEventType> eventTypes = toEventTypes(tr.getTransitionType());
for (final SubscriptionEventType eventType : eventTypes) {
final SubscriptionEvent event = toSubscriptionEvent(tr, eventType, internalTenantContext);
insertSubscriptionEvent(event, result);
}
}
}
return result;
} | [
"private",
"LinkedList",
"<",
"SubscriptionEvent",
">",
"computeSubscriptionBaseEvents",
"(",
"final",
"Iterable",
"<",
"Entitlement",
">",
"entitlements",
",",
"final",
"InternalTenantContext",
"internalTenantContext",
")",
"{",
"final",
"LinkedList",
"<",
"SubscriptionEvent",
">",
"result",
"=",
"new",
"LinkedList",
"<",
"SubscriptionEvent",
">",
"(",
")",
";",
"for",
"(",
"final",
"Entitlement",
"cur",
":",
"entitlements",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"cur",
"instanceof",
"DefaultEntitlement",
",",
"\"Entitlement %s is not a DefaultEntitlement\"",
",",
"cur",
")",
";",
"final",
"SubscriptionBase",
"base",
"=",
"(",
"(",
"DefaultEntitlement",
")",
"cur",
")",
".",
"getSubscriptionBase",
"(",
")",
";",
"final",
"List",
"<",
"SubscriptionBaseTransition",
">",
"baseTransitions",
"=",
"base",
".",
"getAllTransitions",
"(",
")",
";",
"for",
"(",
"final",
"SubscriptionBaseTransition",
"tr",
":",
"baseTransitions",
")",
"{",
"final",
"List",
"<",
"SubscriptionEventType",
">",
"eventTypes",
"=",
"toEventTypes",
"(",
"tr",
".",
"getTransitionType",
"(",
")",
")",
";",
"for",
"(",
"final",
"SubscriptionEventType",
"eventType",
":",
"eventTypes",
")",
"{",
"final",
"SubscriptionEvent",
"event",
"=",
"toSubscriptionEvent",
"(",
"tr",
",",
"eventType",
",",
"internalTenantContext",
")",
";",
"insertSubscriptionEvent",
"(",
"event",
",",
"result",
")",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | Compute the initial stream of events based on the subscription base events | [
"Compute",
"the",
"initial",
"stream",
"of",
"events",
"based",
"on",
"the",
"subscription",
"base",
"events"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/entitlement/src/main/java/org/killbill/billing/entitlement/api/SubscriptionEventOrdering.java#L69-L85 |
27,263 | killbill/killbill | entitlement/src/main/java/org/killbill/billing/entitlement/api/SubscriptionEventOrdering.java | SubscriptionEventOrdering.removeOverlappingSubscriptionEvents | private void removeOverlappingSubscriptionEvents(final LinkedList<SubscriptionEvent> events) {
final Iterator<SubscriptionEvent> iterator = events.iterator();
final Map<String, DefaultSubscriptionEvent> prevPerService = new HashMap<String, DefaultSubscriptionEvent>();
while (iterator.hasNext()) {
final DefaultSubscriptionEvent current = (DefaultSubscriptionEvent) iterator.next();
final DefaultSubscriptionEvent prev = prevPerService.get(current.getServiceName());
if (prev != null) {
if (current.overlaps(prev)) {
iterator.remove();
} else {
prevPerService.put(current.getServiceName(), current);
}
} else {
prevPerService.put(current.getServiceName(), current);
}
}
} | java | private void removeOverlappingSubscriptionEvents(final LinkedList<SubscriptionEvent> events) {
final Iterator<SubscriptionEvent> iterator = events.iterator();
final Map<String, DefaultSubscriptionEvent> prevPerService = new HashMap<String, DefaultSubscriptionEvent>();
while (iterator.hasNext()) {
final DefaultSubscriptionEvent current = (DefaultSubscriptionEvent) iterator.next();
final DefaultSubscriptionEvent prev = prevPerService.get(current.getServiceName());
if (prev != null) {
if (current.overlaps(prev)) {
iterator.remove();
} else {
prevPerService.put(current.getServiceName(), current);
}
} else {
prevPerService.put(current.getServiceName(), current);
}
}
} | [
"private",
"void",
"removeOverlappingSubscriptionEvents",
"(",
"final",
"LinkedList",
"<",
"SubscriptionEvent",
">",
"events",
")",
"{",
"final",
"Iterator",
"<",
"SubscriptionEvent",
">",
"iterator",
"=",
"events",
".",
"iterator",
"(",
")",
";",
"final",
"Map",
"<",
"String",
",",
"DefaultSubscriptionEvent",
">",
"prevPerService",
"=",
"new",
"HashMap",
"<",
"String",
",",
"DefaultSubscriptionEvent",
">",
"(",
")",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"DefaultSubscriptionEvent",
"current",
"=",
"(",
"DefaultSubscriptionEvent",
")",
"iterator",
".",
"next",
"(",
")",
";",
"final",
"DefaultSubscriptionEvent",
"prev",
"=",
"prevPerService",
".",
"get",
"(",
"current",
".",
"getServiceName",
"(",
")",
")",
";",
"if",
"(",
"prev",
"!=",
"null",
")",
"{",
"if",
"(",
"current",
".",
"overlaps",
"(",
"prev",
")",
")",
"{",
"iterator",
".",
"remove",
"(",
")",
";",
"}",
"else",
"{",
"prevPerService",
".",
"put",
"(",
"current",
".",
"getServiceName",
"(",
")",
",",
"current",
")",
";",
"}",
"}",
"else",
"{",
"prevPerService",
".",
"put",
"(",
"current",
".",
"getServiceName",
"(",
")",
",",
"current",
")",
";",
"}",
"}",
"}"
] | Make sure the argument supports the remove operation - hence expect a LinkedList, not a List | [
"Make",
"sure",
"the",
"argument",
"supports",
"the",
"remove",
"operation",
"-",
"hence",
"expect",
"a",
"LinkedList",
"not",
"a",
"List"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/entitlement/src/main/java/org/killbill/billing/entitlement/api/SubscriptionEventOrdering.java#L170-L186 |
27,264 | killbill/killbill | overdue/src/main/java/org/killbill/billing/overdue/calculator/BillingStateCalculator.java | BillingStateCalculator.earliest | Invoice earliest(final SortedSet<Invoice> unpaidInvoices) {
try {
return unpaidInvoices.first();
} catch (NoSuchElementException e) {
return null;
}
} | java | Invoice earliest(final SortedSet<Invoice> unpaidInvoices) {
try {
return unpaidInvoices.first();
} catch (NoSuchElementException e) {
return null;
}
} | [
"Invoice",
"earliest",
"(",
"final",
"SortedSet",
"<",
"Invoice",
">",
"unpaidInvoices",
")",
"{",
"try",
"{",
"return",
"unpaidInvoices",
".",
"first",
"(",
")",
";",
"}",
"catch",
"(",
"NoSuchElementException",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] | Package scope for testing | [
"Package",
"scope",
"for",
"testing"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/overdue/src/main/java/org/killbill/billing/overdue/calculator/BillingStateCalculator.java#L92-L98 |
27,265 | killbill/killbill | util/src/main/java/org/killbill/billing/util/export/dao/CSVExportOutputStream.java | CSVExportOutputStream.sanitize | private Object sanitize(final Object o) {
if (!(o instanceof String)) {
return o;
} else {
// Use Python3 way of escaping characters: https://docs.python.org/3.3/howto/unicode.html#the-string-type
return ((String) o).replace("\n", "\\N{LINE FEED}")
.replace("|", "\\N{VERTICAL LINE}");
}
} | java | private Object sanitize(final Object o) {
if (!(o instanceof String)) {
return o;
} else {
// Use Python3 way of escaping characters: https://docs.python.org/3.3/howto/unicode.html#the-string-type
return ((String) o).replace("\n", "\\N{LINE FEED}")
.replace("|", "\\N{VERTICAL LINE}");
}
} | [
"private",
"Object",
"sanitize",
"(",
"final",
"Object",
"o",
")",
"{",
"if",
"(",
"!",
"(",
"o",
"instanceof",
"String",
")",
")",
"{",
"return",
"o",
";",
"}",
"else",
"{",
"// Use Python3 way of escaping characters: https://docs.python.org/3.3/howto/unicode.html#the-string-type",
"return",
"(",
"(",
"String",
")",
"o",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\\\\N{LINE FEED}\"",
")",
".",
"replace",
"(",
"\"|\"",
",",
"\"\\\\N{VERTICAL LINE}\"",
")",
";",
"}",
"}"
] | Sanitize special characters which could impact the import process | [
"Sanitize",
"special",
"characters",
"which",
"could",
"impact",
"the",
"import",
"process"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/export/dao/CSVExportOutputStream.java#L104-L112 |
27,266 | killbill/killbill | catalog/src/main/java/org/killbill/billing/catalog/caching/DefaultCatalogCache.java | DefaultCatalogCache.initializeCacheLoaderArgument | private CacheLoaderArgument initializeCacheLoaderArgument(final boolean filterTemplateCatalog) {
final LoaderCallback loaderCallback = new LoaderCallback() {
@Override
public Catalog loadCatalog(final List<String> catalogXMLs, final Long tenantRecordId) throws CatalogApiException {
return loader.load(catalogXMLs, filterTemplateCatalog, tenantRecordId);
}
};
final Object[] args = new Object[1];
args[0] = loaderCallback;
final ObjectType irrelevant = null;
final InternalTenantContext notUsed = null;
return new CacheLoaderArgument(irrelevant, args, notUsed);
} | java | private CacheLoaderArgument initializeCacheLoaderArgument(final boolean filterTemplateCatalog) {
final LoaderCallback loaderCallback = new LoaderCallback() {
@Override
public Catalog loadCatalog(final List<String> catalogXMLs, final Long tenantRecordId) throws CatalogApiException {
return loader.load(catalogXMLs, filterTemplateCatalog, tenantRecordId);
}
};
final Object[] args = new Object[1];
args[0] = loaderCallback;
final ObjectType irrelevant = null;
final InternalTenantContext notUsed = null;
return new CacheLoaderArgument(irrelevant, args, notUsed);
} | [
"private",
"CacheLoaderArgument",
"initializeCacheLoaderArgument",
"(",
"final",
"boolean",
"filterTemplateCatalog",
")",
"{",
"final",
"LoaderCallback",
"loaderCallback",
"=",
"new",
"LoaderCallback",
"(",
")",
"{",
"@",
"Override",
"public",
"Catalog",
"loadCatalog",
"(",
"final",
"List",
"<",
"String",
">",
"catalogXMLs",
",",
"final",
"Long",
"tenantRecordId",
")",
"throws",
"CatalogApiException",
"{",
"return",
"loader",
".",
"load",
"(",
"catalogXMLs",
",",
"filterTemplateCatalog",
",",
"tenantRecordId",
")",
";",
"}",
"}",
";",
"final",
"Object",
"[",
"]",
"args",
"=",
"new",
"Object",
"[",
"1",
"]",
";",
"args",
"[",
"0",
"]",
"=",
"loaderCallback",
";",
"final",
"ObjectType",
"irrelevant",
"=",
"null",
";",
"final",
"InternalTenantContext",
"notUsed",
"=",
"null",
";",
"return",
"new",
"CacheLoaderArgument",
"(",
"irrelevant",
",",
"args",
",",
"notUsed",
")",
";",
"}"
] | This is a contract between the TenantCatalogCacheLoader and the DefaultCatalogCache | [
"This",
"is",
"a",
"contract",
"between",
"the",
"TenantCatalogCacheLoader",
"and",
"the",
"DefaultCatalogCache"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/catalog/src/main/java/org/killbill/billing/catalog/caching/DefaultCatalogCache.java#L214-L226 |
27,267 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/generator/InvoiceWithMetadata.java | InvoiceWithMetadata.build | private void build() {
// nextRecurringDate are computed based on *proposed* items, and not missing items (= proposed - existing). So
// we need to filter out the dates for which there is no item left otherwsie we may end up in creating too many notification dates
// and in particular that could lead to an infinite loop.
for (final UUID subscriptionId : perSubscriptionFutureNotificationDates.keySet()) {
final SubscriptionFutureNotificationDates tmp = perSubscriptionFutureNotificationDates.get(subscriptionId);
if (tmp.getRecurringBillingMode() == BillingMode.IN_ADVANCE && !hasItemsForSubscription(subscriptionId, InvoiceItemType.RECURRING)) {
tmp.resetNextRecurringDate();
}
}
if (invoice != null && invoice.getInvoiceItems().isEmpty()) {
invoice = null;
}
} | java | private void build() {
// nextRecurringDate are computed based on *proposed* items, and not missing items (= proposed - existing). So
// we need to filter out the dates for which there is no item left otherwsie we may end up in creating too many notification dates
// and in particular that could lead to an infinite loop.
for (final UUID subscriptionId : perSubscriptionFutureNotificationDates.keySet()) {
final SubscriptionFutureNotificationDates tmp = perSubscriptionFutureNotificationDates.get(subscriptionId);
if (tmp.getRecurringBillingMode() == BillingMode.IN_ADVANCE && !hasItemsForSubscription(subscriptionId, InvoiceItemType.RECURRING)) {
tmp.resetNextRecurringDate();
}
}
if (invoice != null && invoice.getInvoiceItems().isEmpty()) {
invoice = null;
}
} | [
"private",
"void",
"build",
"(",
")",
"{",
"// nextRecurringDate are computed based on *proposed* items, and not missing items (= proposed - existing). So",
"// we need to filter out the dates for which there is no item left otherwsie we may end up in creating too many notification dates",
"// and in particular that could lead to an infinite loop.",
"for",
"(",
"final",
"UUID",
"subscriptionId",
":",
"perSubscriptionFutureNotificationDates",
".",
"keySet",
"(",
")",
")",
"{",
"final",
"SubscriptionFutureNotificationDates",
"tmp",
"=",
"perSubscriptionFutureNotificationDates",
".",
"get",
"(",
"subscriptionId",
")",
";",
"if",
"(",
"tmp",
".",
"getRecurringBillingMode",
"(",
")",
"==",
"BillingMode",
".",
"IN_ADVANCE",
"&&",
"!",
"hasItemsForSubscription",
"(",
"subscriptionId",
",",
"InvoiceItemType",
".",
"RECURRING",
")",
")",
"{",
"tmp",
".",
"resetNextRecurringDate",
"(",
")",
";",
"}",
"}",
"if",
"(",
"invoice",
"!=",
"null",
"&&",
"invoice",
".",
"getInvoiceItems",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"invoice",
"=",
"null",
";",
"}",
"}"
] | Remove all the IN_ADVANCE items for which we have no invoice items | [
"Remove",
"all",
"the",
"IN_ADVANCE",
"items",
"for",
"which",
"we",
"have",
"no",
"invoice",
"items"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/generator/InvoiceWithMetadata.java#L61-L74 |
27,268 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/calculator/InvoiceCalculatorUtils.java | InvoiceCalculatorUtils.computeInvoiceAmountAdjustedForAccountCredit | private static BigDecimal computeInvoiceAmountAdjustedForAccountCredit(final Currency currency, final Iterable<InvoiceItem> invoiceItems) {
BigDecimal amountAdjusted = BigDecimal.ZERO;
if (invoiceItems == null || !invoiceItems.iterator().hasNext()) {
return KillBillMoney.of(amountAdjusted, currency);
}
for (final InvoiceItem invoiceItem : invoiceItems) {
final Iterable<InvoiceItem> otherInvoiceItems = Iterables.filter(invoiceItems, new Predicate<InvoiceItem>() {
@Override
public boolean apply(final InvoiceItem input) {
return !input.getId().equals(invoiceItem.getId());
}
});
if (InvoiceItemType.CREDIT_ADJ.equals(invoiceItem.getInvoiceItemType()) &&
(Iterables.size(otherInvoiceItems) == 1 &&
InvoiceItemType.CBA_ADJ.equals(otherInvoiceItems.iterator().next().getInvoiceItemType()) &&
otherInvoiceItems.iterator().next().getInvoiceId().equals(invoiceItem.getInvoiceId()) &&
otherInvoiceItems.iterator().next().getAmount().compareTo(invoiceItem.getAmount().negate()) == 0)) {
amountAdjusted = amountAdjusted.add(invoiceItem.getAmount());
}
}
return KillBillMoney.of(amountAdjusted, currency);
} | java | private static BigDecimal computeInvoiceAmountAdjustedForAccountCredit(final Currency currency, final Iterable<InvoiceItem> invoiceItems) {
BigDecimal amountAdjusted = BigDecimal.ZERO;
if (invoiceItems == null || !invoiceItems.iterator().hasNext()) {
return KillBillMoney.of(amountAdjusted, currency);
}
for (final InvoiceItem invoiceItem : invoiceItems) {
final Iterable<InvoiceItem> otherInvoiceItems = Iterables.filter(invoiceItems, new Predicate<InvoiceItem>() {
@Override
public boolean apply(final InvoiceItem input) {
return !input.getId().equals(invoiceItem.getId());
}
});
if (InvoiceItemType.CREDIT_ADJ.equals(invoiceItem.getInvoiceItemType()) &&
(Iterables.size(otherInvoiceItems) == 1 &&
InvoiceItemType.CBA_ADJ.equals(otherInvoiceItems.iterator().next().getInvoiceItemType()) &&
otherInvoiceItems.iterator().next().getInvoiceId().equals(invoiceItem.getInvoiceId()) &&
otherInvoiceItems.iterator().next().getAmount().compareTo(invoiceItem.getAmount().negate()) == 0)) {
amountAdjusted = amountAdjusted.add(invoiceItem.getAmount());
}
}
return KillBillMoney.of(amountAdjusted, currency);
} | [
"private",
"static",
"BigDecimal",
"computeInvoiceAmountAdjustedForAccountCredit",
"(",
"final",
"Currency",
"currency",
",",
"final",
"Iterable",
"<",
"InvoiceItem",
">",
"invoiceItems",
")",
"{",
"BigDecimal",
"amountAdjusted",
"=",
"BigDecimal",
".",
"ZERO",
";",
"if",
"(",
"invoiceItems",
"==",
"null",
"||",
"!",
"invoiceItems",
".",
"iterator",
"(",
")",
".",
"hasNext",
"(",
")",
")",
"{",
"return",
"KillBillMoney",
".",
"of",
"(",
"amountAdjusted",
",",
"currency",
")",
";",
"}",
"for",
"(",
"final",
"InvoiceItem",
"invoiceItem",
":",
"invoiceItems",
")",
"{",
"final",
"Iterable",
"<",
"InvoiceItem",
">",
"otherInvoiceItems",
"=",
"Iterables",
".",
"filter",
"(",
"invoiceItems",
",",
"new",
"Predicate",
"<",
"InvoiceItem",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"final",
"InvoiceItem",
"input",
")",
"{",
"return",
"!",
"input",
".",
"getId",
"(",
")",
".",
"equals",
"(",
"invoiceItem",
".",
"getId",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"InvoiceItemType",
".",
"CREDIT_ADJ",
".",
"equals",
"(",
"invoiceItem",
".",
"getInvoiceItemType",
"(",
")",
")",
"&&",
"(",
"Iterables",
".",
"size",
"(",
"otherInvoiceItems",
")",
"==",
"1",
"&&",
"InvoiceItemType",
".",
"CBA_ADJ",
".",
"equals",
"(",
"otherInvoiceItems",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
".",
"getInvoiceItemType",
"(",
")",
")",
"&&",
"otherInvoiceItems",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
".",
"getInvoiceId",
"(",
")",
".",
"equals",
"(",
"invoiceItem",
".",
"getInvoiceId",
"(",
")",
")",
"&&",
"otherInvoiceItems",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
".",
"getAmount",
"(",
")",
".",
"compareTo",
"(",
"invoiceItem",
".",
"getAmount",
"(",
")",
".",
"negate",
"(",
")",
")",
"==",
"0",
")",
")",
"{",
"amountAdjusted",
"=",
"amountAdjusted",
".",
"add",
"(",
"invoiceItem",
".",
"getAmount",
"(",
")",
")",
";",
"}",
"}",
"return",
"KillBillMoney",
".",
"of",
"(",
"amountAdjusted",
",",
"currency",
")",
";",
"}"
] | Snowflake for the CREDIT_ADJ on its own invoice | [
"Snowflake",
"for",
"the",
"CREDIT_ADJ",
"on",
"its",
"own",
"invoice"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/calculator/InvoiceCalculatorUtils.java#L111-L135 |
27,269 | killbill/killbill | subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java | PlanAligner.getCurrentAndNextTimedPhaseOnCreate | public TimedPhase[] getCurrentAndNextTimedPhaseOnCreate(final DateTime alignStartDate,
final DateTime bundleStartDate,
final Plan plan,
@Nullable final PhaseType initialPhase,
final String priceList,
final DateTime effectiveDate,
final Catalog catalog,
final InternalTenantContext context) throws CatalogApiException, SubscriptionBaseApiException {
final List<TimedPhase> timedPhases = getTimedPhaseOnCreate(alignStartDate,
bundleStartDate,
plan,
initialPhase,
catalog,
effectiveDate,
context);
final TimedPhase[] result = new TimedPhase[2];
result[0] = getTimedPhase(timedPhases, effectiveDate, WhichPhase.CURRENT);
result[1] = getTimedPhase(timedPhases, effectiveDate, WhichPhase.NEXT);
return result;
} | java | public TimedPhase[] getCurrentAndNextTimedPhaseOnCreate(final DateTime alignStartDate,
final DateTime bundleStartDate,
final Plan plan,
@Nullable final PhaseType initialPhase,
final String priceList,
final DateTime effectiveDate,
final Catalog catalog,
final InternalTenantContext context) throws CatalogApiException, SubscriptionBaseApiException {
final List<TimedPhase> timedPhases = getTimedPhaseOnCreate(alignStartDate,
bundleStartDate,
plan,
initialPhase,
catalog,
effectiveDate,
context);
final TimedPhase[] result = new TimedPhase[2];
result[0] = getTimedPhase(timedPhases, effectiveDate, WhichPhase.CURRENT);
result[1] = getTimedPhase(timedPhases, effectiveDate, WhichPhase.NEXT);
return result;
} | [
"public",
"TimedPhase",
"[",
"]",
"getCurrentAndNextTimedPhaseOnCreate",
"(",
"final",
"DateTime",
"alignStartDate",
",",
"final",
"DateTime",
"bundleStartDate",
",",
"final",
"Plan",
"plan",
",",
"@",
"Nullable",
"final",
"PhaseType",
"initialPhase",
",",
"final",
"String",
"priceList",
",",
"final",
"DateTime",
"effectiveDate",
",",
"final",
"Catalog",
"catalog",
",",
"final",
"InternalTenantContext",
"context",
")",
"throws",
"CatalogApiException",
",",
"SubscriptionBaseApiException",
"{",
"final",
"List",
"<",
"TimedPhase",
">",
"timedPhases",
"=",
"getTimedPhaseOnCreate",
"(",
"alignStartDate",
",",
"bundleStartDate",
",",
"plan",
",",
"initialPhase",
",",
"catalog",
",",
"effectiveDate",
",",
"context",
")",
";",
"final",
"TimedPhase",
"[",
"]",
"result",
"=",
"new",
"TimedPhase",
"[",
"2",
"]",
";",
"result",
"[",
"0",
"]",
"=",
"getTimedPhase",
"(",
"timedPhases",
",",
"effectiveDate",
",",
"WhichPhase",
".",
"CURRENT",
")",
";",
"result",
"[",
"1",
"]",
"=",
"getTimedPhase",
"(",
"timedPhases",
",",
"effectiveDate",
",",
"WhichPhase",
".",
"NEXT",
")",
";",
"return",
"result",
";",
"}"
] | Returns the current and next phase for the subscription in creation
@param alignStartDate the subscription (align) startDate for the subscription
@param bundleStartDate the bundle startDate used alignment
@param plan the current Plan
@param initialPhase the initialPhase on which we should create that subscription. can be null
@param priceList the priceList
@param effectiveDate the effective creation date (driven by the catalog policy, i.e. when the creation occurs)
@return the current and next phases
@throws CatalogApiException for catalog errors
@throws org.killbill.billing.subscription.api.user.SubscriptionBaseApiException for subscription errors | [
"Returns",
"the",
"current",
"and",
"next",
"phase",
"for",
"the",
"subscription",
"in",
"creation"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java#L80-L99 |
27,270 | killbill/killbill | subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java | PlanAligner.getCurrentTimedPhaseOnChange | public TimedPhase getCurrentTimedPhaseOnChange(final DefaultSubscriptionBase subscription,
final Plan plan,
final DateTime effectiveDate,
final PhaseType newPlanInitialPhaseType,
final Catalog catalog,
final InternalTenantContext context) throws CatalogApiException, SubscriptionBaseApiException {
return getTimedPhaseOnChange(subscription, plan, effectiveDate, newPlanInitialPhaseType, WhichPhase.CURRENT, catalog, context);
} | java | public TimedPhase getCurrentTimedPhaseOnChange(final DefaultSubscriptionBase subscription,
final Plan plan,
final DateTime effectiveDate,
final PhaseType newPlanInitialPhaseType,
final Catalog catalog,
final InternalTenantContext context) throws CatalogApiException, SubscriptionBaseApiException {
return getTimedPhaseOnChange(subscription, plan, effectiveDate, newPlanInitialPhaseType, WhichPhase.CURRENT, catalog, context);
} | [
"public",
"TimedPhase",
"getCurrentTimedPhaseOnChange",
"(",
"final",
"DefaultSubscriptionBase",
"subscription",
",",
"final",
"Plan",
"plan",
",",
"final",
"DateTime",
"effectiveDate",
",",
"final",
"PhaseType",
"newPlanInitialPhaseType",
",",
"final",
"Catalog",
"catalog",
",",
"final",
"InternalTenantContext",
"context",
")",
"throws",
"CatalogApiException",
",",
"SubscriptionBaseApiException",
"{",
"return",
"getTimedPhaseOnChange",
"(",
"subscription",
",",
"plan",
",",
"effectiveDate",
",",
"newPlanInitialPhaseType",
",",
"WhichPhase",
".",
"CURRENT",
",",
"catalog",
",",
"context",
")",
";",
"}"
] | Returns current Phase for that Plan change
@param subscription the subscription in change (only start date, bundle start date, current phase, plan and pricelist
are looked at)
@param plan the current Plan
@param effectiveDate the effective change date (driven by the catalog policy, i.e. when the change occurs)
@param newPlanInitialPhaseType the phase on which to start when switching to new plan
@return the current phase
@throws CatalogApiException for catalog errors
@throws org.killbill.billing.subscription.api.user.SubscriptionBaseApiException for subscription errors | [
"Returns",
"current",
"Phase",
"for",
"that",
"Plan",
"change"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java#L113-L121 |
27,271 | killbill/killbill | subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java | PlanAligner.getNextTimedPhase | public TimedPhase getNextTimedPhase(final DefaultSubscriptionBase subscription, final DateTime effectiveDate, final Catalog catalog, final InternalTenantContext context) {
try {
final SubscriptionBaseTransition pendingOrLastPlanTransition;
if (subscription.getState() == EntitlementState.PENDING) {
pendingOrLastPlanTransition = subscription.getPendingTransition();
} else {
pendingOrLastPlanTransition = subscription.getLastTransitionForCurrentPlan();
}
switch (pendingOrLastPlanTransition.getTransitionType()) {
// If we never had any Plan change, borrow the logic for createPlan alignment
case CREATE:
case TRANSFER:
final List<TimedPhase> timedPhases = getTimedPhaseOnCreate(subscription.getAlignStartDate(),
subscription.getBundleStartDate(),
pendingOrLastPlanTransition.getNextPlan(),
pendingOrLastPlanTransition.getNextPhase().getPhaseType(),
catalog,
// Use the catalog version at subscription creation time: this allows
// for PHASE events and uncancel operations for plans/products/pricelists already retired
// This is not 100% correct in a scenario where the catalog was updated and the alignment rules changed since
// See https://github.com/killbill/killbill/issues/784
subscription.getAlignStartDate(),
context);
return getTimedPhase(timedPhases, effectiveDate, WhichPhase.NEXT);
case CHANGE:
return getTimedPhaseOnChange(subscription.getAlignStartDate(),
subscription.getBundleStartDate(),
pendingOrLastPlanTransition.getPreviousPhase(),
pendingOrLastPlanTransition.getPreviousPlan(),
pendingOrLastPlanTransition.getNextPlan(),
effectiveDate,
// Same remark as above
subscription.getAlignStartDate(),
pendingOrLastPlanTransition.getEffectiveTransitionTime(),
subscription.getAllTransitions().get(0).getNextPhase().getPhaseType(),
null,
WhichPhase.NEXT,
catalog,
context);
default:
throw new SubscriptionBaseError(String.format("Unexpected initial transition %s for current plan %s on subscription %s",
pendingOrLastPlanTransition.getTransitionType(), subscription.getCurrentPlan(), subscription.getId()));
}
} catch (Exception /* SubscriptionBaseApiException, CatalogApiException */ e) {
throw new SubscriptionBaseError(String.format("Could not compute next phase change for subscription %s", subscription.getId()), e);
}
} | java | public TimedPhase getNextTimedPhase(final DefaultSubscriptionBase subscription, final DateTime effectiveDate, final Catalog catalog, final InternalTenantContext context) {
try {
final SubscriptionBaseTransition pendingOrLastPlanTransition;
if (subscription.getState() == EntitlementState.PENDING) {
pendingOrLastPlanTransition = subscription.getPendingTransition();
} else {
pendingOrLastPlanTransition = subscription.getLastTransitionForCurrentPlan();
}
switch (pendingOrLastPlanTransition.getTransitionType()) {
// If we never had any Plan change, borrow the logic for createPlan alignment
case CREATE:
case TRANSFER:
final List<TimedPhase> timedPhases = getTimedPhaseOnCreate(subscription.getAlignStartDate(),
subscription.getBundleStartDate(),
pendingOrLastPlanTransition.getNextPlan(),
pendingOrLastPlanTransition.getNextPhase().getPhaseType(),
catalog,
// Use the catalog version at subscription creation time: this allows
// for PHASE events and uncancel operations for plans/products/pricelists already retired
// This is not 100% correct in a scenario where the catalog was updated and the alignment rules changed since
// See https://github.com/killbill/killbill/issues/784
subscription.getAlignStartDate(),
context);
return getTimedPhase(timedPhases, effectiveDate, WhichPhase.NEXT);
case CHANGE:
return getTimedPhaseOnChange(subscription.getAlignStartDate(),
subscription.getBundleStartDate(),
pendingOrLastPlanTransition.getPreviousPhase(),
pendingOrLastPlanTransition.getPreviousPlan(),
pendingOrLastPlanTransition.getNextPlan(),
effectiveDate,
// Same remark as above
subscription.getAlignStartDate(),
pendingOrLastPlanTransition.getEffectiveTransitionTime(),
subscription.getAllTransitions().get(0).getNextPhase().getPhaseType(),
null,
WhichPhase.NEXT,
catalog,
context);
default:
throw new SubscriptionBaseError(String.format("Unexpected initial transition %s for current plan %s on subscription %s",
pendingOrLastPlanTransition.getTransitionType(), subscription.getCurrentPlan(), subscription.getId()));
}
} catch (Exception /* SubscriptionBaseApiException, CatalogApiException */ e) {
throw new SubscriptionBaseError(String.format("Could not compute next phase change for subscription %s", subscription.getId()), e);
}
} | [
"public",
"TimedPhase",
"getNextTimedPhase",
"(",
"final",
"DefaultSubscriptionBase",
"subscription",
",",
"final",
"DateTime",
"effectiveDate",
",",
"final",
"Catalog",
"catalog",
",",
"final",
"InternalTenantContext",
"context",
")",
"{",
"try",
"{",
"final",
"SubscriptionBaseTransition",
"pendingOrLastPlanTransition",
";",
"if",
"(",
"subscription",
".",
"getState",
"(",
")",
"==",
"EntitlementState",
".",
"PENDING",
")",
"{",
"pendingOrLastPlanTransition",
"=",
"subscription",
".",
"getPendingTransition",
"(",
")",
";",
"}",
"else",
"{",
"pendingOrLastPlanTransition",
"=",
"subscription",
".",
"getLastTransitionForCurrentPlan",
"(",
")",
";",
"}",
"switch",
"(",
"pendingOrLastPlanTransition",
".",
"getTransitionType",
"(",
")",
")",
"{",
"// If we never had any Plan change, borrow the logic for createPlan alignment",
"case",
"CREATE",
":",
"case",
"TRANSFER",
":",
"final",
"List",
"<",
"TimedPhase",
">",
"timedPhases",
"=",
"getTimedPhaseOnCreate",
"(",
"subscription",
".",
"getAlignStartDate",
"(",
")",
",",
"subscription",
".",
"getBundleStartDate",
"(",
")",
",",
"pendingOrLastPlanTransition",
".",
"getNextPlan",
"(",
")",
",",
"pendingOrLastPlanTransition",
".",
"getNextPhase",
"(",
")",
".",
"getPhaseType",
"(",
")",
",",
"catalog",
",",
"// Use the catalog version at subscription creation time: this allows",
"// for PHASE events and uncancel operations for plans/products/pricelists already retired",
"// This is not 100% correct in a scenario where the catalog was updated and the alignment rules changed since",
"// See https://github.com/killbill/killbill/issues/784",
"subscription",
".",
"getAlignStartDate",
"(",
")",
",",
"context",
")",
";",
"return",
"getTimedPhase",
"(",
"timedPhases",
",",
"effectiveDate",
",",
"WhichPhase",
".",
"NEXT",
")",
";",
"case",
"CHANGE",
":",
"return",
"getTimedPhaseOnChange",
"(",
"subscription",
".",
"getAlignStartDate",
"(",
")",
",",
"subscription",
".",
"getBundleStartDate",
"(",
")",
",",
"pendingOrLastPlanTransition",
".",
"getPreviousPhase",
"(",
")",
",",
"pendingOrLastPlanTransition",
".",
"getPreviousPlan",
"(",
")",
",",
"pendingOrLastPlanTransition",
".",
"getNextPlan",
"(",
")",
",",
"effectiveDate",
",",
"// Same remark as above",
"subscription",
".",
"getAlignStartDate",
"(",
")",
",",
"pendingOrLastPlanTransition",
".",
"getEffectiveTransitionTime",
"(",
")",
",",
"subscription",
".",
"getAllTransitions",
"(",
")",
".",
"get",
"(",
"0",
")",
".",
"getNextPhase",
"(",
")",
".",
"getPhaseType",
"(",
")",
",",
"null",
",",
"WhichPhase",
".",
"NEXT",
",",
"catalog",
",",
"context",
")",
";",
"default",
":",
"throw",
"new",
"SubscriptionBaseError",
"(",
"String",
".",
"format",
"(",
"\"Unexpected initial transition %s for current plan %s on subscription %s\"",
",",
"pendingOrLastPlanTransition",
".",
"getTransitionType",
"(",
")",
",",
"subscription",
".",
"getCurrentPlan",
"(",
")",
",",
"subscription",
".",
"getId",
"(",
")",
")",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"/* SubscriptionBaseApiException, CatalogApiException */",
"e",
")",
"{",
"throw",
"new",
"SubscriptionBaseError",
"(",
"String",
".",
"format",
"(",
"\"Could not compute next phase change for subscription %s\"",
",",
"subscription",
".",
"getId",
"(",
")",
")",
",",
"e",
")",
";",
"}",
"}"
] | Returns next Phase for that SubscriptionBase at a point in time
@param subscription the subscription for which we need to compute the next Phase event
@return the next phase | [
"Returns",
"next",
"Phase",
"for",
"that",
"SubscriptionBase",
"at",
"a",
"point",
"in",
"time"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java#L150-L198 |
27,272 | killbill/killbill | subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java | PlanAligner.getTimedPhase | private TimedPhase getTimedPhase(final List<TimedPhase> timedPhases, final DateTime effectiveDate, final WhichPhase which) {
TimedPhase cur = null;
TimedPhase next = null;
for (final TimedPhase phase : timedPhases) {
if (phase.getStartPhase().isAfter(effectiveDate)) {
next = phase;
break;
}
cur = phase;
}
switch (which) {
case CURRENT:
return cur;
case NEXT:
return next;
default:
throw new SubscriptionBaseError(String.format("Unexpected %s TimedPhase", which));
}
} | java | private TimedPhase getTimedPhase(final List<TimedPhase> timedPhases, final DateTime effectiveDate, final WhichPhase which) {
TimedPhase cur = null;
TimedPhase next = null;
for (final TimedPhase phase : timedPhases) {
if (phase.getStartPhase().isAfter(effectiveDate)) {
next = phase;
break;
}
cur = phase;
}
switch (which) {
case CURRENT:
return cur;
case NEXT:
return next;
default:
throw new SubscriptionBaseError(String.format("Unexpected %s TimedPhase", which));
}
} | [
"private",
"TimedPhase",
"getTimedPhase",
"(",
"final",
"List",
"<",
"TimedPhase",
">",
"timedPhases",
",",
"final",
"DateTime",
"effectiveDate",
",",
"final",
"WhichPhase",
"which",
")",
"{",
"TimedPhase",
"cur",
"=",
"null",
";",
"TimedPhase",
"next",
"=",
"null",
";",
"for",
"(",
"final",
"TimedPhase",
"phase",
":",
"timedPhases",
")",
"{",
"if",
"(",
"phase",
".",
"getStartPhase",
"(",
")",
".",
"isAfter",
"(",
"effectiveDate",
")",
")",
"{",
"next",
"=",
"phase",
";",
"break",
";",
"}",
"cur",
"=",
"phase",
";",
"}",
"switch",
"(",
"which",
")",
"{",
"case",
"CURRENT",
":",
"return",
"cur",
";",
"case",
"NEXT",
":",
"return",
"next",
";",
"default",
":",
"throw",
"new",
"SubscriptionBaseError",
"(",
"String",
".",
"format",
"(",
"\"Unexpected %s TimedPhase\"",
",",
"which",
")",
")",
";",
"}",
"}"
] | STEPH check for non evergreen Plans and what happens | [
"STEPH",
"check",
"for",
"non",
"evergreen",
"Plans",
"and",
"what",
"happens"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java#L339-L358 |
27,273 | killbill/killbill | util/src/main/java/org/killbill/billing/util/glue/EhcacheShiroManagerProvider.java | EhcacheShiroManagerProvider.getEhcacheManager | private org.ehcache.CacheManager getEhcacheManager() {
try {
final Field f = eh107CacheManager.getClass().getDeclaredField("ehCacheManager");
f.setAccessible(true);
return (org.ehcache.CacheManager) f.get(eh107CacheManager);
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
} catch (final NoSuchFieldException e) {
throw new RuntimeException(e);
}
} | java | private org.ehcache.CacheManager getEhcacheManager() {
try {
final Field f = eh107CacheManager.getClass().getDeclaredField("ehCacheManager");
f.setAccessible(true);
return (org.ehcache.CacheManager) f.get(eh107CacheManager);
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
} catch (final NoSuchFieldException e) {
throw new RuntimeException(e);
}
} | [
"private",
"org",
".",
"ehcache",
".",
"CacheManager",
"getEhcacheManager",
"(",
")",
"{",
"try",
"{",
"final",
"Field",
"f",
"=",
"eh107CacheManager",
".",
"getClass",
"(",
")",
".",
"getDeclaredField",
"(",
"\"ehCacheManager\"",
")",
";",
"f",
".",
"setAccessible",
"(",
"true",
")",
";",
"return",
"(",
"org",
".",
"ehcache",
".",
"CacheManager",
")",
"f",
".",
"get",
"(",
"eh107CacheManager",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"final",
"NoSuchFieldException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | Shiro isn't JCache compatible | [
"Shiro",
"isn",
"t",
"JCache",
"compatible"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/glue/EhcacheShiroManagerProvider.java#L77-L88 |
27,274 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsInterval.java | ItemsInterval.buildForMissingInterval | public void buildForMissingInterval(@Nullable final LocalDate startDate, @Nullable final LocalDate endDate, @Nullable final UUID targetInvoiceId, final Collection<Item> output, final boolean addRepair) {
final Item item = createNewItem(startDate, endDate, targetInvoiceId, addRepair);
if (item != null) {
output.add(item);
}
} | java | public void buildForMissingInterval(@Nullable final LocalDate startDate, @Nullable final LocalDate endDate, @Nullable final UUID targetInvoiceId, final Collection<Item> output, final boolean addRepair) {
final Item item = createNewItem(startDate, endDate, targetInvoiceId, addRepair);
if (item != null) {
output.add(item);
}
} | [
"public",
"void",
"buildForMissingInterval",
"(",
"@",
"Nullable",
"final",
"LocalDate",
"startDate",
",",
"@",
"Nullable",
"final",
"LocalDate",
"endDate",
",",
"@",
"Nullable",
"final",
"UUID",
"targetInvoiceId",
",",
"final",
"Collection",
"<",
"Item",
">",
"output",
",",
"final",
"boolean",
"addRepair",
")",
"{",
"final",
"Item",
"item",
"=",
"createNewItem",
"(",
"startDate",
",",
"endDate",
",",
"targetInvoiceId",
",",
"addRepair",
")",
";",
"if",
"(",
"item",
"!=",
"null",
")",
"{",
"output",
".",
"add",
"(",
"item",
")",
";",
"}",
"}"
] | Called for missing service periods | [
"Called",
"for",
"missing",
"service",
"periods"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsInterval.java#L152-L157 |
27,275 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsInterval.java | ItemsInterval.buildFromItems | public void buildFromItems(final Collection<Item> output, final boolean mergeMode) {
buildForMissingInterval(null, null, null, output, mergeMode);
} | java | public void buildFromItems(final Collection<Item> output, final boolean mergeMode) {
buildForMissingInterval(null, null, null, output, mergeMode);
} | [
"public",
"void",
"buildFromItems",
"(",
"final",
"Collection",
"<",
"Item",
">",
"output",
",",
"final",
"boolean",
"mergeMode",
")",
"{",
"buildForMissingInterval",
"(",
"null",
",",
"null",
",",
"null",
",",
"output",
",",
"mergeMode",
")",
";",
"}"
] | Called on the last node | [
"Called",
"on",
"the",
"last",
"node"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsInterval.java#L160-L162 |
27,276 | killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/generator/InvoiceDateUtils.java | InvoiceDateUtils.calculateProrationBetweenDates | private static BigDecimal calculateProrationBetweenDates(final LocalDate startDate, final LocalDate endDate, final LocalDate previousBillingCycleDate, final LocalDate nextBillingCycleDate) {
final int daysBetween = Days.daysBetween(previousBillingCycleDate, nextBillingCycleDate).getDays();
return calculateProrationBetweenDates(startDate, endDate, daysBetween);
} | java | private static BigDecimal calculateProrationBetweenDates(final LocalDate startDate, final LocalDate endDate, final LocalDate previousBillingCycleDate, final LocalDate nextBillingCycleDate) {
final int daysBetween = Days.daysBetween(previousBillingCycleDate, nextBillingCycleDate).getDays();
return calculateProrationBetweenDates(startDate, endDate, daysBetween);
} | [
"private",
"static",
"BigDecimal",
"calculateProrationBetweenDates",
"(",
"final",
"LocalDate",
"startDate",
",",
"final",
"LocalDate",
"endDate",
",",
"final",
"LocalDate",
"previousBillingCycleDate",
",",
"final",
"LocalDate",
"nextBillingCycleDate",
")",
"{",
"final",
"int",
"daysBetween",
"=",
"Days",
".",
"daysBetween",
"(",
"previousBillingCycleDate",
",",
"nextBillingCycleDate",
")",
".",
"getDays",
"(",
")",
";",
"return",
"calculateProrationBetweenDates",
"(",
"startDate",
",",
"endDate",
",",
"daysBetween",
")",
";",
"}"
] | Called internally to calculate proration or when we recalculate approximate repair amount
@param startDate start date of the prorated interval
@param endDate end date of the prorated interval
@param previousBillingCycleDate start date of the period
@param nextBillingCycleDate end date of the period | [
"Called",
"internally",
"to",
"calculate",
"proration",
"or",
"when",
"we",
"recalculate",
"approximate",
"repair",
"amount"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/generator/InvoiceDateUtils.java#L73-L76 |
27,277 | killbill/killbill | payment/src/main/java/org/killbill/billing/payment/core/janitor/IncompletePaymentTransactionTask.java | IncompletePaymentTransactionTask.computeNewTransactionStatusFromPaymentTransactionInfoPlugin | private TransactionStatus computeNewTransactionStatusFromPaymentTransactionInfoPlugin(final PaymentTransactionInfoPlugin input, final TransactionStatus currentTransactionStatus) {
final TransactionStatus newTransactionStatus = PaymentTransactionInfoPluginConverter.toTransactionStatus(input);
return (newTransactionStatus != TransactionStatus.UNKNOWN) ? newTransactionStatus : currentTransactionStatus;
} | java | private TransactionStatus computeNewTransactionStatusFromPaymentTransactionInfoPlugin(final PaymentTransactionInfoPlugin input, final TransactionStatus currentTransactionStatus) {
final TransactionStatus newTransactionStatus = PaymentTransactionInfoPluginConverter.toTransactionStatus(input);
return (newTransactionStatus != TransactionStatus.UNKNOWN) ? newTransactionStatus : currentTransactionStatus;
} | [
"private",
"TransactionStatus",
"computeNewTransactionStatusFromPaymentTransactionInfoPlugin",
"(",
"final",
"PaymentTransactionInfoPlugin",
"input",
",",
"final",
"TransactionStatus",
"currentTransactionStatus",
")",
"{",
"final",
"TransactionStatus",
"newTransactionStatus",
"=",
"PaymentTransactionInfoPluginConverter",
".",
"toTransactionStatus",
"(",
"input",
")",
";",
"return",
"(",
"newTransactionStatus",
"!=",
"TransactionStatus",
".",
"UNKNOWN",
")",
"?",
"newTransactionStatus",
":",
"currentTransactionStatus",
";",
"}"
] | Keep the existing currentTransactionStatus if we can't obtain a better answer from the plugin; if not, return the newTransactionStatus | [
"Keep",
"the",
"existing",
"currentTransactionStatus",
"if",
"we",
"can",
"t",
"obtain",
"a",
"better",
"answer",
"from",
"the",
"plugin",
";",
"if",
"not",
"return",
"the",
"newTransactionStatus"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/payment/src/main/java/org/killbill/billing/payment/core/janitor/IncompletePaymentTransactionTask.java#L271-L274 |
27,278 | killbill/killbill | entitlement/src/main/java/org/killbill/billing/entitlement/api/BlockingStateOrdering.java | BlockingStateOrdering.insertFromBlockingEvent | private int insertFromBlockingEvent(final Collection<UUID> allEntitlementUUIDs, final BlockingState currentBlockingState, final List<SubscriptionEvent> inputExistingEvents, final SupportForOlderVersionThan_0_17_X backwardCompatibleContext, final InternalTenantContext internalTenantContext, final Collection<SubscriptionEvent> outputNewEvents) {
// Keep the current state per entitlement
final Map<UUID, TargetState> targetStates = new HashMap<UUID, TargetState>();
for (final UUID cur : allEntitlementUUIDs) {
targetStates.put(cur, new TargetState());
}
//
// Find out where to insert next event, and calculate current state for each entitlement at the position where we stop.
//
int index = -1;
final Iterator<SubscriptionEvent> it = inputExistingEvents.iterator();
// Where we need to insert in that stream
DefaultSubscriptionEvent curInsertion = null;
while (it.hasNext()) {
final DefaultSubscriptionEvent cur = (DefaultSubscriptionEvent) it.next();
final int compEffectiveDate = currentBlockingState.getEffectiveDate().compareTo(cur.getEffectiveDateTime());
final boolean shouldContinue;
switch (compEffectiveDate) {
case -1:
shouldContinue = false;
break;
case 0:
shouldContinue = compareBlockingStateWithNextSubscriptionEvent(currentBlockingState, cur) > 0;
break;
case 1:
shouldContinue = true;
break;
default:
// Make compiler happy
throw new IllegalStateException("Cannot reach statement");
}
if (!shouldContinue) {
break;
}
index++;
final TargetState curTargetState = targetStates.get(cur.getEntitlementId());
switch (cur.getSubscriptionEventType()) {
case START_ENTITLEMENT:
curTargetState.setEntitlementStarted();
break;
case STOP_ENTITLEMENT:
curTargetState.setEntitlementStopped();
break;
case START_BILLING:
// For older subscriptions we miss the START_ENTITLEMENT (the START_BILLING marks both start of billing and entitlement)
if (backwardCompatibleContext.isOlderEntitlement(cur.getEntitlementId())) {
curTargetState.setEntitlementStarted();
}
curTargetState.setBillingStarted();
break;
case PAUSE_BILLING:
case PAUSE_ENTITLEMENT:
case RESUME_ENTITLEMENT:
case RESUME_BILLING:
case SERVICE_STATE_CHANGE:
curTargetState.addEntitlementEvent(cur);
break;
case STOP_BILLING:
curTargetState.setBillingStopped();
break;
}
curInsertion = cur;
}
// Extract the list of targets based on the type of blocking state
final List<UUID> targetEntitlementIds = currentBlockingState.getType() == BlockingStateType.SUBSCRIPTION ? ImmutableList.<UUID>of(currentBlockingState.getBlockedId()) :
ImmutableList.<UUID>copyOf(allEntitlementUUIDs);
// For each target compute the new events that should be inserted in the stream
for (final UUID targetEntitlementId : targetEntitlementIds) {
final SubscriptionEvent[] prevNext = findPrevNext(inputExistingEvents, targetEntitlementId, curInsertion);
final TargetState curTargetState = targetStates.get(targetEntitlementId);
final List<SubscriptionEventType> eventTypes = curTargetState.addStateAndReturnEventTypes(currentBlockingState);
for (final SubscriptionEventType t : eventTypes) {
outputNewEvents.add(toSubscriptionEvent(prevNext[0], prevNext[1], targetEntitlementId, currentBlockingState, t, internalTenantContext));
}
}
return index;
} | java | private int insertFromBlockingEvent(final Collection<UUID> allEntitlementUUIDs, final BlockingState currentBlockingState, final List<SubscriptionEvent> inputExistingEvents, final SupportForOlderVersionThan_0_17_X backwardCompatibleContext, final InternalTenantContext internalTenantContext, final Collection<SubscriptionEvent> outputNewEvents) {
// Keep the current state per entitlement
final Map<UUID, TargetState> targetStates = new HashMap<UUID, TargetState>();
for (final UUID cur : allEntitlementUUIDs) {
targetStates.put(cur, new TargetState());
}
//
// Find out where to insert next event, and calculate current state for each entitlement at the position where we stop.
//
int index = -1;
final Iterator<SubscriptionEvent> it = inputExistingEvents.iterator();
// Where we need to insert in that stream
DefaultSubscriptionEvent curInsertion = null;
while (it.hasNext()) {
final DefaultSubscriptionEvent cur = (DefaultSubscriptionEvent) it.next();
final int compEffectiveDate = currentBlockingState.getEffectiveDate().compareTo(cur.getEffectiveDateTime());
final boolean shouldContinue;
switch (compEffectiveDate) {
case -1:
shouldContinue = false;
break;
case 0:
shouldContinue = compareBlockingStateWithNextSubscriptionEvent(currentBlockingState, cur) > 0;
break;
case 1:
shouldContinue = true;
break;
default:
// Make compiler happy
throw new IllegalStateException("Cannot reach statement");
}
if (!shouldContinue) {
break;
}
index++;
final TargetState curTargetState = targetStates.get(cur.getEntitlementId());
switch (cur.getSubscriptionEventType()) {
case START_ENTITLEMENT:
curTargetState.setEntitlementStarted();
break;
case STOP_ENTITLEMENT:
curTargetState.setEntitlementStopped();
break;
case START_BILLING:
// For older subscriptions we miss the START_ENTITLEMENT (the START_BILLING marks both start of billing and entitlement)
if (backwardCompatibleContext.isOlderEntitlement(cur.getEntitlementId())) {
curTargetState.setEntitlementStarted();
}
curTargetState.setBillingStarted();
break;
case PAUSE_BILLING:
case PAUSE_ENTITLEMENT:
case RESUME_ENTITLEMENT:
case RESUME_BILLING:
case SERVICE_STATE_CHANGE:
curTargetState.addEntitlementEvent(cur);
break;
case STOP_BILLING:
curTargetState.setBillingStopped();
break;
}
curInsertion = cur;
}
// Extract the list of targets based on the type of blocking state
final List<UUID> targetEntitlementIds = currentBlockingState.getType() == BlockingStateType.SUBSCRIPTION ? ImmutableList.<UUID>of(currentBlockingState.getBlockedId()) :
ImmutableList.<UUID>copyOf(allEntitlementUUIDs);
// For each target compute the new events that should be inserted in the stream
for (final UUID targetEntitlementId : targetEntitlementIds) {
final SubscriptionEvent[] prevNext = findPrevNext(inputExistingEvents, targetEntitlementId, curInsertion);
final TargetState curTargetState = targetStates.get(targetEntitlementId);
final List<SubscriptionEventType> eventTypes = curTargetState.addStateAndReturnEventTypes(currentBlockingState);
for (final SubscriptionEventType t : eventTypes) {
outputNewEvents.add(toSubscriptionEvent(prevNext[0], prevNext[1], targetEntitlementId, currentBlockingState, t, internalTenantContext));
}
}
return index;
} | [
"private",
"int",
"insertFromBlockingEvent",
"(",
"final",
"Collection",
"<",
"UUID",
">",
"allEntitlementUUIDs",
",",
"final",
"BlockingState",
"currentBlockingState",
",",
"final",
"List",
"<",
"SubscriptionEvent",
">",
"inputExistingEvents",
",",
"final",
"SupportForOlderVersionThan_0_17_X",
"backwardCompatibleContext",
",",
"final",
"InternalTenantContext",
"internalTenantContext",
",",
"final",
"Collection",
"<",
"SubscriptionEvent",
">",
"outputNewEvents",
")",
"{",
"// Keep the current state per entitlement",
"final",
"Map",
"<",
"UUID",
",",
"TargetState",
">",
"targetStates",
"=",
"new",
"HashMap",
"<",
"UUID",
",",
"TargetState",
">",
"(",
")",
";",
"for",
"(",
"final",
"UUID",
"cur",
":",
"allEntitlementUUIDs",
")",
"{",
"targetStates",
".",
"put",
"(",
"cur",
",",
"new",
"TargetState",
"(",
")",
")",
";",
"}",
"//",
"// Find out where to insert next event, and calculate current state for each entitlement at the position where we stop.",
"//",
"int",
"index",
"=",
"-",
"1",
";",
"final",
"Iterator",
"<",
"SubscriptionEvent",
">",
"it",
"=",
"inputExistingEvents",
".",
"iterator",
"(",
")",
";",
"// Where we need to insert in that stream",
"DefaultSubscriptionEvent",
"curInsertion",
"=",
"null",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"DefaultSubscriptionEvent",
"cur",
"=",
"(",
"DefaultSubscriptionEvent",
")",
"it",
".",
"next",
"(",
")",
";",
"final",
"int",
"compEffectiveDate",
"=",
"currentBlockingState",
".",
"getEffectiveDate",
"(",
")",
".",
"compareTo",
"(",
"cur",
".",
"getEffectiveDateTime",
"(",
")",
")",
";",
"final",
"boolean",
"shouldContinue",
";",
"switch",
"(",
"compEffectiveDate",
")",
"{",
"case",
"-",
"1",
":",
"shouldContinue",
"=",
"false",
";",
"break",
";",
"case",
"0",
":",
"shouldContinue",
"=",
"compareBlockingStateWithNextSubscriptionEvent",
"(",
"currentBlockingState",
",",
"cur",
")",
">",
"0",
";",
"break",
";",
"case",
"1",
":",
"shouldContinue",
"=",
"true",
";",
"break",
";",
"default",
":",
"// Make compiler happy",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot reach statement\"",
")",
";",
"}",
"if",
"(",
"!",
"shouldContinue",
")",
"{",
"break",
";",
"}",
"index",
"++",
";",
"final",
"TargetState",
"curTargetState",
"=",
"targetStates",
".",
"get",
"(",
"cur",
".",
"getEntitlementId",
"(",
")",
")",
";",
"switch",
"(",
"cur",
".",
"getSubscriptionEventType",
"(",
")",
")",
"{",
"case",
"START_ENTITLEMENT",
":",
"curTargetState",
".",
"setEntitlementStarted",
"(",
")",
";",
"break",
";",
"case",
"STOP_ENTITLEMENT",
":",
"curTargetState",
".",
"setEntitlementStopped",
"(",
")",
";",
"break",
";",
"case",
"START_BILLING",
":",
"// For older subscriptions we miss the START_ENTITLEMENT (the START_BILLING marks both start of billing and entitlement)",
"if",
"(",
"backwardCompatibleContext",
".",
"isOlderEntitlement",
"(",
"cur",
".",
"getEntitlementId",
"(",
")",
")",
")",
"{",
"curTargetState",
".",
"setEntitlementStarted",
"(",
")",
";",
"}",
"curTargetState",
".",
"setBillingStarted",
"(",
")",
";",
"break",
";",
"case",
"PAUSE_BILLING",
":",
"case",
"PAUSE_ENTITLEMENT",
":",
"case",
"RESUME_ENTITLEMENT",
":",
"case",
"RESUME_BILLING",
":",
"case",
"SERVICE_STATE_CHANGE",
":",
"curTargetState",
".",
"addEntitlementEvent",
"(",
"cur",
")",
";",
"break",
";",
"case",
"STOP_BILLING",
":",
"curTargetState",
".",
"setBillingStopped",
"(",
")",
";",
"break",
";",
"}",
"curInsertion",
"=",
"cur",
";",
"}",
"// Extract the list of targets based on the type of blocking state",
"final",
"List",
"<",
"UUID",
">",
"targetEntitlementIds",
"=",
"currentBlockingState",
".",
"getType",
"(",
")",
"==",
"BlockingStateType",
".",
"SUBSCRIPTION",
"?",
"ImmutableList",
".",
"<",
"UUID",
">",
"of",
"(",
"currentBlockingState",
".",
"getBlockedId",
"(",
")",
")",
":",
"ImmutableList",
".",
"<",
"UUID",
">",
"copyOf",
"(",
"allEntitlementUUIDs",
")",
";",
"// For each target compute the new events that should be inserted in the stream",
"for",
"(",
"final",
"UUID",
"targetEntitlementId",
":",
"targetEntitlementIds",
")",
"{",
"final",
"SubscriptionEvent",
"[",
"]",
"prevNext",
"=",
"findPrevNext",
"(",
"inputExistingEvents",
",",
"targetEntitlementId",
",",
"curInsertion",
")",
";",
"final",
"TargetState",
"curTargetState",
"=",
"targetStates",
".",
"get",
"(",
"targetEntitlementId",
")",
";",
"final",
"List",
"<",
"SubscriptionEventType",
">",
"eventTypes",
"=",
"curTargetState",
".",
"addStateAndReturnEventTypes",
"(",
"currentBlockingState",
")",
";",
"for",
"(",
"final",
"SubscriptionEventType",
"t",
":",
"eventTypes",
")",
"{",
"outputNewEvents",
".",
"add",
"(",
"toSubscriptionEvent",
"(",
"prevNext",
"[",
"0",
"]",
",",
"prevNext",
"[",
"1",
"]",
",",
"targetEntitlementId",
",",
"currentBlockingState",
",",
"t",
",",
"internalTenantContext",
")",
")",
";",
"}",
"}",
"return",
"index",
";",
"}"
] | Returns the index and the newEvents generated from the incoming blocking state event. Those new events will all be created for the same effectiveDate and should be ordered. | [
"Returns",
"the",
"index",
"and",
"the",
"newEvents",
"generated",
"from",
"the",
"incoming",
"blocking",
"state",
"event",
".",
"Those",
"new",
"events",
"will",
"all",
"be",
"created",
"for",
"the",
"same",
"effectiveDate",
"and",
"should",
"be",
"ordered",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/entitlement/src/main/java/org/killbill/billing/entitlement/api/BlockingStateOrdering.java#L97-L180 |
27,279 | killbill/killbill | entitlement/src/main/java/org/killbill/billing/entitlement/api/BlockingStateOrdering.java | BlockingStateOrdering.findPrevNext | private SubscriptionEvent[] findPrevNext(final List<SubscriptionEvent> events, final UUID targetEntitlementId, final SubscriptionEvent insertionEvent) {
// Find prev/next event for the same entitlement
final SubscriptionEvent[] result = new DefaultSubscriptionEvent[2];
if (insertionEvent == null) {
result[0] = null;
result[1] = !events.isEmpty() ? events.get(0) : null;
return result;
}
final Iterator<SubscriptionEvent> it = events.iterator();
DefaultSubscriptionEvent prev = null;
DefaultSubscriptionEvent next = null;
boolean foundCur = false;
while (it.hasNext()) {
final DefaultSubscriptionEvent tmp = (DefaultSubscriptionEvent) it.next();
if (tmp.getEntitlementId().equals(targetEntitlementId)) {
if (!foundCur) {
prev = tmp;
} else {
next = tmp;
break;
}
}
// Check both the id and the event type because of multiplexing
if (tmp.getId().equals(insertionEvent.getId()) &&
tmp.getSubscriptionEventType().equals(insertionEvent.getSubscriptionEventType())) {
foundCur = true;
}
}
result[0] = prev;
result[1] = next;
return result;
} | java | private SubscriptionEvent[] findPrevNext(final List<SubscriptionEvent> events, final UUID targetEntitlementId, final SubscriptionEvent insertionEvent) {
// Find prev/next event for the same entitlement
final SubscriptionEvent[] result = new DefaultSubscriptionEvent[2];
if (insertionEvent == null) {
result[0] = null;
result[1] = !events.isEmpty() ? events.get(0) : null;
return result;
}
final Iterator<SubscriptionEvent> it = events.iterator();
DefaultSubscriptionEvent prev = null;
DefaultSubscriptionEvent next = null;
boolean foundCur = false;
while (it.hasNext()) {
final DefaultSubscriptionEvent tmp = (DefaultSubscriptionEvent) it.next();
if (tmp.getEntitlementId().equals(targetEntitlementId)) {
if (!foundCur) {
prev = tmp;
} else {
next = tmp;
break;
}
}
// Check both the id and the event type because of multiplexing
if (tmp.getId().equals(insertionEvent.getId()) &&
tmp.getSubscriptionEventType().equals(insertionEvent.getSubscriptionEventType())) {
foundCur = true;
}
}
result[0] = prev;
result[1] = next;
return result;
} | [
"private",
"SubscriptionEvent",
"[",
"]",
"findPrevNext",
"(",
"final",
"List",
"<",
"SubscriptionEvent",
">",
"events",
",",
"final",
"UUID",
"targetEntitlementId",
",",
"final",
"SubscriptionEvent",
"insertionEvent",
")",
"{",
"// Find prev/next event for the same entitlement",
"final",
"SubscriptionEvent",
"[",
"]",
"result",
"=",
"new",
"DefaultSubscriptionEvent",
"[",
"2",
"]",
";",
"if",
"(",
"insertionEvent",
"==",
"null",
")",
"{",
"result",
"[",
"0",
"]",
"=",
"null",
";",
"result",
"[",
"1",
"]",
"=",
"!",
"events",
".",
"isEmpty",
"(",
")",
"?",
"events",
".",
"get",
"(",
"0",
")",
":",
"null",
";",
"return",
"result",
";",
"}",
"final",
"Iterator",
"<",
"SubscriptionEvent",
">",
"it",
"=",
"events",
".",
"iterator",
"(",
")",
";",
"DefaultSubscriptionEvent",
"prev",
"=",
"null",
";",
"DefaultSubscriptionEvent",
"next",
"=",
"null",
";",
"boolean",
"foundCur",
"=",
"false",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"DefaultSubscriptionEvent",
"tmp",
"=",
"(",
"DefaultSubscriptionEvent",
")",
"it",
".",
"next",
"(",
")",
";",
"if",
"(",
"tmp",
".",
"getEntitlementId",
"(",
")",
".",
"equals",
"(",
"targetEntitlementId",
")",
")",
"{",
"if",
"(",
"!",
"foundCur",
")",
"{",
"prev",
"=",
"tmp",
";",
"}",
"else",
"{",
"next",
"=",
"tmp",
";",
"break",
";",
"}",
"}",
"// Check both the id and the event type because of multiplexing",
"if",
"(",
"tmp",
".",
"getId",
"(",
")",
".",
"equals",
"(",
"insertionEvent",
".",
"getId",
"(",
")",
")",
"&&",
"tmp",
".",
"getSubscriptionEventType",
"(",
")",
".",
"equals",
"(",
"insertionEvent",
".",
"getSubscriptionEventType",
"(",
")",
")",
")",
"{",
"foundCur",
"=",
"true",
";",
"}",
"}",
"result",
"[",
"0",
"]",
"=",
"prev",
";",
"result",
"[",
"1",
"]",
"=",
"next",
";",
"return",
"result",
";",
"}"
] | Extract prev and next events in the stream events for that particular target subscription from the insertionEvent | [
"Extract",
"prev",
"and",
"next",
"events",
"in",
"the",
"stream",
"events",
"for",
"that",
"particular",
"target",
"subscription",
"from",
"the",
"insertionEvent"
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/entitlement/src/main/java/org/killbill/billing/entitlement/api/BlockingStateOrdering.java#L248-L280 |
27,280 | killbill/killbill | util/src/main/java/org/killbill/billing/util/entity/dao/EntitySqlDaoWrapperFactory.java | EntitySqlDaoWrapperFactory.become | public <NewSqlDao extends EntitySqlDao<NewEntityModelDao, NewEntity>,
NewEntityModelDao extends EntityModelDao<NewEntity>,
NewEntity extends Entity> NewSqlDao become(final Class<NewSqlDao> newSqlDaoClass) {
final NewSqlDao newSqlDao = SqlObjectBuilder.attach(handle, newSqlDaoClass);
return create(newSqlDaoClass, newSqlDao);
} | java | public <NewSqlDao extends EntitySqlDao<NewEntityModelDao, NewEntity>,
NewEntityModelDao extends EntityModelDao<NewEntity>,
NewEntity extends Entity> NewSqlDao become(final Class<NewSqlDao> newSqlDaoClass) {
final NewSqlDao newSqlDao = SqlObjectBuilder.attach(handle, newSqlDaoClass);
return create(newSqlDaoClass, newSqlDao);
} | [
"public",
"<",
"NewSqlDao",
"extends",
"EntitySqlDao",
"<",
"NewEntityModelDao",
",",
"NewEntity",
">",
",",
"NewEntityModelDao",
"extends",
"EntityModelDao",
"<",
"NewEntity",
">",
",",
"NewEntity",
"extends",
"Entity",
">",
"NewSqlDao",
"become",
"(",
"final",
"Class",
"<",
"NewSqlDao",
">",
"newSqlDaoClass",
")",
"{",
"final",
"NewSqlDao",
"newSqlDao",
"=",
"SqlObjectBuilder",
".",
"attach",
"(",
"handle",
",",
"newSqlDaoClass",
")",
";",
"return",
"create",
"(",
"newSqlDaoClass",
",",
"newSqlDao",
")",
";",
"}"
] | Get an instance of a specified EntitySqlDao class, sharing the same database session as the
initial sql dao class with which this wrapper factory was created.
@param newSqlDaoClass the class to instantiate
@param <NewSqlDao> EntitySqlDao type to create
@return instance of NewSqlDao | [
"Get",
"an",
"instance",
"of",
"a",
"specified",
"EntitySqlDao",
"class",
"sharing",
"the",
"same",
"database",
"session",
"as",
"the",
"initial",
"sql",
"dao",
"class",
"with",
"which",
"this",
"wrapper",
"factory",
"was",
"created",
"."
] | 6457b485fb32a182c76197a83f428123331f1380 | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/entity/dao/EntitySqlDaoWrapperFactory.java#L59-L64 |
27,281 | aragozin/jvm-tools | hprof-heap/src/main/java/org/gridkit/jvmtool/heapdump/HeapClusterAnalyzer.java | HeapClusterAnalyzer.prepare | public void prepare() {
for(JavaClass jc: heap.getAllClasses()) {
for(TypeFilterStep it: interestingTypes) {
if (it.evaluate(jc)) {
rootClasses.add(jc.getName());
}
}
for(TypeFilterStep bt: blacklistedTypes) {
if (bt.evaluate(jc)) {
blacklist.add(jc.getName());
}
}
for(PathStep[] bp: blacklistedMethods) {
TypeFilterStep ts = (TypeFilterStep) bp[0];
String fn = ((FieldStep) bp[1]).getFieldName();
if (ts.evaluate(jc)) {
for(Field f: jc.getFields()) {
if (fn == null || fn.equals(f.getName())) {
blacklist.add(jc.getName() + "#" + f.getName());
}
}
}
}
}
} | java | public void prepare() {
for(JavaClass jc: heap.getAllClasses()) {
for(TypeFilterStep it: interestingTypes) {
if (it.evaluate(jc)) {
rootClasses.add(jc.getName());
}
}
for(TypeFilterStep bt: blacklistedTypes) {
if (bt.evaluate(jc)) {
blacklist.add(jc.getName());
}
}
for(PathStep[] bp: blacklistedMethods) {
TypeFilterStep ts = (TypeFilterStep) bp[0];
String fn = ((FieldStep) bp[1]).getFieldName();
if (ts.evaluate(jc)) {
for(Field f: jc.getFields()) {
if (fn == null || fn.equals(f.getName())) {
blacklist.add(jc.getName() + "#" + f.getName());
}
}
}
}
}
} | [
"public",
"void",
"prepare",
"(",
")",
"{",
"for",
"(",
"JavaClass",
"jc",
":",
"heap",
".",
"getAllClasses",
"(",
")",
")",
"{",
"for",
"(",
"TypeFilterStep",
"it",
":",
"interestingTypes",
")",
"{",
"if",
"(",
"it",
".",
"evaluate",
"(",
"jc",
")",
")",
"{",
"rootClasses",
".",
"add",
"(",
"jc",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"for",
"(",
"TypeFilterStep",
"bt",
":",
"blacklistedTypes",
")",
"{",
"if",
"(",
"bt",
".",
"evaluate",
"(",
"jc",
")",
")",
"{",
"blacklist",
".",
"add",
"(",
"jc",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"for",
"(",
"PathStep",
"[",
"]",
"bp",
":",
"blacklistedMethods",
")",
"{",
"TypeFilterStep",
"ts",
"=",
"(",
"TypeFilterStep",
")",
"bp",
"[",
"0",
"]",
";",
"String",
"fn",
"=",
"(",
"(",
"FieldStep",
")",
"bp",
"[",
"1",
"]",
")",
".",
"getFieldName",
"(",
")",
";",
"if",
"(",
"ts",
".",
"evaluate",
"(",
"jc",
")",
")",
"{",
"for",
"(",
"Field",
"f",
":",
"jc",
".",
"getFields",
"(",
")",
")",
"{",
"if",
"(",
"fn",
"==",
"null",
"||",
"fn",
".",
"equals",
"(",
"f",
".",
"getName",
"(",
")",
")",
")",
"{",
"blacklist",
".",
"add",
"(",
"jc",
".",
"getName",
"(",
")",
"+",
"\"#\"",
"+",
"f",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"}",
"}",
"}",
"}"
] | Process entry point and blacklist configuration | [
"Process",
"entry",
"point",
"and",
"blacklist",
"configuration"
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/hprof-heap/src/main/java/org/gridkit/jvmtool/heapdump/HeapClusterAnalyzer.java#L112-L136 |
27,282 | aragozin/jvm-tools | hprof-heap/src/main/java/org/netbeans/lib/profiler/heap/LongHashMap.java | LongHashMap.init | private void init(int initCapacity) {
assert (initCapacity & -initCapacity) == initCapacity; // power of 2
assert initCapacity >= MINIMUM_CAPACITY;
assert initCapacity <= MAXIMUM_CAPACITY;
threshold = (initCapacity * 3)/ 4;
table = new long[2 * initCapacity];
} | java | private void init(int initCapacity) {
assert (initCapacity & -initCapacity) == initCapacity; // power of 2
assert initCapacity >= MINIMUM_CAPACITY;
assert initCapacity <= MAXIMUM_CAPACITY;
threshold = (initCapacity * 3)/ 4;
table = new long[2 * initCapacity];
} | [
"private",
"void",
"init",
"(",
"int",
"initCapacity",
")",
"{",
"assert",
"(",
"initCapacity",
"&",
"-",
"initCapacity",
")",
"==",
"initCapacity",
";",
"// power of 2",
"assert",
"initCapacity",
">=",
"MINIMUM_CAPACITY",
";",
"assert",
"initCapacity",
"<=",
"MAXIMUM_CAPACITY",
";",
"threshold",
"=",
"(",
"initCapacity",
"*",
"3",
")",
"/",
"4",
";",
"table",
"=",
"new",
"long",
"[",
"2",
"*",
"initCapacity",
"]",
";",
"}"
] | Initializes object to be an empty map with the specified initial
capacity, which is assumed to be a power of two between
MINIMUM_CAPACITY and MAXIMUM_CAPACITY inclusive. | [
"Initializes",
"object",
"to",
"be",
"an",
"empty",
"map",
"with",
"the",
"specified",
"initial",
"capacity",
"which",
"is",
"assumed",
"to",
"be",
"a",
"power",
"of",
"two",
"between",
"MINIMUM_CAPACITY",
"and",
"MAXIMUM_CAPACITY",
"inclusive",
"."
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/hprof-heap/src/main/java/org/netbeans/lib/profiler/heap/LongHashMap.java#L150-L157 |
27,283 | aragozin/jvm-tools | hprof-heap/src/main/java/org/netbeans/lib/profiler/heap/LongHashMap.java | LongHashMap.resize | private void resize(int newCapacity) {
// assert (newCapacity & -newCapacity) == newCapacity; // power of 2
int newLength = newCapacity * 2;
long[] oldTable = table;
int oldLength = oldTable.length;
if (oldLength == 2*MAXIMUM_CAPACITY) { // can't expand any further
if (threshold == MAXIMUM_CAPACITY-1)
throw new IllegalStateException("Capacity exhausted.");
threshold = MAXIMUM_CAPACITY-1; // Gigantic map!
return;
}
if (oldLength >= newLength)
return;
long[] newTable = new long[newLength];
threshold = (newCapacity * 3) / 4;
for (int j = 0; j < oldLength; j += 2) {
long key = oldTable[j];
if (key != 0) {
long value = oldTable[j+1];
int i = hash(key, newLength);
while (newTable[i] != 0)
i = nextKeyIndex(i, newLength);
newTable[i] = key;
newTable[i + 1] = value;
}
}
table = newTable;
} | java | private void resize(int newCapacity) {
// assert (newCapacity & -newCapacity) == newCapacity; // power of 2
int newLength = newCapacity * 2;
long[] oldTable = table;
int oldLength = oldTable.length;
if (oldLength == 2*MAXIMUM_CAPACITY) { // can't expand any further
if (threshold == MAXIMUM_CAPACITY-1)
throw new IllegalStateException("Capacity exhausted.");
threshold = MAXIMUM_CAPACITY-1; // Gigantic map!
return;
}
if (oldLength >= newLength)
return;
long[] newTable = new long[newLength];
threshold = (newCapacity * 3) / 4;
for (int j = 0; j < oldLength; j += 2) {
long key = oldTable[j];
if (key != 0) {
long value = oldTable[j+1];
int i = hash(key, newLength);
while (newTable[i] != 0)
i = nextKeyIndex(i, newLength);
newTable[i] = key;
newTable[i + 1] = value;
}
}
table = newTable;
} | [
"private",
"void",
"resize",
"(",
"int",
"newCapacity",
")",
"{",
"// assert (newCapacity & -newCapacity) == newCapacity; // power of 2",
"int",
"newLength",
"=",
"newCapacity",
"*",
"2",
";",
"long",
"[",
"]",
"oldTable",
"=",
"table",
";",
"int",
"oldLength",
"=",
"oldTable",
".",
"length",
";",
"if",
"(",
"oldLength",
"==",
"2",
"*",
"MAXIMUM_CAPACITY",
")",
"{",
"// can't expand any further",
"if",
"(",
"threshold",
"==",
"MAXIMUM_CAPACITY",
"-",
"1",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Capacity exhausted.\"",
")",
";",
"threshold",
"=",
"MAXIMUM_CAPACITY",
"-",
"1",
";",
"// Gigantic map!",
"return",
";",
"}",
"if",
"(",
"oldLength",
">=",
"newLength",
")",
"return",
";",
"long",
"[",
"]",
"newTable",
"=",
"new",
"long",
"[",
"newLength",
"]",
";",
"threshold",
"=",
"(",
"newCapacity",
"*",
"3",
")",
"/",
"4",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"oldLength",
";",
"j",
"+=",
"2",
")",
"{",
"long",
"key",
"=",
"oldTable",
"[",
"j",
"]",
";",
"if",
"(",
"key",
"!=",
"0",
")",
"{",
"long",
"value",
"=",
"oldTable",
"[",
"j",
"+",
"1",
"]",
";",
"int",
"i",
"=",
"hash",
"(",
"key",
",",
"newLength",
")",
";",
"while",
"(",
"newTable",
"[",
"i",
"]",
"!=",
"0",
")",
"i",
"=",
"nextKeyIndex",
"(",
"i",
",",
"newLength",
")",
";",
"newTable",
"[",
"i",
"]",
"=",
"key",
";",
"newTable",
"[",
"i",
"+",
"1",
"]",
"=",
"value",
";",
"}",
"}",
"table",
"=",
"newTable",
";",
"}"
] | Resize the table to hold given capacity.
@param newCapacity the new capacity, must be a power of two. | [
"Resize",
"the",
"table",
"to",
"hold",
"given",
"capacity",
"."
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/hprof-heap/src/main/java/org/netbeans/lib/profiler/heap/LongHashMap.java#L341-L371 |
27,284 | aragozin/jvm-tools | sjk-stacktrace/src/main/java/org/gridkit/jvmtool/stacktrace/MagicReader.java | MagicReader.readMagic | public static byte[] readMagic(InputStream is) throws IOException {
byte[] buf = new byte[32];
int n = 0;
while(true) {
int c = is.read();
if (c < 0) {
throw new EOFException("Cannot read magic");
}
if (n >= buf.length) {
throw new IOException("Cannot read magic");
}
if (c == ' ') {
buf[n] = (byte) c;
++n;
break;
}
else if (MAGIC_APHLABET.indexOf(c) >= 0) {
buf[n] = (byte) c;
}
else {
throw new IOException("Invalid magic");
}
++n;
}
return Arrays.copyOf(buf, n);
} | java | public static byte[] readMagic(InputStream is) throws IOException {
byte[] buf = new byte[32];
int n = 0;
while(true) {
int c = is.read();
if (c < 0) {
throw new EOFException("Cannot read magic");
}
if (n >= buf.length) {
throw new IOException("Cannot read magic");
}
if (c == ' ') {
buf[n] = (byte) c;
++n;
break;
}
else if (MAGIC_APHLABET.indexOf(c) >= 0) {
buf[n] = (byte) c;
}
else {
throw new IOException("Invalid magic");
}
++n;
}
return Arrays.copyOf(buf, n);
} | [
"public",
"static",
"byte",
"[",
"]",
"readMagic",
"(",
"InputStream",
"is",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"32",
"]",
";",
"int",
"n",
"=",
"0",
";",
"while",
"(",
"true",
")",
"{",
"int",
"c",
"=",
"is",
".",
"read",
"(",
")",
";",
"if",
"(",
"c",
"<",
"0",
")",
"{",
"throw",
"new",
"EOFException",
"(",
"\"Cannot read magic\"",
")",
";",
"}",
"if",
"(",
"n",
">=",
"buf",
".",
"length",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Cannot read magic\"",
")",
";",
"}",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"buf",
"[",
"n",
"]",
"=",
"(",
"byte",
")",
"c",
";",
"++",
"n",
";",
"break",
";",
"}",
"else",
"if",
"(",
"MAGIC_APHLABET",
".",
"indexOf",
"(",
"c",
")",
">=",
"0",
")",
"{",
"buf",
"[",
"n",
"]",
"=",
"(",
"byte",
")",
"c",
";",
"}",
"else",
"{",
"throw",
"new",
"IOException",
"(",
"\"Invalid magic\"",
")",
";",
"}",
"++",
"n",
";",
"}",
"return",
"Arrays",
".",
"copyOf",
"(",
"buf",
",",
"n",
")",
";",
"}"
] | reads chars until space | [
"reads",
"chars",
"until",
"space"
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/sjk-stacktrace/src/main/java/org/gridkit/jvmtool/stacktrace/MagicReader.java#L13-L38 |
27,285 | aragozin/jvm-tools | sjk-cli/src/main/java/org/gridkit/jvmtool/cli/CommandLauncher.java | CommandLauncher.breakCage | private void breakCage(String... args) {
if ("false".equalsIgnoreCase(System.getProperty("sjk.breakCage", "true"))) {
// do not break
return;
}
RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean();
String spec = rtBean.getSpecVersion();
if (spec.startsWith("1.")) {
// good classic Java
if (verbose) {
System.out.println("Java version " + spec + " skipping cage break");
}
return;
}
else {
if (getModulesUnlockCommand().length > 0) {
// we need to unlock some modules
StringBuilder sb = new StringBuilder();
for(String a: rtBean.getInputArguments()) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(a);
}
if (isUnlocked(sb.toString())) {
// modules are unlocked
if (verbose) {
System.out.println("All required modules are unlocked, skipping cage break");
}
return;
}
else {
// break cage
List<String> command = new ArrayList<String>();
File jhome = new File(System.getProperty("java.home"));
File jbin = new File(jhome, "bin/java");
command.add(jbin.getPath());
for(String m: getModulesUnlockCommand()) {
command.add("--add-opens");
command.add(m);
}
command.add("-Dsjk.breakCage=false");
command.add("-cp");
command.add(rtBean.getClassPath());
command.addAll(rtBean.getInputArguments());
command.add(this.getClass().getName());
command.addAll(Arrays.asList(args));
System.err.println("Restarting java with unlocked package access");
if (verbose) {
System.err.println("Exec command: " + formatCmd(command));
}
ProcessSpawner.start(command);
}
}
}
} | java | private void breakCage(String... args) {
if ("false".equalsIgnoreCase(System.getProperty("sjk.breakCage", "true"))) {
// do not break
return;
}
RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean();
String spec = rtBean.getSpecVersion();
if (spec.startsWith("1.")) {
// good classic Java
if (verbose) {
System.out.println("Java version " + spec + " skipping cage break");
}
return;
}
else {
if (getModulesUnlockCommand().length > 0) {
// we need to unlock some modules
StringBuilder sb = new StringBuilder();
for(String a: rtBean.getInputArguments()) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(a);
}
if (isUnlocked(sb.toString())) {
// modules are unlocked
if (verbose) {
System.out.println("All required modules are unlocked, skipping cage break");
}
return;
}
else {
// break cage
List<String> command = new ArrayList<String>();
File jhome = new File(System.getProperty("java.home"));
File jbin = new File(jhome, "bin/java");
command.add(jbin.getPath());
for(String m: getModulesUnlockCommand()) {
command.add("--add-opens");
command.add(m);
}
command.add("-Dsjk.breakCage=false");
command.add("-cp");
command.add(rtBean.getClassPath());
command.addAll(rtBean.getInputArguments());
command.add(this.getClass().getName());
command.addAll(Arrays.asList(args));
System.err.println("Restarting java with unlocked package access");
if (verbose) {
System.err.println("Exec command: " + formatCmd(command));
}
ProcessSpawner.start(command);
}
}
}
} | [
"private",
"void",
"breakCage",
"(",
"String",
"...",
"args",
")",
"{",
"if",
"(",
"\"false\"",
".",
"equalsIgnoreCase",
"(",
"System",
".",
"getProperty",
"(",
"\"sjk.breakCage\"",
",",
"\"true\"",
")",
")",
")",
"{",
"// do not break",
"return",
";",
"}",
"RuntimeMXBean",
"rtBean",
"=",
"ManagementFactory",
".",
"getRuntimeMXBean",
"(",
")",
";",
"String",
"spec",
"=",
"rtBean",
".",
"getSpecVersion",
"(",
")",
";",
"if",
"(",
"spec",
".",
"startsWith",
"(",
"\"1.\"",
")",
")",
"{",
"// good classic Java",
"if",
"(",
"verbose",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"Java version \"",
"+",
"spec",
"+",
"\" skipping cage break\"",
")",
";",
"}",
"return",
";",
"}",
"else",
"{",
"if",
"(",
"getModulesUnlockCommand",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"// we need to unlock some modules",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"String",
"a",
":",
"rtBean",
".",
"getInputArguments",
"(",
")",
")",
"{",
"if",
"(",
"sb",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"\" \"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"a",
")",
";",
"}",
"if",
"(",
"isUnlocked",
"(",
"sb",
".",
"toString",
"(",
")",
")",
")",
"{",
"// modules are unlocked",
"if",
"(",
"verbose",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"All required modules are unlocked, skipping cage break\"",
")",
";",
"}",
"return",
";",
"}",
"else",
"{",
"// break cage",
"List",
"<",
"String",
">",
"command",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"File",
"jhome",
"=",
"new",
"File",
"(",
"System",
".",
"getProperty",
"(",
"\"java.home\"",
")",
")",
";",
"File",
"jbin",
"=",
"new",
"File",
"(",
"jhome",
",",
"\"bin/java\"",
")",
";",
"command",
".",
"add",
"(",
"jbin",
".",
"getPath",
"(",
")",
")",
";",
"for",
"(",
"String",
"m",
":",
"getModulesUnlockCommand",
"(",
")",
")",
"{",
"command",
".",
"add",
"(",
"\"--add-opens\"",
")",
";",
"command",
".",
"add",
"(",
"m",
")",
";",
"}",
"command",
".",
"add",
"(",
"\"-Dsjk.breakCage=false\"",
")",
";",
"command",
".",
"add",
"(",
"\"-cp\"",
")",
";",
"command",
".",
"add",
"(",
"rtBean",
".",
"getClassPath",
"(",
")",
")",
";",
"command",
".",
"addAll",
"(",
"rtBean",
".",
"getInputArguments",
"(",
")",
")",
";",
"command",
".",
"add",
"(",
"this",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"command",
".",
"addAll",
"(",
"Arrays",
".",
"asList",
"(",
"args",
")",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
"\"Restarting java with unlocked package access\"",
")",
";",
"if",
"(",
"verbose",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"Exec command: \"",
"+",
"formatCmd",
"(",
"command",
")",
")",
";",
"}",
"ProcessSpawner",
".",
"start",
"(",
"command",
")",
";",
"}",
"}",
"}",
"}"
] | special hack to workaround Java module system | [
"special",
"hack",
"to",
"workaround",
"Java",
"module",
"system"
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/sjk-cli/src/main/java/org/gridkit/jvmtool/cli/CommandLauncher.java#L301-L358 |
27,286 | aragozin/jvm-tools | mxdump/src/main/java/org/gridkit/jvmtool/jackson/JsonWriteContext.java | JsonWriteContext.writeFieldName | public final int writeFieldName(String name)
{
if (_type == TYPE_OBJECT) {
if (_currentName != null) { // just wrote a name...
return STATUS_EXPECT_VALUE;
}
_currentName = name;
return (_index < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA;
}
return STATUS_EXPECT_VALUE;
} | java | public final int writeFieldName(String name)
{
if (_type == TYPE_OBJECT) {
if (_currentName != null) { // just wrote a name...
return STATUS_EXPECT_VALUE;
}
_currentName = name;
return (_index < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA;
}
return STATUS_EXPECT_VALUE;
} | [
"public",
"final",
"int",
"writeFieldName",
"(",
"String",
"name",
")",
"{",
"if",
"(",
"_type",
"==",
"TYPE_OBJECT",
")",
"{",
"if",
"(",
"_currentName",
"!=",
"null",
")",
"{",
"// just wrote a name...",
"return",
"STATUS_EXPECT_VALUE",
";",
"}",
"_currentName",
"=",
"name",
";",
"return",
"(",
"_index",
"<",
"0",
")",
"?",
"STATUS_OK_AS_IS",
":",
"STATUS_OK_AFTER_COMMA",
";",
"}",
"return",
"STATUS_EXPECT_VALUE",
";",
"}"
] | Method that writer is to call before it writes a field name.
@return Index of the field entry (0-based) | [
"Method",
"that",
"writer",
"is",
"to",
"call",
"before",
"it",
"writes",
"a",
"field",
"name",
"."
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/mxdump/src/main/java/org/gridkit/jvmtool/jackson/JsonWriteContext.java#L101-L111 |
27,287 | aragozin/jvm-tools | mxdump/src/main/java/org/gridkit/jvmtool/jackson/WriterBasedGenerator.java | WriterBasedGenerator._writeLongString | private void _writeLongString(String text)
throws IOException, JsonGenerationException
{
// First things first: let's flush the buffer to get some more room
_flushBuffer();
// Then we can write
final int textLen = text.length();
int offset = 0;
do {
int max = _outputEnd;
int segmentLen = ((offset + max) > textLen)
? (textLen - offset) : max;
text.getChars(offset, offset+segmentLen, _outputBuffer, 0);
if (_maximumNonEscapedChar != 0) {
_writeSegmentASCII(segmentLen, _maximumNonEscapedChar);
} else {
_writeSegment(segmentLen);
}
offset += segmentLen;
} while (offset < textLen);
} | java | private void _writeLongString(String text)
throws IOException, JsonGenerationException
{
// First things first: let's flush the buffer to get some more room
_flushBuffer();
// Then we can write
final int textLen = text.length();
int offset = 0;
do {
int max = _outputEnd;
int segmentLen = ((offset + max) > textLen)
? (textLen - offset) : max;
text.getChars(offset, offset+segmentLen, _outputBuffer, 0);
if (_maximumNonEscapedChar != 0) {
_writeSegmentASCII(segmentLen, _maximumNonEscapedChar);
} else {
_writeSegment(segmentLen);
}
offset += segmentLen;
} while (offset < textLen);
} | [
"private",
"void",
"_writeLongString",
"(",
"String",
"text",
")",
"throws",
"IOException",
",",
"JsonGenerationException",
"{",
"// First things first: let's flush the buffer to get some more room",
"_flushBuffer",
"(",
")",
";",
"// Then we can write ",
"final",
"int",
"textLen",
"=",
"text",
".",
"length",
"(",
")",
";",
"int",
"offset",
"=",
"0",
";",
"do",
"{",
"int",
"max",
"=",
"_outputEnd",
";",
"int",
"segmentLen",
"=",
"(",
"(",
"offset",
"+",
"max",
")",
">",
"textLen",
")",
"?",
"(",
"textLen",
"-",
"offset",
")",
":",
"max",
";",
"text",
".",
"getChars",
"(",
"offset",
",",
"offset",
"+",
"segmentLen",
",",
"_outputBuffer",
",",
"0",
")",
";",
"if",
"(",
"_maximumNonEscapedChar",
"!=",
"0",
")",
"{",
"_writeSegmentASCII",
"(",
"segmentLen",
",",
"_maximumNonEscapedChar",
")",
";",
"}",
"else",
"{",
"_writeSegment",
"(",
"segmentLen",
")",
";",
"}",
"offset",
"+=",
"segmentLen",
";",
"}",
"while",
"(",
"offset",
"<",
"textLen",
")",
";",
"}"
] | Method called to write "long strings", strings whose length exceeds
output buffer length. | [
"Method",
"called",
"to",
"write",
"long",
"strings",
"strings",
"whose",
"length",
"exceeds",
"output",
"buffer",
"length",
"."
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/mxdump/src/main/java/org/gridkit/jvmtool/jackson/WriterBasedGenerator.java#L882-L903 |
27,288 | aragozin/jvm-tools | mxdump/src/main/java/org/gridkit/jvmtool/jackson/WriterBasedGenerator.java | WriterBasedGenerator._writeString | private final void _writeString(char[] text, int offset, int len)
throws IOException, JsonGenerationException
{
if (_maximumNonEscapedChar != 0) {
_writeStringASCII(text, offset, len, _maximumNonEscapedChar);
return;
}
/* Let's just find longest spans of non-escapable
* content, and for each see if it makes sense
* to copy them, or write through
*/
len += offset; // -> len marks the end from now on
final int[] escCodes = _outputEscapes;
final int escLen = escCodes.length;
while (offset < len) {
int start = offset;
while (true) {
char c = text[offset];
if (c < escLen && escCodes[c] != 0) {
break;
}
if (++offset >= len) {
break;
}
}
// Short span? Better just copy it to buffer first:
int newAmount = offset - start;
if (newAmount < SHORT_WRITE) {
// Note: let's reserve room for escaped char (up to 6 chars)
if ((_outputTail + newAmount) > _outputEnd) {
_flushBuffer();
}
if (newAmount > 0) {
System.arraycopy(text, start, _outputBuffer, _outputTail, newAmount);
_outputTail += newAmount;
}
} else { // Nope: better just write through
_flushBuffer();
_writer.write(text, start, newAmount);
}
// Was this the end?
if (offset >= len) { // yup
break;
}
// Nope, need to escape the char.
char c = text[offset++];
_appendCharacterEscape(c, escCodes[c]);
}
} | java | private final void _writeString(char[] text, int offset, int len)
throws IOException, JsonGenerationException
{
if (_maximumNonEscapedChar != 0) {
_writeStringASCII(text, offset, len, _maximumNonEscapedChar);
return;
}
/* Let's just find longest spans of non-escapable
* content, and for each see if it makes sense
* to copy them, or write through
*/
len += offset; // -> len marks the end from now on
final int[] escCodes = _outputEscapes;
final int escLen = escCodes.length;
while (offset < len) {
int start = offset;
while (true) {
char c = text[offset];
if (c < escLen && escCodes[c] != 0) {
break;
}
if (++offset >= len) {
break;
}
}
// Short span? Better just copy it to buffer first:
int newAmount = offset - start;
if (newAmount < SHORT_WRITE) {
// Note: let's reserve room for escaped char (up to 6 chars)
if ((_outputTail + newAmount) > _outputEnd) {
_flushBuffer();
}
if (newAmount > 0) {
System.arraycopy(text, start, _outputBuffer, _outputTail, newAmount);
_outputTail += newAmount;
}
} else { // Nope: better just write through
_flushBuffer();
_writer.write(text, start, newAmount);
}
// Was this the end?
if (offset >= len) { // yup
break;
}
// Nope, need to escape the char.
char c = text[offset++];
_appendCharacterEscape(c, escCodes[c]);
}
} | [
"private",
"final",
"void",
"_writeString",
"(",
"char",
"[",
"]",
"text",
",",
"int",
"offset",
",",
"int",
"len",
")",
"throws",
"IOException",
",",
"JsonGenerationException",
"{",
"if",
"(",
"_maximumNonEscapedChar",
"!=",
"0",
")",
"{",
"_writeStringASCII",
"(",
"text",
",",
"offset",
",",
"len",
",",
"_maximumNonEscapedChar",
")",
";",
"return",
";",
"}",
"/* Let's just find longest spans of non-escapable\n * content, and for each see if it makes sense\n * to copy them, or write through\n */",
"len",
"+=",
"offset",
";",
"// -> len marks the end from now on",
"final",
"int",
"[",
"]",
"escCodes",
"=",
"_outputEscapes",
";",
"final",
"int",
"escLen",
"=",
"escCodes",
".",
"length",
";",
"while",
"(",
"offset",
"<",
"len",
")",
"{",
"int",
"start",
"=",
"offset",
";",
"while",
"(",
"true",
")",
"{",
"char",
"c",
"=",
"text",
"[",
"offset",
"]",
";",
"if",
"(",
"c",
"<",
"escLen",
"&&",
"escCodes",
"[",
"c",
"]",
"!=",
"0",
")",
"{",
"break",
";",
"}",
"if",
"(",
"++",
"offset",
">=",
"len",
")",
"{",
"break",
";",
"}",
"}",
"// Short span? Better just copy it to buffer first:",
"int",
"newAmount",
"=",
"offset",
"-",
"start",
";",
"if",
"(",
"newAmount",
"<",
"SHORT_WRITE",
")",
"{",
"// Note: let's reserve room for escaped char (up to 6 chars)",
"if",
"(",
"(",
"_outputTail",
"+",
"newAmount",
")",
">",
"_outputEnd",
")",
"{",
"_flushBuffer",
"(",
")",
";",
"}",
"if",
"(",
"newAmount",
">",
"0",
")",
"{",
"System",
".",
"arraycopy",
"(",
"text",
",",
"start",
",",
"_outputBuffer",
",",
"_outputTail",
",",
"newAmount",
")",
";",
"_outputTail",
"+=",
"newAmount",
";",
"}",
"}",
"else",
"{",
"// Nope: better just write through",
"_flushBuffer",
"(",
")",
";",
"_writer",
".",
"write",
"(",
"text",
",",
"start",
",",
"newAmount",
")",
";",
"}",
"// Was this the end?",
"if",
"(",
"offset",
">=",
"len",
")",
"{",
"// yup",
"break",
";",
"}",
"// Nope, need to escape the char.",
"char",
"c",
"=",
"text",
"[",
"offset",
"++",
"]",
";",
"_appendCharacterEscape",
"(",
"c",
",",
"escCodes",
"[",
"c",
"]",
")",
";",
"}",
"}"
] | This method called when the string content is already in
a char buffer, and need not be copied for processing. | [
"This",
"method",
"called",
"when",
"the",
"string",
"content",
"is",
"already",
"in",
"a",
"char",
"buffer",
"and",
"need",
"not",
"be",
"copied",
"for",
"processing",
"."
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/mxdump/src/main/java/org/gridkit/jvmtool/jackson/WriterBasedGenerator.java#L958-L1009 |
27,289 | aragozin/jvm-tools | mxdump/src/main/java/org/gridkit/jvmtool/jackson/WriterBasedGenerator.java | WriterBasedGenerator._writeSimpleObject | protected void _writeSimpleObject(Object value) throws IOException, JsonGenerationException {
/* 31-Dec-2009, tatu: Actually, we could just handle some basic
* types even without codec. This can improve interoperability,
* and specifically help with TokenBuffer.
*/
if (value == null) {
writeNull();
return;
}
if (value instanceof String) {
writeString((String) value);
return;
}
if (value instanceof Number) {
Number n = (Number) value;
if (n instanceof Integer) {
writeNumber(n.intValue());
return;
} else if (n instanceof Long) {
writeNumber(n.longValue());
return;
} else if (n instanceof Double) {
writeNumber(n.doubleValue());
return;
} else if (n instanceof Float) {
writeNumber(n.floatValue());
return;
} else if (n instanceof Short) {
writeNumber(n.shortValue());
return;
} else if (n instanceof Byte) {
writeNumber(n.byteValue());
return;
} else if (n instanceof BigInteger) {
writeNumber((BigInteger) n);
return;
} else if (n instanceof BigDecimal) {
writeNumber((BigDecimal) n);
return;
// then Atomic types
} else if (n instanceof AtomicInteger) {
writeNumber(((AtomicInteger) n).get());
return;
} else if (n instanceof AtomicLong) {
writeNumber(((AtomicLong) n).get());
return;
}
} else if (value instanceof Boolean) {
writeBoolean(((Boolean) value).booleanValue());
return;
} else if (value instanceof AtomicBoolean) {
writeBoolean(((AtomicBoolean) value).get());
return;
}
throw new IllegalStateException("No ObjectCodec defined for the generator, can only serialize simple wrapper types (type passed "
+value.getClass().getName()+")");
} | java | protected void _writeSimpleObject(Object value) throws IOException, JsonGenerationException {
/* 31-Dec-2009, tatu: Actually, we could just handle some basic
* types even without codec. This can improve interoperability,
* and specifically help with TokenBuffer.
*/
if (value == null) {
writeNull();
return;
}
if (value instanceof String) {
writeString((String) value);
return;
}
if (value instanceof Number) {
Number n = (Number) value;
if (n instanceof Integer) {
writeNumber(n.intValue());
return;
} else if (n instanceof Long) {
writeNumber(n.longValue());
return;
} else if (n instanceof Double) {
writeNumber(n.doubleValue());
return;
} else if (n instanceof Float) {
writeNumber(n.floatValue());
return;
} else if (n instanceof Short) {
writeNumber(n.shortValue());
return;
} else if (n instanceof Byte) {
writeNumber(n.byteValue());
return;
} else if (n instanceof BigInteger) {
writeNumber((BigInteger) n);
return;
} else if (n instanceof BigDecimal) {
writeNumber((BigDecimal) n);
return;
// then Atomic types
} else if (n instanceof AtomicInteger) {
writeNumber(((AtomicInteger) n).get());
return;
} else if (n instanceof AtomicLong) {
writeNumber(((AtomicLong) n).get());
return;
}
} else if (value instanceof Boolean) {
writeBoolean(((Boolean) value).booleanValue());
return;
} else if (value instanceof AtomicBoolean) {
writeBoolean(((AtomicBoolean) value).get());
return;
}
throw new IllegalStateException("No ObjectCodec defined for the generator, can only serialize simple wrapper types (type passed "
+value.getClass().getName()+")");
} | [
"protected",
"void",
"_writeSimpleObject",
"(",
"Object",
"value",
")",
"throws",
"IOException",
",",
"JsonGenerationException",
"{",
"/* 31-Dec-2009, tatu: Actually, we could just handle some basic\n\t * types even without codec. This can improve interoperability,\n\t * and specifically help with TokenBuffer.\n\t */",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"writeNull",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"value",
"instanceof",
"String",
")",
"{",
"writeString",
"(",
"(",
"String",
")",
"value",
")",
";",
"return",
";",
"}",
"if",
"(",
"value",
"instanceof",
"Number",
")",
"{",
"Number",
"n",
"=",
"(",
"Number",
")",
"value",
";",
"if",
"(",
"n",
"instanceof",
"Integer",
")",
"{",
"writeNumber",
"(",
"n",
".",
"intValue",
"(",
")",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"n",
"instanceof",
"Long",
")",
"{",
"writeNumber",
"(",
"n",
".",
"longValue",
"(",
")",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"n",
"instanceof",
"Double",
")",
"{",
"writeNumber",
"(",
"n",
".",
"doubleValue",
"(",
")",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"n",
"instanceof",
"Float",
")",
"{",
"writeNumber",
"(",
"n",
".",
"floatValue",
"(",
")",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"n",
"instanceof",
"Short",
")",
"{",
"writeNumber",
"(",
"n",
".",
"shortValue",
"(",
")",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"n",
"instanceof",
"Byte",
")",
"{",
"writeNumber",
"(",
"n",
".",
"byteValue",
"(",
")",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"n",
"instanceof",
"BigInteger",
")",
"{",
"writeNumber",
"(",
"(",
"BigInteger",
")",
"n",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"n",
"instanceof",
"BigDecimal",
")",
"{",
"writeNumber",
"(",
"(",
"BigDecimal",
")",
"n",
")",
";",
"return",
";",
"// then Atomic types",
"}",
"else",
"if",
"(",
"n",
"instanceof",
"AtomicInteger",
")",
"{",
"writeNumber",
"(",
"(",
"(",
"AtomicInteger",
")",
"n",
")",
".",
"get",
"(",
")",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"n",
"instanceof",
"AtomicLong",
")",
"{",
"writeNumber",
"(",
"(",
"(",
"AtomicLong",
")",
"n",
")",
".",
"get",
"(",
")",
")",
";",
"return",
";",
"}",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Boolean",
")",
"{",
"writeBoolean",
"(",
"(",
"(",
"Boolean",
")",
"value",
")",
".",
"booleanValue",
"(",
")",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"AtomicBoolean",
")",
"{",
"writeBoolean",
"(",
"(",
"(",
"AtomicBoolean",
")",
"value",
")",
".",
"get",
"(",
")",
")",
";",
"return",
";",
"}",
"throw",
"new",
"IllegalStateException",
"(",
"\"No ObjectCodec defined for the generator, can only serialize simple wrapper types (type passed \"",
"+",
"value",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\")\"",
")",
";",
"}"
] | Helper method to try to call appropriate write method for given
untyped Object. At this point, no structural conversions should be done,
only simple basic types are to be coerced as necessary.
@param value Non-null value to write | [
"Helper",
"method",
"to",
"try",
"to",
"call",
"appropriate",
"write",
"method",
"for",
"given",
"untyped",
"Object",
".",
"At",
"this",
"point",
"no",
"structural",
"conversions",
"should",
"be",
"done",
"only",
"simple",
"basic",
"types",
"are",
"to",
"be",
"coerced",
"as",
"necessary",
"."
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/mxdump/src/main/java/org/gridkit/jvmtool/jackson/WriterBasedGenerator.java#L1473-L1531 |
27,290 | aragozin/jvm-tools | mxdump/src/main/java/org/gridkit/jvmtool/jackson/JsonProcessingException.java | JsonProcessingException.getMessage | @Override
public String getMessage()
{
String msg = super.getMessage();
if (msg == null) {
msg = "N/A";
}
JsonLocation loc = getLocation();
if (loc != null) {
StringBuilder sb = new StringBuilder();
sb.append(msg);
sb.append('\n');
sb.append(" at ");
sb.append(loc.toString());
return sb.toString();
}
return msg;
} | java | @Override
public String getMessage()
{
String msg = super.getMessage();
if (msg == null) {
msg = "N/A";
}
JsonLocation loc = getLocation();
if (loc != null) {
StringBuilder sb = new StringBuilder();
sb.append(msg);
sb.append('\n');
sb.append(" at ");
sb.append(loc.toString());
return sb.toString();
}
return msg;
} | [
"@",
"Override",
"public",
"String",
"getMessage",
"(",
")",
"{",
"String",
"msg",
"=",
"super",
".",
"getMessage",
"(",
")",
";",
"if",
"(",
"msg",
"==",
"null",
")",
"{",
"msg",
"=",
"\"N/A\"",
";",
"}",
"JsonLocation",
"loc",
"=",
"getLocation",
"(",
")",
";",
"if",
"(",
"loc",
"!=",
"null",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"msg",
")",
";",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"sb",
".",
"append",
"(",
"\" at \"",
")",
";",
"sb",
".",
"append",
"(",
"loc",
".",
"toString",
"(",
")",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"return",
"msg",
";",
"}"
] | Default method overridden so that we can add location information | [
"Default",
"method",
"overridden",
"so",
"that",
"we",
"can",
"add",
"location",
"information"
] | d3a4d0c6a47fb9317f274988569655f30dcd2f76 | https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/mxdump/src/main/java/org/gridkit/jvmtool/jackson/JsonProcessingException.java#L57-L74 |
27,291 | atomix/atomix | cluster/src/main/java/io/atomix/cluster/messaging/impl/ChannelPool.java | ChannelPool.getChannelPool | private List<CompletableFuture<Channel>> getChannelPool(Address address) {
List<CompletableFuture<Channel>> channelPool = channels.get(address);
if (channelPool != null) {
return channelPool;
}
return channels.computeIfAbsent(address, e -> {
List<CompletableFuture<Channel>> defaultList = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
defaultList.add(null);
}
return Lists.newCopyOnWriteArrayList(defaultList);
});
} | java | private List<CompletableFuture<Channel>> getChannelPool(Address address) {
List<CompletableFuture<Channel>> channelPool = channels.get(address);
if (channelPool != null) {
return channelPool;
}
return channels.computeIfAbsent(address, e -> {
List<CompletableFuture<Channel>> defaultList = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
defaultList.add(null);
}
return Lists.newCopyOnWriteArrayList(defaultList);
});
} | [
"private",
"List",
"<",
"CompletableFuture",
"<",
"Channel",
">",
">",
"getChannelPool",
"(",
"Address",
"address",
")",
"{",
"List",
"<",
"CompletableFuture",
"<",
"Channel",
">>",
"channelPool",
"=",
"channels",
".",
"get",
"(",
"address",
")",
";",
"if",
"(",
"channelPool",
"!=",
"null",
")",
"{",
"return",
"channelPool",
";",
"}",
"return",
"channels",
".",
"computeIfAbsent",
"(",
"address",
",",
"e",
"->",
"{",
"List",
"<",
"CompletableFuture",
"<",
"Channel",
">>",
"defaultList",
"=",
"new",
"ArrayList",
"<>",
"(",
"size",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"defaultList",
".",
"add",
"(",
"null",
")",
";",
"}",
"return",
"Lists",
".",
"newCopyOnWriteArrayList",
"(",
"defaultList",
")",
";",
"}",
")",
";",
"}"
] | Returns the channel pool for the given address.
@param address the address for which to return the channel pool
@return the channel pool for the given address | [
"Returns",
"the",
"channel",
"pool",
"for",
"the",
"given",
"address",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/messaging/impl/ChannelPool.java#L52-L64 |
27,292 | atomix/atomix | cluster/src/main/java/io/atomix/cluster/messaging/impl/ChannelPool.java | ChannelPool.getChannel | CompletableFuture<Channel> getChannel(Address address, String messageType) {
List<CompletableFuture<Channel>> channelPool = getChannelPool(address);
int offset = getChannelOffset(messageType);
CompletableFuture<Channel> channelFuture = channelPool.get(offset);
if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
synchronized (channelPool) {
channelFuture = channelPool.get(offset);
if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
LOGGER.debug("Connecting to {}", address);
channelFuture = factory.apply(address);
channelFuture.whenComplete((channel, error) -> {
if (error == null) {
LOGGER.debug("Connected to {}", channel.remoteAddress());
} else {
LOGGER.debug("Failed to connect to {}", address, error);
}
});
channelPool.set(offset, channelFuture);
}
}
}
final CompletableFuture<Channel> future = new CompletableFuture<>();
final CompletableFuture<Channel> finalFuture = channelFuture;
finalFuture.whenComplete((channel, error) -> {
if (error == null) {
if (!channel.isActive()) {
CompletableFuture<Channel> currentFuture;
synchronized (channelPool) {
currentFuture = channelPool.get(offset);
if (currentFuture == finalFuture) {
channelPool.set(offset, null);
} else if (currentFuture == null) {
currentFuture = factory.apply(address);
currentFuture.whenComplete((c, e) -> {
if (e == null) {
LOGGER.debug("Connected to {}", channel.remoteAddress());
} else {
LOGGER.debug("Failed to connect to {}", channel.remoteAddress(), e);
}
});
channelPool.set(offset, currentFuture);
}
}
if (currentFuture == finalFuture) {
getChannel(address, messageType).whenComplete((recursiveResult, recursiveError) -> {
if (recursiveError == null) {
future.complete(recursiveResult);
} else {
future.completeExceptionally(recursiveError);
}
});
} else {
currentFuture.whenComplete((recursiveResult, recursiveError) -> {
if (recursiveError == null) {
future.complete(recursiveResult);
} else {
future.completeExceptionally(recursiveError);
}
});
}
} else {
future.complete(channel);
}
} else {
future.completeExceptionally(error);
}
});
return future;
} | java | CompletableFuture<Channel> getChannel(Address address, String messageType) {
List<CompletableFuture<Channel>> channelPool = getChannelPool(address);
int offset = getChannelOffset(messageType);
CompletableFuture<Channel> channelFuture = channelPool.get(offset);
if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
synchronized (channelPool) {
channelFuture = channelPool.get(offset);
if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
LOGGER.debug("Connecting to {}", address);
channelFuture = factory.apply(address);
channelFuture.whenComplete((channel, error) -> {
if (error == null) {
LOGGER.debug("Connected to {}", channel.remoteAddress());
} else {
LOGGER.debug("Failed to connect to {}", address, error);
}
});
channelPool.set(offset, channelFuture);
}
}
}
final CompletableFuture<Channel> future = new CompletableFuture<>();
final CompletableFuture<Channel> finalFuture = channelFuture;
finalFuture.whenComplete((channel, error) -> {
if (error == null) {
if (!channel.isActive()) {
CompletableFuture<Channel> currentFuture;
synchronized (channelPool) {
currentFuture = channelPool.get(offset);
if (currentFuture == finalFuture) {
channelPool.set(offset, null);
} else if (currentFuture == null) {
currentFuture = factory.apply(address);
currentFuture.whenComplete((c, e) -> {
if (e == null) {
LOGGER.debug("Connected to {}", channel.remoteAddress());
} else {
LOGGER.debug("Failed to connect to {}", channel.remoteAddress(), e);
}
});
channelPool.set(offset, currentFuture);
}
}
if (currentFuture == finalFuture) {
getChannel(address, messageType).whenComplete((recursiveResult, recursiveError) -> {
if (recursiveError == null) {
future.complete(recursiveResult);
} else {
future.completeExceptionally(recursiveError);
}
});
} else {
currentFuture.whenComplete((recursiveResult, recursiveError) -> {
if (recursiveError == null) {
future.complete(recursiveResult);
} else {
future.completeExceptionally(recursiveError);
}
});
}
} else {
future.complete(channel);
}
} else {
future.completeExceptionally(error);
}
});
return future;
} | [
"CompletableFuture",
"<",
"Channel",
">",
"getChannel",
"(",
"Address",
"address",
",",
"String",
"messageType",
")",
"{",
"List",
"<",
"CompletableFuture",
"<",
"Channel",
">>",
"channelPool",
"=",
"getChannelPool",
"(",
"address",
")",
";",
"int",
"offset",
"=",
"getChannelOffset",
"(",
"messageType",
")",
";",
"CompletableFuture",
"<",
"Channel",
">",
"channelFuture",
"=",
"channelPool",
".",
"get",
"(",
"offset",
")",
";",
"if",
"(",
"channelFuture",
"==",
"null",
"||",
"channelFuture",
".",
"isCompletedExceptionally",
"(",
")",
")",
"{",
"synchronized",
"(",
"channelPool",
")",
"{",
"channelFuture",
"=",
"channelPool",
".",
"get",
"(",
"offset",
")",
";",
"if",
"(",
"channelFuture",
"==",
"null",
"||",
"channelFuture",
".",
"isCompletedExceptionally",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Connecting to {}\"",
",",
"address",
")",
";",
"channelFuture",
"=",
"factory",
".",
"apply",
"(",
"address",
")",
";",
"channelFuture",
".",
"whenComplete",
"(",
"(",
"channel",
",",
"error",
")",
"->",
"{",
"if",
"(",
"error",
"==",
"null",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Connected to {}\"",
",",
"channel",
".",
"remoteAddress",
"(",
")",
")",
";",
"}",
"else",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Failed to connect to {}\"",
",",
"address",
",",
"error",
")",
";",
"}",
"}",
")",
";",
"channelPool",
".",
"set",
"(",
"offset",
",",
"channelFuture",
")",
";",
"}",
"}",
"}",
"final",
"CompletableFuture",
"<",
"Channel",
">",
"future",
"=",
"new",
"CompletableFuture",
"<>",
"(",
")",
";",
"final",
"CompletableFuture",
"<",
"Channel",
">",
"finalFuture",
"=",
"channelFuture",
";",
"finalFuture",
".",
"whenComplete",
"(",
"(",
"channel",
",",
"error",
")",
"->",
"{",
"if",
"(",
"error",
"==",
"null",
")",
"{",
"if",
"(",
"!",
"channel",
".",
"isActive",
"(",
")",
")",
"{",
"CompletableFuture",
"<",
"Channel",
">",
"currentFuture",
";",
"synchronized",
"(",
"channelPool",
")",
"{",
"currentFuture",
"=",
"channelPool",
".",
"get",
"(",
"offset",
")",
";",
"if",
"(",
"currentFuture",
"==",
"finalFuture",
")",
"{",
"channelPool",
".",
"set",
"(",
"offset",
",",
"null",
")",
";",
"}",
"else",
"if",
"(",
"currentFuture",
"==",
"null",
")",
"{",
"currentFuture",
"=",
"factory",
".",
"apply",
"(",
"address",
")",
";",
"currentFuture",
".",
"whenComplete",
"(",
"(",
"c",
",",
"e",
")",
"->",
"{",
"if",
"(",
"e",
"==",
"null",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Connected to {}\"",
",",
"channel",
".",
"remoteAddress",
"(",
")",
")",
";",
"}",
"else",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Failed to connect to {}\"",
",",
"channel",
".",
"remoteAddress",
"(",
")",
",",
"e",
")",
";",
"}",
"}",
")",
";",
"channelPool",
".",
"set",
"(",
"offset",
",",
"currentFuture",
")",
";",
"}",
"}",
"if",
"(",
"currentFuture",
"==",
"finalFuture",
")",
"{",
"getChannel",
"(",
"address",
",",
"messageType",
")",
".",
"whenComplete",
"(",
"(",
"recursiveResult",
",",
"recursiveError",
")",
"->",
"{",
"if",
"(",
"recursiveError",
"==",
"null",
")",
"{",
"future",
".",
"complete",
"(",
"recursiveResult",
")",
";",
"}",
"else",
"{",
"future",
".",
"completeExceptionally",
"(",
"recursiveError",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"currentFuture",
".",
"whenComplete",
"(",
"(",
"recursiveResult",
",",
"recursiveError",
")",
"->",
"{",
"if",
"(",
"recursiveError",
"==",
"null",
")",
"{",
"future",
".",
"complete",
"(",
"recursiveResult",
")",
";",
"}",
"else",
"{",
"future",
".",
"completeExceptionally",
"(",
"recursiveError",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"else",
"{",
"future",
".",
"complete",
"(",
"channel",
")",
";",
"}",
"}",
"else",
"{",
"future",
".",
"completeExceptionally",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"return",
"future",
";",
"}"
] | Gets or creates a pooled channel to the given address for the given message type.
@param address the address for which to get the channel
@param messageType the message type for which to get the channel
@return a future to be completed with a channel from the pool | [
"Gets",
"or",
"creates",
"a",
"pooled",
"channel",
"to",
"the",
"given",
"address",
"for",
"the",
"given",
"message",
"type",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/messaging/impl/ChannelPool.java#L83-L154 |
27,293 | atomix/atomix | utils/src/main/java/io/atomix/utils/misc/Match.java | Match.map | public <V> Match<V> map(Function<T, V> mapper) {
if (matchAny) {
return any();
} else if (value == null) {
return negation ? ifNotNull() : ifNull();
} else {
return negation ? ifNotValue(mapper.apply(value)) : ifValue(mapper.apply(value));
}
} | java | public <V> Match<V> map(Function<T, V> mapper) {
if (matchAny) {
return any();
} else if (value == null) {
return negation ? ifNotNull() : ifNull();
} else {
return negation ? ifNotValue(mapper.apply(value)) : ifValue(mapper.apply(value));
}
} | [
"public",
"<",
"V",
">",
"Match",
"<",
"V",
">",
"map",
"(",
"Function",
"<",
"T",
",",
"V",
">",
"mapper",
")",
"{",
"if",
"(",
"matchAny",
")",
"{",
"return",
"any",
"(",
")",
";",
"}",
"else",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"negation",
"?",
"ifNotNull",
"(",
")",
":",
"ifNull",
"(",
")",
";",
"}",
"else",
"{",
"return",
"negation",
"?",
"ifNotValue",
"(",
"mapper",
".",
"apply",
"(",
"value",
")",
")",
":",
"ifValue",
"(",
"mapper",
".",
"apply",
"(",
"value",
")",
")",
";",
"}",
"}"
] | Maps this instance to a Match of another type.
@param mapper transformation function
@param <V> new match type
@return new instance | [
"Maps",
"this",
"instance",
"to",
"a",
"Match",
"of",
"another",
"type",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/misc/Match.java#L110-L118 |
27,294 | atomix/atomix | utils/src/main/java/io/atomix/utils/misc/Match.java | Match.matches | public boolean matches(T other) {
if (matchAny) {
return true;
} else if (other == null) {
return negation ? value != null : value == null;
} else {
if (value instanceof byte[]) {
boolean equal = Arrays.equals((byte[]) value, (byte[]) other);
return negation ? !equal : equal;
}
return negation ? !Objects.equals(value, other) : Objects.equals(value, other);
} | java | public boolean matches(T other) {
if (matchAny) {
return true;
} else if (other == null) {
return negation ? value != null : value == null;
} else {
if (value instanceof byte[]) {
boolean equal = Arrays.equals((byte[]) value, (byte[]) other);
return negation ? !equal : equal;
}
return negation ? !Objects.equals(value, other) : Objects.equals(value, other);
} | [
"public",
"boolean",
"matches",
"(",
"T",
"other",
")",
"{",
"if",
"(",
"matchAny",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"other",
"==",
"null",
")",
"{",
"return",
"negation",
"?",
"value",
"!=",
"null",
":",
"value",
"==",
"null",
";",
"}",
"else",
"{",
"if",
"(",
"value",
"instanceof",
"byte",
"[",
"]",
")",
"{",
"boolean",
"equal",
"=",
"Arrays",
".",
"equals",
"(",
"(",
"byte",
"[",
"]",
")",
"value",
",",
"(",
"byte",
"[",
"]",
")",
"other",
")",
";",
"return",
"negation",
"?",
"!",
"equal",
":",
"equal",
";",
"}",
"return",
"negation",
"?",
"!",
"Objects",
".",
"equals",
"(",
"value",
",",
"other",
")",
":",
"Objects",
".",
"equals",
"(",
"value",
",",
"other",
")",
";",
"}"
] | Checks if this instance matches specified value.
@param other other value
@return true if matches; false otherwise | [
"Checks",
"if",
"this",
"instance",
"matches",
"specified",
"value",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/misc/Match.java#L126-L137 |
27,295 | atomix/atomix | protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/SynchronousReplicator.java | SynchronousReplicator.completeFutures | private void completeFutures() {
long commitIndex = queues.values().stream()
.map(queue -> queue.ackedIndex)
.reduce(Math::min)
.orElse(0L);
for (long i = context.getCommitIndex() + 1; i <= commitIndex; i++) {
CompletableFuture<Void> future = futures.remove(i);
if (future != null) {
future.complete(null);
}
}
context.setCommitIndex(commitIndex);
} | java | private void completeFutures() {
long commitIndex = queues.values().stream()
.map(queue -> queue.ackedIndex)
.reduce(Math::min)
.orElse(0L);
for (long i = context.getCommitIndex() + 1; i <= commitIndex; i++) {
CompletableFuture<Void> future = futures.remove(i);
if (future != null) {
future.complete(null);
}
}
context.setCommitIndex(commitIndex);
} | [
"private",
"void",
"completeFutures",
"(",
")",
"{",
"long",
"commitIndex",
"=",
"queues",
".",
"values",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"queue",
"->",
"queue",
".",
"ackedIndex",
")",
".",
"reduce",
"(",
"Math",
"::",
"min",
")",
".",
"orElse",
"(",
"0L",
")",
";",
"for",
"(",
"long",
"i",
"=",
"context",
".",
"getCommitIndex",
"(",
")",
"+",
"1",
";",
"i",
"<=",
"commitIndex",
";",
"i",
"++",
")",
"{",
"CompletableFuture",
"<",
"Void",
">",
"future",
"=",
"futures",
".",
"remove",
"(",
"i",
")",
";",
"if",
"(",
"future",
"!=",
"null",
")",
"{",
"future",
".",
"complete",
"(",
"null",
")",
";",
"}",
"}",
"context",
".",
"setCommitIndex",
"(",
"commitIndex",
")",
";",
"}"
] | Completes futures. | [
"Completes",
"futures",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/SynchronousReplicator.java#L64-L76 |
27,296 | atomix/atomix | storage/src/main/java/io/atomix/storage/journal/MappableJournalSegmentReader.java | MappableJournalSegmentReader.map | void map(ByteBuffer buffer) {
if (!(reader instanceof MappedJournalSegmentReader)) {
JournalReader<E> reader = this.reader;
this.reader = new MappedJournalSegmentReader<>(buffer, segment, maxEntrySize, index, namespace);
this.reader.reset(reader.getNextIndex());
reader.close();
}
} | java | void map(ByteBuffer buffer) {
if (!(reader instanceof MappedJournalSegmentReader)) {
JournalReader<E> reader = this.reader;
this.reader = new MappedJournalSegmentReader<>(buffer, segment, maxEntrySize, index, namespace);
this.reader.reset(reader.getNextIndex());
reader.close();
}
} | [
"void",
"map",
"(",
"ByteBuffer",
"buffer",
")",
"{",
"if",
"(",
"!",
"(",
"reader",
"instanceof",
"MappedJournalSegmentReader",
")",
")",
"{",
"JournalReader",
"<",
"E",
">",
"reader",
"=",
"this",
".",
"reader",
";",
"this",
".",
"reader",
"=",
"new",
"MappedJournalSegmentReader",
"<>",
"(",
"buffer",
",",
"segment",
",",
"maxEntrySize",
",",
"index",
",",
"namespace",
")",
";",
"this",
".",
"reader",
".",
"reset",
"(",
"reader",
".",
"getNextIndex",
"(",
")",
")",
";",
"reader",
".",
"close",
"(",
")",
";",
"}",
"}"
] | Converts the reader to a mapped reader using the given buffer.
@param buffer the mapped buffer | [
"Converts",
"the",
"reader",
"to",
"a",
"mapped",
"reader",
"using",
"the",
"given",
"buffer",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/MappableJournalSegmentReader.java#L56-L63 |
27,297 | atomix/atomix | storage/src/main/java/io/atomix/storage/journal/MappableJournalSegmentReader.java | MappableJournalSegmentReader.unmap | void unmap() {
if (reader instanceof MappedJournalSegmentReader) {
JournalReader<E> reader = this.reader;
this.reader = new FileChannelJournalSegmentReader<>(channel, segment, maxEntrySize, index, namespace);
this.reader.reset(reader.getNextIndex());
reader.close();
}
} | java | void unmap() {
if (reader instanceof MappedJournalSegmentReader) {
JournalReader<E> reader = this.reader;
this.reader = new FileChannelJournalSegmentReader<>(channel, segment, maxEntrySize, index, namespace);
this.reader.reset(reader.getNextIndex());
reader.close();
}
} | [
"void",
"unmap",
"(",
")",
"{",
"if",
"(",
"reader",
"instanceof",
"MappedJournalSegmentReader",
")",
"{",
"JournalReader",
"<",
"E",
">",
"reader",
"=",
"this",
".",
"reader",
";",
"this",
".",
"reader",
"=",
"new",
"FileChannelJournalSegmentReader",
"<>",
"(",
"channel",
",",
"segment",
",",
"maxEntrySize",
",",
"index",
",",
"namespace",
")",
";",
"this",
".",
"reader",
".",
"reset",
"(",
"reader",
".",
"getNextIndex",
"(",
")",
")",
";",
"reader",
".",
"close",
"(",
")",
";",
"}",
"}"
] | Converts the reader to an unmapped reader. | [
"Converts",
"the",
"reader",
"to",
"an",
"unmapped",
"reader",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/MappableJournalSegmentReader.java#L68-L75 |
27,298 | atomix/atomix | protocols/log/src/main/java/io/atomix/protocols/log/impl/DistributedLogServerContext.java | DistributedLogServerContext.compactBySize | private void compactBySize() {
if (maxLogSize > 0 && journal.size() > maxLogSize) {
JournalSegment<LogEntry> compactSegment = null;
Long compactIndex = null;
for (JournalSegment<LogEntry> segment : journal.segments()) {
Collection<JournalSegment<LogEntry>> remainingSegments = journal.segments(segment.lastIndex() + 1);
long remainingSize = remainingSegments.stream().mapToLong(JournalSegment::size).sum();
if (remainingSize > maxLogSize) {
log.debug("Found outsize journal segment {}", segment.file().file());
compactSegment = segment;
} else if (compactSegment != null) {
compactIndex = segment.index();
break;
}
}
if (compactIndex != null) {
log.info("Compacting journal by size up to {}", compactIndex);
journal.compact(compactIndex);
}
}
} | java | private void compactBySize() {
if (maxLogSize > 0 && journal.size() > maxLogSize) {
JournalSegment<LogEntry> compactSegment = null;
Long compactIndex = null;
for (JournalSegment<LogEntry> segment : journal.segments()) {
Collection<JournalSegment<LogEntry>> remainingSegments = journal.segments(segment.lastIndex() + 1);
long remainingSize = remainingSegments.stream().mapToLong(JournalSegment::size).sum();
if (remainingSize > maxLogSize) {
log.debug("Found outsize journal segment {}", segment.file().file());
compactSegment = segment;
} else if (compactSegment != null) {
compactIndex = segment.index();
break;
}
}
if (compactIndex != null) {
log.info("Compacting journal by size up to {}", compactIndex);
journal.compact(compactIndex);
}
}
} | [
"private",
"void",
"compactBySize",
"(",
")",
"{",
"if",
"(",
"maxLogSize",
">",
"0",
"&&",
"journal",
".",
"size",
"(",
")",
">",
"maxLogSize",
")",
"{",
"JournalSegment",
"<",
"LogEntry",
">",
"compactSegment",
"=",
"null",
";",
"Long",
"compactIndex",
"=",
"null",
";",
"for",
"(",
"JournalSegment",
"<",
"LogEntry",
">",
"segment",
":",
"journal",
".",
"segments",
"(",
")",
")",
"{",
"Collection",
"<",
"JournalSegment",
"<",
"LogEntry",
">>",
"remainingSegments",
"=",
"journal",
".",
"segments",
"(",
"segment",
".",
"lastIndex",
"(",
")",
"+",
"1",
")",
";",
"long",
"remainingSize",
"=",
"remainingSegments",
".",
"stream",
"(",
")",
".",
"mapToLong",
"(",
"JournalSegment",
"::",
"size",
")",
".",
"sum",
"(",
")",
";",
"if",
"(",
"remainingSize",
">",
"maxLogSize",
")",
"{",
"log",
".",
"debug",
"(",
"\"Found outsize journal segment {}\"",
",",
"segment",
".",
"file",
"(",
")",
".",
"file",
"(",
")",
")",
";",
"compactSegment",
"=",
"segment",
";",
"}",
"else",
"if",
"(",
"compactSegment",
"!=",
"null",
")",
"{",
"compactIndex",
"=",
"segment",
".",
"index",
"(",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"compactIndex",
"!=",
"null",
")",
"{",
"log",
".",
"info",
"(",
"\"Compacting journal by size up to {}\"",
",",
"compactIndex",
")",
";",
"journal",
".",
"compact",
"(",
"compactIndex",
")",
";",
"}",
"}",
"}"
] | Compacts the log by size. | [
"Compacts",
"the",
"log",
"by",
"size",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/log/src/main/java/io/atomix/protocols/log/impl/DistributedLogServerContext.java#L294-L315 |
27,299 | atomix/atomix | protocols/log/src/main/java/io/atomix/protocols/log/impl/DistributedLogServerContext.java | DistributedLogServerContext.compactByAge | private void compactByAge() {
if (maxLogAge != null) {
long currentTime = System.currentTimeMillis();
JournalSegment<LogEntry> compactSegment = null;
Long compactIndex = null;
for (JournalSegment<LogEntry> segment : journal.segments()) {
if (currentTime - segment.descriptor().updated() > maxLogAge.toMillis()) {
log.debug("Found expired journal segment {}", segment.file().file());
compactSegment = segment;
} else if (compactSegment != null) {
compactIndex = segment.index();
break;
}
}
if (compactIndex != null) {
log.info("Compacting journal by age up to {}", compactIndex);
journal.compact(compactIndex);
}
}
} | java | private void compactByAge() {
if (maxLogAge != null) {
long currentTime = System.currentTimeMillis();
JournalSegment<LogEntry> compactSegment = null;
Long compactIndex = null;
for (JournalSegment<LogEntry> segment : journal.segments()) {
if (currentTime - segment.descriptor().updated() > maxLogAge.toMillis()) {
log.debug("Found expired journal segment {}", segment.file().file());
compactSegment = segment;
} else if (compactSegment != null) {
compactIndex = segment.index();
break;
}
}
if (compactIndex != null) {
log.info("Compacting journal by age up to {}", compactIndex);
journal.compact(compactIndex);
}
}
} | [
"private",
"void",
"compactByAge",
"(",
")",
"{",
"if",
"(",
"maxLogAge",
"!=",
"null",
")",
"{",
"long",
"currentTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"JournalSegment",
"<",
"LogEntry",
">",
"compactSegment",
"=",
"null",
";",
"Long",
"compactIndex",
"=",
"null",
";",
"for",
"(",
"JournalSegment",
"<",
"LogEntry",
">",
"segment",
":",
"journal",
".",
"segments",
"(",
")",
")",
"{",
"if",
"(",
"currentTime",
"-",
"segment",
".",
"descriptor",
"(",
")",
".",
"updated",
"(",
")",
">",
"maxLogAge",
".",
"toMillis",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Found expired journal segment {}\"",
",",
"segment",
".",
"file",
"(",
")",
".",
"file",
"(",
")",
")",
";",
"compactSegment",
"=",
"segment",
";",
"}",
"else",
"if",
"(",
"compactSegment",
"!=",
"null",
")",
"{",
"compactIndex",
"=",
"segment",
".",
"index",
"(",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"compactIndex",
"!=",
"null",
")",
"{",
"log",
".",
"info",
"(",
"\"Compacting journal by age up to {}\"",
",",
"compactIndex",
")",
";",
"journal",
".",
"compact",
"(",
"compactIndex",
")",
";",
"}",
"}",
"}"
] | Compacts the log by age. | [
"Compacts",
"the",
"log",
"by",
"age",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/log/src/main/java/io/atomix/protocols/log/impl/DistributedLogServerContext.java#L320-L340 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.