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
partition
stringclasses
1 value
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.isTimeZone
private boolean isTimeZone(JsonObject root) { for (String key : TIMEZONE_KEYS) { if (root.has(key)) { return true; } } return false; }
java
private boolean isTimeZone(JsonObject root) { for (String key : TIMEZONE_KEYS) { if (root.has(key)) { return true; } } return false; }
[ "private", "boolean", "isTimeZone", "(", "JsonObject", "root", ")", "{", "for", "(", "String", "key", ":", "TIMEZONE_KEYS", ")", "{", "if", "(", "root", ".", "has", "(", "key", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", ...
Returns true if this object looks like it holds TimeZoneInfo, otherwise false.
[ "Returns", "true", "if", "this", "object", "looks", "like", "it", "holds", "TimeZoneInfo", "otherwise", "false", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1060-L1067
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseTimeZoneAliases
private void parseTimeZoneAliases(JsonObject root) { JsonObject node = resolve(root, "supplemental", "metadata", "alias", "zoneAlias"); parseTimeZoneAlias(node, Collections.emptyList()); }
java
private void parseTimeZoneAliases(JsonObject root) { JsonObject node = resolve(root, "supplemental", "metadata", "alias", "zoneAlias"); parseTimeZoneAlias(node, Collections.emptyList()); }
[ "private", "void", "parseTimeZoneAliases", "(", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"metadata\"", ",", "\"alias\"", ",", "\"zoneAlias\"", ")", ";", "parseTimeZoneAlias", "(", "node", ...
Parses timezone aliases. These are timezone ids that have been removed for a given reason.
[ "Parses", "timezone", "aliases", ".", "These", "are", "timezone", "ids", "that", "have", "been", "removed", "for", "a", "given", "reason", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1126-L1129
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseTimeZoneAlias
private void parseTimeZoneAlias(JsonObject root, List<String> prefix) { for (String label : objectKeys(root)) { JsonObject node = resolve(root, label); List<String> zone = new ArrayList<>(prefix); zone.add(label); String replacement = string(node, "_replacement", null); if (replacement != null) { String name = StringUtils.join(zone, '/'); timezoneAliases.put(name, replacement); } else { parseTimeZoneAlias(node, zone); } } }
java
private void parseTimeZoneAlias(JsonObject root, List<String> prefix) { for (String label : objectKeys(root)) { JsonObject node = resolve(root, label); List<String> zone = new ArrayList<>(prefix); zone.add(label); String replacement = string(node, "_replacement", null); if (replacement != null) { String name = StringUtils.join(zone, '/'); timezoneAliases.put(name, replacement); } else { parseTimeZoneAlias(node, zone); } } }
[ "private", "void", "parseTimeZoneAlias", "(", "JsonObject", "root", ",", "List", "<", "String", ">", "prefix", ")", "{", "for", "(", "String", "label", ":", "objectKeys", "(", "root", ")", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",",...
Recursively parse timezone aliases.
[ "Recursively", "parse", "timezone", "aliases", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1134-L1147
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseLanguageAliases
private void parseLanguageAliases(JsonObject root) { JsonObject node = resolve(root, "supplemental", "metadata", "alias", "languageAlias"); for (String tag : objectKeys(node)) { JsonObject value = node.getAsJsonObject(tag); String replacement = string(value, "_replacement"); languageAliases.put(tag, replacement); } }
java
private void parseLanguageAliases(JsonObject root) { JsonObject node = resolve(root, "supplemental", "metadata", "alias", "languageAlias"); for (String tag : objectKeys(node)) { JsonObject value = node.getAsJsonObject(tag); String replacement = string(value, "_replacement"); languageAliases.put(tag, replacement); } }
[ "private", "void", "parseLanguageAliases", "(", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"metadata\"", ",", "\"alias\"", ",", "\"languageAlias\"", ")", ";", "for", "(", "String", "tag", ...
Parse the supplemental language aliases map.
[ "Parse", "the", "supplemental", "language", "aliases", "map", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1152-L1159
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseTerritoryAliases
private void parseTerritoryAliases(JsonObject root) { JsonObject node = resolve(root, "supplemental", "metadata", "alias", "territoryAlias"); for (String tag : objectKeys(node)) { JsonObject value = node.getAsJsonObject(tag); String replacement = string(value, "_replacement"); territoryAliases.put(tag, replacement); } }
java
private void parseTerritoryAliases(JsonObject root) { JsonObject node = resolve(root, "supplemental", "metadata", "alias", "territoryAlias"); for (String tag : objectKeys(node)) { JsonObject value = node.getAsJsonObject(tag); String replacement = string(value, "_replacement"); territoryAliases.put(tag, replacement); } }
[ "private", "void", "parseTerritoryAliases", "(", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"metadata\"", ",", "\"alias\"", ",", "\"territoryAlias\"", ")", ";", "for", "(", "String", "tag", ...
Parse the supplemental territory aliases map.
[ "Parse", "the", "supplemental", "territory", "aliases", "map", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1164-L1171
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseMetaZones
private void parseMetaZones(JsonObject root) { JsonObject node = resolve(root, "supplemental", "metaZones", "metazoneInfo", "timezone"); for (MetaZone zone : _parseMetaZones(node, Collections.emptyList())) { metazones.put(zone.zone, zone); } }
java
private void parseMetaZones(JsonObject root) { JsonObject node = resolve(root, "supplemental", "metaZones", "metazoneInfo", "timezone"); for (MetaZone zone : _parseMetaZones(node, Collections.emptyList())) { metazones.put(zone.zone, zone); } }
[ "private", "void", "parseMetaZones", "(", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"supplemental\"", ",", "\"metaZones\"", ",", "\"metazoneInfo\"", ",", "\"timezone\"", ")", ";", "for", "(", "MetaZone", "zone", ...
Parse the metazone mapping from supplemental data.
[ "Parse", "the", "metazone", "mapping", "from", "supplemental", "data", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1176-L1181
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseUnitData
private UnitData parseUnitData(String code, JsonObject root) { JsonObject node = resolve(root, "main", code, "units"); UnitData data = new UnitData(); data.long_ = parseUnitPatterns(node, "long"); data.narrow = parseUnitPatterns(node, "narrow"); data.short_ = parseUnitPatterns(node, "short"); return data; }
java
private UnitData parseUnitData(String code, JsonObject root) { JsonObject node = resolve(root, "main", code, "units"); UnitData data = new UnitData(); data.long_ = parseUnitPatterns(node, "long"); data.narrow = parseUnitPatterns(node, "narrow"); data.short_ = parseUnitPatterns(node, "short"); return data; }
[ "private", "UnitData", "parseUnitData", "(", "String", "code", ",", "JsonObject", "root", ")", "{", "JsonObject", "node", "=", "resolve", "(", "root", ",", "\"main\"", ",", "code", ",", "\"units\"", ")", ";", "UnitData", "data", "=", "new", "UnitData", "("...
Parse unit formatting patterns.
[ "Parse", "unit", "formatting", "patterns", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1230-L1237
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.parseUnitPatterns
private UnitPatterns parseUnitPatterns(JsonObject node, String width) { node = resolve(node, width); UnitPatterns result = new UnitPatterns(); result.compoundUnitPattern = string(resolve(node, "per"), "compoundUnitPattern"); result.coordinatePatterns = new HashMap<>(); JsonObject parent = resolve(node, "coordinateUnit"); for (String direction : objectKeys(parent)) { result.coordinatePatterns.put(direction, parent.get(direction).getAsString()); } node.remove("per"); node.remove("coordinateUnit"); Set<PluralCategory> categories = new HashSet<>(); result.unitPatterns = new EnumMap<Unit, UnitData.UnitPattern>(Unit.class); for (String unitKey : objectKeys(node)) { JsonObject obj = node.get(unitKey).getAsJsonObject(); // Special case as "generic" is ambiguous Unit unit = null; if (unitKey.equalsIgnoreCase("temperature-generic")) { unit = Unit.TEMPERATURE_GENERIC; } else { int index = unitKey.indexOf('-'); String identifier = unitKey.substring(index + 1); unit = Unit.fromIdentifier(identifier); } if (unit == null) { throw new RuntimeException("unsupported unit found: " + unitKey); } UnitPattern pattern = new UnitPattern(); pattern.displayName = string(obj, "displayName"); pattern.perUnitPattern = string(obj, "perUnitPattern", null); pattern.patterns = new HashMap<>(); for (String patternKey : objectKeys(obj)) { if (!patternKey.startsWith("unitPattern-count-")) { continue; } String value = string(obj, patternKey); PluralCategory category = PluralCategory.fromString(patternKey.split("-")[2]); categories.add(category); pattern.patterns.put(category, value); } result.unitPatterns.put(unit, pattern); } // Fill in default of OTHER where necessary for (Unit unit : Unit.values()) { UnitPattern pattern = result.unitPatterns.get(unit); String other = pattern.patterns.get(PluralCategory.OTHER); for (PluralCategory category : categories) { if (pattern.patterns.get(category) == null) { pattern.patterns.put(category, other); } } } return result; }
java
private UnitPatterns parseUnitPatterns(JsonObject node, String width) { node = resolve(node, width); UnitPatterns result = new UnitPatterns(); result.compoundUnitPattern = string(resolve(node, "per"), "compoundUnitPattern"); result.coordinatePatterns = new HashMap<>(); JsonObject parent = resolve(node, "coordinateUnit"); for (String direction : objectKeys(parent)) { result.coordinatePatterns.put(direction, parent.get(direction).getAsString()); } node.remove("per"); node.remove("coordinateUnit"); Set<PluralCategory> categories = new HashSet<>(); result.unitPatterns = new EnumMap<Unit, UnitData.UnitPattern>(Unit.class); for (String unitKey : objectKeys(node)) { JsonObject obj = node.get(unitKey).getAsJsonObject(); // Special case as "generic" is ambiguous Unit unit = null; if (unitKey.equalsIgnoreCase("temperature-generic")) { unit = Unit.TEMPERATURE_GENERIC; } else { int index = unitKey.indexOf('-'); String identifier = unitKey.substring(index + 1); unit = Unit.fromIdentifier(identifier); } if (unit == null) { throw new RuntimeException("unsupported unit found: " + unitKey); } UnitPattern pattern = new UnitPattern(); pattern.displayName = string(obj, "displayName"); pattern.perUnitPattern = string(obj, "perUnitPattern", null); pattern.patterns = new HashMap<>(); for (String patternKey : objectKeys(obj)) { if (!patternKey.startsWith("unitPattern-count-")) { continue; } String value = string(obj, patternKey); PluralCategory category = PluralCategory.fromString(patternKey.split("-")[2]); categories.add(category); pattern.patterns.put(category, value); } result.unitPatterns.put(unit, pattern); } // Fill in default of OTHER where necessary for (Unit unit : Unit.values()) { UnitPattern pattern = result.unitPatterns.get(unit); String other = pattern.patterns.get(PluralCategory.OTHER); for (PluralCategory category : categories) { if (pattern.patterns.get(category) == null) { pattern.patterns.put(category, other); } } } return result; }
[ "private", "UnitPatterns", "parseUnitPatterns", "(", "JsonObject", "node", ",", "String", "width", ")", "{", "node", "=", "resolve", "(", "node", ",", "width", ")", ";", "UnitPatterns", "result", "=", "new", "UnitPatterns", "(", ")", ";", "result", ".", "c...
Parse unit patterns of a given width.
[ "Parse", "unit", "patterns", "of", "a", "given", "width", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1242-L1304
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.resolve
private JsonObject resolve(JsonObject node, String ...keys) { for (String key : keys) { JsonElement n = node.get(key); if (n == null) { return null; } node = n.getAsJsonObject(); } return node; }
java
private JsonObject resolve(JsonObject node, String ...keys) { for (String key : keys) { JsonElement n = node.get(key); if (n == null) { return null; } node = n.getAsJsonObject(); } return node; }
[ "private", "JsonObject", "resolve", "(", "JsonObject", "node", ",", "String", "...", "keys", ")", "{", "for", "(", "String", "key", ":", "keys", ")", "{", "JsonElement", "n", "=", "node", ".", "get", "(", "key", ")", ";", "if", "(", "n", "==", "nul...
Recursively resolve a series of keys against a JSON object. This is used to drill down into a JSON object tree.
[ "Recursively", "resolve", "a", "series", "of", "keys", "against", "a", "JSON", "object", ".", "This", "is", "used", "to", "drill", "down", "into", "a", "JSON", "object", "tree", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1317-L1326
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.string
private String string(JsonObject node, String key, String default_) { JsonElement value = node.get(key); if (value != null && value.isJsonPrimitive()) { return value.getAsString(); } return default_; }
java
private String string(JsonObject node, String key, String default_) { JsonElement value = node.get(key); if (value != null && value.isJsonPrimitive()) { return value.getAsString(); } return default_; }
[ "private", "String", "string", "(", "JsonObject", "node", ",", "String", "key", ",", "String", "default_", ")", "{", "JsonElement", "value", "=", "node", ".", "get", "(", "key", ")", ";", "if", "(", "value", "!=", "null", "&&", "value", ".", "isJsonPri...
Extract a value from a JSON object and convert it to a string.
[ "Extract", "a", "value", "from", "a", "JSON", "object", "and", "convert", "it", "to", "a", "string", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1338-L1344
train
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java
DataReader.objectKeys
private List<String> objectKeys(JsonObject obj) { List<String> keys = new ArrayList<>(); for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { keys.add(entry.getKey()); } return keys; }
java
private List<String> objectKeys(JsonObject obj) { List<String> keys = new ArrayList<>(); for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { keys.add(entry.getKey()); } return keys; }
[ "private", "List", "<", "String", ">", "objectKeys", "(", "JsonObject", "obj", ")", "{", "List", "<", "String", ">", "keys", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "JsonElement", ">", "entry...
Return a list of the keys on a JSON object.
[ "Return", "a", "list", "of", "the", "keys", "on", "a", "JSON", "object", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/reader/DataReader.java#L1360-L1366
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/units/Rational.java
Rational.multiply
public Rational multiply(Rational other) { return new Rational( numerator.multiply(other.numerator), denominator.multiply(other.denominator)); }
java
public Rational multiply(Rational other) { return new Rational( numerator.multiply(other.numerator), denominator.multiply(other.denominator)); }
[ "public", "Rational", "multiply", "(", "Rational", "other", ")", "{", "return", "new", "Rational", "(", "numerator", ".", "multiply", "(", "other", ".", "numerator", ")", ",", "denominator", ".", "multiply", "(", "other", ".", "denominator", ")", ")", ";",...
Multiply this rational by another and return a new rational.
[ "Multiply", "this", "rational", "by", "another", "and", "return", "a", "new", "rational", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/Rational.java#L47-L51
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/units/Rational.java
Rational.compute
public BigDecimal compute(RoundingMode mode) { int scale = numerator.precision() + denominator.precision(); scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale)); return numerator.divide(denominator, scale, mode).stripTrailingZeros(); }
java
public BigDecimal compute(RoundingMode mode) { int scale = numerator.precision() + denominator.precision(); scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale)); return numerator.divide(denominator, scale, mode).stripTrailingZeros(); }
[ "public", "BigDecimal", "compute", "(", "RoundingMode", "mode", ")", "{", "int", "scale", "=", "numerator", ".", "precision", "(", ")", "+", "denominator", ".", "precision", "(", ")", ";", "scale", "=", "Math", ".", "max", "(", "MIN_SCALE", ",", "Math", ...
Divide the numerator by the denominator and return the resulting decimal number.
[ "Divide", "the", "numerator", "by", "the", "denominator", "and", "return", "the", "resulting", "decimal", "number", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/Rational.java#L64-L68
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/units/Rational.java
Rational.compute
public BigDecimal compute(int scale, RoundingMode mode) { return numerator.divide(denominator, scale, mode).stripTrailingZeros(); }
java
public BigDecimal compute(int scale, RoundingMode mode) { return numerator.divide(denominator, scale, mode).stripTrailingZeros(); }
[ "public", "BigDecimal", "compute", "(", "int", "scale", ",", "RoundingMode", "mode", ")", "{", "return", "numerator", ".", "divide", "(", "denominator", ",", "scale", ",", "mode", ")", ".", "stripTrailingZeros", "(", ")", ";", "}" ]
Divide the numerator by the denominator, using the given scale and rounding mode, and return the resulting decimal number.
[ "Divide", "the", "numerator", "by", "the", "denominator", "using", "the", "given", "scale", "and", "rounding", "mode", "and", "return", "the", "resulting", "decimal", "number", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/Rational.java#L74-L76
train
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/dates/CalendarFormattingUtils.java
CalendarFormattingUtils.sameDay
public static boolean sameDay(ZonedDateTime d1, ZonedDateTime d2) { DateTimeField field = greatestDifference(d1, d2); return (field != YEAR && field != MONTH && field != DAY); }
java
public static boolean sameDay(ZonedDateTime d1, ZonedDateTime d2) { DateTimeField field = greatestDifference(d1, d2); return (field != YEAR && field != MONTH && field != DAY); }
[ "public", "static", "boolean", "sameDay", "(", "ZonedDateTime", "d1", ",", "ZonedDateTime", "d2", ")", "{", "DateTimeField", "field", "=", "greatestDifference", "(", "d1", ",", "d2", ")", ";", "return", "(", "field", "!=", "YEAR", "&&", "field", "!=", "MON...
Returns a boolean indicating the two date times are on the same day.
[ "Returns", "a", "boolean", "indicating", "the", "two", "date", "times", "are", "on", "the", "same", "day", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/dates/CalendarFormattingUtils.java#L21-L24
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MetaLocale.java
MetaLocale.parse
protected static MetaLocale parse(String tag) { if (tag.indexOf('_') != -1) { tag = tag.replace('_', SEP); } Maybe<Pair<MetaLocale, CharSequence>> result = P_LANGUAGE_TAG.parse(tag); // This parser is for internal use only during code generation, so we blow up // severely if a language tag fails to parse.. if (result.isNothing()) { throw new IllegalArgumentException("Failed to parse language tag: '" + tag + "'"); } return result.get()._1; }
java
protected static MetaLocale parse(String tag) { if (tag.indexOf('_') != -1) { tag = tag.replace('_', SEP); } Maybe<Pair<MetaLocale, CharSequence>> result = P_LANGUAGE_TAG.parse(tag); // This parser is for internal use only during code generation, so we blow up // severely if a language tag fails to parse.. if (result.isNothing()) { throw new IllegalArgumentException("Failed to parse language tag: '" + tag + "'"); } return result.get()._1; }
[ "protected", "static", "MetaLocale", "parse", "(", "String", "tag", ")", "{", "if", "(", "tag", ".", "indexOf", "(", "'", "'", ")", "!=", "-", "1", ")", "{", "tag", "=", "tag", ".", "replace", "(", "'", "'", ",", "SEP", ")", ";", "}", "Maybe", ...
Internal method for parsing well-formed language tags.
[ "Internal", "method", "for", "parsing", "well", "-", "formed", "language", "tags", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MetaLocale.java#L101-L112
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MetaLocale.java
MetaLocale.fromLanguageTag
public static MetaLocale fromLanguageTag(String tag) { if (tag.indexOf('_') != -1) { tag = tag.replace('_', SEP); } return fromJavaLocale(java.util.Locale.forLanguageTag(tag)); }
java
public static MetaLocale fromLanguageTag(String tag) { if (tag.indexOf('_') != -1) { tag = tag.replace('_', SEP); } return fromJavaLocale(java.util.Locale.forLanguageTag(tag)); }
[ "public", "static", "MetaLocale", "fromLanguageTag", "(", "String", "tag", ")", "{", "if", "(", "tag", ".", "indexOf", "(", "'", "'", ")", "!=", "-", "1", ")", "{", "tag", "=", "tag", ".", "replace", "(", "'", "'", ",", "SEP", ")", ";", "}", "r...
Constructs a MetaLocale from a language tag string.
[ "Constructs", "a", "MetaLocale", "from", "a", "language", "tag", "string", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MetaLocale.java#L117-L122
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MetaLocale.java
MetaLocale.fromJavaLocale
public static MetaLocale fromJavaLocale(java.util.Locale java) { // Some confusing cases can arise here based on the getLanguage() method // returning the deprecated language codes in a handful of cases. See // MetaLocaleTest for test cases for these examples. String language = java.getLanguage(); switch (language) { case "iw": language = "he"; break; case "in": language = "id"; break; case "ji": language = "yi"; break; } return new MetaLocale(language, java.getScript(), java.getCountry(), java.getVariant()); }
java
public static MetaLocale fromJavaLocale(java.util.Locale java) { // Some confusing cases can arise here based on the getLanguage() method // returning the deprecated language codes in a handful of cases. See // MetaLocaleTest for test cases for these examples. String language = java.getLanguage(); switch (language) { case "iw": language = "he"; break; case "in": language = "id"; break; case "ji": language = "yi"; break; } return new MetaLocale(language, java.getScript(), java.getCountry(), java.getVariant()); }
[ "public", "static", "MetaLocale", "fromJavaLocale", "(", "java", ".", "util", ".", "Locale", "java", ")", "{", "// Some confusing cases can arise here based on the getLanguage() method", "// returning the deprecated language codes in a handful of cases. See", "// MetaLocaleTest for tes...
Constructs a MetaLocale from a Java Locale object.
[ "Constructs", "a", "MetaLocale", "from", "a", "Java", "Locale", "object", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MetaLocale.java#L127-L146
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MetaLocale.java
MetaLocale.reset
protected void reset() { fields[LANGUAGE] = null; fields[SCRIPT] = null; fields[TERRITORY] = null; fields[VARIANT] = null; }
java
protected void reset() { fields[LANGUAGE] = null; fields[SCRIPT] = null; fields[TERRITORY] = null; fields[VARIANT] = null; }
[ "protected", "void", "reset", "(", ")", "{", "fields", "[", "LANGUAGE", "]", "=", "null", ";", "fields", "[", "SCRIPT", "]", "=", "null", ";", "fields", "[", "TERRITORY", "]", "=", "null", ";", "fields", "[", "VARIANT", "]", "=", "null", ";", "}" ]
Resets this locale to full undefined state.
[ "Resets", "this", "locale", "to", "full", "undefined", "state", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MetaLocale.java#L312-L317
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MetaLocale.java
MetaLocale.render
private String render(boolean compact) { StringBuilder buf = new StringBuilder(); render(buf, LANGUAGE, UNDEF_LANGUAGE, compact); render(buf, SCRIPT, UNDEF_SCRIPT, compact); render(buf, TERRITORY, UNDEF_TERRITORY, compact); render(buf, VARIANT, UNDEF_VARIANT, compact); return buf.toString(); }
java
private String render(boolean compact) { StringBuilder buf = new StringBuilder(); render(buf, LANGUAGE, UNDEF_LANGUAGE, compact); render(buf, SCRIPT, UNDEF_SCRIPT, compact); render(buf, TERRITORY, UNDEF_TERRITORY, compact); render(buf, VARIANT, UNDEF_VARIANT, compact); return buf.toString(); }
[ "private", "String", "render", "(", "boolean", "compact", ")", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", ")", ";", "render", "(", "buf", ",", "LANGUAGE", ",", "UNDEF_LANGUAGE", ",", "compact", ")", ";", "render", "(", "buf", ",", "SC...
Render this locale to a string in compact or expanded form.
[ "Render", "this", "locale", "to", "a", "string", "in", "compact", "or", "expanded", "form", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MetaLocale.java#L322-L329
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MetaLocale.java
MetaLocale.render
private void render(StringBuilder buf, int key, String undef, boolean expanded) { boolean force = key != VARIANT && (key == LANGUAGE || expanded); String value = fields[key]; if (value != null || force) { if (buf.length() > 0) { buf.append(SEP); } buf.append(value == null ? undef : value); } }
java
private void render(StringBuilder buf, int key, String undef, boolean expanded) { boolean force = key != VARIANT && (key == LANGUAGE || expanded); String value = fields[key]; if (value != null || force) { if (buf.length() > 0) { buf.append(SEP); } buf.append(value == null ? undef : value); } }
[ "private", "void", "render", "(", "StringBuilder", "buf", ",", "int", "key", ",", "String", "undef", ",", "boolean", "expanded", ")", "{", "boolean", "force", "=", "key", "!=", "VARIANT", "&&", "(", "key", "==", "LANGUAGE", "||", "expanded", ")", ";", ...
Render a locale field to the buffer. Language field is always emitted, and variant field is always omitted unless it has a value.
[ "Render", "a", "locale", "field", "to", "the", "buffer", ".", "Language", "field", "is", "always", "emitted", "and", "variant", "field", "is", "always", "omitted", "unless", "it", "has", "a", "value", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MetaLocale.java#L335-L344
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MetaLocale.java
MetaLocale.getField
private String getField(int key, String undef) { String value = fields[key]; return value == null ? undef : value; }
java
private String getField(int key, String undef) { String value = fields[key]; return value == null ? undef : value; }
[ "private", "String", "getField", "(", "int", "key", ",", "String", "undef", ")", "{", "String", "value", "=", "fields", "[", "key", "]", ";", "return", "value", "==", "null", "?", "undef", ":", "value", ";", "}" ]
Return a field's value or the undefined value.
[ "Return", "a", "field", "s", "value", "or", "the", "undefined", "value", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MetaLocale.java#L349-L352
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MetaLocale.java
MetaLocale.setFieldIf
private void setFieldIf(int key, String value, String undef) { if (value == null) { this.fields[key] = value; } else { // Special case for language: replace BCP 47 field "root" with undefined value. if (key == LANGUAGE && value.equals("root")) { this.fields[key] = null; } else { this.fields[key] = value.equals("") || value.equals(undef) ? null : value; } } }
java
private void setFieldIf(int key, String value, String undef) { if (value == null) { this.fields[key] = value; } else { // Special case for language: replace BCP 47 field "root" with undefined value. if (key == LANGUAGE && value.equals("root")) { this.fields[key] = null; } else { this.fields[key] = value.equals("") || value.equals(undef) ? null : value; } } }
[ "private", "void", "setFieldIf", "(", "int", "key", ",", "String", "value", ",", "String", "undef", ")", "{", "if", "(", "value", "==", "null", ")", "{", "this", ".", "fields", "[", "key", "]", "=", "value", ";", "}", "else", "{", "// Special case fo...
All public set methods pass through here.
[ "All", "public", "set", "methods", "pass", "through", "here", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MetaLocale.java#L357-L368
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java
NumberFormatterBase.formatUnits
public void formatUnits(List<UnitValue> values, StringBuilder destination, UnitFormatOptions options) { int size = values.size(); for (int i = 0; i < size; i++) { if (i > 0) { destination.append(' '); } formatUnit(values.get(i), destination, options); } }
java
public void formatUnits(List<UnitValue> values, StringBuilder destination, UnitFormatOptions options) { int size = values.size(); for (int i = 0; i < size; i++) { if (i > 0) { destination.append(' '); } formatUnit(values.get(i), destination, options); } }
[ "public", "void", "formatUnits", "(", "List", "<", "UnitValue", ">", "values", ",", "StringBuilder", "destination", ",", "UnitFormatOptions", "options", ")", "{", "int", "size", "=", "values", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0",...
Format a sequence of unit values.
[ "Format", "a", "sequence", "of", "unit", "values", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java#L96-L104
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java
NumberFormatterBase.formatUnit
public void formatUnit(UnitValue value, StringBuilder destination, UnitFormatOptions options) { BigDecimal n = value.amount(); boolean grouping = orDefault(options.grouping(), false); NumberFormatContext ctx = new NumberFormatContext(options, NumberFormatMode.DEFAULT); NumberPattern numberPattern = select(n, unitStandard); ctx.set(numberPattern); BigDecimal q = ctx.adjust(n); NumberOperands operands = new NumberOperands(q.toPlainString()); PluralCategory category = PLURAL_RULES.evalCardinal(bundleId.language(), operands); Unit unit = value.unit(); List<FieldPattern.Node> unitPattern = null; // We allow unit to be null to accomodate the caller as a last resort. // If the unit is not available we still format a number. if (unit != null) { switch (options.format()) { case LONG: unitPattern = getPattern_UNITS_LONG(unit, category); break; case NARROW: unitPattern = getPattern_UNITS_NARROW(unit, category); break; case SHORT: default: unitPattern = getPattern_UNITS_SHORT(unit, category); break; } } DigitBuffer number = new DigitBuffer(); NumberFormattingUtils.format(q, number, params, false, grouping, ctx.minIntDigits(), numberPattern.format.primaryGroupingSize(), numberPattern.format.secondaryGroupingSize()); if (unitPattern == null) { number.appendTo(destination); } else { DigitBuffer dbuf = new DigitBuffer(); for (FieldPattern.Node node : unitPattern) { if (node instanceof FieldPattern.Text) { dbuf.append(((FieldPattern.Text)node).text()); } else if (node instanceof Field) { Field field = (Field)node; if (field.ch() == '0') { format(numberPattern, number, dbuf, null, null); } } } dbuf.appendTo(destination); } }
java
public void formatUnit(UnitValue value, StringBuilder destination, UnitFormatOptions options) { BigDecimal n = value.amount(); boolean grouping = orDefault(options.grouping(), false); NumberFormatContext ctx = new NumberFormatContext(options, NumberFormatMode.DEFAULT); NumberPattern numberPattern = select(n, unitStandard); ctx.set(numberPattern); BigDecimal q = ctx.adjust(n); NumberOperands operands = new NumberOperands(q.toPlainString()); PluralCategory category = PLURAL_RULES.evalCardinal(bundleId.language(), operands); Unit unit = value.unit(); List<FieldPattern.Node> unitPattern = null; // We allow unit to be null to accomodate the caller as a last resort. // If the unit is not available we still format a number. if (unit != null) { switch (options.format()) { case LONG: unitPattern = getPattern_UNITS_LONG(unit, category); break; case NARROW: unitPattern = getPattern_UNITS_NARROW(unit, category); break; case SHORT: default: unitPattern = getPattern_UNITS_SHORT(unit, category); break; } } DigitBuffer number = new DigitBuffer(); NumberFormattingUtils.format(q, number, params, false, grouping, ctx.minIntDigits(), numberPattern.format.primaryGroupingSize(), numberPattern.format.secondaryGroupingSize()); if (unitPattern == null) { number.appendTo(destination); } else { DigitBuffer dbuf = new DigitBuffer(); for (FieldPattern.Node node : unitPattern) { if (node instanceof FieldPattern.Text) { dbuf.append(((FieldPattern.Text)node).text()); } else if (node instanceof Field) { Field field = (Field)node; if (field.ch() == '0') { format(numberPattern, number, dbuf, null, null); } } } dbuf.appendTo(destination); } }
[ "public", "void", "formatUnit", "(", "UnitValue", "value", ",", "StringBuilder", "destination", ",", "UnitFormatOptions", "options", ")", "{", "BigDecimal", "n", "=", "value", ".", "amount", "(", ")", ";", "boolean", "grouping", "=", "orDefault", "(", "options...
Format a unit value.
[ "Format", "a", "unit", "value", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java#L109-L165
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java
NumberFormatterBase.select
protected static NumberPattern select(BigDecimal n, NumberPattern[] patterns) { return n.signum() == -1 ? patterns[1] : patterns[0]; }
java
protected static NumberPattern select(BigDecimal n, NumberPattern[] patterns) { return n.signum() == -1 ? patterns[1] : patterns[0]; }
[ "protected", "static", "NumberPattern", "select", "(", "BigDecimal", "n", ",", "NumberPattern", "[", "]", "patterns", ")", "{", "return", "n", ".", "signum", "(", ")", "==", "-", "1", "?", "patterns", "[", "1", "]", ":", "patterns", "[", "0", "]", ";...
Select the appropriate pattern to format a positive or negative number.
[ "Select", "the", "appropriate", "pattern", "to", "format", "a", "positive", "or", "negative", "number", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java#L407-L409
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java
NumberFormatterBase.parse
protected static NumberPattern parse(String pattern) { return NUMBER_PATTERN_CACHE.computeIfAbsent(pattern, s -> new NumberPatternParser().parse(s)); }
java
protected static NumberPattern parse(String pattern) { return NUMBER_PATTERN_CACHE.computeIfAbsent(pattern, s -> new NumberPatternParser().parse(s)); }
[ "protected", "static", "NumberPattern", "parse", "(", "String", "pattern", ")", "{", "return", "NUMBER_PATTERN_CACHE", ".", "computeIfAbsent", "(", "pattern", ",", "s", "->", "new", "NumberPatternParser", "(", ")", ".", "parse", "(", "s", ")", ")", ";", "}" ...
Parse a string as a number pattern.
[ "Parse", "a", "string", "as", "a", "number", "pattern", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java#L442-L444
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java
NumberFormatterBase.format
protected void format( NumberPattern pattern, DigitBuffer number, DigitBuffer buf, String currency, String percent) { // Flag indicating if we've emitted the formatted number yet. boolean emitted = false; // Iterate over the nodes in the format, handling each type. List<Node> nodes = pattern.parsed(); int size = nodes.size(); for (int i = 0; i < size; i++) { Node node = nodes.get(i); if (node instanceof Text) { buf.append(((Text)node).text()); } else if (node instanceof Format) { buf.append(number); emitted = true; } else if (node instanceof Symbol) { switch ((Symbol)node) { case MINUS: buf.append(params.minus); break; case PERCENT: if (percent != null) { buf.append(percent); } break; case CURRENCY: if (currency == null || currency.isEmpty()) { break; } // Spacing around currency depending on if it occurs before or // after the formatted digits. if (emitted) { char firstCh = currency.charAt(0); if (!isSymbol(firstCh) && Character.isDigit(buf.last())) { buf.append(NBSP); } buf.append(currency); } else { buf.append(currency); boolean nextFormat = i < (size - 1) && nodes.get(i + 1) instanceof Format; char lastCh = currency.charAt(currency.length() - 1); if (!isSymbol(lastCh) && nextFormat) { buf.append(NBSP); } } break; } } } }
java
protected void format( NumberPattern pattern, DigitBuffer number, DigitBuffer buf, String currency, String percent) { // Flag indicating if we've emitted the formatted number yet. boolean emitted = false; // Iterate over the nodes in the format, handling each type. List<Node> nodes = pattern.parsed(); int size = nodes.size(); for (int i = 0; i < size; i++) { Node node = nodes.get(i); if (node instanceof Text) { buf.append(((Text)node).text()); } else if (node instanceof Format) { buf.append(number); emitted = true; } else if (node instanceof Symbol) { switch ((Symbol)node) { case MINUS: buf.append(params.minus); break; case PERCENT: if (percent != null) { buf.append(percent); } break; case CURRENCY: if (currency == null || currency.isEmpty()) { break; } // Spacing around currency depending on if it occurs before or // after the formatted digits. if (emitted) { char firstCh = currency.charAt(0); if (!isSymbol(firstCh) && Character.isDigit(buf.last())) { buf.append(NBSP); } buf.append(currency); } else { buf.append(currency); boolean nextFormat = i < (size - 1) && nodes.get(i + 1) instanceof Format; char lastCh = currency.charAt(currency.length() - 1); if (!isSymbol(lastCh) && nextFormat) { buf.append(NBSP); } } break; } } } }
[ "protected", "void", "format", "(", "NumberPattern", "pattern", ",", "DigitBuffer", "number", ",", "DigitBuffer", "buf", ",", "String", "currency", ",", "String", "percent", ")", "{", "// Flag indicating if we've emitted the formatted number yet.", "boolean", "emitted", ...
Formats a number using a pattern and options.
[ "Formats", "a", "number", "using", "a", "pattern", "and", "options", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java#L509-L569
train
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java
NumberFormatterBase.isSymbol
public static boolean isSymbol(char ch) { switch (Character.getType(ch)) { case Character.MATH_SYMBOL: case Character.CURRENCY_SYMBOL: case Character.MODIFIER_SYMBOL: case Character.OTHER_SYMBOL: return true; default: return false; } }
java
public static boolean isSymbol(char ch) { switch (Character.getType(ch)) { case Character.MATH_SYMBOL: case Character.CURRENCY_SYMBOL: case Character.MODIFIER_SYMBOL: case Character.OTHER_SYMBOL: return true; default: return false; } }
[ "public", "static", "boolean", "isSymbol", "(", "char", "ch", ")", "{", "switch", "(", "Character", ".", "getType", "(", "ch", ")", ")", "{", "case", "Character", ".", "MATH_SYMBOL", ":", "case", "Character", ".", "CURRENCY_SYMBOL", ":", "case", "Character...
Returns true if the character is in any of the symbol categories.
[ "Returns", "true", "if", "the", "character", "is", "in", "any", "of", "the", "symbol", "categories", "." ]
54b752d4ec2457df56e98461618f9c0eec41e1e1
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/numbers/NumberFormatterBase.java#L574-L585
train
rodionmoiseev/c10n
core/src/main/java/com/github/rodionmoiseev/c10n/C10NConfigBase.java
C10NConfigBase.getAnnotationToLocaleMapping
Map<Class<? extends Annotation>, Set<Locale>> getAnnotationToLocaleMapping() { Map<Class<? extends Annotation>, Set<Locale>> res = new HashMap<Class<? extends Annotation>, Set<Locale>>(); for (Entry<Class<? extends Annotation>, C10NAnnotationBinder> entry : annotationBinders.entrySet()) { Set<Locale> locales = getLocales(entry.getKey(), res); locales.add(entry.getValue().getLocale()); } return res; }
java
Map<Class<? extends Annotation>, Set<Locale>> getAnnotationToLocaleMapping() { Map<Class<? extends Annotation>, Set<Locale>> res = new HashMap<Class<? extends Annotation>, Set<Locale>>(); for (Entry<Class<? extends Annotation>, C10NAnnotationBinder> entry : annotationBinders.entrySet()) { Set<Locale> locales = getLocales(entry.getKey(), res); locales.add(entry.getValue().getLocale()); } return res; }
[ "Map", "<", "Class", "<", "?", "extends", "Annotation", ">", ",", "Set", "<", "Locale", ">", ">", "getAnnotationToLocaleMapping", "(", ")", "{", "Map", "<", "Class", "<", "?", "extends", "Annotation", ">", ",", "Set", "<", "Locale", ">", ">", "res", ...
For each annotation bound in this configuration find all locales it has been bound to. @return annotation -&gt; set of locale mapping
[ "For", "each", "annotation", "bound", "in", "this", "configuration", "find", "all", "locales", "it", "has", "been", "bound", "to", "." ]
8f3ce95395b1775b536294ed34b1b5c1e4540b03
https://github.com/rodionmoiseev/c10n/blob/8f3ce95395b1775b536294ed34b1b5c1e4540b03/core/src/main/java/com/github/rodionmoiseev/c10n/C10NConfigBase.java#L399-L406
train
rodionmoiseev/c10n
core/src/main/java/com/github/rodionmoiseev/c10n/C10NConfigBase.java
C10NConfigBase.getImplLocales
Set<Locale> getImplLocales(Class<?> c10nInterface) { Set<Locale> res = new HashSet<Locale>(); C10NImplementationBinder<?> binder = binders.get(c10nInterface); if (binder != null) { res.addAll(binder.bindings.keySet()); } return res; }
java
Set<Locale> getImplLocales(Class<?> c10nInterface) { Set<Locale> res = new HashSet<Locale>(); C10NImplementationBinder<?> binder = binders.get(c10nInterface); if (binder != null) { res.addAll(binder.bindings.keySet()); } return res; }
[ "Set", "<", "Locale", ">", "getImplLocales", "(", "Class", "<", "?", ">", "c10nInterface", ")", "{", "Set", "<", "Locale", ">", "res", "=", "new", "HashSet", "<", "Locale", ">", "(", ")", ";", "C10NImplementationBinder", "<", "?", ">", "binder", "=", ...
Find all locales that have explicit implementation class bindings for this c10n interface. @param c10nInterface interface to find bindings for (not-null) @return Set of locales (not-null)
[ "Find", "all", "locales", "that", "have", "explicit", "implementation", "class", "bindings", "for", "this", "c10n", "interface", "." ]
8f3ce95395b1775b536294ed34b1b5c1e4540b03
https://github.com/rodionmoiseev/c10n/blob/8f3ce95395b1775b536294ed34b1b5c1e4540b03/core/src/main/java/com/github/rodionmoiseev/c10n/C10NConfigBase.java#L445-L452
train
michael-simons/wro4j-spring-boot-starter
src/main/java/ac/simons/spring/boot/wro4j/Wro4jAutoConfiguration.java
Wro4jAutoConfiguration.getBeanOrInstantiateProcessor
<T> T getBeanOrInstantiateProcessor(final Class<? extends T> c) { T rv; try { rv = this.applicationContext.getBean(c); } catch (NoSuchBeanDefinitionException e) { LOGGER.warn("Could not get processor from context, instantiating new instance instead", e); rv = (T) new BeanWrapperImpl(c).getWrappedInstance(); } return rv; }
java
<T> T getBeanOrInstantiateProcessor(final Class<? extends T> c) { T rv; try { rv = this.applicationContext.getBean(c); } catch (NoSuchBeanDefinitionException e) { LOGGER.warn("Could not get processor from context, instantiating new instance instead", e); rv = (T) new BeanWrapperImpl(c).getWrappedInstance(); } return rv; }
[ "<", "T", ">", "T", "getBeanOrInstantiateProcessor", "(", "final", "Class", "<", "?", "extends", "T", ">", "c", ")", "{", "T", "rv", ";", "try", "{", "rv", "=", "this", ".", "applicationContext", ".", "getBean", "(", "c", ")", ";", "}", "catch", "(...
This method tries to load a processor from the application context by class name. If it fails, the processor is instantiated manually bot not added to the context. @param <T> Type of the processor to load @param c Class of the processor to load @return A processor instance
[ "This", "method", "tries", "to", "load", "a", "processor", "from", "the", "application", "context", "by", "class", "name", "." ]
c0d7cc5c03b6f884f63596c36c5e0aa86cd54141
https://github.com/michael-simons/wro4j-spring-boot-starter/blob/c0d7cc5c03b6f884f63596c36c5e0aa86cd54141/src/main/java/ac/simons/spring/boot/wro4j/Wro4jAutoConfiguration.java#L159-L168
train
michael-simons/wro4j-spring-boot-starter
src/main/java/ac/simons/spring/boot/wro4j/Wro4jAutoConfiguration.java
Wro4jAutoConfiguration.defaultCacheStrategy
@Bean @ConditionalOnMissingBean(CacheStrategy.class) @Order(-90) <K, V> CacheStrategy<K, V> defaultCacheStrategy() { LOGGER.debug("Creating cache strategy 'LruMemoryCacheStrategy'"); return new LruMemoryCacheStrategy<>(); }
java
@Bean @ConditionalOnMissingBean(CacheStrategy.class) @Order(-90) <K, V> CacheStrategy<K, V> defaultCacheStrategy() { LOGGER.debug("Creating cache strategy 'LruMemoryCacheStrategy'"); return new LruMemoryCacheStrategy<>(); }
[ "@", "Bean", "@", "ConditionalOnMissingBean", "(", "CacheStrategy", ".", "class", ")", "@", "Order", "(", "-", "90", ")", "<", "K", ",", "V", ">", "CacheStrategy", "<", "K", ",", "V", ">", "defaultCacheStrategy", "(", ")", "{", "LOGGER", ".", "debug", ...
This is the default "Least recently used memory cache" strategy of Wro4j which will be configured per default. @param <K> Type of the cache keys @param <V> Type of the cache values @return A default Wro4j cache strategy
[ "This", "is", "the", "default", "Least", "recently", "used", "memory", "cache", "strategy", "of", "Wro4j", "which", "will", "be", "configured", "per", "default", "." ]
c0d7cc5c03b6f884f63596c36c5e0aa86cd54141
https://github.com/michael-simons/wro4j-spring-boot-starter/blob/c0d7cc5c03b6f884f63596c36c5e0aa86cd54141/src/main/java/ac/simons/spring/boot/wro4j/Wro4jAutoConfiguration.java#L199-L205
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/crawldelaymechanism/AdaptiveCrawlDelayMechanism.java
AdaptiveCrawlDelayMechanism.getDelay
@Override public long getDelay() { long delayInMillis = (long) jsExecutor.executeScript(DELAY_CALCULATION_JS); if (delayInMillis < minDelayInMillis) { return minDelayInMillis; } else if (delayInMillis > maxDelayInMillis) { return maxDelayInMillis; } return delayInMillis; }
java
@Override public long getDelay() { long delayInMillis = (long) jsExecutor.executeScript(DELAY_CALCULATION_JS); if (delayInMillis < minDelayInMillis) { return minDelayInMillis; } else if (delayInMillis > maxDelayInMillis) { return maxDelayInMillis; } return delayInMillis; }
[ "@", "Override", "public", "long", "getDelay", "(", ")", "{", "long", "delayInMillis", "=", "(", "long", ")", "jsExecutor", ".", "executeScript", "(", "DELAY_CALCULATION_JS", ")", ";", "if", "(", "delayInMillis", "<", "minDelayInMillis", ")", "{", "return", ...
Calculates the page loading time and returns the delay accordingly, between the specified min-max range. If the calculated delay is smaller than the minimum, it returns the minimum delay. If the calculated delay is higher than the maximum, it returns the maximum delay. @return the delay in milliseconds
[ "Calculates", "the", "page", "loading", "time", "and", "returns", "the", "delay", "accordingly", "between", "the", "specified", "min", "-", "max", "range", ".", "If", "the", "calculated", "delay", "is", "smaller", "than", "the", "minimum", "it", "returns", "...
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/crawldelaymechanism/AdaptiveCrawlDelayMechanism.java#L65-L76
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/CrawlFrontier.java
CrawlFrontier.feedRequest
public void feedRequest(final CrawlRequest request, final boolean isCrawlSeed) { if (config.isOffsiteRequestFilteringEnabled()) { boolean inCrawlDomain = false; for (CrawlDomain allowedCrawlDomain : config.getAllowedCrawlDomains()) { if (allowedCrawlDomain.contains(request.getDomain())) { inCrawlDomain = true; break; } } if (!inCrawlDomain) { return; } } if (config.isDuplicateRequestFilteringEnabled()) { String urlFingerprint = createFingerprintForUrl(request.getRequestUrl()); if (urlFingerprints.contains(urlFingerprint)) { return; } urlFingerprints.add(urlFingerprint); } CrawlCandidateBuilder builder = new CrawlCandidateBuilder(request); if (!isCrawlSeed) { int crawlDepthLimit = config.getMaximumCrawlDepth(); int nextCrawlDepth = currentCandidate.getCrawlDepth() + 1; if (crawlDepthLimit != 0 && nextCrawlDepth > crawlDepthLimit) { return; } builder = builder .setRefererUrl(currentCandidate.getRequestUrl()) .setCrawlDepth(nextCrawlDepth); } candidates.add(builder.build()); }
java
public void feedRequest(final CrawlRequest request, final boolean isCrawlSeed) { if (config.isOffsiteRequestFilteringEnabled()) { boolean inCrawlDomain = false; for (CrawlDomain allowedCrawlDomain : config.getAllowedCrawlDomains()) { if (allowedCrawlDomain.contains(request.getDomain())) { inCrawlDomain = true; break; } } if (!inCrawlDomain) { return; } } if (config.isDuplicateRequestFilteringEnabled()) { String urlFingerprint = createFingerprintForUrl(request.getRequestUrl()); if (urlFingerprints.contains(urlFingerprint)) { return; } urlFingerprints.add(urlFingerprint); } CrawlCandidateBuilder builder = new CrawlCandidateBuilder(request); if (!isCrawlSeed) { int crawlDepthLimit = config.getMaximumCrawlDepth(); int nextCrawlDepth = currentCandidate.getCrawlDepth() + 1; if (crawlDepthLimit != 0 && nextCrawlDepth > crawlDepthLimit) { return; } builder = builder .setRefererUrl(currentCandidate.getRequestUrl()) .setCrawlDepth(nextCrawlDepth); } candidates.add(builder.build()); }
[ "public", "void", "feedRequest", "(", "final", "CrawlRequest", "request", ",", "final", "boolean", "isCrawlSeed", ")", "{", "if", "(", "config", ".", "isOffsiteRequestFilteringEnabled", "(", ")", ")", "{", "boolean", "inCrawlDomain", "=", "false", ";", "for", ...
Feeds a crawl request to the frontier. @param request the crawl request @param isCrawlSeed indicates if the request is a crawl seed
[ "Feeds", "a", "crawl", "request", "to", "the", "frontier", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/CrawlFrontier.java#L70-L112
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/CrawlFrontier.java
CrawlFrontier.createFingerprintForUrl
private static String createFingerprintForUrl(final URI url) { StringBuilder truncatedUrl = new StringBuilder(url.getHost()); String path = url.getPath(); if (path != null) { truncatedUrl.append(path); } String query = url.getQuery(); if (query != null) { truncatedUrl.append("?"); String[] queryParams = url.getQuery().split("&"); List<String> queryParamList = Arrays.asList(queryParams); queryParamList.stream() .sorted(String::compareToIgnoreCase) .forEachOrdered(truncatedUrl::append); } return DigestUtils.sha256Hex(truncatedUrl.toString()); }
java
private static String createFingerprintForUrl(final URI url) { StringBuilder truncatedUrl = new StringBuilder(url.getHost()); String path = url.getPath(); if (path != null) { truncatedUrl.append(path); } String query = url.getQuery(); if (query != null) { truncatedUrl.append("?"); String[] queryParams = url.getQuery().split("&"); List<String> queryParamList = Arrays.asList(queryParams); queryParamList.stream() .sorted(String::compareToIgnoreCase) .forEachOrdered(truncatedUrl::append); } return DigestUtils.sha256Hex(truncatedUrl.toString()); }
[ "private", "static", "String", "createFingerprintForUrl", "(", "final", "URI", "url", ")", "{", "StringBuilder", "truncatedUrl", "=", "new", "StringBuilder", "(", "url", ".", "getHost", "(", ")", ")", ";", "String", "path", "=", "url", ".", "getPath", "(", ...
Creates the fingerprint of the given URL. If the URL contains query parameters, it sorts them. This way URLs with different order of query parameters get the same fingerprint. @param url the URL for which the fingerprint is created @return the fingerprint of the URL
[ "Creates", "the", "fingerprint", "of", "the", "given", "URL", ".", "If", "the", "URL", "contains", "query", "parameters", "it", "sorts", "them", ".", "This", "way", "URLs", "with", "different", "order", "of", "query", "parameters", "get", "the", "same", "f...
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/CrawlFrontier.java#L141-L162
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/CrawlFrontier.java
CrawlFrontier.createPriorityQueue
@SuppressWarnings("checkstyle:MissingSwitchDefault") private PriorityQueue<CrawlCandidate> createPriorityQueue() { Function crawlDepthGetter = (Function<CrawlCandidate, Integer> & Serializable) CrawlCandidate::getCrawlDepth; Function priorityGetter = (Function<CrawlCandidate, Integer> & Serializable) CrawlCandidate::getPriority; switch (config.getCrawlStrategy()) { case BREADTH_FIRST: Comparator breadthFirstComparator = Comparator.comparing(crawlDepthGetter) .thenComparing(priorityGetter, Comparator.reverseOrder()); return new PriorityQueue<>(breadthFirstComparator); case DEPTH_FIRST: Comparator depthFirstComparator = Comparator.comparing(crawlDepthGetter, Comparator.reverseOrder()) .thenComparing(priorityGetter, Comparator.reverseOrder()); return new PriorityQueue<>(depthFirstComparator); } throw new IllegalArgumentException("Unsupported crawl strategy."); }
java
@SuppressWarnings("checkstyle:MissingSwitchDefault") private PriorityQueue<CrawlCandidate> createPriorityQueue() { Function crawlDepthGetter = (Function<CrawlCandidate, Integer> & Serializable) CrawlCandidate::getCrawlDepth; Function priorityGetter = (Function<CrawlCandidate, Integer> & Serializable) CrawlCandidate::getPriority; switch (config.getCrawlStrategy()) { case BREADTH_FIRST: Comparator breadthFirstComparator = Comparator.comparing(crawlDepthGetter) .thenComparing(priorityGetter, Comparator.reverseOrder()); return new PriorityQueue<>(breadthFirstComparator); case DEPTH_FIRST: Comparator depthFirstComparator = Comparator.comparing(crawlDepthGetter, Comparator.reverseOrder()) .thenComparing(priorityGetter, Comparator.reverseOrder()); return new PriorityQueue<>(depthFirstComparator); } throw new IllegalArgumentException("Unsupported crawl strategy."); }
[ "@", "SuppressWarnings", "(", "\"checkstyle:MissingSwitchDefault\"", ")", "private", "PriorityQueue", "<", "CrawlCandidate", ">", "createPriorityQueue", "(", ")", "{", "Function", "crawlDepthGetter", "=", "(", "Function", "<", "CrawlCandidate", ",", "Integer", ">", "&...
Creates a priority queue using the strategy specified in the configuration. @return the priority queue using the strategy specified in the configuration
[ "Creates", "a", "priority", "queue", "using", "the", "strategy", "specified", "in", "the", "configuration", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/CrawlFrontier.java#L169-L191
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/event/EventCallbackManager.java
EventCallbackManager.setDefaultEventCallback
public <T extends EventObject> void setDefaultEventCallback( final CrawlEvent event, final Consumer<T> callback) { defaultCallbacks.put(event, callback); }
java
public <T extends EventObject> void setDefaultEventCallback( final CrawlEvent event, final Consumer<T> callback) { defaultCallbacks.put(event, callback); }
[ "public", "<", "T", "extends", "EventObject", ">", "void", "setDefaultEventCallback", "(", "final", "CrawlEvent", "event", ",", "final", "Consumer", "<", "T", ">", "callback", ")", "{", "defaultCallbacks", ".", "put", "(", "event", ",", "callback", ")", ";",...
Sets the default callback for the specific event. @param <T> the type of the input to the operation @param event the event for which the callback should be invoked @param callback the operation to be performed
[ "Sets", "the", "default", "callback", "for", "the", "specific", "event", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/event/EventCallbackManager.java#L55-L59
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/event/EventCallbackManager.java
EventCallbackManager.addCustomEventCallback
public void addCustomEventCallback( final CrawlEvent event, final PatternMatchingCallback callback) { customCallbacks.computeIfAbsent(event, key -> new ArrayList<>()).add(callback); }
java
public void addCustomEventCallback( final CrawlEvent event, final PatternMatchingCallback callback) { customCallbacks.computeIfAbsent(event, key -> new ArrayList<>()).add(callback); }
[ "public", "void", "addCustomEventCallback", "(", "final", "CrawlEvent", "event", ",", "final", "PatternMatchingCallback", "callback", ")", "{", "customCallbacks", ".", "computeIfAbsent", "(", "event", ",", "key", "->", "new", "ArrayList", "<>", "(", ")", ")", "....
Associates a pattern matching callback with the specific event. @param event the event for which the callback should be invoked @param callback the pattern matching callback to invoke
[ "Associates", "a", "pattern", "matching", "callback", "with", "the", "specific", "event", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/event/EventCallbackManager.java#L67-L71
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/event/EventCallbackManager.java
EventCallbackManager.call
public <T extends EventObject> void call(final CrawlEvent event, final T eventObject) { if (!customCallbacks.containsKey(event)) { ((Consumer<T>) defaultCallbacks.get(event)).accept(eventObject); return; } String requestUrl = eventObject.getCrawlCandidate().getRequestUrl().toString(); List<PatternMatchingCallback> applicableCallbacks = customCallbacks.get(event) .stream() .filter(callback -> callback.getUrlPattern().matcher(requestUrl).matches()) .collect(Collectors.toList()); if (applicableCallbacks.isEmpty()) { ((Consumer<T>) defaultCallbacks.get(event)).accept(eventObject); return; } applicableCallbacks.stream() .map(PatternMatchingCallback::getCallback) .forEach(op -> op.accept(eventObject)); }
java
public <T extends EventObject> void call(final CrawlEvent event, final T eventObject) { if (!customCallbacks.containsKey(event)) { ((Consumer<T>) defaultCallbacks.get(event)).accept(eventObject); return; } String requestUrl = eventObject.getCrawlCandidate().getRequestUrl().toString(); List<PatternMatchingCallback> applicableCallbacks = customCallbacks.get(event) .stream() .filter(callback -> callback.getUrlPattern().matcher(requestUrl).matches()) .collect(Collectors.toList()); if (applicableCallbacks.isEmpty()) { ((Consumer<T>) defaultCallbacks.get(event)).accept(eventObject); return; } applicableCallbacks.stream() .map(PatternMatchingCallback::getCallback) .forEach(op -> op.accept(eventObject)); }
[ "public", "<", "T", "extends", "EventObject", ">", "void", "call", "(", "final", "CrawlEvent", "event", ",", "final", "T", "eventObject", ")", "{", "if", "(", "!", "customCallbacks", ".", "containsKey", "(", "event", ")", ")", "{", "(", "(", "Consumer", ...
Invokes the default callback for the specific event, if no custom callbacks are registered for it. Otherwise, it calls all the associated callbacks whose pattern matches the URL of the request. @param <T> the type of the input to the operation @param event the event for which the callback should be invoked @param eventObject the input parameter for the callback
[ "Invokes", "the", "default", "callback", "for", "the", "specific", "event", "if", "no", "custom", "callbacks", "are", "registered", "for", "it", ".", "Otherwise", "it", "calls", "all", "the", "associated", "callbacks", "whose", "pattern", "matches", "the", "UR...
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/event/EventCallbackManager.java#L82-L102
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.start
private void start(final WebDriver webDriver, final boolean isResuming) { try { Validate.validState(isStopped, "The crawler is already running."); this.webDriver = Validate.notNull(webDriver, "The webdriver cannot be null."); // If the crawl delay strategy is set to adaptive, we check if the browser supports the // Navigation Timing API or not. However HtmlUnit requires a page to be loaded first // before executing JavaScript, so we load a blank page. if (webDriver instanceof HtmlUnitDriver && config.getCrawlDelayStrategy().equals(CrawlDelayStrategy.ADAPTIVE)) { webDriver.get(WebClient.ABOUT_BLANK); } if (!isResuming) { crawlFrontier = new CrawlFrontier(config); } cookieStore = new BasicCookieStore(); httpClient = HttpClientBuilder.create() .setDefaultCookieStore(cookieStore) .useSystemProperties() .build(); crawlDelayMechanism = createCrawlDelayMechanism(); isStopped = false; run(); } finally { HttpClientUtils.closeQuietly(httpClient); if (this.webDriver != null) { this.webDriver.quit(); } isStopping = false; isStopped = true; } }
java
private void start(final WebDriver webDriver, final boolean isResuming) { try { Validate.validState(isStopped, "The crawler is already running."); this.webDriver = Validate.notNull(webDriver, "The webdriver cannot be null."); // If the crawl delay strategy is set to adaptive, we check if the browser supports the // Navigation Timing API or not. However HtmlUnit requires a page to be loaded first // before executing JavaScript, so we load a blank page. if (webDriver instanceof HtmlUnitDriver && config.getCrawlDelayStrategy().equals(CrawlDelayStrategy.ADAPTIVE)) { webDriver.get(WebClient.ABOUT_BLANK); } if (!isResuming) { crawlFrontier = new CrawlFrontier(config); } cookieStore = new BasicCookieStore(); httpClient = HttpClientBuilder.create() .setDefaultCookieStore(cookieStore) .useSystemProperties() .build(); crawlDelayMechanism = createCrawlDelayMechanism(); isStopped = false; run(); } finally { HttpClientUtils.closeQuietly(httpClient); if (this.webDriver != null) { this.webDriver.quit(); } isStopping = false; isStopped = true; } }
[ "private", "void", "start", "(", "final", "WebDriver", "webDriver", ",", "final", "boolean", "isResuming", ")", "{", "try", "{", "Validate", ".", "validState", "(", "isStopped", ",", "\"The crawler is already running.\"", ")", ";", "this", ".", "webDriver", "=",...
Performs initialization and runs the crawler. @param isResuming indicates if a previously saved state is to be resumed
[ "Performs", "initialization", "and", "runs", "the", "crawler", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L151-L187
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.saveState
public final void saveState(final OutputStream outStream) { Validate.validState(crawlFrontier != null, "Cannot save state at this point."); CrawlerState state = new CrawlerState(); state.putStateObject(config); state.putStateObject(crawlFrontier); SerializationUtils.serialize(state, outStream); }
java
public final void saveState(final OutputStream outStream) { Validate.validState(crawlFrontier != null, "Cannot save state at this point."); CrawlerState state = new CrawlerState(); state.putStateObject(config); state.putStateObject(crawlFrontier); SerializationUtils.serialize(state, outStream); }
[ "public", "final", "void", "saveState", "(", "final", "OutputStream", "outStream", ")", "{", "Validate", ".", "validState", "(", "crawlFrontier", "!=", "null", ",", "\"Cannot save state at this point.\"", ")", ";", "CrawlerState", "state", "=", "new", "CrawlerState"...
Saves the current state of the crawler to the given output stream. @param outStream the output stream
[ "Saves", "the", "current", "state", "of", "the", "crawler", "to", "the", "given", "output", "stream", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L194-L202
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.registerCustomEventCallback
protected final void registerCustomEventCallback( final CrawlEvent event, final PatternMatchingCallback callback) { Validate.notNull(event, "The event cannot be null."); Validate.notNull(callback, "The callback cannot be null."); callbackManager.addCustomEventCallback(event, callback); }
java
protected final void registerCustomEventCallback( final CrawlEvent event, final PatternMatchingCallback callback) { Validate.notNull(event, "The event cannot be null."); Validate.notNull(callback, "The callback cannot be null."); callbackManager.addCustomEventCallback(event, callback); }
[ "protected", "final", "void", "registerCustomEventCallback", "(", "final", "CrawlEvent", "event", ",", "final", "PatternMatchingCallback", "callback", ")", "{", "Validate", ".", "notNull", "(", "event", ",", "\"The event cannot be null.\"", ")", ";", "Validate", ".", ...
Registers an operation which is invoked when the specific event occurs and the provided pattern matches the request URL. @param event the event for which the callback should be triggered @param callback the pattern matching callback to invoke
[ "Registers", "an", "operation", "which", "is", "invoked", "when", "the", "specific", "event", "occurs", "and", "the", "provided", "pattern", "matches", "the", "request", "URL", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L231-L238
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.crawl
protected final void crawl(final CrawlRequest request) { Validate.validState(!isStopped, "The crawler is not started. Maybe you meant to add this request as a crawl seed?"); Validate.validState(!isStopping, "Cannot add request when the crawler is stopping."); Validate.notNull(request, "The request cannot be null."); crawlFrontier.feedRequest(request, false); }
java
protected final void crawl(final CrawlRequest request) { Validate.validState(!isStopped, "The crawler is not started. Maybe you meant to add this request as a crawl seed?"); Validate.validState(!isStopping, "Cannot add request when the crawler is stopping."); Validate.notNull(request, "The request cannot be null."); crawlFrontier.feedRequest(request, false); }
[ "protected", "final", "void", "crawl", "(", "final", "CrawlRequest", "request", ")", "{", "Validate", ".", "validState", "(", "!", "isStopped", ",", "\"The crawler is not started. Maybe you meant to add this request as a crawl seed?\"", ")", ";", "Validate", ".", "validSt...
Feeds a crawl request to the crawler. The crawler should be running, otherwise the request has to be added as a crawl seed instead. @param request the crawl request
[ "Feeds", "a", "crawl", "request", "to", "the", "crawler", ".", "The", "crawler", "should", "be", "running", "otherwise", "the", "request", "has", "to", "be", "added", "as", "a", "crawl", "seed", "instead", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L257-L264
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.downloadFile
protected final void downloadFile(final URI source, final File destination) throws IOException { Validate.validState(!isStopped, "Cannot download file when the crawler is not started."); Validate.validState(!isStopping, "Cannot download file when the crawler is stopping."); Validate.notNull(source, "The source URL cannot be null."); Validate.notNull(destination, "The destination file cannot be null."); HttpGet request = new HttpGet(source); try (CloseableHttpResponse response = httpClient.execute(request)) { HttpEntity entity = response.getEntity(); if (entity != null) { FileUtils.copyInputStreamToFile(entity.getContent(), destination); } } }
java
protected final void downloadFile(final URI source, final File destination) throws IOException { Validate.validState(!isStopped, "Cannot download file when the crawler is not started."); Validate.validState(!isStopping, "Cannot download file when the crawler is stopping."); Validate.notNull(source, "The source URL cannot be null."); Validate.notNull(destination, "The destination file cannot be null."); HttpGet request = new HttpGet(source); try (CloseableHttpResponse response = httpClient.execute(request)) { HttpEntity entity = response.getEntity(); if (entity != null) { FileUtils.copyInputStreamToFile(entity.getContent(), destination); } } }
[ "protected", "final", "void", "downloadFile", "(", "final", "URI", "source", ",", "final", "File", "destination", ")", "throws", "IOException", "{", "Validate", ".", "validState", "(", "!", "isStopped", ",", "\"Cannot download file when the crawler is not started.\"", ...
Downloads the file specified by the URL. @param source the source URL @param destination the destination file @throws IOException if an I/O error occurs while downloading the file
[ "Downloads", "the", "file", "specified", "by", "the", "URL", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L284-L297
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.run
private void run() { onStart(); while (!isStopping && crawlFrontier.hasNextCandidate()) { CrawlCandidate currentCandidate = crawlFrontier.getNextCandidate(); String candidateUrl = currentCandidate.getRequestUrl().toString(); HttpClientContext context = HttpClientContext.create(); CloseableHttpResponse httpHeadResponse = null; boolean isUnsuccessfulRequest = false; try { // Send an HTTP HEAD request to determine its availability and content type httpHeadResponse = getHttpHeadResponse(candidateUrl, context); } catch (IOException exception) { callbackManager.call(CrawlEvent.REQUEST_ERROR, new RequestErrorEvent(currentCandidate, exception)); isUnsuccessfulRequest = true; } if (!isUnsuccessfulRequest) { String responseUrl = getFinalResponseUrl(context, candidateUrl); if (responseUrl.equals(candidateUrl)) { String responseMimeType = getResponseMimeType(httpHeadResponse); if (responseMimeType.equals(ContentType.TEXT_HTML.getMimeType())) { boolean isTimedOut = false; TimeoutException timeoutException = null; try { // Open URL in browser webDriver.get(candidateUrl); } catch (TimeoutException exception) { isTimedOut = true; timeoutException = exception; } // Ensure the HTTP client and Selenium have the same state syncHttpClientCookies(); if (isTimedOut) { callbackManager.call(CrawlEvent.PAGE_LOAD_TIMEOUT, new PageLoadTimeoutEvent(currentCandidate, timeoutException)); } else { String loadedPageUrl = webDriver.getCurrentUrl(); if (!loadedPageUrl.equals(candidateUrl)) { // Create a new crawl request for the redirected URL (JS redirect) handleRequestRedirect(currentCandidate, loadedPageUrl); } else { callbackManager.call(CrawlEvent.PAGE_LOAD, new PageLoadEvent(currentCandidate, webDriver)); } } } else { // URLs that point to non-HTML content should not be opened in the browser callbackManager.call(CrawlEvent.NON_HTML_CONTENT, new NonHtmlContentEvent(currentCandidate, responseMimeType)); } } else { // Create a new crawl request for the redirected URL handleRequestRedirect(currentCandidate, responseUrl); } } HttpClientUtils.closeQuietly(httpHeadResponse); performDelay(); } onStop(); }
java
private void run() { onStart(); while (!isStopping && crawlFrontier.hasNextCandidate()) { CrawlCandidate currentCandidate = crawlFrontier.getNextCandidate(); String candidateUrl = currentCandidate.getRequestUrl().toString(); HttpClientContext context = HttpClientContext.create(); CloseableHttpResponse httpHeadResponse = null; boolean isUnsuccessfulRequest = false; try { // Send an HTTP HEAD request to determine its availability and content type httpHeadResponse = getHttpHeadResponse(candidateUrl, context); } catch (IOException exception) { callbackManager.call(CrawlEvent.REQUEST_ERROR, new RequestErrorEvent(currentCandidate, exception)); isUnsuccessfulRequest = true; } if (!isUnsuccessfulRequest) { String responseUrl = getFinalResponseUrl(context, candidateUrl); if (responseUrl.equals(candidateUrl)) { String responseMimeType = getResponseMimeType(httpHeadResponse); if (responseMimeType.equals(ContentType.TEXT_HTML.getMimeType())) { boolean isTimedOut = false; TimeoutException timeoutException = null; try { // Open URL in browser webDriver.get(candidateUrl); } catch (TimeoutException exception) { isTimedOut = true; timeoutException = exception; } // Ensure the HTTP client and Selenium have the same state syncHttpClientCookies(); if (isTimedOut) { callbackManager.call(CrawlEvent.PAGE_LOAD_TIMEOUT, new PageLoadTimeoutEvent(currentCandidate, timeoutException)); } else { String loadedPageUrl = webDriver.getCurrentUrl(); if (!loadedPageUrl.equals(candidateUrl)) { // Create a new crawl request for the redirected URL (JS redirect) handleRequestRedirect(currentCandidate, loadedPageUrl); } else { callbackManager.call(CrawlEvent.PAGE_LOAD, new PageLoadEvent(currentCandidate, webDriver)); } } } else { // URLs that point to non-HTML content should not be opened in the browser callbackManager.call(CrawlEvent.NON_HTML_CONTENT, new NonHtmlContentEvent(currentCandidate, responseMimeType)); } } else { // Create a new crawl request for the redirected URL handleRequestRedirect(currentCandidate, responseUrl); } } HttpClientUtils.closeQuietly(httpHeadResponse); performDelay(); } onStop(); }
[ "private", "void", "run", "(", ")", "{", "onStart", "(", ")", ";", "while", "(", "!", "isStopping", "&&", "crawlFrontier", ".", "hasNextCandidate", "(", ")", ")", "{", "CrawlCandidate", "currentCandidate", "=", "crawlFrontier", ".", "getNextCandidate", "(", ...
Defines the workflow of the crawler.
[ "Defines", "the", "workflow", "of", "the", "crawler", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L302-L369
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.createCrawlDelayMechanism
@SuppressWarnings("checkstyle:MissingSwitchDefault") private CrawlDelayMechanism createCrawlDelayMechanism() { switch (config.getCrawlDelayStrategy()) { case FIXED: return new FixedCrawlDelayMechanism(config); case RANDOM: return new RandomCrawlDelayMechanism(config); case ADAPTIVE: return new AdaptiveCrawlDelayMechanism(config, (JavascriptExecutor) webDriver); } throw new IllegalArgumentException("Unsupported crawl delay strategy."); }
java
@SuppressWarnings("checkstyle:MissingSwitchDefault") private CrawlDelayMechanism createCrawlDelayMechanism() { switch (config.getCrawlDelayStrategy()) { case FIXED: return new FixedCrawlDelayMechanism(config); case RANDOM: return new RandomCrawlDelayMechanism(config); case ADAPTIVE: return new AdaptiveCrawlDelayMechanism(config, (JavascriptExecutor) webDriver); } throw new IllegalArgumentException("Unsupported crawl delay strategy."); }
[ "@", "SuppressWarnings", "(", "\"checkstyle:MissingSwitchDefault\"", ")", "private", "CrawlDelayMechanism", "createCrawlDelayMechanism", "(", ")", "{", "switch", "(", "config", ".", "getCrawlDelayStrategy", "(", ")", ")", "{", "case", "FIXED", ":", "return", "new", ...
Creates the crawl delay mechanism according to the configuration. @return the created crawl delay mechanism
[ "Creates", "the", "crawl", "delay", "mechanism", "according", "to", "the", "configuration", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L376-L388
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.getHttpHeadResponse
private CloseableHttpResponse getHttpHeadResponse( final String destinationUrl, final HttpClientContext context) throws IOException { HttpHead request = new HttpHead(destinationUrl); return httpClient.execute(request, context); }
java
private CloseableHttpResponse getHttpHeadResponse( final String destinationUrl, final HttpClientContext context) throws IOException { HttpHead request = new HttpHead(destinationUrl); return httpClient.execute(request, context); }
[ "private", "CloseableHttpResponse", "getHttpHeadResponse", "(", "final", "String", "destinationUrl", ",", "final", "HttpClientContext", "context", ")", "throws", "IOException", "{", "HttpHead", "request", "=", "new", "HttpHead", "(", "destinationUrl", ")", ";", "retur...
Sends an HTTP HEAD request to the given URL and returns the response. @param destinationUrl the destination URL @return the HTTP HEAD response @throws IOException if an error occurs while trying to fulfill the request
[ "Sends", "an", "HTTP", "HEAD", "request", "to", "the", "given", "URL", "and", "returns", "the", "response", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L399-L404
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.getFinalResponseUrl
private static String getFinalResponseUrl( final HttpClientContext context, final String candidateUrl) { List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { return redirectLocations.get(redirectLocations.size() - 1).toString(); } return candidateUrl; }
java
private static String getFinalResponseUrl( final HttpClientContext context, final String candidateUrl) { List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { return redirectLocations.get(redirectLocations.size() - 1).toString(); } return candidateUrl; }
[ "private", "static", "String", "getFinalResponseUrl", "(", "final", "HttpClientContext", "context", ",", "final", "String", "candidateUrl", ")", "{", "List", "<", "URI", ">", "redirectLocations", "=", "context", ".", "getRedirectLocations", "(", ")", ";", "if", ...
If the HTTP HEAD request was redirected, it returns the final redirected URL. If not, it returns the original URL of the candidate. @param context the current HTTP client context @param candidateUrl the URL of the candidate @return the final response URL
[ "If", "the", "HTTP", "HEAD", "request", "was", "redirected", "it", "returns", "the", "final", "redirected", "URL", ".", "If", "not", "it", "returns", "the", "original", "URL", "of", "the", "candidate", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L415-L424
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.handleRequestRedirect
private void handleRequestRedirect( final CrawlCandidate currentCrawlCandidate, final String redirectedUrl) { CrawlRequestBuilder builder = new CrawlRequestBuilder(redirectedUrl) .setPriority(currentCrawlCandidate.getPriority()); currentCrawlCandidate.getMetadata().ifPresent(builder::setMetadata); CrawlRequest redirectedRequest = builder.build(); crawlFrontier.feedRequest(redirectedRequest, false); callbackManager.call(CrawlEvent.REQUEST_REDIRECT, new RequestRedirectEvent(currentCrawlCandidate, redirectedRequest)); }
java
private void handleRequestRedirect( final CrawlCandidate currentCrawlCandidate, final String redirectedUrl) { CrawlRequestBuilder builder = new CrawlRequestBuilder(redirectedUrl) .setPriority(currentCrawlCandidate.getPriority()); currentCrawlCandidate.getMetadata().ifPresent(builder::setMetadata); CrawlRequest redirectedRequest = builder.build(); crawlFrontier.feedRequest(redirectedRequest, false); callbackManager.call(CrawlEvent.REQUEST_REDIRECT, new RequestRedirectEvent(currentCrawlCandidate, redirectedRequest)); }
[ "private", "void", "handleRequestRedirect", "(", "final", "CrawlCandidate", "currentCrawlCandidate", ",", "final", "String", "redirectedUrl", ")", "{", "CrawlRequestBuilder", "builder", "=", "new", "CrawlRequestBuilder", "(", "redirectedUrl", ")", ".", "setPriority", "(...
Creates a crawl request for the redirected URL, feeds it to the crawler and calls the appropriate event callback. @param currentCrawlCandidate the current crawl candidate @param redirectedUrl the URL of the redirected request
[ "Creates", "a", "crawl", "request", "for", "the", "redirected", "URL", "feeds", "it", "to", "the", "crawler", "and", "calls", "the", "appropriate", "event", "callback", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L457-L468
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.syncHttpClientCookies
private void syncHttpClientCookies() { webDriver.manage() .getCookies() .stream() .map(CookieConverter::convertToHttpClientCookie) .forEach(cookieStore::addCookie); }
java
private void syncHttpClientCookies() { webDriver.manage() .getCookies() .stream() .map(CookieConverter::convertToHttpClientCookie) .forEach(cookieStore::addCookie); }
[ "private", "void", "syncHttpClientCookies", "(", ")", "{", "webDriver", ".", "manage", "(", ")", ".", "getCookies", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "CookieConverter", "::", "convertToHttpClientCookie", ")", ".", "forEach", "(", "cookieSto...
Copies all the Selenium cookies for the current domain to the HTTP client cookie store.
[ "Copies", "all", "the", "Selenium", "cookies", "for", "the", "current", "domain", "to", "the", "HTTP", "client", "cookie", "store", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L473-L479
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.performDelay
private void performDelay() { try { TimeUnit.MILLISECONDS.sleep(crawlDelayMechanism.getDelay()); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); isStopping = true; } }
java
private void performDelay() { try { TimeUnit.MILLISECONDS.sleep(crawlDelayMechanism.getDelay()); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); isStopping = true; } }
[ "private", "void", "performDelay", "(", ")", "{", "try", "{", "TimeUnit", ".", "MILLISECONDS", ".", "sleep", "(", "crawlDelayMechanism", ".", "getDelay", "(", ")", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "Thread", ".", "current...
Delays the next request.
[ "Delays", "the", "next", "request", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L484-L491
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.onPageLoad
protected void onPageLoad(final PageLoadEvent event) { LOGGER.log(Level.INFO, "onPageLoad: {0}", event.getCrawlCandidate().getRequestUrl()); }
java
protected void onPageLoad(final PageLoadEvent event) { LOGGER.log(Level.INFO, "onPageLoad: {0}", event.getCrawlCandidate().getRequestUrl()); }
[ "protected", "void", "onPageLoad", "(", "final", "PageLoadEvent", "event", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "INFO", ",", "\"onPageLoad: {0}\"", ",", "event", ".", "getCrawlCandidate", "(", ")", ".", "getRequestUrl", "(", ")", ")", ";", "}...
Callback which gets called when the browser loads the page. @param event the <code>PageLoadEvent</code> instance
[ "Callback", "which", "gets", "called", "when", "the", "browser", "loads", "the", "page", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L505-L507
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.onNonHtmlContent
protected void onNonHtmlContent(final NonHtmlContentEvent event) { LOGGER.log(Level.INFO, "onNonHtmlContent: {0}", event.getCrawlCandidate().getRequestUrl()); }
java
protected void onNonHtmlContent(final NonHtmlContentEvent event) { LOGGER.log(Level.INFO, "onNonHtmlContent: {0}", event.getCrawlCandidate().getRequestUrl()); }
[ "protected", "void", "onNonHtmlContent", "(", "final", "NonHtmlContentEvent", "event", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "INFO", ",", "\"onNonHtmlContent: {0}\"", ",", "event", ".", "getCrawlCandidate", "(", ")", ".", "getRequestUrl", "(", ")", ...
Callback which gets called when the content type is not HTML. @param event the <code>NonHtmlContentEvent</code> instance
[ "Callback", "which", "gets", "called", "when", "the", "content", "type", "is", "not", "HTML", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L514-L516
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.onRequestError
protected void onRequestError(final RequestErrorEvent event) { LOGGER.log(Level.INFO, "onRequestError: {0}", event.getCrawlCandidate().getRequestUrl()); }
java
protected void onRequestError(final RequestErrorEvent event) { LOGGER.log(Level.INFO, "onRequestError: {0}", event.getCrawlCandidate().getRequestUrl()); }
[ "protected", "void", "onRequestError", "(", "final", "RequestErrorEvent", "event", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "INFO", ",", "\"onRequestError: {0}\"", ",", "event", ".", "getCrawlCandidate", "(", ")", ".", "getRequestUrl", "(", ")", ")",...
Callback which gets called when a request error occurs. @param event the <code>RequestErrorEvent</code> instance
[ "Callback", "which", "gets", "called", "when", "a", "request", "error", "occurs", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L523-L525
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.onRequestRedirect
protected void onRequestRedirect(final RequestRedirectEvent event) { LOGGER.log(Level.INFO, "onRequestRedirect: {0} -> {1}", new Object[]{ event.getCrawlCandidate().getRequestUrl(), event.getRedirectedCrawlRequest().getRequestUrl() }); }
java
protected void onRequestRedirect(final RequestRedirectEvent event) { LOGGER.log(Level.INFO, "onRequestRedirect: {0} -> {1}", new Object[]{ event.getCrawlCandidate().getRequestUrl(), event.getRedirectedCrawlRequest().getRequestUrl() }); }
[ "protected", "void", "onRequestRedirect", "(", "final", "RequestRedirectEvent", "event", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "INFO", ",", "\"onRequestRedirect: {0} -> {1}\"", ",", "new", "Object", "[", "]", "{", "event", ".", "getCrawlCandidate", ...
Callback which gets called when a request is redirected. @param event the <code>RequestRedirectEvent</code> instance
[ "Callback", "which", "gets", "called", "when", "a", "request", "is", "redirected", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L532-L538
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.onPageLoadTimeout
protected void onPageLoadTimeout(final PageLoadTimeoutEvent event) { LOGGER.log(Level.INFO, "onPageLoadTimeout: {0}", event.getCrawlCandidate().getRequestUrl()); }
java
protected void onPageLoadTimeout(final PageLoadTimeoutEvent event) { LOGGER.log(Level.INFO, "onPageLoadTimeout: {0}", event.getCrawlCandidate().getRequestUrl()); }
[ "protected", "void", "onPageLoadTimeout", "(", "final", "PageLoadTimeoutEvent", "event", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "INFO", ",", "\"onPageLoadTimeout: {0}\"", ",", "event", ".", "getCrawlCandidate", "(", ")", ".", "getRequestUrl", "(", ")...
Callback which gets called when the page does not load in the browser within the timeout period. @param event the <code>PageLoadTimeoutEvent</code> instance
[ "Callback", "which", "gets", "called", "when", "the", "page", "does", "not", "load", "in", "the", "browser", "within", "the", "timeout", "period", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L546-L548
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/CrawlDomain.java
CrawlDomain.contains
public boolean contains(final InternetDomainName domain) { ImmutableList<String> otherDomainParts = domain.parts(); if (parts.size() > otherDomainParts.size()) { return false; } otherDomainParts = otherDomainParts.reverse() .subList(0, parts.size()); return parts.reverse() .equals(otherDomainParts); }
java
public boolean contains(final InternetDomainName domain) { ImmutableList<String> otherDomainParts = domain.parts(); if (parts.size() > otherDomainParts.size()) { return false; } otherDomainParts = otherDomainParts.reverse() .subList(0, parts.size()); return parts.reverse() .equals(otherDomainParts); }
[ "public", "boolean", "contains", "(", "final", "InternetDomainName", "domain", ")", "{", "ImmutableList", "<", "String", ">", "otherDomainParts", "=", "domain", ".", "parts", "(", ")", ";", "if", "(", "parts", ".", "size", "(", ")", ">", "otherDomainParts", ...
Indicates if this crawl domain contains the specific internet domain. @param domain an immutable well-formed internet domain name @return <code>true</code> if belongs, <code>false</code> otherwise
[ "Indicates", "if", "this", "crawl", "domain", "contains", "the", "specific", "internet", "domain", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/CrawlDomain.java#L80-L92
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/CookieConverter.java
CookieConverter.convertToHttpClientCookie
public static BasicClientCookie convertToHttpClientCookie(final Cookie seleniumCookie) { BasicClientCookie httpClientCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue()); httpClientCookie.setDomain(seleniumCookie.getDomain()); httpClientCookie.setPath(seleniumCookie.getPath()); httpClientCookie.setExpiryDate(seleniumCookie.getExpiry()); httpClientCookie.setSecure(seleniumCookie.isSecure()); if (seleniumCookie.isHttpOnly()) { httpClientCookie.setAttribute(HTTP_ONLY_ATTRIBUTE, StringUtils.EMPTY); } return httpClientCookie; }
java
public static BasicClientCookie convertToHttpClientCookie(final Cookie seleniumCookie) { BasicClientCookie httpClientCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue()); httpClientCookie.setDomain(seleniumCookie.getDomain()); httpClientCookie.setPath(seleniumCookie.getPath()); httpClientCookie.setExpiryDate(seleniumCookie.getExpiry()); httpClientCookie.setSecure(seleniumCookie.isSecure()); if (seleniumCookie.isHttpOnly()) { httpClientCookie.setAttribute(HTTP_ONLY_ATTRIBUTE, StringUtils.EMPTY); } return httpClientCookie; }
[ "public", "static", "BasicClientCookie", "convertToHttpClientCookie", "(", "final", "Cookie", "seleniumCookie", ")", "{", "BasicClientCookie", "httpClientCookie", "=", "new", "BasicClientCookie", "(", "seleniumCookie", ".", "getName", "(", ")", ",", "seleniumCookie", "....
Converts a Selenium cookie to a HTTP client one. @param seleniumCookie the browser cookie to be converted @return the converted HTTP client cookie
[ "Converts", "a", "Selenium", "cookie", "to", "a", "HTTP", "client", "one", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/CookieConverter.java#L39-L52
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/helper/UrlFinder.java
UrlFinder.findUrlsInPage
public List<String> findUrlsInPage(final PageLoadEvent event) { Set<String> foundUrls = new HashSet<>(); // Find elements using the specified locating mechanisms Set<WebElement> extractedElements = locatingMechanisms.stream() .map(event.getWebDriver()::findElements) .flatMap(List::stream) .collect(Collectors.toSet()); // Find URLs in the attribute values of the found elements extractedElements.forEach((WebElement element) -> { attributes.stream() .map(element::getAttribute) .filter(StringUtils::isNotBlank) .map(this::findUrlsInAttributeValue) .flatMap(List::stream) .forEach(foundUrls::add); }); return foundUrls.stream() .collect(Collectors.toList()); }
java
public List<String> findUrlsInPage(final PageLoadEvent event) { Set<String> foundUrls = new HashSet<>(); // Find elements using the specified locating mechanisms Set<WebElement> extractedElements = locatingMechanisms.stream() .map(event.getWebDriver()::findElements) .flatMap(List::stream) .collect(Collectors.toSet()); // Find URLs in the attribute values of the found elements extractedElements.forEach((WebElement element) -> { attributes.stream() .map(element::getAttribute) .filter(StringUtils::isNotBlank) .map(this::findUrlsInAttributeValue) .flatMap(List::stream) .forEach(foundUrls::add); }); return foundUrls.stream() .collect(Collectors.toList()); }
[ "public", "List", "<", "String", ">", "findUrlsInPage", "(", "final", "PageLoadEvent", "event", ")", "{", "Set", "<", "String", ">", "foundUrls", "=", "new", "HashSet", "<>", "(", ")", ";", "// Find elements using the specified locating mechanisms", "Set", "<", ...
Returns a list of validated URLs found in the page's HTML source. @param event the <code>PageLoadEvent</code> instance @return the list of found URLs
[ "Returns", "a", "list", "of", "validated", "URLs", "found", "in", "the", "page", "s", "HTML", "source", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/helper/UrlFinder.java#L73-L94
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/helper/UrlFinder.java
UrlFinder.findUrlsInAttributeValue
private List<String> findUrlsInAttributeValue(final String attributeValue) { List<String> foundUrls = new ArrayList<>(); urlPatterns.stream() .map((Pattern urlPattern) -> urlPattern.matcher(attributeValue)) .forEach((Matcher urlPatternMatcher) -> { while (urlPatternMatcher.find()) { String foundUrl = urlPatternMatcher.group().trim(); if (validator.test(foundUrl)) { foundUrls.add(foundUrl); } } }); return foundUrls; }
java
private List<String> findUrlsInAttributeValue(final String attributeValue) { List<String> foundUrls = new ArrayList<>(); urlPatterns.stream() .map((Pattern urlPattern) -> urlPattern.matcher(attributeValue)) .forEach((Matcher urlPatternMatcher) -> { while (urlPatternMatcher.find()) { String foundUrl = urlPatternMatcher.group().trim(); if (validator.test(foundUrl)) { foundUrls.add(foundUrl); } } }); return foundUrls; }
[ "private", "List", "<", "String", ">", "findUrlsInAttributeValue", "(", "final", "String", "attributeValue", ")", "{", "List", "<", "String", ">", "foundUrls", "=", "new", "ArrayList", "<>", "(", ")", ";", "urlPatterns", ".", "stream", "(", ")", ".", "map"...
Returns a list of validated URLs found in the attribute's value. @param attributeValue the value of the attribute @return the list of found URLs
[ "Returns", "a", "list", "of", "validated", "URLs", "found", "in", "the", "attribute", "s", "value", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/helper/UrlFinder.java#L103-L119
train
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/internal/CrawlerState.java
CrawlerState.getStateObject
public <T extends Serializable> T getStateObject(final Class<T> stateObjectClass) { return (T) stateObjects.get(stateObjectClass); }
java
public <T extends Serializable> T getStateObject(final Class<T> stateObjectClass) { return (T) stateObjects.get(stateObjectClass); }
[ "public", "<", "T", "extends", "Serializable", ">", "T", "getStateObject", "(", "final", "Class", "<", "T", ">", "stateObjectClass", ")", "{", "return", "(", "T", ")", "stateObjects", ".", "get", "(", "stateObjectClass", ")", ";", "}" ]
Returns the state object specified by its class. @param <T> the type of the state object @param stateObjectClass the runtime class of the state object @return the state object specified by its class
[ "Returns", "the", "state", "object", "specified", "by", "its", "class", "." ]
10ed6f82c90fa1dccd684382b68b5d77a37652c0
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/internal/CrawlerState.java#L57-L59
train
pwittchen/kirai
src/main/java/com/github/pwittchen/kirai/library/Preconditions.java
Preconditions.checkNotEmpty
public static void checkNotEmpty(CharSequence str, String message) { if (str == null || str.length() == 0) { throw new IllegalArgumentException(message); } }
java
public static void checkNotEmpty(CharSequence str, String message) { if (str == null || str.length() == 0) { throw new IllegalArgumentException(message); } }
[ "public", "static", "void", "checkNotEmpty", "(", "CharSequence", "str", ",", "String", "message", ")", "{", "if", "(", "str", "==", "null", "||", "str", ".", "length", "(", ")", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "mess...
Throws an exception with a message, when CharSequence is null @param str is a CharSequence to examine @param message for IllegalArgumentException
[ "Throws", "an", "exception", "with", "a", "message", "when", "CharSequence", "is", "null" ]
0b8080a1f28c1e068a00e5bd2804dc3d2fb3c334
https://github.com/pwittchen/kirai/blob/0b8080a1f28c1e068a00e5bd2804dc3d2fb3c334/src/main/java/com/github/pwittchen/kirai/library/Preconditions.java#L25-L29
train
pwittchen/kirai
src/main/java/com/github/pwittchen/kirai/library/Kirai.java
Kirai.format
public CharSequence format(Formatter formatter) { CharSequence input = format(); return formatter.format(String.valueOf(input)); }
java
public CharSequence format(Formatter formatter) { CharSequence input = format(); return formatter.format(String.valueOf(input)); }
[ "public", "CharSequence", "format", "(", "Formatter", "formatter", ")", "{", "CharSequence", "input", "=", "format", "(", ")", ";", "return", "formatter", ".", "format", "(", "String", ".", "valueOf", "(", "input", ")", ")", ";", "}" ]
Returns CharSequence formatted with custom formatter implementation @param formatter implementation @return formatted CharSequence
[ "Returns", "CharSequence", "formatted", "with", "custom", "formatter", "implementation" ]
0b8080a1f28c1e068a00e5bd2804dc3d2fb3c334
https://github.com/pwittchen/kirai/blob/0b8080a1f28c1e068a00e5bd2804dc3d2fb3c334/src/main/java/com/github/pwittchen/kirai/library/Kirai.java#L123-L126
train
pwittchen/kirai
src/main/java/com/github/pwittchen/kirai/library/Kirai.java
Kirai.format
public CharSequence format() { if (pieces.isEmpty()) { return input; } String target; for (Piece piece : pieces) { target = BRACE_START + piece.getKey() + BRACE_END; input = input.replace(target, String.valueOf(piece.getValue())); } return input; }
java
public CharSequence format() { if (pieces.isEmpty()) { return input; } String target; for (Piece piece : pieces) { target = BRACE_START + piece.getKey() + BRACE_END; input = input.replace(target, String.valueOf(piece.getValue())); } return input; }
[ "public", "CharSequence", "format", "(", ")", "{", "if", "(", "pieces", ".", "isEmpty", "(", ")", ")", "{", "return", "input", ";", "}", "String", "target", ";", "for", "(", "Piece", "piece", ":", "pieces", ")", "{", "target", "=", "BRACE_START", "+"...
Returns formatted CharSequence without additional operations @return formatted CharSequence
[ "Returns", "formatted", "CharSequence", "without", "additional", "operations" ]
0b8080a1f28c1e068a00e5bd2804dc3d2fb3c334
https://github.com/pwittchen/kirai/blob/0b8080a1f28c1e068a00e5bd2804dc3d2fb3c334/src/main/java/com/github/pwittchen/kirai/library/Kirai.java#L133-L146
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.setHref
public EntityBuilder setHref(String href) { if(StringUtils.isBlank(href)) { throw new IllegalArgumentException("href cannot be null or empty."); } addStep("setHref", new Object[] { href }); isEmbedded = true; return this; }
java
public EntityBuilder setHref(String href) { if(StringUtils.isBlank(href)) { throw new IllegalArgumentException("href cannot be null or empty."); } addStep("setHref", new Object[] { href }); isEmbedded = true; return this; }
[ "public", "EntityBuilder", "setHref", "(", "String", "href", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "href", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"href cannot be null or empty.\"", ")", ";", "}", "addStep", "(", "\...
Set the href of the entity to be built. This method can be called many times but only the value of the last call is used in the built entity. This is a required property if this entity is an embedded link, as specified by the Siren specification. If set then this entity will be considered an embedded link. @param href cannot be <code>null</code> or empty. @return <code>this</code> builder, never <code>null</code>.
[ "Set", "the", "href", "of", "the", "entity", "to", "be", "built", ".", "This", "method", "can", "be", "called", "many", "times", "but", "only", "the", "value", "of", "the", "last", "call", "is", "used", "in", "the", "built", "entity", ".", "This", "i...
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L145-L152
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.addProperty
public EntityBuilder addProperty(String name, Object value) { if(StringUtils.isBlank(name)) { throw new IllegalArgumentException("name cannot be null or empty."); } addStep("_addProperty", new Object[] { name, value }, new Class<?>[]{String.class, Object.class}, true); return this; }
java
public EntityBuilder addProperty(String name, Object value) { if(StringUtils.isBlank(name)) { throw new IllegalArgumentException("name cannot be null or empty."); } addStep("_addProperty", new Object[] { name, value }, new Class<?>[]{String.class, Object.class}, true); return this; }
[ "public", "EntityBuilder", "addProperty", "(", "String", "name", ",", "Object", "value", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "name", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"name cannot be null or empty.\"", ")", ";...
Adds a single property to the entity to be built. Properties are optional according to the Siren specification. @param name cannot be <code>null</code> or empty. @param value may be <code>null</code> or empty. @return <code>this</code> builder, never <code>null</code>.
[ "Adds", "a", "single", "property", "to", "the", "entity", "to", "be", "built", ".", "Properties", "are", "optional", "according", "to", "the", "Siren", "specification", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L161-L167
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.addProperties
public EntityBuilder addProperties(Map<String, Object> properties) { if(MapUtils.isEmpty(properties)) { throw new IllegalArgumentException("properties cannot be null or empty."); } for (String key : properties.keySet()) { addProperty(key, properties.get(key)); } return this; }
java
public EntityBuilder addProperties(Map<String, Object> properties) { if(MapUtils.isEmpty(properties)) { throw new IllegalArgumentException("properties cannot be null or empty."); } for (String key : properties.keySet()) { addProperty(key, properties.get(key)); } return this; }
[ "public", "EntityBuilder", "addProperties", "(", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "if", "(", "MapUtils", ".", "isEmpty", "(", "properties", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"properties cannot be n...
Adds a map of properties to the entity to be built. Properties are optional according to the Siren specification. @param properties cannot be <code>null</code>. @return <code>this</code> builder, never <code>null</code>.
[ "Adds", "a", "map", "of", "properties", "to", "the", "entity", "to", "be", "built", ".", "Properties", "are", "optional", "according", "to", "the", "Siren", "specification", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L175-L183
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.addSubEntity
public EntityBuilder addSubEntity(Entity subEntity) { if(subEntity == null) { throw new IllegalArgumentException("subEntity cannot be null."); } addStep("_addEntity", new Object[] { subEntity }, true); return this; }
java
public EntityBuilder addSubEntity(Entity subEntity) { if(subEntity == null) { throw new IllegalArgumentException("subEntity cannot be null."); } addStep("_addEntity", new Object[] { subEntity }, true); return this; }
[ "public", "EntityBuilder", "addSubEntity", "(", "Entity", "subEntity", ")", "{", "if", "(", "subEntity", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"subEntity cannot be null.\"", ")", ";", "}", "addStep", "(", "\"_addEntity\"", ",",...
Add a sub entity to the entity to be built. Sub entities are optional according to the Siren specification. @param subEntity cannot be <code>null</code>. @return <code>this</code> builder, never <code>null</code>.
[ "Add", "a", "sub", "entity", "to", "the", "entity", "to", "be", "built", ".", "Sub", "entities", "are", "optional", "according", "to", "the", "Siren", "specification", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L191-L197
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.addSubEntities
public EntityBuilder addSubEntities(List<Entity> entities) { if(entities == null) { throw new IllegalArgumentException("entities cannot be null."); } for (Entity entity : entities) { addSubEntity(entity); } return this; }
java
public EntityBuilder addSubEntities(List<Entity> entities) { if(entities == null) { throw new IllegalArgumentException("entities cannot be null."); } for (Entity entity : entities) { addSubEntity(entity); } return this; }
[ "public", "EntityBuilder", "addSubEntities", "(", "List", "<", "Entity", ">", "entities", ")", "{", "if", "(", "entities", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"entities cannot be null.\"", ")", ";", "}", "for", "(", "Enti...
Add a list of sub entities to the entity to be built. Sub entities are optional according to the Siren specification. @param entities cannot be <code>null</code>, may be empty. @return <code>this</code> builder, never <code>null</code>.
[ "Add", "a", "list", "of", "sub", "entities", "to", "the", "entity", "to", "be", "built", ".", "Sub", "entities", "are", "optional", "according", "to", "the", "Siren", "specification", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L205-L213
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.addLink
public EntityBuilder addLink(Link link) { if(link == null) { throw new IllegalArgumentException("link cannot be null."); } addStep("_addLink", new Object[] { link }, true); return this; }
java
public EntityBuilder addLink(Link link) { if(link == null) { throw new IllegalArgumentException("link cannot be null."); } addStep("_addLink", new Object[] { link }, true); return this; }
[ "public", "EntityBuilder", "addLink", "(", "Link", "link", ")", "{", "if", "(", "link", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"link cannot be null.\"", ")", ";", "}", "addStep", "(", "\"_addLink\"", ",", "new", "Object", ...
Add a link to the entity to be built. Links are optional according to the Siren specification, however an entity should always have a 'self' link to be considered HATEAOS compliant. @param link cannot be <code>null</code> or empty. @return <code>this</code> builder, never <code>null</code>.
[ "Add", "a", "link", "to", "the", "entity", "to", "be", "built", ".", "Links", "are", "optional", "according", "to", "the", "Siren", "specification", "however", "an", "entity", "should", "always", "have", "a", "self", "link", "to", "be", "considered", "HATE...
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L221-L227
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.addLinks
public EntityBuilder addLinks(List<Link> links) { if(links == null) { throw new IllegalArgumentException("links cannot be null."); } for (Link link : links) { addLink(link); } return this; }
java
public EntityBuilder addLinks(List<Link> links) { if(links == null) { throw new IllegalArgumentException("links cannot be null."); } for (Link link : links) { addLink(link); } return this; }
[ "public", "EntityBuilder", "addLinks", "(", "List", "<", "Link", ">", "links", ")", "{", "if", "(", "links", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"links cannot be null.\"", ")", ";", "}", "for", "(", "Link", "link", ":...
Adds list of links to the entity to be built. Links are optional according to the Siren specification, however an entity should always have a 'self' link to be considered HATEAOS compliant. @param links cannot be <code>null</code>, may be empty. @return <code>this</code> builder, never <code>null</code>.
[ "Adds", "list", "of", "links", "to", "the", "entity", "to", "be", "built", ".", "Links", "are", "optional", "according", "to", "the", "Siren", "specification", "however", "an", "entity", "should", "always", "have", "a", "self", "link", "to", "be", "conside...
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L235-L243
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.addAction
public EntityBuilder addAction(Action action) { if(action == null) { throw new IllegalArgumentException("action cannot be null."); } addStep("_addAction", new Object[] { action }, true); return this; }
java
public EntityBuilder addAction(Action action) { if(action == null) { throw new IllegalArgumentException("action cannot be null."); } addStep("_addAction", new Object[] { action }, true); return this; }
[ "public", "EntityBuilder", "addAction", "(", "Action", "action", ")", "{", "if", "(", "action", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"action cannot be null.\"", ")", ";", "}", "addStep", "(", "\"_addAction\"", ",", "new", ...
Add an action to the entity to be built. Actions are options according to the Siren specification. @param action cannot be <code>null</code>. @return <code>this</code> builder, never <code>null</code>.
[ "Add", "an", "action", "to", "the", "entity", "to", "be", "built", ".", "Actions", "are", "options", "according", "to", "the", "Siren", "specification", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L250-L256
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.addActions
public EntityBuilder addActions(List<Action> actions) { if(actions == null) { throw new IllegalArgumentException("actions cannot be null."); } for (Action action : actions) { addAction(action); } return this; }
java
public EntityBuilder addActions(List<Action> actions) { if(actions == null) { throw new IllegalArgumentException("actions cannot be null."); } for (Action action : actions) { addAction(action); } return this; }
[ "public", "EntityBuilder", "addActions", "(", "List", "<", "Action", ">", "actions", ")", "{", "if", "(", "actions", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"actions cannot be null.\"", ")", ";", "}", "for", "(", "Action", ...
Add a list of actions to the entity to be built. Actions are options according to the Siren specification. @param actions cannot be <code>null</code>, may be empty. @return <code>this</code> builder, never <code>null</code>.
[ "Add", "a", "list", "of", "actions", "to", "the", "entity", "to", "be", "built", ".", "Actions", "are", "options", "according", "to", "the", "Siren", "specification", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L263-L271
train
eserating/siren4j
src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java
EntityBuilder.validateSubEntities
private void validateSubEntities(Entity obj) { // Validate that all sub entities have a "rel" set. String relRequired = "Sub entities are required to have a <rel> property set."; String hrefReqForEmbed = "Sub entities that are embedded links are required to have a <href> property set."; if (!CollectionUtils.isEmpty(obj.getEntities())) { for (Entity e : obj.getEntities()) { if (e.getRel() == null || ArrayUtils.isEmpty(e.getRel())) { throw new Siren4JBuilderValidationException("entities", obj.getClass(), relRequired); } if ((e instanceof EmbeddedEntityImpl) && StringUtils.isBlank(e.getHref())) { throw new Siren4JBuilderValidationException("entities", obj.getClass(), hrefReqForEmbed); } } } }
java
private void validateSubEntities(Entity obj) { // Validate that all sub entities have a "rel" set. String relRequired = "Sub entities are required to have a <rel> property set."; String hrefReqForEmbed = "Sub entities that are embedded links are required to have a <href> property set."; if (!CollectionUtils.isEmpty(obj.getEntities())) { for (Entity e : obj.getEntities()) { if (e.getRel() == null || ArrayUtils.isEmpty(e.getRel())) { throw new Siren4JBuilderValidationException("entities", obj.getClass(), relRequired); } if ((e instanceof EmbeddedEntityImpl) && StringUtils.isBlank(e.getHref())) { throw new Siren4JBuilderValidationException("entities", obj.getClass(), hrefReqForEmbed); } } } }
[ "private", "void", "validateSubEntities", "(", "Entity", "obj", ")", "{", "// Validate that all sub entities have a \"rel\" set.\r", "String", "relRequired", "=", "\"Sub entities are required to have a <rel> property set.\"", ";", "String", "hrefReqForEmbed", "=", "\"Sub entities t...
Validate sub entities ensuring the existence of a relationship and if an embedded link then ensure the existence of an href. @param obj assumed not <code>null</code>.
[ "Validate", "sub", "entities", "ensuring", "the", "existence", "of", "a", "relationship", "and", "if", "an", "embedded", "link", "then", "ensure", "the", "existence", "of", "an", "href", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/EntityBuilder.java#L324-L338
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.handleSetProperties
private void handleSetProperties(Object obj, Class<?> clazz, Entity entity, List<ReflectedInfo> fieldInfo) throws Siren4JConversionException { if (!MapUtils.isEmpty(entity.getProperties())) { for (String key : entity.getProperties().keySet()) { if (key.startsWith(Siren4J.CLASS_RESERVED_PROPERTY)) { continue; } ReflectedInfo info = ReflectionUtils.getFieldInfoByEffectiveName(fieldInfo, key); if (info == null) { info = ReflectionUtils.getFieldInfoByName(fieldInfo, key); } if (info != null) { Object val = entity.getProperties().get(key); try { ReflectionUtils.setFieldValue(obj, info, val); } catch (Siren4JException e) { throw new Siren4JConversionException(e); } } else if (isErrorOnMissingProperty() && !(obj instanceof Collection && key.equals("size"))) { //Houston we have a problem!! throw new Siren4JConversionException( "Unable to find field: " + key + " for class: " + clazz.getName()); } } } }
java
private void handleSetProperties(Object obj, Class<?> clazz, Entity entity, List<ReflectedInfo> fieldInfo) throws Siren4JConversionException { if (!MapUtils.isEmpty(entity.getProperties())) { for (String key : entity.getProperties().keySet()) { if (key.startsWith(Siren4J.CLASS_RESERVED_PROPERTY)) { continue; } ReflectedInfo info = ReflectionUtils.getFieldInfoByEffectiveName(fieldInfo, key); if (info == null) { info = ReflectionUtils.getFieldInfoByName(fieldInfo, key); } if (info != null) { Object val = entity.getProperties().get(key); try { ReflectionUtils.setFieldValue(obj, info, val); } catch (Siren4JException e) { throw new Siren4JConversionException(e); } } else if (isErrorOnMissingProperty() && !(obj instanceof Collection && key.equals("size"))) { //Houston we have a problem!! throw new Siren4JConversionException( "Unable to find field: " + key + " for class: " + clazz.getName()); } } } }
[ "private", "void", "handleSetProperties", "(", "Object", "obj", ",", "Class", "<", "?", ">", "clazz", ",", "Entity", "entity", ",", "List", "<", "ReflectedInfo", ">", "fieldInfo", ")", "throws", "Siren4JConversionException", "{", "if", "(", "!", "MapUtils", ...
Sets field value for an entity's property field. @param obj assumed not <code>null</code>. @param clazz assumed not <code>null</code>. @param entity assumed not <code>null</code>. @param fieldInfo assumed not <code>null</code>. @throws Siren4JConversionException
[ "Sets", "field", "value", "for", "an", "entity", "s", "property", "field", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L216-L241
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.handleSetSubEntities
@SuppressWarnings({"rawtypes", "unchecked"}) private void handleSetSubEntities(Object obj, Class<?> clazz, Entity entity, List<ReflectedInfo> fieldInfo) throws Siren4JConversionException { if (!CollectionUtils.isEmpty(entity.getEntities())) { for (Entity ent : entity.getEntities()) { //Skip embedded as we can't deal with them. if (StringUtils.isNotBlank(ent.getHref())) { continue; } String[] rel = ent.getRel(); if (ArrayUtils.isEmpty(rel)) { throw new Siren4JConversionException("No relationship set on sub entity. Can't go on."); } String fieldKey = rel.length == 1 ? rel[0] : ArrayUtils.toString(rel); ReflectedInfo info = ReflectionUtils.getFieldInfoByEffectiveName(fieldInfo, fieldKey); if (info != null) { try { Object subObj = toObject(ent); if (subObj != null) { if (subObj.getClass().equals(CollectionResource.class)) { ReflectionUtils.setFieldValue(obj, info, subObj); continue; // If subObj is collection resource then continue // or it will get wrapped into another collection which we don't want. } if (isCollection(obj, info.getField())) { //If we are a collection we need to add each subObj via the add method //and not a setter. So we need to grab the collection from the field value. try { Collection coll = (Collection) info.getField().get(obj); if (coll == null) { //In the highly unlikely event that no collection is set on the //field value we will create a new collection here. coll = new CollectionResource(); ReflectionUtils.setFieldValue(obj, info, coll); } coll.add(subObj); } catch (Exception e) { throw new Siren4JConversionException(e); } } else { ReflectionUtils.setFieldValue(obj, info, subObj); } } } catch (Siren4JException e) { throw new Siren4JConversionException(e); } } else { throw new Siren4JConversionException( "Unable to find field: " + fieldKey + " for class: " + clazz.getName()); } } } }
java
@SuppressWarnings({"rawtypes", "unchecked"}) private void handleSetSubEntities(Object obj, Class<?> clazz, Entity entity, List<ReflectedInfo> fieldInfo) throws Siren4JConversionException { if (!CollectionUtils.isEmpty(entity.getEntities())) { for (Entity ent : entity.getEntities()) { //Skip embedded as we can't deal with them. if (StringUtils.isNotBlank(ent.getHref())) { continue; } String[] rel = ent.getRel(); if (ArrayUtils.isEmpty(rel)) { throw new Siren4JConversionException("No relationship set on sub entity. Can't go on."); } String fieldKey = rel.length == 1 ? rel[0] : ArrayUtils.toString(rel); ReflectedInfo info = ReflectionUtils.getFieldInfoByEffectiveName(fieldInfo, fieldKey); if (info != null) { try { Object subObj = toObject(ent); if (subObj != null) { if (subObj.getClass().equals(CollectionResource.class)) { ReflectionUtils.setFieldValue(obj, info, subObj); continue; // If subObj is collection resource then continue // or it will get wrapped into another collection which we don't want. } if (isCollection(obj, info.getField())) { //If we are a collection we need to add each subObj via the add method //and not a setter. So we need to grab the collection from the field value. try { Collection coll = (Collection) info.getField().get(obj); if (coll == null) { //In the highly unlikely event that no collection is set on the //field value we will create a new collection here. coll = new CollectionResource(); ReflectionUtils.setFieldValue(obj, info, coll); } coll.add(subObj); } catch (Exception e) { throw new Siren4JConversionException(e); } } else { ReflectionUtils.setFieldValue(obj, info, subObj); } } } catch (Siren4JException e) { throw new Siren4JConversionException(e); } } else { throw new Siren4JConversionException( "Unable to find field: " + fieldKey + " for class: " + clazz.getName()); } } } }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "private", "void", "handleSetSubEntities", "(", "Object", "obj", ",", "Class", "<", "?", ">", "clazz", ",", "Entity", "entity", ",", "List", "<", "ReflectedInfo", ">", "fieldI...
Sets field value for an entity's sub entities field. @param obj assumed not <code>null</code>. @param clazz assumed not <code>null</code>. @param entity assumed not <code>null</code>. @param fieldInfo assumed not <code>null</code>. @throws Siren4JConversionException
[ "Sets", "field", "value", "for", "an", "entity", "s", "sub", "entities", "field", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L252-L304
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.handleSubEntity
private void handleSubEntity(EntityBuilder builder, Object obj, Field currentField, List<ReflectedInfo> fieldInfo) throws Siren4JException { Siren4JSubEntity subAnno = getSubEntityAnnotation(currentField, fieldInfo); if (subAnno != null) { if (isCollection(obj, currentField)) { Collection<?> coll = (Collection<?>) ReflectionUtils.getFieldValue(currentField, obj); if (coll != null) { for (Object o : coll) { builder.addSubEntity(toEntity(o, currentField, obj, fieldInfo)); } } } else { Object subObj = ReflectionUtils.getFieldValue(currentField, obj); if (subObj != null) { builder.addSubEntity(toEntity(subObj, currentField, obj, fieldInfo)); } } } }
java
private void handleSubEntity(EntityBuilder builder, Object obj, Field currentField, List<ReflectedInfo> fieldInfo) throws Siren4JException { Siren4JSubEntity subAnno = getSubEntityAnnotation(currentField, fieldInfo); if (subAnno != null) { if (isCollection(obj, currentField)) { Collection<?> coll = (Collection<?>) ReflectionUtils.getFieldValue(currentField, obj); if (coll != null) { for (Object o : coll) { builder.addSubEntity(toEntity(o, currentField, obj, fieldInfo)); } } } else { Object subObj = ReflectionUtils.getFieldValue(currentField, obj); if (subObj != null) { builder.addSubEntity(toEntity(subObj, currentField, obj, fieldInfo)); } } } }
[ "private", "void", "handleSubEntity", "(", "EntityBuilder", "builder", ",", "Object", "obj", ",", "Field", "currentField", ",", "List", "<", "ReflectedInfo", ">", "fieldInfo", ")", "throws", "Siren4JException", "{", "Siren4JSubEntity", "subAnno", "=", "getSubEntityA...
Handles sub entities. @param builder assumed not <code>null</code>. @param obj assumed not <code>null</code>. @param currentField assumed not <code>null</code>. @throws Siren4JException
[ "Handles", "sub", "entities", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L474-L494
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.resolveUri
private String resolveUri(String rawUri, EntityContext context, boolean handleURIOverride) throws Siren4JException { String resolvedUri = rawUri; String baseUri = null; boolean fullyQualified = false; if (context.getCurrentObject() instanceof Resource) { Resource resource = (Resource) context.getCurrentObject(); baseUri = resource.getBaseUri(); fullyQualified = resource.isFullyQualifiedLinks() == null ? false : resource.isFullyQualifiedLinks(); String override = resource.getOverrideUri(); if (handleURIOverride && StringUtils.isNotBlank(override)) { resolvedUri = override; } } resolvedUri = handleTokenReplacement(resolvedUri, context); if (fullyQualified && StringUtils.isNotBlank(baseUri) && !isAbsoluteUri(resolvedUri)) { StringBuffer sb = new StringBuffer(); sb.append(baseUri.endsWith("/") ? baseUri.substring(0, baseUri.length() - 1) : baseUri); sb.append(resolvedUri.startsWith("/") ? resolvedUri : "/" + resolvedUri); resolvedUri = sb.toString(); } return resolvedUri; }
java
private String resolveUri(String rawUri, EntityContext context, boolean handleURIOverride) throws Siren4JException { String resolvedUri = rawUri; String baseUri = null; boolean fullyQualified = false; if (context.getCurrentObject() instanceof Resource) { Resource resource = (Resource) context.getCurrentObject(); baseUri = resource.getBaseUri(); fullyQualified = resource.isFullyQualifiedLinks() == null ? false : resource.isFullyQualifiedLinks(); String override = resource.getOverrideUri(); if (handleURIOverride && StringUtils.isNotBlank(override)) { resolvedUri = override; } } resolvedUri = handleTokenReplacement(resolvedUri, context); if (fullyQualified && StringUtils.isNotBlank(baseUri) && !isAbsoluteUri(resolvedUri)) { StringBuffer sb = new StringBuffer(); sb.append(baseUri.endsWith("/") ? baseUri.substring(0, baseUri.length() - 1) : baseUri); sb.append(resolvedUri.startsWith("/") ? resolvedUri : "/" + resolvedUri); resolvedUri = sb.toString(); } return resolvedUri; }
[ "private", "String", "resolveUri", "(", "String", "rawUri", ",", "EntityContext", "context", ",", "boolean", "handleURIOverride", ")", "throws", "Siren4JException", "{", "String", "resolvedUri", "=", "rawUri", ";", "String", "baseUri", "=", "null", ";", "boolean",...
Resolves the raw uri by replacing field tokens with the actual data. @param rawUri assumed not <code>null</code> or . @param context @return uri with tokens resolved. @throws Siren4JException
[ "Resolves", "the", "raw", "uri", "by", "replacing", "field", "tokens", "with", "the", "actual", "data", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L504-L527
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.handleTokenReplacement
private String handleTokenReplacement(String str, EntityContext context) throws Siren4JException { String result = ""; // First resolve parents result = ReflectionUtils.replaceFieldTokens( context.getParentObject(), str, context.getParentFieldInfo(), true); // Now resolve others result = ReflectionUtils.flattenReservedTokens(ReflectionUtils.replaceFieldTokens( context.getCurrentObject(), result, context.getCurrentFieldInfo(), false)); return result; }
java
private String handleTokenReplacement(String str, EntityContext context) throws Siren4JException { String result = ""; // First resolve parents result = ReflectionUtils.replaceFieldTokens( context.getParentObject(), str, context.getParentFieldInfo(), true); // Now resolve others result = ReflectionUtils.flattenReservedTokens(ReflectionUtils.replaceFieldTokens( context.getCurrentObject(), result, context.getCurrentFieldInfo(), false)); return result; }
[ "private", "String", "handleTokenReplacement", "(", "String", "str", ",", "EntityContext", "context", ")", "throws", "Siren4JException", "{", "String", "result", "=", "\"\"", ";", "// First resolve parents\r", "result", "=", "ReflectionUtils", ".", "replaceFieldTokens",...
Helper method to do token replacement for strings. @param str @param context @return @throws Siren4JException
[ "Helper", "method", "to", "do", "token", "replacement", "for", "strings", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L542-L551
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.getSubEntityAnnotation
private Siren4JSubEntity getSubEntityAnnotation(Field currentField, List<ReflectedInfo> fieldInfo) { Siren4JSubEntity result = null; result = currentField.getAnnotation(Siren4JSubEntity.class); if (result == null && fieldInfo != null) { ReflectedInfo info = ReflectionUtils.getFieldInfoByName(fieldInfo, currentField.getName()); if (info != null && info.getGetter() != null) { result = info.getGetter().getAnnotation(Siren4JSubEntity.class); } } return result; }
java
private Siren4JSubEntity getSubEntityAnnotation(Field currentField, List<ReflectedInfo> fieldInfo) { Siren4JSubEntity result = null; result = currentField.getAnnotation(Siren4JSubEntity.class); if (result == null && fieldInfo != null) { ReflectedInfo info = ReflectionUtils.getFieldInfoByName(fieldInfo, currentField.getName()); if (info != null && info.getGetter() != null) { result = info.getGetter().getAnnotation(Siren4JSubEntity.class); } } return result; }
[ "private", "Siren4JSubEntity", "getSubEntityAnnotation", "(", "Field", "currentField", ",", "List", "<", "ReflectedInfo", ">", "fieldInfo", ")", "{", "Siren4JSubEntity", "result", "=", "null", ";", "result", "=", "currentField", ".", "getAnnotation", "(", "Siren4JSu...
Helper to retrieve a sub entity annotation from either the field itself or the getter. If an annotation exists on both, then the field wins. @param currentField assumed not <code>null</code>. @param fieldInfo assumed not <code>null</code>. @return the annotation if found else <code>null</code>.
[ "Helper", "to", "retrieve", "a", "sub", "entity", "annotation", "from", "either", "the", "field", "itself", "or", "the", "getter", ".", "If", "an", "annotation", "exists", "on", "both", "then", "the", "field", "wins", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L561-L571
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.handleSelfLink
private void handleSelfLink(EntityBuilder builder, String resolvedUri) { if (StringUtils.isBlank(resolvedUri)) { return; } Link link = LinkBuilder.newInstance().setRelationship(Link.RELATIONSHIP_SELF).setHref(resolvedUri).build(); builder.addLink(link); }
java
private void handleSelfLink(EntityBuilder builder, String resolvedUri) { if (StringUtils.isBlank(resolvedUri)) { return; } Link link = LinkBuilder.newInstance().setRelationship(Link.RELATIONSHIP_SELF).setHref(resolvedUri).build(); builder.addLink(link); }
[ "private", "void", "handleSelfLink", "(", "EntityBuilder", "builder", ",", "String", "resolvedUri", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "resolvedUri", ")", ")", "{", "return", ";", "}", "Link", "link", "=", "LinkBuilder", ".", "newInstan...
Add the self link to the entity. @param builder assumed not <code>null</code>. @param resolvedUri the token resolved uri. Assumed not blank.
[ "Add", "the", "self", "link", "to", "the", "entity", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L579-L585
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.handleBaseUriLink
private void handleBaseUriLink(EntityBuilder builder, String baseUri) { if (StringUtils.isBlank(baseUri)) { return; } Link link = LinkBuilder.newInstance().setRelationship(Link.RELATIONSHIP_BASEURI).setHref(baseUri).build(); builder.addLink(link); }
java
private void handleBaseUriLink(EntityBuilder builder, String baseUri) { if (StringUtils.isBlank(baseUri)) { return; } Link link = LinkBuilder.newInstance().setRelationship(Link.RELATIONSHIP_BASEURI).setHref(baseUri).build(); builder.addLink(link); }
[ "private", "void", "handleBaseUriLink", "(", "EntityBuilder", "builder", ",", "String", "baseUri", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "baseUri", ")", ")", "{", "return", ";", "}", "Link", "link", "=", "LinkBuilder", ".", "newInstance", ...
Add the baseUri link to the entity if the baseUri is set on the entity. @param builder assumed not <code>null</code>. @param baseUri the token resolved uri. Assumed not blank.
[ "Add", "the", "baseUri", "link", "to", "the", "entity", "if", "the", "baseUri", "is", "set", "on", "the", "entity", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L593-L599
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.handleEntityLinks
private void handleEntityLinks(EntityBuilder builder, EntityContext context) throws Siren4JException { Class<?> clazz = context.getCurrentObject().getClass(); Map<String, Link> links = new HashMap<String, Link>(); /* Caution!! Order matters when adding to the links map */ Siren4JEntity entity = clazz.getAnnotation(Siren4JEntity.class); if (entity != null && ArrayUtils.isNotEmpty(entity.links())) { for (Siren4JLink l : entity.links()) { if (evaluateConditional(l.condition(), context)) { links.put(ArrayUtils.toString(l.rel()), annotationToLink(l, context)); } } } if (context.getParentField() != null) { Siren4JSubEntity subentity = context.getParentField().getAnnotation(Siren4JSubEntity.class); if (subentity != null && ArrayUtils.isNotEmpty(subentity.links())) { for (Siren4JLink l : subentity.links()) { if (evaluateConditional(l.condition(), context)) { links.put(ArrayUtils.toString(l.rel()), annotationToLink(l, context)); } } } } Collection<Link> resourceLinks = context.getCurrentObject() instanceof Resource ? ((Resource) context.getCurrentObject()).getEntityLinks() : null; if (resourceLinks != null) { for (Link l : resourceLinks) { links.put(ArrayUtils.toString(l.getRel()), l); } } for (Link l : links.values()) { l.setHref(resolveUri(l.getHref(), context, false)); builder.addLink(l); } }
java
private void handleEntityLinks(EntityBuilder builder, EntityContext context) throws Siren4JException { Class<?> clazz = context.getCurrentObject().getClass(); Map<String, Link> links = new HashMap<String, Link>(); /* Caution!! Order matters when adding to the links map */ Siren4JEntity entity = clazz.getAnnotation(Siren4JEntity.class); if (entity != null && ArrayUtils.isNotEmpty(entity.links())) { for (Siren4JLink l : entity.links()) { if (evaluateConditional(l.condition(), context)) { links.put(ArrayUtils.toString(l.rel()), annotationToLink(l, context)); } } } if (context.getParentField() != null) { Siren4JSubEntity subentity = context.getParentField().getAnnotation(Siren4JSubEntity.class); if (subentity != null && ArrayUtils.isNotEmpty(subentity.links())) { for (Siren4JLink l : subentity.links()) { if (evaluateConditional(l.condition(), context)) { links.put(ArrayUtils.toString(l.rel()), annotationToLink(l, context)); } } } } Collection<Link> resourceLinks = context.getCurrentObject() instanceof Resource ? ((Resource) context.getCurrentObject()).getEntityLinks() : null; if (resourceLinks != null) { for (Link l : resourceLinks) { links.put(ArrayUtils.toString(l.getRel()), l); } } for (Link l : links.values()) { l.setHref(resolveUri(l.getHref(), context, false)); builder.addLink(l); } }
[ "private", "void", "handleEntityLinks", "(", "EntityBuilder", "builder", ",", "EntityContext", "context", ")", "throws", "Siren4JException", "{", "Class", "<", "?", ">", "clazz", "=", "context", ".", "getCurrentObject", "(", ")", ".", "getClass", "(", ")", ";"...
Handles getting all entity links both dynamically set and via annotations and merges them together overriding with the proper precedence order which is Dynamic > SubEntity > Entity. Href and uri's are resolved with the correct data bound in. @param builder assumed not <code>null</code>. @param context assumed not <code>null</code>. @throws Exception
[ "Handles", "getting", "all", "entity", "links", "both", "dynamically", "set", "and", "via", "annotations", "and", "merges", "them", "together", "overriding", "with", "the", "proper", "precedence", "order", "which", "is", "Dynamic", ">", "SubEntity", ">", "Entity...
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L610-L647
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.handleEntityActions
private void handleEntityActions(EntityBuilder builder, EntityContext context) throws Siren4JException { Class<?> clazz = context.getCurrentObject().getClass(); Map<String, Action> actions = new HashMap<String, Action>(); /* Caution!! Order matters when adding to the actions map */ Siren4JEntity entity = clazz.getAnnotation(Siren4JEntity.class); if (entity != null && ArrayUtils.isNotEmpty(entity.actions())) { for (Siren4JAction a : entity.actions()) { if (evaluateConditional(a.condition(), context)) { actions.put(a.name(), annotationToAction(a, context)); } } } if (context.getParentField() != null) { Siren4JSubEntity subentity = context.getParentField().getAnnotation(Siren4JSubEntity.class); if (subentity != null && ArrayUtils.isNotEmpty(subentity.actions())) { for (Siren4JAction a : subentity.actions()) { if (evaluateConditional(a.condition(), context)) { actions.put(a.name(), annotationToAction(a, context)); } } } } Collection<Action> resourceLinks = context.getCurrentObject() instanceof Resource ? ((Resource) context.getCurrentObject()).getEntityActions() : null; if (resourceLinks != null) { for (Action a : resourceLinks) { actions.put(a.getName(), a); } } for (Action a : actions.values()) { a.setHref(resolveUri(a.getHref(), context, false)); builder.addAction(a); } }
java
private void handleEntityActions(EntityBuilder builder, EntityContext context) throws Siren4JException { Class<?> clazz = context.getCurrentObject().getClass(); Map<String, Action> actions = new HashMap<String, Action>(); /* Caution!! Order matters when adding to the actions map */ Siren4JEntity entity = clazz.getAnnotation(Siren4JEntity.class); if (entity != null && ArrayUtils.isNotEmpty(entity.actions())) { for (Siren4JAction a : entity.actions()) { if (evaluateConditional(a.condition(), context)) { actions.put(a.name(), annotationToAction(a, context)); } } } if (context.getParentField() != null) { Siren4JSubEntity subentity = context.getParentField().getAnnotation(Siren4JSubEntity.class); if (subentity != null && ArrayUtils.isNotEmpty(subentity.actions())) { for (Siren4JAction a : subentity.actions()) { if (evaluateConditional(a.condition(), context)) { actions.put(a.name(), annotationToAction(a, context)); } } } } Collection<Action> resourceLinks = context.getCurrentObject() instanceof Resource ? ((Resource) context.getCurrentObject()).getEntityActions() : null; if (resourceLinks != null) { for (Action a : resourceLinks) { actions.put(a.getName(), a); } } for (Action a : actions.values()) { a.setHref(resolveUri(a.getHref(), context, false)); builder.addAction(a); } }
[ "private", "void", "handleEntityActions", "(", "EntityBuilder", "builder", ",", "EntityContext", "context", ")", "throws", "Siren4JException", "{", "Class", "<", "?", ">", "clazz", "=", "context", ".", "getCurrentObject", "(", ")", ".", "getClass", "(", ")", "...
Handles getting all entity actions both dynamically set and via annotations and merges them together overriding with the proper precedence order which is Dynamic > SubEntity > Entity. Href and uri's are resolved with the correct data bound in. @param builder @param context @throws Exception
[ "Handles", "getting", "all", "entity", "actions", "both", "dynamically", "set", "and", "via", "annotations", "and", "merges", "them", "together", "overriding", "with", "the", "proper", "precedence", "order", "which", "is", "Dynamic", ">", "SubEntity", ">", "Enti...
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L658-L693
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.evaluateConditional
private boolean evaluateConditional(Siren4JCondition condition, EntityContext context) { boolean result = true; if (condition != null && !("null".equals(condition.name()))) { result = false; Object val = null; ConditionFactory factory = ConditionFactory.getInstance(); Condition cond = factory.getCondition(condition.logic()); Object obj = condition.name().startsWith("parent.") ? context.getParentObject() : context.getCurrentObject(); String name = condition.name().startsWith("parent.") ? condition.name().substring(7) : condition.name(); if (obj == null) { throw new Siren4JRuntimeException( "No object found. Conditional probably references a parent but does not have a parent: " + condition .name()); } if (condition.type().equals(Type.METHOD)) { try { Method method = ReflectionUtils.findMethod(obj.getClass(), name, null); if (method != null) { method.setAccessible(true); val = method.invoke(obj, new Object[]{}); result = cond.evaluate(val); } else { throw new Siren4JException( "Method referenced in condition does not exist: " + condition.name()); } } catch (Exception e) { throw new Siren4JRuntimeException(e); } } else { try { Field field = ReflectionUtils.findField(obj.getClass(), name); if (field != null) { field.setAccessible(true); val = field.get(obj); result = cond.evaluate(val); } else { throw new Siren4JException("Field referenced in condition does not exist: " + condition.name()); } } catch (Exception e) { throw new Siren4JRuntimeException(e); } } } return result; }
java
private boolean evaluateConditional(Siren4JCondition condition, EntityContext context) { boolean result = true; if (condition != null && !("null".equals(condition.name()))) { result = false; Object val = null; ConditionFactory factory = ConditionFactory.getInstance(); Condition cond = factory.getCondition(condition.logic()); Object obj = condition.name().startsWith("parent.") ? context.getParentObject() : context.getCurrentObject(); String name = condition.name().startsWith("parent.") ? condition.name().substring(7) : condition.name(); if (obj == null) { throw new Siren4JRuntimeException( "No object found. Conditional probably references a parent but does not have a parent: " + condition .name()); } if (condition.type().equals(Type.METHOD)) { try { Method method = ReflectionUtils.findMethod(obj.getClass(), name, null); if (method != null) { method.setAccessible(true); val = method.invoke(obj, new Object[]{}); result = cond.evaluate(val); } else { throw new Siren4JException( "Method referenced in condition does not exist: " + condition.name()); } } catch (Exception e) { throw new Siren4JRuntimeException(e); } } else { try { Field field = ReflectionUtils.findField(obj.getClass(), name); if (field != null) { field.setAccessible(true); val = field.get(obj); result = cond.evaluate(val); } else { throw new Siren4JException("Field referenced in condition does not exist: " + condition.name()); } } catch (Exception e) { throw new Siren4JRuntimeException(e); } } } return result; }
[ "private", "boolean", "evaluateConditional", "(", "Siren4JCondition", "condition", ",", "EntityContext", "context", ")", "{", "boolean", "result", "=", "true", ";", "if", "(", "condition", "!=", "null", "&&", "!", "(", "\"null\"", ".", "equals", "(", "conditio...
Evaluates a value against its specified conditional. @param condition @param context @return
[ "Evaluates", "a", "value", "against", "its", "specified", "conditional", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L702-L751
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.annotationToLink
private Link annotationToLink(Siren4JLink linkAnno, EntityContext context) { LinkBuilder builder = LinkBuilder.newInstance().setRelationship(linkAnno.rel()).setHref(linkAnno.href()); if (StringUtils.isNotBlank(linkAnno.title())) { builder.setTitle(linkAnno.title()); } if (ArrayUtils.isNotEmpty(linkAnno.linkClass())) { builder.setComponentClass(linkAnno.linkClass()); } return builder.build(); }
java
private Link annotationToLink(Siren4JLink linkAnno, EntityContext context) { LinkBuilder builder = LinkBuilder.newInstance().setRelationship(linkAnno.rel()).setHref(linkAnno.href()); if (StringUtils.isNotBlank(linkAnno.title())) { builder.setTitle(linkAnno.title()); } if (ArrayUtils.isNotEmpty(linkAnno.linkClass())) { builder.setComponentClass(linkAnno.linkClass()); } return builder.build(); }
[ "private", "Link", "annotationToLink", "(", "Siren4JLink", "linkAnno", ",", "EntityContext", "context", ")", "{", "LinkBuilder", "builder", "=", "LinkBuilder", ".", "newInstance", "(", ")", ".", "setRelationship", "(", "linkAnno", ".", "rel", "(", ")", ")", "....
Convert a link annotation to an actual link. The href will not be resolved in the instantiated link, this will need to be post processed. @param linkAnno assumed not <code>null</code>. @return new link, never <code>null</code>.
[ "Convert", "a", "link", "annotation", "to", "an", "actual", "link", ".", "The", "href", "will", "not", "be", "resolved", "in", "the", "instantiated", "link", "this", "will", "need", "to", "be", "post", "processed", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L760-L769
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.annotationToAction
private Action annotationToAction(Siren4JAction actionAnno, EntityContext context) throws Siren4JException { ActionBuilder builder = ActionBuilder.newInstance(); builder.setName(actionAnno.name()).setHref(actionAnno.href()).setMethod(actionAnno.method()); if (ArrayUtils.isNotEmpty(actionAnno.actionClass())) { builder.setComponentClass(actionAnno.actionClass()); } if (StringUtils.isNotBlank(actionAnno.title())) { builder.setTitle(actionAnno.title()); } if (StringUtils.isNotBlank(actionAnno.type())) { builder.setType(actionAnno.type()); } if (ArrayUtils.isNotEmpty(actionAnno.fields())) { for (Siren4JActionField f : actionAnno.fields()) { builder.addField(annotationToField(f, context)); } } if (ArrayUtils.isNotEmpty(actionAnno.urlParams())) { for (Siren4JActionField f : actionAnno.urlParams()) { builder.addUrlParam(annotationToField(f, context)); } } if (ArrayUtils.isNotEmpty(actionAnno.headers())) { for (Siren4JActionField f : actionAnno.headers()) { builder.addHeader(annotationToField(f, context)); } } if(ArrayUtils.isNotEmpty(actionAnno.metaData())) { Map<String, String> metaData = new HashMap(); for(Siren4JMetaData mdAnno : actionAnno.metaData()) { metaData.put(mdAnno.key(), handleTokenReplacement(mdAnno.value(), context)); } builder.setMetaData(metaData); } return builder.build(); }
java
private Action annotationToAction(Siren4JAction actionAnno, EntityContext context) throws Siren4JException { ActionBuilder builder = ActionBuilder.newInstance(); builder.setName(actionAnno.name()).setHref(actionAnno.href()).setMethod(actionAnno.method()); if (ArrayUtils.isNotEmpty(actionAnno.actionClass())) { builder.setComponentClass(actionAnno.actionClass()); } if (StringUtils.isNotBlank(actionAnno.title())) { builder.setTitle(actionAnno.title()); } if (StringUtils.isNotBlank(actionAnno.type())) { builder.setType(actionAnno.type()); } if (ArrayUtils.isNotEmpty(actionAnno.fields())) { for (Siren4JActionField f : actionAnno.fields()) { builder.addField(annotationToField(f, context)); } } if (ArrayUtils.isNotEmpty(actionAnno.urlParams())) { for (Siren4JActionField f : actionAnno.urlParams()) { builder.addUrlParam(annotationToField(f, context)); } } if (ArrayUtils.isNotEmpty(actionAnno.headers())) { for (Siren4JActionField f : actionAnno.headers()) { builder.addHeader(annotationToField(f, context)); } } if(ArrayUtils.isNotEmpty(actionAnno.metaData())) { Map<String, String> metaData = new HashMap(); for(Siren4JMetaData mdAnno : actionAnno.metaData()) { metaData.put(mdAnno.key(), handleTokenReplacement(mdAnno.value(), context)); } builder.setMetaData(metaData); } return builder.build(); }
[ "private", "Action", "annotationToAction", "(", "Siren4JAction", "actionAnno", ",", "EntityContext", "context", ")", "throws", "Siren4JException", "{", "ActionBuilder", "builder", "=", "ActionBuilder", ".", "newInstance", "(", ")", ";", "builder", ".", "setName", "(...
Convert an action annotation to an actual action. The href will not be resolved in the instantiated action, this will need to be post processed. @param actionAnno assumed not <code>null</code>. @return new action, never <code>null</code>.
[ "Convert", "an", "action", "annotation", "to", "an", "actual", "action", ".", "The", "href", "will", "not", "be", "resolved", "in", "the", "instantiated", "action", "this", "will", "need", "to", "be", "post", "processed", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L778-L813
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.skipProperty
private boolean skipProperty(Object obj, Field field) throws Siren4JException { boolean skip = false; Class<?> clazz = obj.getClass(); Include inc = Include.ALWAYS; Siren4JInclude typeInclude = clazz.getAnnotation(Siren4JInclude.class); if (typeInclude != null) { inc = typeInclude.value(); } Siren4JInclude fieldInclude = field.getAnnotation(Siren4JInclude.class); if (fieldInclude != null) { inc = fieldInclude.value(); } try { Object val = field.get(obj); switch (inc) { case NON_EMPTY: if (val != null) { if (String.class.equals(field.getType())) { skip = StringUtils.isBlank((String) val); } else if (CollectionResource.class.equals(field.getType())) { skip = ((CollectionResource<?>) val).isEmpty(); } } else { skip = true; } break; case NON_NULL: if (val == null) { skip = true; } break; case ALWAYS: } } catch (Exception e) { throw new Siren4JRuntimeException(e); } return skip; }
java
private boolean skipProperty(Object obj, Field field) throws Siren4JException { boolean skip = false; Class<?> clazz = obj.getClass(); Include inc = Include.ALWAYS; Siren4JInclude typeInclude = clazz.getAnnotation(Siren4JInclude.class); if (typeInclude != null) { inc = typeInclude.value(); } Siren4JInclude fieldInclude = field.getAnnotation(Siren4JInclude.class); if (fieldInclude != null) { inc = fieldInclude.value(); } try { Object val = field.get(obj); switch (inc) { case NON_EMPTY: if (val != null) { if (String.class.equals(field.getType())) { skip = StringUtils.isBlank((String) val); } else if (CollectionResource.class.equals(field.getType())) { skip = ((CollectionResource<?>) val).isEmpty(); } } else { skip = true; } break; case NON_NULL: if (val == null) { skip = true; } break; case ALWAYS: } } catch (Exception e) { throw new Siren4JRuntimeException(e); } return skip; }
[ "private", "boolean", "skipProperty", "(", "Object", "obj", ",", "Field", "field", ")", "throws", "Siren4JException", "{", "boolean", "skip", "=", "false", ";", "Class", "<", "?", ">", "clazz", "=", "obj", ".", "getClass", "(", ")", ";", "Include", "inc"...
Determine if the property or entity should be skipped based on any existing include policy. The TYPE annotation is checked first and then the field annotation, the field annotation takes precedence. @param obj assumed not <code>null</code>. @param field assumed not <code>null</code>. @return <code>true</code> if the property/enity should be skipped. @throws Siren4JException
[ "Determine", "if", "the", "property", "or", "entity", "should", "be", "skipped", "based", "on", "any", "existing", "include", "policy", ".", "The", "TYPE", "annotation", "is", "checked", "first", "and", "then", "the", "field", "annotation", "the", "field", "...
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L899-L936
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.getEntityClass
public String[] getEntityClass(Object obj, String name, Siren4JEntity entityAnno) { Class<?> clazz = obj.getClass(); String[] compClass = entityAnno == null ? null : entityAnno.entityClass(); //If entity class specified then use it. if (compClass != null && !ArrayUtils.isEmpty(compClass)) { return compClass; } //Else use name or class. List<String> entityClass = new ArrayList<String>(); entityClass.add(StringUtils.defaultString(name, clazz.getName())); if (obj instanceof CollectionResource) { String tag = getCollectionClassTag(); if (StringUtils.isNotBlank(tag)) { entityClass.add(tag); } } return entityClass.toArray(new String[]{}); }
java
public String[] getEntityClass(Object obj, String name, Siren4JEntity entityAnno) { Class<?> clazz = obj.getClass(); String[] compClass = entityAnno == null ? null : entityAnno.entityClass(); //If entity class specified then use it. if (compClass != null && !ArrayUtils.isEmpty(compClass)) { return compClass; } //Else use name or class. List<String> entityClass = new ArrayList<String>(); entityClass.add(StringUtils.defaultString(name, clazz.getName())); if (obj instanceof CollectionResource) { String tag = getCollectionClassTag(); if (StringUtils.isNotBlank(tag)) { entityClass.add(tag); } } return entityClass.toArray(new String[]{}); }
[ "public", "String", "[", "]", "getEntityClass", "(", "Object", "obj", ",", "String", "name", ",", "Siren4JEntity", "entityAnno", ")", "{", "Class", "<", "?", ">", "clazz", "=", "obj", ".", "getClass", "(", ")", ";", "String", "[", "]", "compClass", "="...
Determine entity class by first using the name set on the Siren entity and then if not found using the actual class name, though it is preferable to use the first option to not tie to a language specific class. @param obj @param name @return
[ "Determine", "entity", "class", "by", "first", "using", "the", "name", "set", "on", "the", "Siren", "entity", "and", "then", "if", "not", "found", "using", "the", "actual", "class", "name", "though", "it", "is", "preferable", "to", "use", "the", "first", ...
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L946-L963
train
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.isCollection
public boolean isCollection(Object obj, Field field) { try { Object val = field.get(obj); boolean isCollResource = false; if (val != null) { isCollResource = CollectionResource.class.equals(val.getClass()); } return (!isCollResource && !field.getType().equals(CollectionResource.class)) && (Collection.class.equals(field.getType()) || ArrayUtils.contains(field.getType().getInterfaces(), Collection.class)); } catch (Exception e) { throw new Siren4JRuntimeException(e); } }
java
public boolean isCollection(Object obj, Field field) { try { Object val = field.get(obj); boolean isCollResource = false; if (val != null) { isCollResource = CollectionResource.class.equals(val.getClass()); } return (!isCollResource && !field.getType().equals(CollectionResource.class)) && (Collection.class.equals(field.getType()) || ArrayUtils.contains(field.getType().getInterfaces(), Collection.class)); } catch (Exception e) { throw new Siren4JRuntimeException(e); } }
[ "public", "boolean", "isCollection", "(", "Object", "obj", ",", "Field", "field", ")", "{", "try", "{", "Object", "val", "=", "field", ".", "get", "(", "obj", ")", ";", "boolean", "isCollResource", "=", "false", ";", "if", "(", "val", "!=", "null", "...
Determine if the field is a Collection class and not a CollectionResource class which needs special treatment. @param field @return
[ "Determine", "if", "the", "field", "is", "a", "Collection", "class", "and", "not", "a", "CollectionResource", "class", "which", "needs", "special", "treatment", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L971-L984
train
eserating/siren4j
src/main/java/com/google/code/siren4j/util/ReflectionUtils.java
ReflectionUtils.getGetterField
public static Field getGetterField(Method method) { if (method == null) { throw new IllegalArgumentException("method cannot be null."); } Class<?> clazz = method.getDeclaringClass(); String fName = stripGetterPrefix(method.getName()); Field field = null; try { field = findField(clazz, fName); } catch (Exception ignore) { } return field; }
java
public static Field getGetterField(Method method) { if (method == null) { throw new IllegalArgumentException("method cannot be null."); } Class<?> clazz = method.getDeclaringClass(); String fName = stripGetterPrefix(method.getName()); Field field = null; try { field = findField(clazz, fName); } catch (Exception ignore) { } return field; }
[ "public", "static", "Field", "getGetterField", "(", "Method", "method", ")", "{", "if", "(", "method", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"method cannot be null.\"", ")", ";", "}", "Class", "<", "?", ">", "clazz", "=",...
Find the field for the getter method based on the get methods name. It finds the field on the declaring class. @param method cannot be <code>null</code>. @return the field or <code>null</code> if not found.
[ "Find", "the", "field", "for", "the", "getter", "method", "based", "on", "the", "get", "methods", "name", ".", "It", "finds", "the", "field", "on", "the", "declaring", "class", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L95-L108
train
eserating/siren4j
src/main/java/com/google/code/siren4j/util/ReflectionUtils.java
ReflectionUtils.getExposedFieldInfo
public static List<ReflectedInfo> getExposedFieldInfo(final Class<?> clazz) { List<ReflectedInfo> results = null; try { results = fieldInfoCache.get(clazz, new Callable<List<ReflectedInfo>>() { /** * This method is called if the value is not found in the cache. This * is where the real reflection work is done. */ public List<ReflectedInfo> call() throws Exception { List<ReflectedInfo> exposed = new ArrayList<ReflectedInfo>(); for (Method m : clazz.getMethods()) { if(isIgnored(m)) { continue; } boolean methodIsSirenProperty = m.getAnnotation(Siren4JProperty.class) != null; String methodAnnotationName = extractEffectiveName(m, null); if (ReflectionUtils.isGetter(m)) { Field f = getGetterField(m); if(f != null && isIgnored(f)) { continue; } if (f != null) { String fieldAnnotationName = extractEffectiveName(f, null); String effectiveName = (String)findFirstNonNull( Arrays.asList(fieldAnnotationName, methodAnnotationName, f.getName()).iterator() ); exposed.add( new ReflectedInfo(f, m, ReflectionUtils.getSetter(clazz, f), effectiveName) ); } else if(methodIsSirenProperty) {// looks like we have getter not backed by field exposed.add( ReflectedInfoBuilder.aReflectedInfo(). withGetter(m). withEffectiveName(extractEffectiveName(m, stripGetterPrefix(m.getName()))). build() ); } } else if(methodIsSirenProperty) { exposed.add( ReflectedInfoBuilder.aReflectedInfo(). withGetter(m). withEffectiveName(extractEffectiveName(m, m.getName())). build() ); } } return exposed; } }); } catch (ExecutionException e) { throw new Siren4JRuntimeException(e); } return results; }
java
public static List<ReflectedInfo> getExposedFieldInfo(final Class<?> clazz) { List<ReflectedInfo> results = null; try { results = fieldInfoCache.get(clazz, new Callable<List<ReflectedInfo>>() { /** * This method is called if the value is not found in the cache. This * is where the real reflection work is done. */ public List<ReflectedInfo> call() throws Exception { List<ReflectedInfo> exposed = new ArrayList<ReflectedInfo>(); for (Method m : clazz.getMethods()) { if(isIgnored(m)) { continue; } boolean methodIsSirenProperty = m.getAnnotation(Siren4JProperty.class) != null; String methodAnnotationName = extractEffectiveName(m, null); if (ReflectionUtils.isGetter(m)) { Field f = getGetterField(m); if(f != null && isIgnored(f)) { continue; } if (f != null) { String fieldAnnotationName = extractEffectiveName(f, null); String effectiveName = (String)findFirstNonNull( Arrays.asList(fieldAnnotationName, methodAnnotationName, f.getName()).iterator() ); exposed.add( new ReflectedInfo(f, m, ReflectionUtils.getSetter(clazz, f), effectiveName) ); } else if(methodIsSirenProperty) {// looks like we have getter not backed by field exposed.add( ReflectedInfoBuilder.aReflectedInfo(). withGetter(m). withEffectiveName(extractEffectiveName(m, stripGetterPrefix(m.getName()))). build() ); } } else if(methodIsSirenProperty) { exposed.add( ReflectedInfoBuilder.aReflectedInfo(). withGetter(m). withEffectiveName(extractEffectiveName(m, m.getName())). build() ); } } return exposed; } }); } catch (ExecutionException e) { throw new Siren4JRuntimeException(e); } return results; }
[ "public", "static", "List", "<", "ReflectedInfo", ">", "getExposedFieldInfo", "(", "final", "Class", "<", "?", ">", "clazz", ")", "{", "List", "<", "ReflectedInfo", ">", "results", "=", "null", ";", "try", "{", "results", "=", "fieldInfoCache", ".", "get",...
Retrieve all fields deemed as Exposed, i.e. they are public or have a public accessor method or are marked by an annotation to be exposed. @param clazz cannot be <code>null</code>. @return
[ "Retrieve", "all", "fields", "deemed", "as", "Exposed", "i", ".", "e", ".", "they", "are", "public", "or", "have", "a", "public", "accessor", "method", "or", "are", "marked", "by", "an", "annotation", "to", "be", "exposed", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L117-L171
train
eserating/siren4j
src/main/java/com/google/code/siren4j/util/ReflectionUtils.java
ReflectionUtils.isGetter
public static boolean isGetter(Method method) { String name = method.getName(); String[] splitname = StringUtils.splitByCharacterTypeCamelCase(name); return !method.getReturnType().equals(void.class) && Modifier.isPublic(method.getModifiers()) && (splitname[0].equals(GETTER_PREFIX_BOOLEAN) || splitname[0].equals(GETTER_PREFIX)); }
java
public static boolean isGetter(Method method) { String name = method.getName(); String[] splitname = StringUtils.splitByCharacterTypeCamelCase(name); return !method.getReturnType().equals(void.class) && Modifier.isPublic(method.getModifiers()) && (splitname[0].equals(GETTER_PREFIX_BOOLEAN) || splitname[0].equals(GETTER_PREFIX)); }
[ "public", "static", "boolean", "isGetter", "(", "Method", "method", ")", "{", "String", "name", "=", "method", ".", "getName", "(", ")", ";", "String", "[", "]", "splitname", "=", "StringUtils", ".", "splitByCharacterTypeCamelCase", "(", "name", ")", ";", ...
Determine if the method is a getter. @param method @return
[ "Determine", "if", "the", "method", "is", "a", "getter", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L212-L217
train
eserating/siren4j
src/main/java/com/google/code/siren4j/util/ReflectionUtils.java
ReflectionUtils.isSetter
public static boolean isSetter(Method method) { String name = method.getName(); String[] splitname = StringUtils.splitByCharacterTypeCamelCase(name); return method.getReturnType().equals(void.class) && Modifier.isPublic(method.getModifiers()) && splitname[0].equals(SETTER_PREFIX); }
java
public static boolean isSetter(Method method) { String name = method.getName(); String[] splitname = StringUtils.splitByCharacterTypeCamelCase(name); return method.getReturnType().equals(void.class) && Modifier.isPublic(method.getModifiers()) && splitname[0].equals(SETTER_PREFIX); }
[ "public", "static", "boolean", "isSetter", "(", "Method", "method", ")", "{", "String", "name", "=", "method", ".", "getName", "(", ")", ";", "String", "[", "]", "splitname", "=", "StringUtils", ".", "splitByCharacterTypeCamelCase", "(", "name", ")", ";", ...
Determine if the method is a setter. @param method @return
[ "Determine", "if", "the", "method", "is", "a", "setter", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L225-L230
train
eserating/siren4j
src/main/java/com/google/code/siren4j/util/ReflectionUtils.java
ReflectionUtils.replaceFieldTokens
public static String replaceFieldTokens(Object obj, String str, List<ReflectedInfo> fields, boolean parentMode) throws Siren4JException { Map<String, Field> index = new HashMap<String, Field>(); if (StringUtils.isBlank(str)) { return str; } if (fields != null) { for (ReflectedInfo info : fields) { Field f = info.getField(); if (f != null) { index.put(f.getName(), f); } } } try { for (String key : ReflectionUtils.getTokenKeys(str)) { if ((!parentMode && !key.startsWith("parent.")) || (parentMode && key.startsWith("parent."))) { String fieldname = key.startsWith("parent.") ? key.substring(7) : key; if (index.containsKey(fieldname)) { Field f = index.get(fieldname); if (f.getType().isEnum() || ArrayUtils.contains(propertyTypes, f.getType())) { String replacement = ""; Object theObject = f.get(obj); if(f.getType().isEnum()) { replacement = theObject == null ? "" : ((Enum)theObject).name(); } else { replacement = theObject == null ? "" : theObject.toString(); } str = str.replaceAll("\\{" + key + "\\}", Matcher.quoteReplacement("" + replacement)); } } } } } catch (Exception e) { throw new Siren4JException(e); } return str; }
java
public static String replaceFieldTokens(Object obj, String str, List<ReflectedInfo> fields, boolean parentMode) throws Siren4JException { Map<String, Field> index = new HashMap<String, Field>(); if (StringUtils.isBlank(str)) { return str; } if (fields != null) { for (ReflectedInfo info : fields) { Field f = info.getField(); if (f != null) { index.put(f.getName(), f); } } } try { for (String key : ReflectionUtils.getTokenKeys(str)) { if ((!parentMode && !key.startsWith("parent.")) || (parentMode && key.startsWith("parent."))) { String fieldname = key.startsWith("parent.") ? key.substring(7) : key; if (index.containsKey(fieldname)) { Field f = index.get(fieldname); if (f.getType().isEnum() || ArrayUtils.contains(propertyTypes, f.getType())) { String replacement = ""; Object theObject = f.get(obj); if(f.getType().isEnum()) { replacement = theObject == null ? "" : ((Enum)theObject).name(); } else { replacement = theObject == null ? "" : theObject.toString(); } str = str.replaceAll("\\{" + key + "\\}", Matcher.quoteReplacement("" + replacement)); } } } } } catch (Exception e) { throw new Siren4JException(e); } return str; }
[ "public", "static", "String", "replaceFieldTokens", "(", "Object", "obj", ",", "String", "str", ",", "List", "<", "ReflectedInfo", ">", "fields", ",", "boolean", "parentMode", ")", "throws", "Siren4JException", "{", "Map", "<", "String", ",", "Field", ">", "...
Replaces field tokens with the actual value in the fields. The field types must be simple property types @param str @param fields info @param parentMode @param obj @return @throws Siren4JException
[ "Replaces", "field", "tokens", "with", "the", "actual", "value", "in", "the", "fields", ".", "The", "field", "types", "must", "be", "simple", "property", "types" ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L242-L281
train
eserating/siren4j
src/main/java/com/google/code/siren4j/util/ReflectionUtils.java
ReflectionUtils.flattenReservedTokens
public static String flattenReservedTokens(String str) { if (StringUtils.isBlank(str)) { return str; } return str.replaceAll("\\{\\[", "{").replaceAll("\\]\\}", "}"); }
java
public static String flattenReservedTokens(String str) { if (StringUtils.isBlank(str)) { return str; } return str.replaceAll("\\{\\[", "{").replaceAll("\\]\\}", "}"); }
[ "public", "static", "String", "flattenReservedTokens", "(", "String", "str", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "str", ")", ")", "{", "return", "str", ";", "}", "return", "str", ".", "replaceAll", "(", "\"\\\\{\\\\[\"", ",", "\"{\"", ...
Removes the square brackets that signify reserved from inside the tokens in the string. @param str @return
[ "Removes", "the", "square", "brackets", "that", "signify", "reserved", "from", "inside", "the", "tokens", "in", "the", "string", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L289-L294
train
eserating/siren4j
src/main/java/com/google/code/siren4j/util/ReflectionUtils.java
ReflectionUtils.getTokenKeys
public static Set<String> getTokenKeys(String str) { Set<String> results = new HashSet<String>(); String sDelim = "{"; String eDelim = "}"; if (StringUtils.isBlank(str)) { return results; } int start = -1; int end = 0; do { start = str.indexOf(sDelim, end); if (start != -1) { end = str.indexOf(eDelim, start); if (end != -1) { results.add(str.substring(start + sDelim.length(), end)); } } } while (start != -1 && end != -1); return results; }
java
public static Set<String> getTokenKeys(String str) { Set<String> results = new HashSet<String>(); String sDelim = "{"; String eDelim = "}"; if (StringUtils.isBlank(str)) { return results; } int start = -1; int end = 0; do { start = str.indexOf(sDelim, end); if (start != -1) { end = str.indexOf(eDelim, start); if (end != -1) { results.add(str.substring(start + sDelim.length(), end)); } } } while (start != -1 && end != -1); return results; }
[ "public", "static", "Set", "<", "String", ">", "getTokenKeys", "(", "String", "str", ")", "{", "Set", "<", "String", ">", "results", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "String", "sDelim", "=", "\"{\"", ";", "String", "eDelim", ...
Retrieve all token keys from a string. A token is found by its its start and end delimiters which are open and close curly braces. @param str the string to parse, may be <code>null</code> or empty. @return the set of unique token keys. Never <code>null</code>.May be empty.
[ "Retrieve", "all", "token", "keys", "from", "a", "string", ".", "A", "token", "is", "found", "by", "its", "its", "start", "and", "end", "delimiters", "which", "are", "open", "and", "close", "curly", "braces", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L313-L334
train
eserating/siren4j
src/main/java/com/google/code/siren4j/util/ReflectionUtils.java
ReflectionUtils.getFieldInfoByEffectiveName
public static ReflectedInfo getFieldInfoByEffectiveName(List<ReflectedInfo> infoList, String name) { if (infoList == null) { throw new IllegalArgumentException("infoList cannot be null."); } if (StringUtils.isBlank(name)) { throw new IllegalArgumentException("name cannot be null or empty."); } ReflectedInfo result = null; for (ReflectedInfo info : infoList) { if (name.equals(info.getEffectiveName())) { result = info; break; } } return result; }
java
public static ReflectedInfo getFieldInfoByEffectiveName(List<ReflectedInfo> infoList, String name) { if (infoList == null) { throw new IllegalArgumentException("infoList cannot be null."); } if (StringUtils.isBlank(name)) { throw new IllegalArgumentException("name cannot be null or empty."); } ReflectedInfo result = null; for (ReflectedInfo info : infoList) { if (name.equals(info.getEffectiveName())) { result = info; break; } } return result; }
[ "public", "static", "ReflectedInfo", "getFieldInfoByEffectiveName", "(", "List", "<", "ReflectedInfo", ">", "infoList", ",", "String", "name", ")", "{", "if", "(", "infoList", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"infoList can...
Helper method to find the field info by its effective name from the passed in list of info. @param infoList cannot be <code>null</code>. @param name cannot be <code>null</code> or empty. @return the info or <code>null</code> if not found.
[ "Helper", "method", "to", "find", "the", "field", "info", "by", "its", "effective", "name", "from", "the", "passed", "in", "list", "of", "info", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L476-L491
train
eserating/siren4j
src/main/java/com/google/code/siren4j/util/ReflectionUtils.java
ReflectionUtils.getFieldInfoByName
public static ReflectedInfo getFieldInfoByName(List<ReflectedInfo> infoList, String name) { if (infoList == null) { throw new IllegalArgumentException("infoList cannot be null."); } if (StringUtils.isBlank(name)) { throw new IllegalArgumentException("name cannot be null or empty."); } ReflectedInfo result = null; for (ReflectedInfo info : infoList) { if (info.getField() == null) { continue; //should never happen. } if (name.equals(info.getField().getName())) { result = info; break; } } return result; }
java
public static ReflectedInfo getFieldInfoByName(List<ReflectedInfo> infoList, String name) { if (infoList == null) { throw new IllegalArgumentException("infoList cannot be null."); } if (StringUtils.isBlank(name)) { throw new IllegalArgumentException("name cannot be null or empty."); } ReflectedInfo result = null; for (ReflectedInfo info : infoList) { if (info.getField() == null) { continue; //should never happen. } if (name.equals(info.getField().getName())) { result = info; break; } } return result; }
[ "public", "static", "ReflectedInfo", "getFieldInfoByName", "(", "List", "<", "ReflectedInfo", ">", "infoList", ",", "String", "name", ")", "{", "if", "(", "infoList", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"infoList cannot be nu...
Helper method to find the field info by its name from the passed in list of info. @param infoList cannot be <code>null</code>. @param name cannot be <code>null</code> or empty. @return the info or <code>null</code> if not found.
[ "Helper", "method", "to", "find", "the", "field", "info", "by", "its", "name", "from", "the", "passed", "in", "list", "of", "info", "." ]
f12e3185076ad920352ec4f6eb2a071a3683505f
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L500-L518
train