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
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/util/StringUtils.java
StringUtils.stripTrailingSlash
public static String stripTrailingSlash(String s) { return s == null ? null : CharMatcher.is('/').trimTrailingFrom(s); }
java
public static String stripTrailingSlash(String s) { return s == null ? null : CharMatcher.is('/').trimTrailingFrom(s); }
[ "public", "static", "String", "stripTrailingSlash", "(", "String", "s", ")", "{", "return", "s", "==", "null", "?", "null", ":", "CharMatcher", ".", "is", "(", "'", "'", ")", ".", "trimTrailingFrom", "(", "s", ")", ";", "}" ]
Strips the trailing slash from a string if it has a trailing slash; otherwise return the string unchanged.
[ "Strips", "the", "trailing", "slash", "from", "a", "string", "if", "it", "has", "a", "trailing", "slash", ";", "otherwise", "return", "the", "string", "unchanged", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/util/StringUtils.java#L13-L15
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/Timestamps.java
Timestamps.fromEpoch
public static Timestamp fromEpoch(long epochMillis) { return Timestamp .newBuilder() .setNanos((int) ((epochMillis % MILLIS_PER_SECOND) * NANOS_PER_MILLI)) .setSeconds(epochMillis / MILLIS_PER_SECOND) .build(); }
java
public static Timestamp fromEpoch(long epochMillis) { return Timestamp .newBuilder() .setNanos((int) ((epochMillis % MILLIS_PER_SECOND) * NANOS_PER_MILLI)) .setSeconds(epochMillis / MILLIS_PER_SECOND) .build(); }
[ "public", "static", "Timestamp", "fromEpoch", "(", "long", "epochMillis", ")", "{", "return", "Timestamp", ".", "newBuilder", "(", ")", ".", "setNanos", "(", "(", "int", ")", "(", "(", "epochMillis", "%", "MILLIS_PER_SECOND", ")", "*", "NANOS_PER_MILLI", ")"...
Obtain the current time from the unix epoch @param epochMillis gives the current time in milliseconds since since the epoch @return a {@code Timestamp} corresponding to the ticker's current value
[ "Obtain", "the", "current", "time", "from", "the", "unix", "epoch" ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/Timestamps.java#L61-L67
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/ValidationException.java
ValidationException.pushCurrentThreadValidationContext
public static void pushCurrentThreadValidationContext(Supplier<String> supplier) { Stack<Supplier<String>> stack = contextLocal.get(); if (stack == null) { stack = new Stack<>(); contextLocal.set(stack); } stack.push(supplier); }
java
public static void pushCurrentThreadValidationContext(Supplier<String> supplier) { Stack<Supplier<String>> stack = contextLocal.get(); if (stack == null) { stack = new Stack<>(); contextLocal.set(stack); } stack.push(supplier); }
[ "public", "static", "void", "pushCurrentThreadValidationContext", "(", "Supplier", "<", "String", ">", "supplier", ")", "{", "Stack", "<", "Supplier", "<", "String", ">>", "stack", "=", "contextLocal", ".", "get", "(", ")", ";", "if", "(", "stack", "==", "...
Sets the validation context description. Each thread has its own description, so this is thread safe.
[ "Sets", "the", "validation", "context", "description", ".", "Each", "thread", "has", "its", "own", "description", "so", "this", "is", "thread", "safe", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/ValidationException.java#L40-L47
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/aggregator/ReportRequestAggregator.java
ReportRequestAggregator.report
public boolean report(ReportRequest req) { if (cache == null) { return false; } Preconditions.checkArgument(req.getServiceName().equals(serviceName), "service name mismatch"); if (hasHighImportanceOperation(req)) { return false; } Map<String, Operation> bySignature = opsBySignature(req); // Concurrency: all threads wait while the current thread updates the cache. // // It's better for overall latency to have one thread complete cache update at a time than have // multiple threads interleave updates with the increased cpu cost due to increased context // switching. // // No i/o or computation is occurring, so the wait time should be relatively small and // depend on the number of waiting threads. synchronized (cache) { for (Map.Entry<String, Operation> entry : bySignature.entrySet()) { String signature = entry.getKey(); OperationAggregator agg = cache.getIfPresent(signature); if (agg == null) { cache.put(signature, new OperationAggregator(entry.getValue(), kinds)); } else { agg.add(entry.getValue()); } } } return true; }
java
public boolean report(ReportRequest req) { if (cache == null) { return false; } Preconditions.checkArgument(req.getServiceName().equals(serviceName), "service name mismatch"); if (hasHighImportanceOperation(req)) { return false; } Map<String, Operation> bySignature = opsBySignature(req); // Concurrency: all threads wait while the current thread updates the cache. // // It's better for overall latency to have one thread complete cache update at a time than have // multiple threads interleave updates with the increased cpu cost due to increased context // switching. // // No i/o or computation is occurring, so the wait time should be relatively small and // depend on the number of waiting threads. synchronized (cache) { for (Map.Entry<String, Operation> entry : bySignature.entrySet()) { String signature = entry.getKey(); OperationAggregator agg = cache.getIfPresent(signature); if (agg == null) { cache.put(signature, new OperationAggregator(entry.getValue(), kinds)); } else { agg.add(entry.getValue()); } } } return true; }
[ "public", "boolean", "report", "(", "ReportRequest", "req", ")", "{", "if", "(", "cache", "==", "null", ")", "{", "return", "false", ";", "}", "Preconditions", ".", "checkArgument", "(", "req", ".", "getServiceName", "(", ")", ".", "equals", "(", "servic...
Adds a report request to this instance's cache. @param req a {@code ReportRequest} to cache in this instance. @return {@code true} if {@code req} was cached successfully, otherwise {@code false}
[ "Adds", "a", "report", "request", "to", "this", "instance", "s", "cache", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/aggregator/ReportRequestAggregator.java#L178-L208
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/ConfigFilter.java
ConfigFilter.getRealHttpMethod
public static String getRealHttpMethod(ServletRequest req) { HttpServletRequest httpRequest = (HttpServletRequest) req; String method = (String) httpRequest.getAttribute(HTTP_METHOD_OVERRIDE_ATTRIBUTE); if (method != null) { return method; } return httpRequest.getMethod(); }
java
public static String getRealHttpMethod(ServletRequest req) { HttpServletRequest httpRequest = (HttpServletRequest) req; String method = (String) httpRequest.getAttribute(HTTP_METHOD_OVERRIDE_ATTRIBUTE); if (method != null) { return method; } return httpRequest.getMethod(); }
[ "public", "static", "String", "getRealHttpMethod", "(", "ServletRequest", "req", ")", "{", "HttpServletRequest", "httpRequest", "=", "(", "HttpServletRequest", ")", "req", ";", "String", "method", "=", "(", "String", ")", "httpRequest", ".", "getAttribute", "(", ...
Get the "real" HTTP method for the request, taking into account the X-HTTP-Method-Override header. @param req a {@code ServletRequest} @return the HTTP method for the request
[ "Get", "the", "real", "HTTP", "method", "for", "the", "request", "taking", "into", "account", "the", "X", "-", "HTTP", "-", "Method", "-", "Override", "header", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/ConfigFilter.java#L182-L189
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.parentTemplate
public PathTemplate parentTemplate() { int i = segments.size(); Segment seg = segments.get(--i); if (seg.kind() == SegmentKind.END_BINDING) { while (i > 0 && segments.get(--i).kind() != SegmentKind.BINDING) {} } if (i == 0) { throw new ValidationException("template does not have a parent"); } return new PathTemplate(segments.subList(0, i), urlEncoding); }
java
public PathTemplate parentTemplate() { int i = segments.size(); Segment seg = segments.get(--i); if (seg.kind() == SegmentKind.END_BINDING) { while (i > 0 && segments.get(--i).kind() != SegmentKind.BINDING) {} } if (i == 0) { throw new ValidationException("template does not have a parent"); } return new PathTemplate(segments.subList(0, i), urlEncoding); }
[ "public", "PathTemplate", "parentTemplate", "(", ")", "{", "int", "i", "=", "segments", ".", "size", "(", ")", ";", "Segment", "seg", "=", "segments", ".", "get", "(", "--", "i", ")", ";", "if", "(", "seg", ".", "kind", "(", ")", "==", "SegmentKind...
Returns a template for the parent of this template. @throws ValidationException if the template has no parent.
[ "Returns", "a", "template", "for", "the", "parent", "of", "this", "template", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L262-L272
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.withoutVars
public PathTemplate withoutVars() { StringBuilder result = new StringBuilder(); ListIterator<Segment> iterator = segments.listIterator(); boolean start = true; while (iterator.hasNext()) { Segment seg = iterator.next(); switch (seg.kind()) { case BINDING: case END_BINDING: break; default: if (!start) { result.append(seg.separator()); } else { start = false; } result.append(seg.value()); } } return create(result.toString(), urlEncoding); }
java
public PathTemplate withoutVars() { StringBuilder result = new StringBuilder(); ListIterator<Segment> iterator = segments.listIterator(); boolean start = true; while (iterator.hasNext()) { Segment seg = iterator.next(); switch (seg.kind()) { case BINDING: case END_BINDING: break; default: if (!start) { result.append(seg.separator()); } else { start = false; } result.append(seg.value()); } } return create(result.toString(), urlEncoding); }
[ "public", "PathTemplate", "withoutVars", "(", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "ListIterator", "<", "Segment", ">", "iterator", "=", "segments", ".", "listIterator", "(", ")", ";", "boolean", "start", "=", "tru...
Returns a template where all variable bindings have been replaced by wildcards, but which is equivalent regards matching to this one.
[ "Returns", "a", "template", "where", "all", "variable", "bindings", "have", "been", "replaced", "by", "wildcards", "but", "which", "is", "equivalent", "regards", "matching", "to", "this", "one", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L278-L298
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.singleVar
@Nullable public String singleVar() { if (bindings.size() == 1) { return bindings.entrySet().iterator().next().getKey(); } return null; }
java
@Nullable public String singleVar() { if (bindings.size() == 1) { return bindings.entrySet().iterator().next().getKey(); } return null; }
[ "@", "Nullable", "public", "String", "singleVar", "(", ")", "{", "if", "(", "bindings", ".", "size", "(", ")", "==", "1", ")", "{", "return", "bindings", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ".", "getKey", ...
Returns the name of a singleton variable used by this template. If the template does not contain a single variable, returns null.
[ "Returns", "the", "name", "of", "a", "singleton", "variable", "used", "by", "this", "template", ".", "If", "the", "template", "does", "not", "contain", "a", "single", "variable", "returns", "null", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L360-L366
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.validate
public void validate(String path, String exceptionMessagePrefix) { if (!matches(path)) { throw new ValidationException( String.format( "%s: Parameter \"%s\" must be in the form \"%s\"", exceptionMessagePrefix, path, this.toString())); } }
java
public void validate(String path, String exceptionMessagePrefix) { if (!matches(path)) { throw new ValidationException( String.format( "%s: Parameter \"%s\" must be in the form \"%s\"", exceptionMessagePrefix, path, this.toString())); } }
[ "public", "void", "validate", "(", "String", "path", ",", "String", "exceptionMessagePrefix", ")", "{", "if", "(", "!", "matches", "(", "path", ")", ")", "{", "throw", "new", "ValidationException", "(", "String", ".", "format", "(", "\"%s: Parameter \\\"%s\\\"...
Throws a ValidationException if the template doesn't match the path. The exceptionMessagePrefix parameter will be prepended to the ValidationException message.
[ "Throws", "a", "ValidationException", "if", "the", "template", "doesn", "t", "match", "the", "path", ".", "The", "exceptionMessagePrefix", "parameter", "will", "be", "prepended", "to", "the", "ValidationException", "message", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L375-L382
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.validatedMatch
public ImmutableMap<String, String> validatedMatch(String path, String exceptionMessagePrefix) { ImmutableMap<String, String> matchMap = match(path); if (matchMap == null) { throw new ValidationException( String.format( "%s: Parameter \"%s\" must be in the form \"%s\"", exceptionMessagePrefix, path, this.toString())); } return matchMap; }
java
public ImmutableMap<String, String> validatedMatch(String path, String exceptionMessagePrefix) { ImmutableMap<String, String> matchMap = match(path); if (matchMap == null) { throw new ValidationException( String.format( "%s: Parameter \"%s\" must be in the form \"%s\"", exceptionMessagePrefix, path, this.toString())); } return matchMap; }
[ "public", "ImmutableMap", "<", "String", ",", "String", ">", "validatedMatch", "(", "String", "path", ",", "String", "exceptionMessagePrefix", ")", "{", "ImmutableMap", "<", "String", ",", "String", ">", "matchMap", "=", "match", "(", "path", ")", ";", "if",...
Matches the path, returning a map from variable names to matched values. All matched values will be properly unescaped using URL encoding rules. If the path does not match the template, throws a ValidationException. The exceptionMessagePrefix parameter will be prepended to the ValidationException message. <p>If the path starts with '//', the first segment will be interpreted as a host name and stored in the variable {@link #HOSTNAME_VAR}. <p>See the {@link PathTemplate} class documentation for examples. <p>For free wildcards in the template, the matching process creates variables named '$n', where 'n' is the wildcard's position in the template (starting at n=0). For example: <pre> PathTemplate template = PathTemplate.create("shelves/*&#47;books/*"); assert template.validatedMatch("shelves/s1/books/b2", "User exception string") .equals(ImmutableMap.of("$0", "s1", "$1", "b1")); assert template.validatedMatch("//somewhere.io/shelves/s1/books/b2", "User exception string") .equals(ImmutableMap.of(HOSTNAME_VAR, "//somewhere.io", "$0", "s1", "$1", "b1")); </pre> All matched values will be properly unescaped using URL encoding rules (so long as URL encoding has not been disabled by the {@link #createWithoutUrlEncoding} method).
[ "Matches", "the", "path", "returning", "a", "map", "from", "variable", "names", "to", "matched", "values", ".", "All", "matched", "values", "will", "be", "properly", "unescaped", "using", "URL", "encoding", "rules", ".", "If", "the", "path", "does", "not", ...
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L407-L416
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.match
@Nullable public ImmutableMap<String, String> match(String path) { return match(path, false); }
java
@Nullable public ImmutableMap<String, String> match(String path) { return match(path, false); }
[ "@", "Nullable", "public", "ImmutableMap", "<", "String", ",", "String", ">", "match", "(", "String", "path", ")", "{", "return", "match", "(", "path", ",", "false", ")", ";", "}" ]
Matches the path, returning a map from variable names to matched values. All matched values will be properly unescaped using URL encoding rules. If the path does not match the template, null is returned. <p>If the path starts with '//', the first segment will be interpreted as a host name and stored in the variable {@link #HOSTNAME_VAR}. <p>See the {@link PathTemplate} class documentation for examples. <p>For free wildcards in the template, the matching process creates variables named '$n', where 'n' is the wildcard's position in the template (starting at n=0). For example: <pre> PathTemplate template = PathTemplate.create("shelves/*&#47;books/*"); assert template.match("shelves/s1/books/b2") .equals(ImmutableMap.of("$0", "s1", "$1", "b1")); assert template.match("//somewhere.io/shelves/s1/books/b2") .equals(ImmutableMap.of(HOSTNAME_VAR, "//somewhere.io", "$0", "s1", "$1", "b1")); </pre> All matched values will be properly unescaped using URL encoding rules (so long as URL encoding has not been disabled by the {@link #createWithoutUrlEncoding} method).
[ "Matches", "the", "path", "returning", "a", "map", "from", "variable", "names", "to", "matched", "values", ".", "All", "matched", "values", "will", "be", "properly", "unescaped", "using", "URL", "encoding", "rules", ".", "If", "the", "path", "does", "not", ...
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L447-L450
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.match
private ImmutableMap<String, String> match(String path, boolean forceHostName) { // Quick check for trailing custom verb. Segment last = segments.get(segments.size() - 1); if (last.kind() == SegmentKind.CUSTOM_VERB) { Matcher matcher = CUSTOM_VERB_PATTERN.matcher(path); if (!matcher.find() || !decodeUrl(matcher.group(1)).equals(last.value())) { return null; } path = path.substring(0, matcher.start(0)); } // Do full match. boolean withHostName = path.startsWith("//"); if (withHostName) { path = path.substring(2); } List<String> input = SLASH_SPLITTER.splitToList(path); int inPos = 0; Map<String, String> values = Maps.newLinkedHashMap(); if (withHostName || forceHostName) { if (input.isEmpty()) { return null; } String hostName = input.get(inPos++); if (withHostName) { // Put the // back, so we can distinguish this case from forceHostName. hostName = "//" + hostName; } values.put(HOSTNAME_VAR, hostName); } if (!match(input, inPos, segments, 0, values)) { return null; } return ImmutableMap.copyOf(values); }
java
private ImmutableMap<String, String> match(String path, boolean forceHostName) { // Quick check for trailing custom verb. Segment last = segments.get(segments.size() - 1); if (last.kind() == SegmentKind.CUSTOM_VERB) { Matcher matcher = CUSTOM_VERB_PATTERN.matcher(path); if (!matcher.find() || !decodeUrl(matcher.group(1)).equals(last.value())) { return null; } path = path.substring(0, matcher.start(0)); } // Do full match. boolean withHostName = path.startsWith("//"); if (withHostName) { path = path.substring(2); } List<String> input = SLASH_SPLITTER.splitToList(path); int inPos = 0; Map<String, String> values = Maps.newLinkedHashMap(); if (withHostName || forceHostName) { if (input.isEmpty()) { return null; } String hostName = input.get(inPos++); if (withHostName) { // Put the // back, so we can distinguish this case from forceHostName. hostName = "//" + hostName; } values.put(HOSTNAME_VAR, hostName); } if (!match(input, inPos, segments, 0, values)) { return null; } return ImmutableMap.copyOf(values); }
[ "private", "ImmutableMap", "<", "String", ",", "String", ">", "match", "(", "String", "path", ",", "boolean", "forceHostName", ")", "{", "// Quick check for trailing custom verb.", "Segment", "last", "=", "segments", ".", "get", "(", "segments", ".", "size", "("...
Matches a path.
[ "Matches", "a", "path", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L465-L499
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.match
private boolean match( List<String> input, int inPos, List<Segment> segments, int segPos, Map<String, String> values) { String currentVar = null; while (segPos < segments.size()) { Segment seg = segments.get(segPos++); switch (seg.kind()) { case END_BINDING: // End current variable binding scope. currentVar = null; continue; case BINDING: // Start variable binding scope. currentVar = seg.value(); continue; case CUSTOM_VERB: // This is the final segment, and this check should have already been performed by the // caller. The matching value is no longer present in the input. break; default: if (inPos >= input.size()) { // End of input return false; } // Check literal match. String next = decodeUrl(input.get(inPos++)); if (seg.kind() == SegmentKind.LITERAL) { if (!seg.value().equals(next)) { // Literal does not match. return false; } } if (currentVar != null) { // Create or extend current match String current = values.get(currentVar); if (current == null) { values.put(currentVar, next); } else { values.put(currentVar, current + "/" + next); } } if (seg.kind() == SegmentKind.PATH_WILDCARD) { // Compute the number of additional input the ** can consume. This // is possible because we restrict patterns to have only one **. int segsToMatch = 0; for (int i = segPos; i < segments.size(); i++) { switch (segments.get(i).kind()) { case BINDING: case END_BINDING: // skip continue; default: segsToMatch++; } } int available = (input.size() - inPos) - segsToMatch; while (available-- > 0) { values.put(currentVar, values.get(currentVar) + "/" + decodeUrl(input.get(inPos++))); } } } } return inPos == input.size(); }
java
private boolean match( List<String> input, int inPos, List<Segment> segments, int segPos, Map<String, String> values) { String currentVar = null; while (segPos < segments.size()) { Segment seg = segments.get(segPos++); switch (seg.kind()) { case END_BINDING: // End current variable binding scope. currentVar = null; continue; case BINDING: // Start variable binding scope. currentVar = seg.value(); continue; case CUSTOM_VERB: // This is the final segment, and this check should have already been performed by the // caller. The matching value is no longer present in the input. break; default: if (inPos >= input.size()) { // End of input return false; } // Check literal match. String next = decodeUrl(input.get(inPos++)); if (seg.kind() == SegmentKind.LITERAL) { if (!seg.value().equals(next)) { // Literal does not match. return false; } } if (currentVar != null) { // Create or extend current match String current = values.get(currentVar); if (current == null) { values.put(currentVar, next); } else { values.put(currentVar, current + "/" + next); } } if (seg.kind() == SegmentKind.PATH_WILDCARD) { // Compute the number of additional input the ** can consume. This // is possible because we restrict patterns to have only one **. int segsToMatch = 0; for (int i = segPos; i < segments.size(); i++) { switch (segments.get(i).kind()) { case BINDING: case END_BINDING: // skip continue; default: segsToMatch++; } } int available = (input.size() - inPos) - segsToMatch; while (available-- > 0) { values.put(currentVar, values.get(currentVar) + "/" + decodeUrl(input.get(inPos++))); } } } } return inPos == input.size(); }
[ "private", "boolean", "match", "(", "List", "<", "String", ">", "input", ",", "int", "inPos", ",", "List", "<", "Segment", ">", "segments", ",", "int", "segPos", ",", "Map", "<", "String", ",", "String", ">", "values", ")", "{", "String", "currentVar",...
indicating whether the match was successful.
[ "indicating", "whether", "the", "match", "was", "successful", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L503-L569
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.encode
public String encode(String... values) { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); int i = 0; for (String value : values) { builder.put("$" + i++, value); } // We will get an error if there are named bindings which are not reached by values. return instantiate(builder.build()); }
java
public String encode(String... values) { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); int i = 0; for (String value : values) { builder.put("$" + i++, value); } // We will get an error if there are named bindings which are not reached by values. return instantiate(builder.build()); }
[ "public", "String", "encode", "(", "String", "...", "values", ")", "{", "ImmutableMap", ".", "Builder", "<", "String", ",", "String", ">", "builder", "=", "ImmutableMap", ".", "builder", "(", ")", ";", "int", "i", "=", "0", ";", "for", "(", "String", ...
Instantiates the template from the given positional parameters. The template must not be build from named bindings, but only contain wildcards. Each parameter position corresponds to a wildcard of the according position in the template.
[ "Instantiates", "the", "template", "from", "the", "given", "positional", "parameters", ".", "The", "template", "must", "not", "be", "build", "from", "named", "bindings", "but", "only", "contain", "wildcards", ".", "Each", "parameter", "position", "corresponds", ...
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L694-L702
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.decode
public List<String> decode(String path) { Map<String, String> match = match(path); if (match == null) { throw new IllegalArgumentException(String.format("template '%s' does not match '%s'", this, path)); } List<String> result = Lists.newArrayList(); for (Map.Entry<String, String> entry : match.entrySet()) { String key = entry.getKey(); if (!key.startsWith("$")) { throw new IllegalArgumentException("template must not contain named bindings"); } int i = Integer.parseInt(key.substring(1)); while (result.size() <= i) { result.add(""); } result.set(i, entry.getValue()); } return ImmutableList.copyOf(result); }
java
public List<String> decode(String path) { Map<String, String> match = match(path); if (match == null) { throw new IllegalArgumentException(String.format("template '%s' does not match '%s'", this, path)); } List<String> result = Lists.newArrayList(); for (Map.Entry<String, String> entry : match.entrySet()) { String key = entry.getKey(); if (!key.startsWith("$")) { throw new IllegalArgumentException("template must not contain named bindings"); } int i = Integer.parseInt(key.substring(1)); while (result.size() <= i) { result.add(""); } result.set(i, entry.getValue()); } return ImmutableList.copyOf(result); }
[ "public", "List", "<", "String", ">", "decode", "(", "String", "path", ")", "{", "Map", "<", "String", ",", "String", ">", "match", "=", "match", "(", "path", ")", ";", "if", "(", "match", "==", "null", ")", "{", "throw", "new", "IllegalArgumentExcep...
Matches the template into a list of positional values. The template must not be build from named bindings, but only contain wildcards. For each wildcard in the template, a value is returned at corresponding position in the list.
[ "Matches", "the", "template", "into", "a", "list", "of", "positional", "values", ".", "The", "template", "must", "not", "be", "build", "from", "named", "bindings", "but", "only", "contain", "wildcards", ".", "For", "each", "wildcard", "in", "the", "template"...
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L709-L728
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java
PathTemplate.peek
private static boolean peek(ListIterator<Segment> segments, SegmentKind... kinds) { int start = segments.nextIndex(); boolean success = false; for (SegmentKind kind : kinds) { if (!segments.hasNext() || segments.next().kind() != kind) { success = false; break; } } if (success) { return true; } restore(segments, start); return false; }
java
private static boolean peek(ListIterator<Segment> segments, SegmentKind... kinds) { int start = segments.nextIndex(); boolean success = false; for (SegmentKind kind : kinds) { if (!segments.hasNext() || segments.next().kind() != kind) { success = false; break; } } if (success) { return true; } restore(segments, start); return false; }
[ "private", "static", "boolean", "peek", "(", "ListIterator", "<", "Segment", ">", "segments", ",", "SegmentKind", "...", "kinds", ")", "{", "int", "start", "=", "segments", ".", "nextIndex", "(", ")", ";", "boolean", "success", "=", "false", ";", "for", ...
the list iterator in its state.
[ "the", "list", "iterator", "in", "its", "state", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/PathTemplate.java#L881-L895
train
tracee/tracee
binding/jaxrs2/src/main/java/io/tracee/binding/jaxrs2/TraceeContainerFilter.java
TraceeContainerFilter.filter
@Override public void filter(final ContainerRequestContext containerRequestContext) { if (backend.getConfiguration().shouldProcessContext(IncomingRequest)) { final List<String> serializedTraceeHeaders = containerRequestContext.getHeaders().get(TraceeConstants.TPIC_HEADER); if (serializedTraceeHeaders != null && !serializedTraceeHeaders.isEmpty()) { final Map<String, String> parsed = transportSerialization.parse(serializedTraceeHeaders); backend.putAll(backend.getConfiguration().filterDeniedParams(parsed, IncomingRequest)); } } Utilities.generateInvocationIdIfNecessary(backend); }
java
@Override public void filter(final ContainerRequestContext containerRequestContext) { if (backend.getConfiguration().shouldProcessContext(IncomingRequest)) { final List<String> serializedTraceeHeaders = containerRequestContext.getHeaders().get(TraceeConstants.TPIC_HEADER); if (serializedTraceeHeaders != null && !serializedTraceeHeaders.isEmpty()) { final Map<String, String> parsed = transportSerialization.parse(serializedTraceeHeaders); backend.putAll(backend.getConfiguration().filterDeniedParams(parsed, IncomingRequest)); } } Utilities.generateInvocationIdIfNecessary(backend); }
[ "@", "Override", "public", "void", "filter", "(", "final", "ContainerRequestContext", "containerRequestContext", ")", "{", "if", "(", "backend", ".", "getConfiguration", "(", ")", ".", "shouldProcessContext", "(", "IncomingRequest", ")", ")", "{", "final", "List",...
This method handles the incoming request
[ "This", "method", "handles", "the", "incoming", "request" ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/binding/jaxrs2/src/main/java/io/tracee/binding/jaxrs2/TraceeContainerFilter.java#L39-L51
train
tracee/tracee
binding/jaxrs2/src/main/java/io/tracee/binding/jaxrs2/TraceeContainerFilter.java
TraceeContainerFilter.filter
@Override public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) { if (backend.getConfiguration().shouldProcessContext(OutgoingResponse)) { final Map<String, String> filtered = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), OutgoingResponse); responseContext.getHeaders().putSingle(TraceeConstants.TPIC_HEADER, transportSerialization.render(filtered)); } backend.clear(); }
java
@Override public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) { if (backend.getConfiguration().shouldProcessContext(OutgoingResponse)) { final Map<String, String> filtered = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), OutgoingResponse); responseContext.getHeaders().putSingle(TraceeConstants.TPIC_HEADER, transportSerialization.render(filtered)); } backend.clear(); }
[ "@", "Override", "public", "void", "filter", "(", "final", "ContainerRequestContext", "requestContext", ",", "final", "ContainerResponseContext", "responseContext", ")", "{", "if", "(", "backend", ".", "getConfiguration", "(", ")", ".", "shouldProcessContext", "(", ...
This method handles the outgoing response
[ "This", "method", "handles", "the", "outgoing", "response" ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/binding/jaxrs2/src/main/java/io/tracee/binding/jaxrs2/TraceeContainerFilter.java#L56-L64
train
tracee/tracee
core/src/main/java/io/tracee/transport/SoapHeaderTransport.java
SoapHeaderTransport.parseSoapHeader
public Map<String, String> parseSoapHeader(final Element soapHeader) { final NodeList tpicHeaders = soapHeader.getElementsByTagNameNS(TraceeConstants.SOAP_HEADER_NAMESPACE, TraceeConstants.TPIC_HEADER); final HashMap<String, String> contextMap = new HashMap<>(); if (tpicHeaders != null && tpicHeaders.getLength() > 0) { final int items = tpicHeaders.getLength(); for (int i = 0; i < items; i++) { contextMap.putAll(parseTpicHeader((Element) tpicHeaders.item(i))); } } return contextMap; }
java
public Map<String, String> parseSoapHeader(final Element soapHeader) { final NodeList tpicHeaders = soapHeader.getElementsByTagNameNS(TraceeConstants.SOAP_HEADER_NAMESPACE, TraceeConstants.TPIC_HEADER); final HashMap<String, String> contextMap = new HashMap<>(); if (tpicHeaders != null && tpicHeaders.getLength() > 0) { final int items = tpicHeaders.getLength(); for (int i = 0; i < items; i++) { contextMap.putAll(parseTpicHeader((Element) tpicHeaders.item(i))); } } return contextMap; }
[ "public", "Map", "<", "String", ",", "String", ">", "parseSoapHeader", "(", "final", "Element", "soapHeader", ")", "{", "final", "NodeList", "tpicHeaders", "=", "soapHeader", ".", "getElementsByTagNameNS", "(", "TraceeConstants", ".", "SOAP_HEADER_NAMESPACE", ",", ...
Retrieves the first TPIC header element out of the soap header and parse it @param soapHeader soap header of the message @return TPIC context map
[ "Retrieves", "the", "first", "TPIC", "header", "element", "out", "of", "the", "soap", "header", "and", "parse", "it" ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/core/src/main/java/io/tracee/transport/SoapHeaderTransport.java#L45-L55
train
tracee/tracee
core/src/main/java/io/tracee/transport/SoapHeaderTransport.java
SoapHeaderTransport.renderSoapHeader
public void renderSoapHeader(final Map<String, String> context, final SOAPHeader soapHeader) { renderSoapHeader(SOAP_HEADER_MARSHALLER, context, soapHeader); }
java
public void renderSoapHeader(final Map<String, String> context, final SOAPHeader soapHeader) { renderSoapHeader(SOAP_HEADER_MARSHALLER, context, soapHeader); }
[ "public", "void", "renderSoapHeader", "(", "final", "Map", "<", "String", ",", "String", ">", "context", ",", "final", "SOAPHeader", "soapHeader", ")", "{", "renderSoapHeader", "(", "SOAP_HEADER_MARSHALLER", ",", "context", ",", "soapHeader", ")", ";", "}" ]
Renders a given context map into a given soapHeader.
[ "Renders", "a", "given", "context", "map", "into", "a", "given", "soapHeader", "." ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/core/src/main/java/io/tracee/transport/SoapHeaderTransport.java#L105-L107
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/ControlFilter.java
ControlFilter.createClient
protected Client createClient(String configServiceName) throws GeneralSecurityException, IOException { return new Client.Builder(configServiceName) .setStatsLogFrequency(statsLogFrequency()) .setHttpTransport(new NetHttpTransport()) .build(); }
java
protected Client createClient(String configServiceName) throws GeneralSecurityException, IOException { return new Client.Builder(configServiceName) .setStatsLogFrequency(statsLogFrequency()) .setHttpTransport(new NetHttpTransport()) .build(); }
[ "protected", "Client", "createClient", "(", "String", "configServiceName", ")", "throws", "GeneralSecurityException", ",", "IOException", "{", "return", "new", "Client", ".", "Builder", "(", "configServiceName", ")", ".", "setStatsLogFrequency", "(", "statsLogFrequency"...
A template method for constructing clients. <strong>Intended Usage</strong> <p> Subclasses of may override this method to customize how the client get's built. Note that this method is intended to be invoked by {@link ControlFilter#init(FilterConfig)} when the serviceName parameter is provided. If that parameter is missing, this function will not be called and the client will not be constructed. </p> @param configServiceName the service name to use in constructing the client @return a {@link Client} @throws GeneralSecurityException indicates that client was not created successfully @throws IOException indicates that the client was not created successfully
[ "A", "template", "method", "for", "constructing", "clients", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/ControlFilter.java#L191-L197
train
cloudendpoints/endpoints-management-java
endpoints-auth/src/main/java/com/google/api/auth/DefaultKeyUriSupplier.java
DefaultKeyUriSupplier.constructOpenIdUrl
private static String constructOpenIdUrl(String issuer) { String url = issuer; if (!URI.create(issuer).isAbsolute()) { // Use HTTPS if the protocol scheme is not specified in the URL. url = HTTPS_PROTOCOL_PREFIX + issuer; } if (!url.endsWith("/")) { url += "/"; } return url + OPEN_ID_CONFIG_PATH; }
java
private static String constructOpenIdUrl(String issuer) { String url = issuer; if (!URI.create(issuer).isAbsolute()) { // Use HTTPS if the protocol scheme is not specified in the URL. url = HTTPS_PROTOCOL_PREFIX + issuer; } if (!url.endsWith("/")) { url += "/"; } return url + OPEN_ID_CONFIG_PATH; }
[ "private", "static", "String", "constructOpenIdUrl", "(", "String", "issuer", ")", "{", "String", "url", "=", "issuer", ";", "if", "(", "!", "URI", ".", "create", "(", "issuer", ")", ".", "isAbsolute", "(", ")", ")", "{", "// Use HTTPS if the protocol scheme...
Construct the OpenID discovery URL based on the issuer.
[ "Construct", "the", "OpenID", "discovery", "URL", "based", "on", "the", "issuer", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-auth/src/main/java/com/google/api/auth/DefaultKeyUriSupplier.java#L116-L126
train
tracee/tracee
binding/jms/src/main/java/io/tracee/binding/jms/TraceeMessageProducer.java
TraceeMessageProducer.writeTraceeContextToMessage
protected void writeTraceeContextToMessage(Message message) throws JMSException { if (!backend.isEmpty() && backend.getConfiguration().shouldProcessContext(AsyncDispatch)) { final Map<String, String> filteredContext = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), AsyncDispatch); final String contextAsString = httpHeaderSerialization.render(filteredContext); message.setStringProperty(TraceeConstants.TPIC_HEADER, contextAsString); } }
java
protected void writeTraceeContextToMessage(Message message) throws JMSException { if (!backend.isEmpty() && backend.getConfiguration().shouldProcessContext(AsyncDispatch)) { final Map<String, String> filteredContext = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), AsyncDispatch); final String contextAsString = httpHeaderSerialization.render(filteredContext); message.setStringProperty(TraceeConstants.TPIC_HEADER, contextAsString); } }
[ "protected", "void", "writeTraceeContextToMessage", "(", "Message", "message", ")", "throws", "JMSException", "{", "if", "(", "!", "backend", ".", "isEmpty", "(", ")", "&&", "backend", ".", "getConfiguration", "(", ")", ".", "shouldProcessContext", "(", "AsyncDi...
Writes the current TraceeContext to the given javaee message. This method is idempotent.
[ "Writes", "the", "current", "TraceeContext", "to", "the", "given", "javaee", "message", ".", "This", "method", "is", "idempotent", "." ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/binding/jms/src/main/java/io/tracee/binding/jms/TraceeMessageProducer.java#L38-L46
train
cloudendpoints/endpoints-management-java
endpoints-auth/src/main/java/com/google/api/auth/Authenticator.java
Authenticator.authenticate
public UserInfo authenticate( HttpServletRequest httpServletRequest, AuthInfo authInfo, String serviceName) { Preconditions.checkNotNull(httpServletRequest); Preconditions.checkNotNull(authInfo); Optional<String> maybeAuthToken = extractAuthToken(httpServletRequest); if (!maybeAuthToken.isPresent()) { throw new UnauthenticatedException( "No auth token is contained in the HTTP request"); } JwtClaims jwtClaims = this.authTokenDecoder.decode(maybeAuthToken.get()); UserInfo userInfo = toUserInfo(jwtClaims); String issuer = userInfo.getIssuer(); if (!this.issuersToProviderIds.containsKey(issuer)) { throw new UnauthenticatedException("Unknown issuer: " + issuer); } String providerId = this.issuersToProviderIds.get(issuer); // Check whether the provider id is allowed. if (!authInfo.isProviderIdAllowed(providerId)) { String message = "The requested method does not allowed this provider id: " + providerId; throw new UnauthenticatedException(message); } checkJwtClaims(jwtClaims); // Check the audiences decoded from the auth token. The auth token is allowed when // 1) an audience is equal to the service name, // or 2) at least one audience is allowed in the method configuration. Set<String> audiences = userInfo.getAudiences(); boolean hasServiceName = audiences.contains(serviceName); Set<String> allowedAudiences = authInfo.getAudiencesForProvider(providerId); if (!hasServiceName && Sets.intersection(audiences, allowedAudiences).isEmpty()) { throw new UnauthenticatedException("Audiences not allowed"); } return userInfo; }
java
public UserInfo authenticate( HttpServletRequest httpServletRequest, AuthInfo authInfo, String serviceName) { Preconditions.checkNotNull(httpServletRequest); Preconditions.checkNotNull(authInfo); Optional<String> maybeAuthToken = extractAuthToken(httpServletRequest); if (!maybeAuthToken.isPresent()) { throw new UnauthenticatedException( "No auth token is contained in the HTTP request"); } JwtClaims jwtClaims = this.authTokenDecoder.decode(maybeAuthToken.get()); UserInfo userInfo = toUserInfo(jwtClaims); String issuer = userInfo.getIssuer(); if (!this.issuersToProviderIds.containsKey(issuer)) { throw new UnauthenticatedException("Unknown issuer: " + issuer); } String providerId = this.issuersToProviderIds.get(issuer); // Check whether the provider id is allowed. if (!authInfo.isProviderIdAllowed(providerId)) { String message = "The requested method does not allowed this provider id: " + providerId; throw new UnauthenticatedException(message); } checkJwtClaims(jwtClaims); // Check the audiences decoded from the auth token. The auth token is allowed when // 1) an audience is equal to the service name, // or 2) at least one audience is allowed in the method configuration. Set<String> audiences = userInfo.getAudiences(); boolean hasServiceName = audiences.contains(serviceName); Set<String> allowedAudiences = authInfo.getAudiencesForProvider(providerId); if (!hasServiceName && Sets.intersection(audiences, allowedAudiences).isEmpty()) { throw new UnauthenticatedException("Audiences not allowed"); } return userInfo; }
[ "public", "UserInfo", "authenticate", "(", "HttpServletRequest", "httpServletRequest", ",", "AuthInfo", "authInfo", ",", "String", "serviceName", ")", "{", "Preconditions", ".", "checkNotNull", "(", "httpServletRequest", ")", ";", "Preconditions", ".", "checkNotNull", ...
Authenticate the current HTTP request. @param httpServletRequest is the incoming HTTP request object. @param authInfo contains authentication configurations of the API method being called. @param serviceName is the name of this service. @return a constructed {@link UserInfo} object representing the identity of the caller.
[ "Authenticate", "the", "current", "HTTP", "request", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-auth/src/main/java/com/google/api/auth/Authenticator.java#L91-L133
train
cloudendpoints/endpoints-management-java
endpoints-auth/src/main/java/com/google/api/auth/Authenticator.java
Authenticator.checkJwtClaims
private void checkJwtClaims(JwtClaims jwtClaims) { Optional<NumericDate> expiration = getDateClaim(ReservedClaimNames.EXPIRATION_TIME, jwtClaims); if (!expiration.isPresent()) { throw new UnauthenticatedException("Missing expiration field"); } Optional<NumericDate> notBefore = getDateClaim(ReservedClaimNames.NOT_BEFORE, jwtClaims); NumericDate currentTime = NumericDate.fromMilliseconds(clock.currentTimeMillis()); if (expiration.get().isBefore(currentTime)) { throw new UnauthenticatedException("The auth token has already expired"); } if (notBefore.isPresent() && notBefore.get().isAfter(currentTime)) { String message = "Current time is earlier than the \"nbf\" time"; throw new UnauthenticatedException(message); } }
java
private void checkJwtClaims(JwtClaims jwtClaims) { Optional<NumericDate> expiration = getDateClaim(ReservedClaimNames.EXPIRATION_TIME, jwtClaims); if (!expiration.isPresent()) { throw new UnauthenticatedException("Missing expiration field"); } Optional<NumericDate> notBefore = getDateClaim(ReservedClaimNames.NOT_BEFORE, jwtClaims); NumericDate currentTime = NumericDate.fromMilliseconds(clock.currentTimeMillis()); if (expiration.get().isBefore(currentTime)) { throw new UnauthenticatedException("The auth token has already expired"); } if (notBefore.isPresent() && notBefore.get().isAfter(currentTime)) { String message = "Current time is earlier than the \"nbf\" time"; throw new UnauthenticatedException(message); } }
[ "private", "void", "checkJwtClaims", "(", "JwtClaims", "jwtClaims", ")", "{", "Optional", "<", "NumericDate", ">", "expiration", "=", "getDateClaim", "(", "ReservedClaimNames", ".", "EXPIRATION_TIME", ",", "jwtClaims", ")", ";", "if", "(", "!", "expiration", "."...
Check whether the JWT claims should be accepted.
[ "Check", "whether", "the", "JWT", "claims", "should", "be", "accepted", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-auth/src/main/java/com/google/api/auth/Authenticator.java#L136-L152
train
greenjoe/lambdaFromString
src/main/java/pl/joegreen/lambdaFromString/ClassPathExtractor.java
ClassPathExtractor.getCurrentContextClassLoaderClassPath
public static String getCurrentContextClassLoaderClassPath(){ URLClassLoader contextClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); return getUrlClassLoaderClassPath(contextClassLoader); }
java
public static String getCurrentContextClassLoaderClassPath(){ URLClassLoader contextClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); return getUrlClassLoaderClassPath(contextClassLoader); }
[ "public", "static", "String", "getCurrentContextClassLoaderClassPath", "(", ")", "{", "URLClassLoader", "contextClassLoader", "=", "(", "URLClassLoader", ")", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "return", "getUrlClass...
Assumes that the context class loader of the current thread is a URLClassLoader and will throw a runtime exception if it is not.
[ "Assumes", "that", "the", "context", "class", "loader", "of", "the", "current", "thread", "is", "a", "URLClassLoader", "and", "will", "throw", "a", "runtime", "exception", "if", "it", "is", "not", "." ]
67d383f3922ab066e908b852a531880772bbdf29
https://github.com/greenjoe/lambdaFromString/blob/67d383f3922ab066e908b852a531880772bbdf29/src/main/java/pl/joegreen/lambdaFromString/ClassPathExtractor.java#L21-L24
train
greenjoe/lambdaFromString
src/main/java/pl/joegreen/lambdaFromString/LambdaFactory.java
LambdaFactory.get
public static LambdaFactory get(LambdaFactoryConfiguration configuration) { JavaCompiler compiler = Optional.ofNullable(configuration.getJavaCompiler()).orElseThrow(JavaCompilerNotFoundException::new); return new LambdaFactory( configuration.getDefaultHelperClassSourceProvider(), configuration.getClassFactory(), compiler, configuration.getImports(), configuration.getStaticImports(), configuration.getCompilationClassPath(), configuration.getParentClassLoader()); }
java
public static LambdaFactory get(LambdaFactoryConfiguration configuration) { JavaCompiler compiler = Optional.ofNullable(configuration.getJavaCompiler()).orElseThrow(JavaCompilerNotFoundException::new); return new LambdaFactory( configuration.getDefaultHelperClassSourceProvider(), configuration.getClassFactory(), compiler, configuration.getImports(), configuration.getStaticImports(), configuration.getCompilationClassPath(), configuration.getParentClassLoader()); }
[ "public", "static", "LambdaFactory", "get", "(", "LambdaFactoryConfiguration", "configuration", ")", "{", "JavaCompiler", "compiler", "=", "Optional", ".", "ofNullable", "(", "configuration", ".", "getJavaCompiler", "(", ")", ")", ".", "orElseThrow", "(", "JavaCompi...
Returns a LambdaFactory instance with the given configuration. @throws JavaCompilerNotFoundException if the library cannot find any java compiler and it's not provided in the configuration
[ "Returns", "a", "LambdaFactory", "instance", "with", "the", "given", "configuration", "." ]
67d383f3922ab066e908b852a531880772bbdf29
https://github.com/greenjoe/lambdaFromString/blob/67d383f3922ab066e908b852a531880772bbdf29/src/main/java/pl/joegreen/lambdaFromString/LambdaFactory.java#L27-L37
train
greenjoe/lambdaFromString
src/main/java/pl/joegreen/lambdaFromString/LambdaFactory.java
LambdaFactory.createLambda
public <T> T createLambda(String code, TypeReference<T> typeReference) throws LambdaCreationException { String helperClassSource = helperProvider.getHelperClassSource(typeReference.toString(), code, imports, staticImports); try { Class<?> helperClass = classFactory.createClass(helperProvider.getHelperClassName(), helperClassSource, javaCompiler, createOptionsForCompilationClasspath(compilationClassPath), parentClassLoader); Method lambdaReturningMethod = helperClass.getMethod(helperProvider.getLambdaReturningMethodName()); @SuppressWarnings("unchecked") // the whole point of the class template and runtime compilation is to make this cast work well :-) T lambda = (T) lambdaReturningMethod.invoke(null); return lambda; } catch (ReflectiveOperationException | RuntimeException | NoClassDefFoundError e) { // NoClassDefFoundError can be thrown if provided parent class loader cannot load classes used by the lambda throw new LambdaCreationException(e); } catch (ClassCompilationException classCompilationException) { // that catch differs from the catch above as the exact exception type is known and additional details can be extracted throw new LambdaCreationException(classCompilationException); } }
java
public <T> T createLambda(String code, TypeReference<T> typeReference) throws LambdaCreationException { String helperClassSource = helperProvider.getHelperClassSource(typeReference.toString(), code, imports, staticImports); try { Class<?> helperClass = classFactory.createClass(helperProvider.getHelperClassName(), helperClassSource, javaCompiler, createOptionsForCompilationClasspath(compilationClassPath), parentClassLoader); Method lambdaReturningMethod = helperClass.getMethod(helperProvider.getLambdaReturningMethodName()); @SuppressWarnings("unchecked") // the whole point of the class template and runtime compilation is to make this cast work well :-) T lambda = (T) lambdaReturningMethod.invoke(null); return lambda; } catch (ReflectiveOperationException | RuntimeException | NoClassDefFoundError e) { // NoClassDefFoundError can be thrown if provided parent class loader cannot load classes used by the lambda throw new LambdaCreationException(e); } catch (ClassCompilationException classCompilationException) { // that catch differs from the catch above as the exact exception type is known and additional details can be extracted throw new LambdaCreationException(classCompilationException); } }
[ "public", "<", "T", ">", "T", "createLambda", "(", "String", "code", ",", "TypeReference", "<", "T", ">", "typeReference", ")", "throws", "LambdaCreationException", "{", "String", "helperClassSource", "=", "helperProvider", ".", "getHelperClassSource", "(", "typeR...
Creates lambda from the given code. @param code source of the lambda as you would write it in Java expression {TYPE} lambda = ({CODE}); @param typeReference a subclass of TypeReference class with the generic argument representing the type of the lambda , for example <br> {@code new TypeReference<Function<Integer,Integer>>(){}; } @param <T> type of the lambda you want to get @throws LambdaCreationException when anything goes wrong (no other exceptions are thrown including runtimes), if the exception was caused by compilation failure it will contain a CompilationDetails instance describing them
[ "Creates", "lambda", "from", "the", "given", "code", "." ]
67d383f3922ab066e908b852a531880772bbdf29
https://github.com/greenjoe/lambdaFromString/blob/67d383f3922ab066e908b852a531880772bbdf29/src/main/java/pl/joegreen/lambdaFromString/LambdaFactory.java#L69-L85
train
wilkenstein/redis-mock-java
src/main/java/org/rarefiedredis/redis/adapter/jedis/AbstractJedisIRedisClient.java
AbstractJedisIRedisClient.zadd
@Override public Long zadd(final String key, final ZsetPair scoremember, final ZsetPair ... scoresmembers) throws WrongTypeException { if (scoremember == null) { return null; } Map<String, Double> sms = new HashMap<String, Double>(); sms.put(scoremember.member, scoremember.score); for (ZsetPair pair : scoresmembers) { if (pair == null) { continue; } sms.put(pair.member, pair.score); } Object ret = command("zadd", key, sms); if (ret instanceof WrongTypeException) { throw (WrongTypeException)ret; } return (Long)ret; }
java
@Override public Long zadd(final String key, final ZsetPair scoremember, final ZsetPair ... scoresmembers) throws WrongTypeException { if (scoremember == null) { return null; } Map<String, Double> sms = new HashMap<String, Double>(); sms.put(scoremember.member, scoremember.score); for (ZsetPair pair : scoresmembers) { if (pair == null) { continue; } sms.put(pair.member, pair.score); } Object ret = command("zadd", key, sms); if (ret instanceof WrongTypeException) { throw (WrongTypeException)ret; } return (Long)ret; }
[ "@", "Override", "public", "Long", "zadd", "(", "final", "String", "key", ",", "final", "ZsetPair", "scoremember", ",", "final", "ZsetPair", "...", "scoresmembers", ")", "throws", "WrongTypeException", "{", "if", "(", "scoremember", "==", "null", ")", "{", "...
multi & watch are both abstract.
[ "multi", "&", "watch", "are", "both", "abstract", "." ]
35a73f0d1b9f7401ecd4eaa58d40e59c8dd8a28e
https://github.com/wilkenstein/redis-mock-java/blob/35a73f0d1b9f7401ecd4eaa58d40e59c8dd8a28e/src/main/java/org/rarefiedredis/redis/adapter/jedis/AbstractJedisIRedisClient.java#L897-L914
train
fflewddur/hola
src/main/java/net/straylightlabs/hola/sd/Query.java
Query.runOnceOn
public Set<Instance> runOnceOn(InetAddress localhost) throws IOException { logger.debug("Running query on {}", localhost); initialQuestion = new Question(service, domain); instances = Collections.synchronizedSet(new HashSet<>()); try { Thread listener = null; if (localhost != TEST_SUITE_ADDRESS) { openSocket(localhost); listener = listenForResponses(); while (!isServerIsListening()) { logger.debug("Server is not yet listening"); } } ask(initialQuestion); if (listener != null) { try { listener.join(); } catch (InterruptedException e) { logger.error("InterruptedException while listening for mDNS responses: ", e); } } } finally { closeSocket(); } return instances; }
java
public Set<Instance> runOnceOn(InetAddress localhost) throws IOException { logger.debug("Running query on {}", localhost); initialQuestion = new Question(service, domain); instances = Collections.synchronizedSet(new HashSet<>()); try { Thread listener = null; if (localhost != TEST_SUITE_ADDRESS) { openSocket(localhost); listener = listenForResponses(); while (!isServerIsListening()) { logger.debug("Server is not yet listening"); } } ask(initialQuestion); if (listener != null) { try { listener.join(); } catch (InterruptedException e) { logger.error("InterruptedException while listening for mDNS responses: ", e); } } } finally { closeSocket(); } return instances; }
[ "public", "Set", "<", "Instance", ">", "runOnceOn", "(", "InetAddress", "localhost", ")", "throws", "IOException", "{", "logger", ".", "debug", "(", "\"Running query on {}\"", ",", "localhost", ")", ";", "initialQuestion", "=", "new", "Question", "(", "service",...
Synchronously runs the Query a single time. @param localhost address of the network interface to listen on @return a list of Instances that match this Query @throws IOException thrown on socket and network errors
[ "Synchronously", "runs", "the", "Query", "a", "single", "time", "." ]
08d9b9f3b807fd447181a5c1122f117a950db848
https://github.com/fflewddur/hola/blob/08d9b9f3b807fd447181a5c1122f117a950db848/src/main/java/net/straylightlabs/hola/sd/Query.java#L126-L151
train
fflewddur/hola
src/main/java/net/straylightlabs/hola/sd/Query.java
Query.fetchMissingRecords
private void fetchMissingRecords() throws IOException { logger.debug("Records includes:"); records.forEach(r -> logger.debug("{}", r)); for (PtrRecord ptr : records.stream().filter(r -> r instanceof PtrRecord).map(r -> (PtrRecord) r).collect(Collectors.toList())) { fetchMissingSrvRecordsFor(ptr); fetchMissingTxtRecordsFor(ptr); } for (SrvRecord srv : records.stream().filter(r -> r instanceof SrvRecord).map(r -> (SrvRecord) r).collect(Collectors.toList())) { fetchMissingAddressRecordsFor(srv); } }
java
private void fetchMissingRecords() throws IOException { logger.debug("Records includes:"); records.forEach(r -> logger.debug("{}", r)); for (PtrRecord ptr : records.stream().filter(r -> r instanceof PtrRecord).map(r -> (PtrRecord) r).collect(Collectors.toList())) { fetchMissingSrvRecordsFor(ptr); fetchMissingTxtRecordsFor(ptr); } for (SrvRecord srv : records.stream().filter(r -> r instanceof SrvRecord).map(r -> (SrvRecord) r).collect(Collectors.toList())) { fetchMissingAddressRecordsFor(srv); } }
[ "private", "void", "fetchMissingRecords", "(", ")", "throws", "IOException", "{", "logger", ".", "debug", "(", "\"Records includes:\"", ")", ";", "records", ".", "forEach", "(", "r", "->", "logger", ".", "debug", "(", "\"{}\"", ",", "r", ")", ")", ";", "...
Verify that each PTR record has corresponding SRV, TXT, and either A or AAAA records. Request any that are missing.
[ "Verify", "that", "each", "PTR", "record", "has", "corresponding", "SRV", "TXT", "and", "either", "A", "or", "AAAA", "records", ".", "Request", "any", "that", "are", "missing", "." ]
08d9b9f3b807fd447181a5c1122f117a950db848
https://github.com/fflewddur/hola/blob/08d9b9f3b807fd447181a5c1122f117a950db848/src/main/java/net/straylightlabs/hola/sd/Query.java#L281-L291
train
pandzel/RobotsTxt
src/main/java/com/panforge/robotstxt/Access.java
Access.matches
public boolean matches(String path, MatchingStrategy matchingStrategy) { return path!=null && matchingStrategy.matches(clause, path); }
java
public boolean matches(String path, MatchingStrategy matchingStrategy) { return path!=null && matchingStrategy.matches(clause, path); }
[ "public", "boolean", "matches", "(", "String", "path", ",", "MatchingStrategy", "matchingStrategy", ")", "{", "return", "path", "!=", "null", "&&", "matchingStrategy", ".", "matches", "(", "clause", ",", "path", ")", ";", "}" ]
Checks if path matches access path @param path path to check @param matchingStrategy matcher @return <code>true</code> if path matches access path
[ "Checks", "if", "path", "matches", "access", "path" ]
f5291d21675c87a97c0e77c37453cc112f8a12a9
https://github.com/pandzel/RobotsTxt/blob/f5291d21675c87a97c0e77c37453cc112f8a12a9/src/main/java/com/panforge/robotstxt/Access.java#L70-L72
train
pandzel/RobotsTxt
src/main/java/com/panforge/robotstxt/RobotsTxtImpl.java
RobotsTxtImpl.addGroup
public void addGroup(Group section) { if (section != null) { if (section.isAnyAgent()) { if (this.defaultSection == null) { this.defaultSection = section; } else { this.defaultSection.getAccessList().importAccess(section.getAccessList()); } } else { Group exact = findExactSection(section); if (exact == null) { groups.add(section); } else { exact.getAccessList().importAccess(section.getAccessList()); } } } }
java
public void addGroup(Group section) { if (section != null) { if (section.isAnyAgent()) { if (this.defaultSection == null) { this.defaultSection = section; } else { this.defaultSection.getAccessList().importAccess(section.getAccessList()); } } else { Group exact = findExactSection(section); if (exact == null) { groups.add(section); } else { exact.getAccessList().importAccess(section.getAccessList()); } } } }
[ "public", "void", "addGroup", "(", "Group", "section", ")", "{", "if", "(", "section", "!=", "null", ")", "{", "if", "(", "section", ".", "isAnyAgent", "(", ")", ")", "{", "if", "(", "this", ".", "defaultSection", "==", "null", ")", "{", "this", "....
Adds section. @param section section
[ "Adds", "section", "." ]
f5291d21675c87a97c0e77c37453cc112f8a12a9
https://github.com/pandzel/RobotsTxt/blob/f5291d21675c87a97c0e77c37453cc112f8a12a9/src/main/java/com/panforge/robotstxt/RobotsTxtImpl.java#L118-L135
train
pandzel/RobotsTxt
src/main/java/com/panforge/robotstxt/RobotsTxtImpl.java
RobotsTxtImpl.findExactSection
private Group findExactSection(Group section) { for (Group s : groups) { if (s.isExact(section)) { return s; } } return null; }
java
private Group findExactSection(Group section) { for (Group s : groups) { if (s.isExact(section)) { return s; } } return null; }
[ "private", "Group", "findExactSection", "(", "Group", "section", ")", "{", "for", "(", "Group", "s", ":", "groups", ")", "{", "if", "(", "s", ".", "isExact", "(", "section", ")", ")", "{", "return", "s", ";", "}", "}", "return", "null", ";", "}" ]
Finds exact section. @param section section to find exact @return exact section or {@code null} if no exact section found
[ "Finds", "exact", "section", "." ]
f5291d21675c87a97c0e77c37453cc112f8a12a9
https://github.com/pandzel/RobotsTxt/blob/f5291d21675c87a97c0e77c37453cc112f8a12a9/src/main/java/com/panforge/robotstxt/RobotsTxtImpl.java#L167-L174
train
pandzel/RobotsTxt
src/main/java/com/panforge/robotstxt/RobotsTxtReader.java
RobotsTxtReader.readRobotsTxt
public RobotsTxt readRobotsTxt(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); Group currentGroup = null; boolean startGroup = false; RobotsTxtImpl robots = new RobotsTxtImpl(matchingStrategy, winningStrategy); for (Entry entry = readEntry(reader); entry != null; entry = readEntry(reader)) { switch (entry.getKey().toUpperCase()) { case "USER-AGENT": if (!startGroup && currentGroup != null) { robots.addGroup(currentGroup); currentGroup = null; } if (currentGroup == null) { currentGroup = new Group(); } currentGroup.addUserAgent(entry.getValue()); startGroup = true; break; case "DISALLOW": if (currentGroup != null) { boolean access = entry.getValue().isEmpty(); currentGroup.addAccess(new Access(currentGroup, entry.getSource(), entry.getValue(), access)); startGroup = false; } break; case "ALLOW": if (currentGroup != null) { boolean access = !entry.getValue().isEmpty(); currentGroup.addAccess(new Access(currentGroup, entry.getSource(), entry.getValue(), access)); startGroup = false; } break; case "CRAWL-DELAY": if (currentGroup != null) { try { int crawlDelay = Integer.parseInt(entry.getValue()); currentGroup.setCrawlDelay(crawlDelay); startGroup = false; } catch (NumberFormatException ex) { } } else { } break; case "HOST": robots.setHost(entry.getValue()); startGroup = false; break; case "SITEMAP": robots.getSitemaps().add(entry.getValue()); startGroup = false; break; default: startGroup = false; break; } } if (currentGroup != null) { robots.addGroup(currentGroup); } return robots; }
java
public RobotsTxt readRobotsTxt(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); Group currentGroup = null; boolean startGroup = false; RobotsTxtImpl robots = new RobotsTxtImpl(matchingStrategy, winningStrategy); for (Entry entry = readEntry(reader); entry != null; entry = readEntry(reader)) { switch (entry.getKey().toUpperCase()) { case "USER-AGENT": if (!startGroup && currentGroup != null) { robots.addGroup(currentGroup); currentGroup = null; } if (currentGroup == null) { currentGroup = new Group(); } currentGroup.addUserAgent(entry.getValue()); startGroup = true; break; case "DISALLOW": if (currentGroup != null) { boolean access = entry.getValue().isEmpty(); currentGroup.addAccess(new Access(currentGroup, entry.getSource(), entry.getValue(), access)); startGroup = false; } break; case "ALLOW": if (currentGroup != null) { boolean access = !entry.getValue().isEmpty(); currentGroup.addAccess(new Access(currentGroup, entry.getSource(), entry.getValue(), access)); startGroup = false; } break; case "CRAWL-DELAY": if (currentGroup != null) { try { int crawlDelay = Integer.parseInt(entry.getValue()); currentGroup.setCrawlDelay(crawlDelay); startGroup = false; } catch (NumberFormatException ex) { } } else { } break; case "HOST": robots.setHost(entry.getValue()); startGroup = false; break; case "SITEMAP": robots.getSitemaps().add(entry.getValue()); startGroup = false; break; default: startGroup = false; break; } } if (currentGroup != null) { robots.addGroup(currentGroup); } return robots; }
[ "public", "RobotsTxt", "readRobotsTxt", "(", "InputStream", "inputStream", ")", "throws", "IOException", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "inputStream", ",", "\"UTF-8\"", ")", ")", ";", "Group", "...
Reads robots txt. @param inputStream input stream with robots.txt content. @return parsed robots.txt @throws IOException if reading stream fails
[ "Reads", "robots", "txt", "." ]
f5291d21675c87a97c0e77c37453cc112f8a12a9
https://github.com/pandzel/RobotsTxt/blob/f5291d21675c87a97c0e77c37453cc112f8a12a9/src/main/java/com/panforge/robotstxt/RobotsTxtReader.java#L58-L129
train
pandzel/RobotsTxt
src/main/java/com/panforge/robotstxt/RobotsTxtReader.java
RobotsTxtReader.readEntry
private Entry readEntry(BufferedReader reader) throws IOException { for (String line = reader.readLine(); line != null; line = reader.readLine()) { Entry entry = parseEntry(line); if (entry != null) { return entry; } } return null; }
java
private Entry readEntry(BufferedReader reader) throws IOException { for (String line = reader.readLine(); line != null; line = reader.readLine()) { Entry entry = parseEntry(line); if (entry != null) { return entry; } } return null; }
[ "private", "Entry", "readEntry", "(", "BufferedReader", "reader", ")", "throws", "IOException", "{", "for", "(", "String", "line", "=", "reader", ".", "readLine", "(", ")", ";", "line", "!=", "null", ";", "line", "=", "reader", ".", "readLine", "(", ")",...
Reads next entry from the reader. @return entry or <code>null</code> if no more data in the stream @throws IOException if reading from stream fails
[ "Reads", "next", "entry", "from", "the", "reader", "." ]
f5291d21675c87a97c0e77c37453cc112f8a12a9
https://github.com/pandzel/RobotsTxt/blob/f5291d21675c87a97c0e77c37453cc112f8a12a9/src/main/java/com/panforge/robotstxt/RobotsTxtReader.java#L137-L145
train
pandzel/RobotsTxt
src/main/java/com/panforge/robotstxt/Group.java
Group.isExact
public boolean isExact(Group group) { if (isAnyAgent() && group.isAnyAgent()) return true; if ((isAnyAgent() && !group.isAnyAgent() || (!isAnyAgent() && group.isAnyAgent()))) return false; return group.userAgents.stream().anyMatch(sectionUserAgent->userAgents.stream().anyMatch(userAgent->userAgent.equalsIgnoreCase(sectionUserAgent))); }
java
public boolean isExact(Group group) { if (isAnyAgent() && group.isAnyAgent()) return true; if ((isAnyAgent() && !group.isAnyAgent() || (!isAnyAgent() && group.isAnyAgent()))) return false; return group.userAgents.stream().anyMatch(sectionUserAgent->userAgents.stream().anyMatch(userAgent->userAgent.equalsIgnoreCase(sectionUserAgent))); }
[ "public", "boolean", "isExact", "(", "Group", "group", ")", "{", "if", "(", "isAnyAgent", "(", ")", "&&", "group", ".", "isAnyAgent", "(", ")", ")", "return", "true", ";", "if", "(", "(", "isAnyAgent", "(", ")", "&&", "!", "group", ".", "isAnyAgent",...
Checks if group is exact in terms of user agents. @param group group to compare @return {@code true} if sections are exact.
[ "Checks", "if", "group", "is", "exact", "in", "terms", "of", "user", "agents", "." ]
f5291d21675c87a97c0e77c37453cc112f8a12a9
https://github.com/pandzel/RobotsTxt/blob/f5291d21675c87a97c0e77c37453cc112f8a12a9/src/main/java/com/panforge/robotstxt/Group.java#L47-L52
train
pandzel/RobotsTxt
src/main/java/com/panforge/robotstxt/Group.java
Group.addUserAgent
public void addUserAgent(String userAgent) { if (userAgent.equals("*")) { anyAgent = true; } else { this.userAgents.add(userAgent); } }
java
public void addUserAgent(String userAgent) { if (userAgent.equals("*")) { anyAgent = true; } else { this.userAgents.add(userAgent); } }
[ "public", "void", "addUserAgent", "(", "String", "userAgent", ")", "{", "if", "(", "userAgent", ".", "equals", "(", "\"*\"", ")", ")", "{", "anyAgent", "=", "true", ";", "}", "else", "{", "this", ".", "userAgents", ".", "add", "(", "userAgent", ")", ...
Adds user agent. @param userAgent host name
[ "Adds", "user", "agent", "." ]
f5291d21675c87a97c0e77c37453cc112f8a12a9
https://github.com/pandzel/RobotsTxt/blob/f5291d21675c87a97c0e77c37453cc112f8a12a9/src/main/java/com/panforge/robotstxt/Group.java#L58-L64
train
pandzel/RobotsTxt
src/main/java/com/panforge/robotstxt/Group.java
Group.matchUserAgent
public boolean matchUserAgent(String userAgent) { if (anyAgent) return true; if (!anyAgent && userAgent==null) return false; return userAgents.stream().anyMatch(agent->agent.equalsIgnoreCase(userAgent)); }
java
public boolean matchUserAgent(String userAgent) { if (anyAgent) return true; if (!anyAgent && userAgent==null) return false; return userAgents.stream().anyMatch(agent->agent.equalsIgnoreCase(userAgent)); }
[ "public", "boolean", "matchUserAgent", "(", "String", "userAgent", ")", "{", "if", "(", "anyAgent", ")", "return", "true", ";", "if", "(", "!", "anyAgent", "&&", "userAgent", "==", "null", ")", "return", "false", ";", "return", "userAgents", ".", "stream",...
Checks if the section is applicable for a given user agent. @param userAgent requested user agent @return <code>true</code> if the section is applicable for the requested user agent
[ "Checks", "if", "the", "section", "is", "applicable", "for", "a", "given", "user", "agent", "." ]
f5291d21675c87a97c0e77c37453cc112f8a12a9
https://github.com/pandzel/RobotsTxt/blob/f5291d21675c87a97c0e77c37453cc112f8a12a9/src/main/java/com/panforge/robotstxt/Group.java#L110-L114
train
fflewddur/hola
src/main/java/net/straylightlabs/hola/utils/Utils.java
Utils.getNextPath
public static Path getNextPath(String prefix) { Path path; do { path = Paths.get(String.format("%s%s", prefix, Integer.toString(nextDumpPathSuffix))); nextDumpPathSuffix++; } while (Files.exists(path)); return path; }
java
public static Path getNextPath(String prefix) { Path path; do { path = Paths.get(String.format("%s%s", prefix, Integer.toString(nextDumpPathSuffix))); nextDumpPathSuffix++; } while (Files.exists(path)); return path; }
[ "public", "static", "Path", "getNextPath", "(", "String", "prefix", ")", "{", "Path", "path", ";", "do", "{", "path", "=", "Paths", ".", "get", "(", "String", ".", "format", "(", "\"%s%s\"", ",", "prefix", ",", "Integer", ".", "toString", "(", "nextDum...
Get the next sequential Path for a binary dump file, ensuring we don't overwrite any existing files. @param prefix The start of the file name @return Next sequential Path
[ "Get", "the", "next", "sequential", "Path", "for", "a", "binary", "dump", "file", "ensuring", "we", "don", "t", "overwrite", "any", "existing", "files", "." ]
08d9b9f3b807fd447181a5c1122f117a950db848
https://github.com/fflewddur/hola/blob/08d9b9f3b807fd447181a5c1122f117a950db848/src/main/java/net/straylightlabs/hola/utils/Utils.java#L71-L80
train
fflewddur/hola
src/main/java/net/straylightlabs/hola/utils/Utils.java
Utils.printBuffer
public static void printBuffer(byte[] buffer, String msg) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buffer.length; i++) { if (i % 20 == 0) { sb.append("\n\t"); } sb.append(String.format("%02x", buffer[i])); } logger.info("{}: {}", msg, sb.toString()); }
java
public static void printBuffer(byte[] buffer, String msg) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buffer.length; i++) { if (i % 20 == 0) { sb.append("\n\t"); } sb.append(String.format("%02x", buffer[i])); } logger.info("{}: {}", msg, sb.toString()); }
[ "public", "static", "void", "printBuffer", "(", "byte", "[", "]", "buffer", ",", "String", "msg", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "buffer", ".", "length", ...
Print a formatted version of @buffer in hex @param buffer the byte buffer to display
[ "Print", "a", "formatted", "version", "of" ]
08d9b9f3b807fd447181a5c1122f117a950db848
https://github.com/fflewddur/hola/blob/08d9b9f3b807fd447181a5c1122f117a950db848/src/main/java/net/straylightlabs/hola/utils/Utils.java#L86-L97
train
netshoes/spring-cloud-sleuth-amqp
src/main/java/com/netshoes/springframework/cloud/sleuth/instrument/amqp/support/AmqpMessageHeaderAccessor.java
AmqpMessageHeaderAccessor.getHeader
public <T> T getHeader(String name, Class<T> type) { return (T) headers.get(name); }
java
public <T> T getHeader(String name, Class<T> type) { return (T) headers.get(name); }
[ "public", "<", "T", ">", "T", "getHeader", "(", "String", "name", ",", "Class", "<", "T", ">", "type", ")", "{", "return", "(", "T", ")", "headers", ".", "get", "(", "name", ")", ";", "}" ]
Get a header value casting to expected type. @param name Name of header @param type Expected type of header's value @param <T> Expected type of header's value @return Value of header
[ "Get", "a", "header", "value", "casting", "to", "expected", "type", "." ]
e4616ba6a075286d553548a1e2a500cf0ff85557
https://github.com/netshoes/spring-cloud-sleuth-amqp/blob/e4616ba6a075286d553548a1e2a500cf0ff85557/src/main/java/com/netshoes/springframework/cloud/sleuth/instrument/amqp/support/AmqpMessageHeaderAccessor.java#L79-L81
train
arangodb/java-velocypack
src/main/java/com/arangodb/velocypack/internal/util/NumberUtil.java
NumberUtil.readVariableValueLength
public static long readVariableValueLength(final byte[] array, final int offset, final boolean reverse) { long len = 0; byte v; long p = 0; int i = offset; do { v = array[i]; len += ((long) (v & (byte) 0x7f)) << p; p += 7; if (reverse) { --i; } else { ++i; } } while ((v & (byte) 0x80) != 0); return len; }
java
public static long readVariableValueLength(final byte[] array, final int offset, final boolean reverse) { long len = 0; byte v; long p = 0; int i = offset; do { v = array[i]; len += ((long) (v & (byte) 0x7f)) << p; p += 7; if (reverse) { --i; } else { ++i; } } while ((v & (byte) 0x80) != 0); return len; }
[ "public", "static", "long", "readVariableValueLength", "(", "final", "byte", "[", "]", "array", ",", "final", "int", "offset", ",", "final", "boolean", "reverse", ")", "{", "long", "len", "=", "0", ";", "byte", "v", ";", "long", "p", "=", "0", ";", "...
read a variable length integer in unsigned LEB128 format
[ "read", "a", "variable", "length", "integer", "in", "unsigned", "LEB128", "format" ]
e7a42c462ce251f206891bedd8a384c5127bde88
https://github.com/arangodb/java-velocypack/blob/e7a42c462ce251f206891bedd8a384c5127bde88/src/main/java/com/arangodb/velocypack/internal/util/NumberUtil.java#L73-L89
train
arangodb/java-velocypack
src/main/java/com/arangodb/velocypack/VPackSlice.java
VPackSlice.translateUnchecked
protected VPackSlice translateUnchecked() { final VPackSlice result = attributeTranslator.translate(getAsInt()); return result != null ? result : new VPackSlice(); }
java
protected VPackSlice translateUnchecked() { final VPackSlice result = attributeTranslator.translate(getAsInt()); return result != null ? result : new VPackSlice(); }
[ "protected", "VPackSlice", "translateUnchecked", "(", ")", "{", "final", "VPackSlice", "result", "=", "attributeTranslator", ".", "translate", "(", "getAsInt", "(", ")", ")", ";", "return", "result", "!=", "null", "?", "result", ":", "new", "VPackSlice", "(", ...
translates an integer key into a string, without checks
[ "translates", "an", "integer", "key", "into", "a", "string", "without", "checks" ]
e7a42c462ce251f206891bedd8a384c5127bde88
https://github.com/arangodb/java-velocypack/blob/e7a42c462ce251f206891bedd8a384c5127bde88/src/main/java/com/arangodb/velocypack/VPackSlice.java#L536-L539
train
ptgoetz/storm-jms
src/main/java/org/apache/storm/jms/bolt/JmsBolt.java
JmsBolt.prepare
@Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { if(this.jmsProvider == null || this.producer == null){ throw new IllegalStateException("JMS Provider and MessageProducer not set."); } this.collector = collector; LOG.debug("Connecting JMS.."); try { ConnectionFactory cf = this.jmsProvider.connectionFactory(); Destination dest = this.jmsProvider.destination(); this.connection = cf.createConnection(); this.session = connection.createSession(this.jmsTransactional, this.jmsAcknowledgeMode); this.messageProducer = session.createProducer(dest); connection.start(); } catch (Exception e) { LOG.warn("Error creating JMS connection.", e); } }
java
@Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { if(this.jmsProvider == null || this.producer == null){ throw new IllegalStateException("JMS Provider and MessageProducer not set."); } this.collector = collector; LOG.debug("Connecting JMS.."); try { ConnectionFactory cf = this.jmsProvider.connectionFactory(); Destination dest = this.jmsProvider.destination(); this.connection = cf.createConnection(); this.session = connection.createSession(this.jmsTransactional, this.jmsAcknowledgeMode); this.messageProducer = session.createProducer(dest); connection.start(); } catch (Exception e) { LOG.warn("Error creating JMS connection.", e); } }
[ "@", "Override", "public", "void", "prepare", "(", "Map", "stormConf", ",", "TopologyContext", "context", ",", "OutputCollector", "collector", ")", "{", "if", "(", "this", ".", "jmsProvider", "==", "null", "||", "this", ".", "producer", "==", "null", ")", ...
Initializes JMS resources.
[ "Initializes", "JMS", "resources", "." ]
aab6acdf316c48bf566e37776790116f2794199b
https://github.com/ptgoetz/storm-jms/blob/aab6acdf316c48bf566e37776790116f2794199b/src/main/java/org/apache/storm/jms/bolt/JmsBolt.java#L180-L200
train
wiselenium/wiselenium
wiselenium-factory/src/main/java/com/github/wiselenium/Wiselenium.java
Wiselenium.decorateElement
public static <E> E decorateElement(Class<E> clazz, WebElement webElement) { WiseDecorator decorator = new WiseDecorator(new DefaultElementLocatorFactory(webElement)); return decorator.decorate(clazz, webElement); }
java
public static <E> E decorateElement(Class<E> clazz, WebElement webElement) { WiseDecorator decorator = new WiseDecorator(new DefaultElementLocatorFactory(webElement)); return decorator.decorate(clazz, webElement); }
[ "public", "static", "<", "E", ">", "E", "decorateElement", "(", "Class", "<", "E", ">", "clazz", ",", "WebElement", "webElement", ")", "{", "WiseDecorator", "decorator", "=", "new", "WiseDecorator", "(", "new", "DefaultElementLocatorFactory", "(", "webElement", ...
Decorates a webElement. @param clazz The class of the decorated element. Must be either WebElement or a type annotated with Component or Frame. @param webElement The webElement that will be decorated. @return The decorated element or null if the type isn't supported. @since 0.3.0
[ "Decorates", "a", "webElement", "." ]
15de6484d8f516b3d02391d3bd6a56a03e632706
https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-factory/src/main/java/com/github/wiselenium/Wiselenium.java#L86-L89
train
wiselenium/wiselenium
wiselenium-factory/src/main/java/com/github/wiselenium/Wiselenium.java
Wiselenium.decorateElements
public static <E> List<E> decorateElements(Class<E> clazz, List<WebElement> webElements) { List<E> elements = Lists.newArrayList(); for (WebElement webElement : webElements) { E element = decorateElement(clazz, webElement); if (element != null) elements.add(element); } return elements; }
java
public static <E> List<E> decorateElements(Class<E> clazz, List<WebElement> webElements) { List<E> elements = Lists.newArrayList(); for (WebElement webElement : webElements) { E element = decorateElement(clazz, webElement); if (element != null) elements.add(element); } return elements; }
[ "public", "static", "<", "E", ">", "List", "<", "E", ">", "decorateElements", "(", "Class", "<", "E", ">", "clazz", ",", "List", "<", "WebElement", ">", "webElements", ")", "{", "List", "<", "E", ">", "elements", "=", "Lists", ".", "newArrayList", "(...
Decorates a list of webElements. @param clazz The class of the decorated elements. Must be either WebElement or a type annotated with Component or Frame. @param webElements The webElements that will be decorated. @return The list of decorated elements or an empty list if the type is not supported. @since 0.3.0
[ "Decorates", "a", "list", "of", "webElements", "." ]
15de6484d8f516b3d02391d3bd6a56a03e632706
https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-factory/src/main/java/com/github/wiselenium/Wiselenium.java#L100-L107
train
lukas-krecan/completion-stage
src/main/java/net/javacrumbs/completionstage/CallbackRegistry.java
CallbackRegistry.addCallbacks
void addCallbacks(Consumer<? super T> successCallback, Consumer<Throwable> failureCallback, Executor executor) { Objects.requireNonNull(successCallback, "'successCallback' must not be null"); Objects.requireNonNull(failureCallback, "'failureCallback' must not be null"); Objects.requireNonNull(executor, "'executor' must not be null"); synchronized (mutex) { state = state.addCallbacks(successCallback, failureCallback, executor); } }
java
void addCallbacks(Consumer<? super T> successCallback, Consumer<Throwable> failureCallback, Executor executor) { Objects.requireNonNull(successCallback, "'successCallback' must not be null"); Objects.requireNonNull(failureCallback, "'failureCallback' must not be null"); Objects.requireNonNull(executor, "'executor' must not be null"); synchronized (mutex) { state = state.addCallbacks(successCallback, failureCallback, executor); } }
[ "void", "addCallbacks", "(", "Consumer", "<", "?", "super", "T", ">", "successCallback", ",", "Consumer", "<", "Throwable", ">", "failureCallback", ",", "Executor", "executor", ")", "{", "Objects", ".", "requireNonNull", "(", "successCallback", ",", "\"'successC...
Adds the given callbacks to this registry.
[ "Adds", "the", "given", "callbacks", "to", "this", "registry", "." ]
9c270d779b5fc98dc958a5fb335f6e2ad9d06962
https://github.com/lukas-krecan/completion-stage/blob/9c270d779b5fc98dc958a5fb335f6e2ad9d06962/src/main/java/net/javacrumbs/completionstage/CallbackRegistry.java#L40-L48
train
lukas-krecan/completion-stage
src/main/java/net/javacrumbs/completionstage/CallbackRegistry.java
CallbackRegistry.success
boolean success(T result) { State<T> oldState; synchronized (mutex) { if (state.isCompleted()) { return false; } oldState = state; state = state.getSuccessState(result); } oldState.callSuccessCallbacks(result); return true; }
java
boolean success(T result) { State<T> oldState; synchronized (mutex) { if (state.isCompleted()) { return false; } oldState = state; state = state.getSuccessState(result); } oldState.callSuccessCallbacks(result); return true; }
[ "boolean", "success", "(", "T", "result", ")", "{", "State", "<", "T", ">", "oldState", ";", "synchronized", "(", "mutex", ")", "{", "if", "(", "state", ".", "isCompleted", "(", ")", ")", "{", "return", "false", ";", "}", "oldState", "=", "state", ...
To be called to set the result value. @param result the result value @return true if this result will be used (first result registered)
[ "To", "be", "called", "to", "set", "the", "result", "value", "." ]
9c270d779b5fc98dc958a5fb335f6e2ad9d06962
https://github.com/lukas-krecan/completion-stage/blob/9c270d779b5fc98dc958a5fb335f6e2ad9d06962/src/main/java/net/javacrumbs/completionstage/CallbackRegistry.java#L56-L68
train
lukas-krecan/completion-stage
src/main/java/net/javacrumbs/completionstage/CallbackRegistry.java
CallbackRegistry.failure
boolean failure(Throwable failure) { State<T> oldState; synchronized (mutex) { if (state.isCompleted()) { return false; } oldState = state; state = state.getFailureState(failure); } oldState.callFailureCallbacks(failure); return true; }
java
boolean failure(Throwable failure) { State<T> oldState; synchronized (mutex) { if (state.isCompleted()) { return false; } oldState = state; state = state.getFailureState(failure); } oldState.callFailureCallbacks(failure); return true; }
[ "boolean", "failure", "(", "Throwable", "failure", ")", "{", "State", "<", "T", ">", "oldState", ";", "synchronized", "(", "mutex", ")", "{", "if", "(", "state", ".", "isCompleted", "(", ")", ")", "{", "return", "false", ";", "}", "oldState", "=", "s...
To be called to set the failure exception @param failure the exception @return true if this result will be used (first result registered)
[ "To", "be", "called", "to", "set", "the", "failure", "exception" ]
9c270d779b5fc98dc958a5fb335f6e2ad9d06962
https://github.com/lukas-krecan/completion-stage/blob/9c270d779b5fc98dc958a5fb335f6e2ad9d06962/src/main/java/net/javacrumbs/completionstage/CallbackRegistry.java#L76-L87
train
wiselenium/wiselenium
wiselenium-elements/src/main/java/com/github/wiselenium/elements/page/Page.java
Page.initNextPage
public <E> E initNextPage(Class<E> clazz) { return WisePageFactory.initElements(this.driver, clazz); }
java
public <E> E initNextPage(Class<E> clazz) { return WisePageFactory.initElements(this.driver, clazz); }
[ "public", "<", "E", ">", "E", "initNextPage", "(", "Class", "<", "E", ">", "clazz", ")", "{", "return", "WisePageFactory", ".", "initElements", "(", "this", ".", "driver", ",", "clazz", ")", ";", "}" ]
Instantiates the next page of the user navigation and initialize its elements. @param <E> The type of the page. @param clazz The class of the page. @return An instance of the next page of the user navigation. @since 0.3.0
[ "Instantiates", "the", "next", "page", "of", "the", "user", "navigation", "and", "initialize", "its", "elements", "." ]
15de6484d8f516b3d02391d3bd6a56a03e632706
https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-elements/src/main/java/com/github/wiselenium/elements/page/Page.java#L81-L83
train
lukas-krecan/completion-stage
src/main/java/net/javacrumbs/completionstage/SimpleCompletionStage.java
SimpleCompletionStage.acceptResult
private static <T> void acceptResult(CompletableCompletionStage<T> s, Supplier<? extends T> supplier) { try { // exception can be thrown only by supplier. All callbacks are generated by us and they do not throw any exceptions s.complete(supplier.get()); } catch (Throwable e) { handleFailure(s, e); } }
java
private static <T> void acceptResult(CompletableCompletionStage<T> s, Supplier<? extends T> supplier) { try { // exception can be thrown only by supplier. All callbacks are generated by us and they do not throw any exceptions s.complete(supplier.get()); } catch (Throwable e) { handleFailure(s, e); } }
[ "private", "static", "<", "T", ">", "void", "acceptResult", "(", "CompletableCompletionStage", "<", "T", ">", "s", ",", "Supplier", "<", "?", "extends", "T", ">", "supplier", ")", "{", "try", "{", "// exception can be thrown only by supplier. All callbacks are gener...
Accepts result provided by the Supplier. If an exception is thrown by the supplier, completes exceptionally. @param supplier generates result
[ "Accepts", "result", "provided", "by", "the", "Supplier", ".", "If", "an", "exception", "is", "thrown", "by", "the", "supplier", "completes", "exceptionally", "." ]
9c270d779b5fc98dc958a5fb335f6e2ad9d06962
https://github.com/lukas-krecan/completion-stage/blob/9c270d779b5fc98dc958a5fb335f6e2ad9d06962/src/main/java/net/javacrumbs/completionstage/SimpleCompletionStage.java#L269-L276
train
lukas-krecan/completion-stage
src/main/java/net/javacrumbs/completionstage/SimpleCompletionStage.java
SimpleCompletionStage.completeHandler
private static <T> BiConsumer<T, Throwable> completeHandler(CompletableCompletionStage<T> s) { return (result, failure) -> { if (failure == null) { s.complete(result); } else { handleFailure(s, failure); } }; }
java
private static <T> BiConsumer<T, Throwable> completeHandler(CompletableCompletionStage<T> s) { return (result, failure) -> { if (failure == null) { s.complete(result); } else { handleFailure(s, failure); } }; }
[ "private", "static", "<", "T", ">", "BiConsumer", "<", "T", ",", "Throwable", ">", "completeHandler", "(", "CompletableCompletionStage", "<", "T", ">", "s", ")", "{", "return", "(", "result", ",", "failure", ")", "->", "{", "if", "(", "failure", "==", ...
Handler that can be used in whenComplete method. @return BiConsumer that passes values to this CompletionStage.
[ "Handler", "that", "can", "be", "used", "in", "whenComplete", "method", "." ]
9c270d779b5fc98dc958a5fb335f6e2ad9d06962
https://github.com/lukas-krecan/completion-stage/blob/9c270d779b5fc98dc958a5fb335f6e2ad9d06962/src/main/java/net/javacrumbs/completionstage/SimpleCompletionStage.java#L283-L291
train
lukas-krecan/completion-stage
src/main/java/net/javacrumbs/completionstage/CompletionStageFactory.java
CompletionStageFactory.completedStage
public final <T> CompletionStage<T> completedStage(T value) { CompletableCompletionStage<T> result = createCompletionStage(); result.complete(value); return result; }
java
public final <T> CompletionStage<T> completedStage(T value) { CompletableCompletionStage<T> result = createCompletionStage(); result.complete(value); return result; }
[ "public", "final", "<", "T", ">", "CompletionStage", "<", "T", ">", "completedStage", "(", "T", "value", ")", "{", "CompletableCompletionStage", "<", "T", ">", "result", "=", "createCompletionStage", "(", ")", ";", "result", ".", "complete", "(", "value", ...
Returns a new CompletionStage that is already completed with the given value. @param value the value @param <T> the type of the value @return the completed CompletionStage
[ "Returns", "a", "new", "CompletionStage", "that", "is", "already", "completed", "with", "the", "given", "value", "." ]
9c270d779b5fc98dc958a5fb335f6e2ad9d06962
https://github.com/lukas-krecan/completion-stage/blob/9c270d779b5fc98dc958a5fb335f6e2ad9d06962/src/main/java/net/javacrumbs/completionstage/CompletionStageFactory.java#L56-L60
train
lukas-krecan/completion-stage
src/main/java/net/javacrumbs/completionstage/CompletionStageFactory.java
CompletionStageFactory.supplyAsync
public final <U> CompletionStage<U> supplyAsync(Supplier<U> supplier) { return supplyAsync(supplier, defaultAsyncExecutor); }
java
public final <U> CompletionStage<U> supplyAsync(Supplier<U> supplier) { return supplyAsync(supplier, defaultAsyncExecutor); }
[ "public", "final", "<", "U", ">", "CompletionStage", "<", "U", ">", "supplyAsync", "(", "Supplier", "<", "U", ">", "supplier", ")", "{", "return", "supplyAsync", "(", "supplier", ",", "defaultAsyncExecutor", ")", ";", "}" ]
Returns a new CompletionStage that is asynchronously completed by a task running in the defaultAsyncExecutor with the value obtained by calling the given Supplier. @param supplier a function returning the value to be used to complete the returned CompletionStage @param <U> the function's return type @return the new CompletionStage
[ "Returns", "a", "new", "CompletionStage", "that", "is", "asynchronously", "completed", "by", "a", "task", "running", "in", "the", "defaultAsyncExecutor", "with", "the", "value", "obtained", "by", "calling", "the", "given", "Supplier", "." ]
9c270d779b5fc98dc958a5fb335f6e2ad9d06962
https://github.com/lukas-krecan/completion-stage/blob/9c270d779b5fc98dc958a5fb335f6e2ad9d06962/src/main/java/net/javacrumbs/completionstage/CompletionStageFactory.java#L72-L74
train
lukas-krecan/completion-stage
src/main/java/net/javacrumbs/completionstage/CompletionStageFactory.java
CompletionStageFactory.supplyAsync
public final <U> CompletionStage<U> supplyAsync(Supplier<U> supplier, Executor executor) { Objects.requireNonNull(supplier, "supplier must not be null"); return completedStage(null).thenApplyAsync((ignored) -> supplier.get(), executor); }
java
public final <U> CompletionStage<U> supplyAsync(Supplier<U> supplier, Executor executor) { Objects.requireNonNull(supplier, "supplier must not be null"); return completedStage(null).thenApplyAsync((ignored) -> supplier.get(), executor); }
[ "public", "final", "<", "U", ">", "CompletionStage", "<", "U", ">", "supplyAsync", "(", "Supplier", "<", "U", ">", "supplier", ",", "Executor", "executor", ")", "{", "Objects", ".", "requireNonNull", "(", "supplier", ",", "\"supplier must not be null\"", ")", ...
Returns a new CompletionStage that is asynchronously completed by a task running in the given executor with the value obtained by calling the given Supplier. Subsequent completion stages will use defaultAsyncExecutor as their default executor. @param supplier a function returning the value to be used to complete the returned CompletionStage @param executor the executor to use for asynchronous execution @param <U> the function's return type @return the new CompletionStage
[ "Returns", "a", "new", "CompletionStage", "that", "is", "asynchronously", "completed", "by", "a", "task", "running", "in", "the", "given", "executor", "with", "the", "value", "obtained", "by", "calling", "the", "given", "Supplier", ".", "Subsequent", "completion...
9c270d779b5fc98dc958a5fb335f6e2ad9d06962
https://github.com/lukas-krecan/completion-stage/blob/9c270d779b5fc98dc958a5fb335f6e2ad9d06962/src/main/java/net/javacrumbs/completionstage/CompletionStageFactory.java#L88-L91
train
lukas-krecan/completion-stage
src/main/java/net/javacrumbs/completionstage/CompletionStageFactory.java
CompletionStageFactory.runAsync
public final CompletionStage<Void> runAsync(Runnable runnable, Executor executor) { Objects.requireNonNull(runnable, "runnable must not be null"); return completedStage(null).thenRunAsync(runnable, executor); }
java
public final CompletionStage<Void> runAsync(Runnable runnable, Executor executor) { Objects.requireNonNull(runnable, "runnable must not be null"); return completedStage(null).thenRunAsync(runnable, executor); }
[ "public", "final", "CompletionStage", "<", "Void", ">", "runAsync", "(", "Runnable", "runnable", ",", "Executor", "executor", ")", "{", "Objects", ".", "requireNonNull", "(", "runnable", ",", "\"runnable must not be null\"", ")", ";", "return", "completedStage", "...
Returns a new CompletionStage that is asynchronously completed by a task running in the given executor after it runs the given action. Subsequent completion stages will use defaultAsyncExecutor as their default executor. @param runnable the action to run before completing the returned CompletionStage @param executor the executor to use for asynchronous execution @return the new CompletionStage
[ "Returns", "a", "new", "CompletionStage", "that", "is", "asynchronously", "completed", "by", "a", "task", "running", "in", "the", "given", "executor", "after", "it", "runs", "the", "given", "action", ".", "Subsequent", "completion", "stages", "will", "use", "d...
9c270d779b5fc98dc958a5fb335f6e2ad9d06962
https://github.com/lukas-krecan/completion-stage/blob/9c270d779b5fc98dc958a5fb335f6e2ad9d06962/src/main/java/net/javacrumbs/completionstage/CompletionStageFactory.java#L117-L120
train
wiselenium/wiselenium
wiselenium-factory/src/main/java/com/github/wiselenium/factory/RootInjector.java
RootInjector.rootElement
public static <E> void rootElement(WebElement root, E element) { if (element == null || root == null) return; if (element instanceof WebElement) return; for (Class<?> clazz = element.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { if (Enhancer.isEnhanced(clazz)) continue; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { setRootElementField(root, element, field); } } }
java
public static <E> void rootElement(WebElement root, E element) { if (element == null || root == null) return; if (element instanceof WebElement) return; for (Class<?> clazz = element.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { if (Enhancer.isEnhanced(clazz)) continue; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { setRootElementField(root, element, field); } } }
[ "public", "static", "<", "E", ">", "void", "rootElement", "(", "WebElement", "root", ",", "E", "element", ")", "{", "if", "(", "element", "==", "null", "||", "root", "==", "null", ")", "return", ";", "if", "(", "element", "instanceof", "WebElement", ")...
Injects the root webelement into an element. @param root The root webelement. @param element The element. @since 0.3.0
[ "Injects", "the", "root", "webelement", "into", "an", "element", "." ]
15de6484d8f516b3d02391d3bd6a56a03e632706
https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-factory/src/main/java/com/github/wiselenium/factory/RootInjector.java#L50-L64
train
wiselenium/wiselenium
wiselenium-factory/src/main/java/com/github/wiselenium/factory/RootInjector.java
RootInjector.rootDriver
public static <E> void rootDriver(WebDriver root, E page) { if (page == null || root == null) return; for (Class<?> clazz = page.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { if (Enhancer.isEnhanced(clazz)) continue; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { setRootDriverField(root, page, field); } } }
java
public static <E> void rootDriver(WebDriver root, E page) { if (page == null || root == null) return; for (Class<?> clazz = page.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { if (Enhancer.isEnhanced(clazz)) continue; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { setRootDriverField(root, page, field); } } }
[ "public", "static", "<", "E", ">", "void", "rootDriver", "(", "WebDriver", "root", ",", "E", "page", ")", "{", "if", "(", "page", "==", "null", "||", "root", "==", "null", ")", "return", ";", "for", "(", "Class", "<", "?", ">", "clazz", "=", "pag...
Injects the webdriver into a page. @param root The webdriver. @param element The element. @since 0.3.0
[ "Injects", "the", "webdriver", "into", "a", "page", "." ]
15de6484d8f516b3d02391d3bd6a56a03e632706
https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-factory/src/main/java/com/github/wiselenium/factory/RootInjector.java#L72-L85
train
wiselenium/wiselenium
wiselenium-factory/src/main/java/com/github/wiselenium/WiseContext.java
WiseContext.getDriver
public static WebDriver getDriver() { WebDriver driver = WEB_DRIVER_THREAD_LOCAL.get(); if (driver == null) throw new IllegalStateException("Driver not set on the WiseContext"); return driver; }
java
public static WebDriver getDriver() { WebDriver driver = WEB_DRIVER_THREAD_LOCAL.get(); if (driver == null) throw new IllegalStateException("Driver not set on the WiseContext"); return driver; }
[ "public", "static", "WebDriver", "getDriver", "(", ")", "{", "WebDriver", "driver", "=", "WEB_DRIVER_THREAD_LOCAL", ".", "get", "(", ")", ";", "if", "(", "driver", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Driver not set on the WiseContex...
Retrieves the WebDriver of the current thread. @return The WebDriver of the current thread. @since 0.3.0
[ "Retrieves", "the", "WebDriver", "of", "the", "current", "thread", "." ]
15de6484d8f516b3d02391d3bd6a56a03e632706
https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-factory/src/main/java/com/github/wiselenium/WiseContext.java#L49-L56
train
wiselenium/wiselenium
wiselenium-factory/src/main/java/com/github/wiselenium/factory/util/AnnotationUtils.java
AnnotationUtils.isAnnotationPresent
public static <A extends Annotation> boolean isAnnotationPresent(Class<?> clazz, Class<A> annotationType) { if (findAnnotation(clazz, annotationType) != null) return true; return false; }
java
public static <A extends Annotation> boolean isAnnotationPresent(Class<?> clazz, Class<A> annotationType) { if (findAnnotation(clazz, annotationType) != null) return true; return false; }
[ "public", "static", "<", "A", "extends", "Annotation", ">", "boolean", "isAnnotationPresent", "(", "Class", "<", "?", ">", "clazz", ",", "Class", "<", "A", ">", "annotationType", ")", "{", "if", "(", "findAnnotation", "(", "clazz", ",", "annotationType", "...
Verifies if an annotation is present at a class type hierarchy. @param <A> The annotation type. @param clazz The class. @param annotationType The annotation. @return Whether the annotation is present at the class hierarchy or not. @since 0.3.0
[ "Verifies", "if", "an", "annotation", "is", "present", "at", "a", "class", "type", "hierarchy", "." ]
15de6484d8f516b3d02391d3bd6a56a03e632706
https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-factory/src/main/java/com/github/wiselenium/factory/util/AnnotationUtils.java#L77-L82
train
wiselenium/wiselenium
wiselenium-factory/src/main/java/com/github/wiselenium/factory/WisePageFactory.java
WisePageFactory.initElements
public static <T> T initElements(SearchContext searchContext, T instance) { Class<?> currentInstanceHierarchyClass = instance.getClass(); while (currentInstanceHierarchyClass != Object.class) { proxyElements(searchContext, instance, currentInstanceHierarchyClass); currentInstanceHierarchyClass = currentInstanceHierarchyClass.getSuperclass(); } return instance; }
java
public static <T> T initElements(SearchContext searchContext, T instance) { Class<?> currentInstanceHierarchyClass = instance.getClass(); while (currentInstanceHierarchyClass != Object.class) { proxyElements(searchContext, instance, currentInstanceHierarchyClass); currentInstanceHierarchyClass = currentInstanceHierarchyClass.getSuperclass(); } return instance; }
[ "public", "static", "<", "T", ">", "T", "initElements", "(", "SearchContext", "searchContext", ",", "T", "instance", ")", "{", "Class", "<", "?", ">", "currentInstanceHierarchyClass", "=", "instance", ".", "getClass", "(", ")", ";", "while", "(", "currentIns...
Initializes the elements of an existing object. @param searchContext The context that will be used to look up the elements. @param instance The instance whose fields will be initialized. @return The instance with its elements initialized. @since 0.3.0
[ "Initializes", "the", "elements", "of", "an", "existing", "object", "." ]
15de6484d8f516b3d02391d3bd6a56a03e632706
https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-factory/src/main/java/com/github/wiselenium/factory/WisePageFactory.java#L71-L79
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/OmdbApi.java
OmdbApi.search
public SearchResults search(OmdbParameters searchParams) throws OMDBException { SearchResults resultList; if (!searchParams.has(Param.APIKEY)) { searchParams.add(Param.APIKEY, this.apiKey); } String url = OmdbUrlBuilder.create(searchParams); LOG.trace("URL: {}", url); // Get the JSON String jsonData = requestWebPage(OmdbUrlBuilder.generateUrl(url)); // Process the JSON into an object try { resultList = mapper.readValue(jsonData, SearchResults.class); } catch (IOException ex) { throw new OMDBException(ApiExceptionType.MAPPING_FAILED, jsonData, 0, url, ex); } return resultList; }
java
public SearchResults search(OmdbParameters searchParams) throws OMDBException { SearchResults resultList; if (!searchParams.has(Param.APIKEY)) { searchParams.add(Param.APIKEY, this.apiKey); } String url = OmdbUrlBuilder.create(searchParams); LOG.trace("URL: {}", url); // Get the JSON String jsonData = requestWebPage(OmdbUrlBuilder.generateUrl(url)); // Process the JSON into an object try { resultList = mapper.readValue(jsonData, SearchResults.class); } catch (IOException ex) { throw new OMDBException(ApiExceptionType.MAPPING_FAILED, jsonData, 0, url, ex); } return resultList; }
[ "public", "SearchResults", "search", "(", "OmdbParameters", "searchParams", ")", "throws", "OMDBException", "{", "SearchResults", "resultList", ";", "if", "(", "!", "searchParams", ".", "has", "(", "Param", ".", "APIKEY", ")", ")", "{", "searchParams", ".", "a...
Execute a search using the passed parameters. To create the parameters use the OmdbBuilder builder: <p> E.G.: build(new OmdbBuilder(term).setYear(1900).build()); @param searchParams Use the OmdbBuilder to build the parameters @return @throws com.omertron.omdbapi.OMDBException
[ "Execute", "a", "search", "using", "the", "passed", "parameters", "." ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/OmdbApi.java#L121-L140
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/OmdbApi.java
OmdbApi.search
public SearchResults search(String title) throws OMDBException { return search(new OmdbBuilder() .setApiKey(apiKey) .setSearchTerm(title) .build()); }
java
public SearchResults search(String title) throws OMDBException { return search(new OmdbBuilder() .setApiKey(apiKey) .setSearchTerm(title) .build()); }
[ "public", "SearchResults", "search", "(", "String", "title", ")", "throws", "OMDBException", "{", "return", "search", "(", "new", "OmdbBuilder", "(", ")", ".", "setApiKey", "(", "apiKey", ")", ".", "setSearchTerm", "(", "title", ")", ".", "build", "(", ")"...
Get a list of movies using the movie title. @param title @return @throws OMDBException
[ "Get", "a", "list", "of", "movies", "using", "the", "movie", "title", "." ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/OmdbApi.java#L167-L172
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/OmdbApi.java
OmdbApi.getInfo
public OmdbVideoFull getInfo(OmdbParameters parameters) throws OMDBException { OmdbVideoFull result; //Api key should be added only if parameters do not have it already if (!parameters.has(Param.APIKEY)) { parameters.add(Param.APIKEY, this.apiKey); } URL url = OmdbUrlBuilder.createUrl(parameters); // Get the JSON String jsonData = requestWebPage(url); // Process the JSON into an object try { result = mapper.readValue(jsonData, OmdbVideoFull.class); if (result == null || !result.isResponse()) { throw new OMDBException(ApiExceptionType.ID_NOT_FOUND, result == null ? "No data returned" : result.getError()); } } catch (IOException ex) { throw new OMDBException(ApiExceptionType.MAPPING_FAILED, jsonData, 0, url, ex); } return result; }
java
public OmdbVideoFull getInfo(OmdbParameters parameters) throws OMDBException { OmdbVideoFull result; //Api key should be added only if parameters do not have it already if (!parameters.has(Param.APIKEY)) { parameters.add(Param.APIKEY, this.apiKey); } URL url = OmdbUrlBuilder.createUrl(parameters); // Get the JSON String jsonData = requestWebPage(url); // Process the JSON into an object try { result = mapper.readValue(jsonData, OmdbVideoFull.class); if (result == null || !result.isResponse()) { throw new OMDBException(ApiExceptionType.ID_NOT_FOUND, result == null ? "No data returned" : result.getError()); } } catch (IOException ex) { throw new OMDBException(ApiExceptionType.MAPPING_FAILED, jsonData, 0, url, ex); } return result; }
[ "public", "OmdbVideoFull", "getInfo", "(", "OmdbParameters", "parameters", ")", "throws", "OMDBException", "{", "OmdbVideoFull", "result", ";", "//Api key should be added only if parameters do not have it already", "if", "(", "!", "parameters", ".", "has", "(", "Param", "...
Get movie information using the supplied parameters @param parameters parameters to use to retrieve the information @return @throws OMDBException
[ "Get", "movie", "information", "using", "the", "supplied", "parameters" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/OmdbApi.java#L197-L220
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/model/AbstractJsonMapping.java
AbstractJsonMapping.handleUnknown
@JsonAnySetter protected void handleUnknown(String key, Object value) { StringBuilder unknown = new StringBuilder(this.getClass().getSimpleName()); unknown.append(": Unknown property='").append(key); unknown.append("' value='").append(value).append("'"); LOG.trace(unknown.toString()); }
java
@JsonAnySetter protected void handleUnknown(String key, Object value) { StringBuilder unknown = new StringBuilder(this.getClass().getSimpleName()); unknown.append(": Unknown property='").append(key); unknown.append("' value='").append(value).append("'"); LOG.trace(unknown.toString()); }
[ "@", "JsonAnySetter", "protected", "void", "handleUnknown", "(", "String", "key", ",", "Object", "value", ")", "{", "StringBuilder", "unknown", "=", "new", "StringBuilder", "(", "this", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "...
Handle unknown properties and print a message @param key @param value
[ "Handle", "unknown", "properties", "and", "print", "a", "message" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/model/AbstractJsonMapping.java#L63-L70
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbUrlBuilder.java
OmdbUrlBuilder.create
public static String create(final OmdbParameters params) throws OMDBException { StringBuilder sb = new StringBuilder(BASE_URL); sb.append(DELIMITER_FIRST); //Add the APIKey first if (params.has(Param.APIKEY)) { String apikey = (String) params.get(Param.APIKEY); sb.append(Param.APIKEY.getValue()).append(apikey); } else { throw new OMDBException(ApiExceptionType.AUTH_FAILURE, "Must include an ApiKey to make a call"); } //Needed for everything after sb.append(DELIMITER_SUBSEQUENT); if (params.has(Param.SEARCH)) { String search = (String) params.get(Param.SEARCH); sb.append(Param.SEARCH.getValue()).append(search.replace(" ", "+")); } else if (params.has(Param.IMDB)) { sb.append(Param.IMDB.getValue()).append(params.get(Param.IMDB)); } else if (params.has(Param.TITLE)) { String title = (String) params.get(Param.TITLE); sb.append(Param.TITLE.getValue()).append(title.replace(" ", "+")); } else { throw new OMDBException(ApiExceptionType.INVALID_URL, "Must include a search or ID"); } // Append the year appendParam(params, Param.YEAR, sb); // Append the plot requirement if (params.has(Param.PLOT) && (PlotType) params.get(Param.PLOT) != PlotType.getDefault()) { appendParam(params, Param.PLOT, sb); } // Append the tomatoes requirement appendParam(params, Param.TOMATOES, sb); // Append the Type appendParam(params, Param.RESULT, sb); // Append the JSON request - This is not used by this API appendParam(params, Param.DATA, sb); // Append the version appendParam(params, Param.VERSION, sb); // Append the callback function - This is not used by this API appendParam(params, Param.CALLBACK, sb); LOG.trace("Created URL: {}", sb.toString()); return sb.toString(); }
java
public static String create(final OmdbParameters params) throws OMDBException { StringBuilder sb = new StringBuilder(BASE_URL); sb.append(DELIMITER_FIRST); //Add the APIKey first if (params.has(Param.APIKEY)) { String apikey = (String) params.get(Param.APIKEY); sb.append(Param.APIKEY.getValue()).append(apikey); } else { throw new OMDBException(ApiExceptionType.AUTH_FAILURE, "Must include an ApiKey to make a call"); } //Needed for everything after sb.append(DELIMITER_SUBSEQUENT); if (params.has(Param.SEARCH)) { String search = (String) params.get(Param.SEARCH); sb.append(Param.SEARCH.getValue()).append(search.replace(" ", "+")); } else if (params.has(Param.IMDB)) { sb.append(Param.IMDB.getValue()).append(params.get(Param.IMDB)); } else if (params.has(Param.TITLE)) { String title = (String) params.get(Param.TITLE); sb.append(Param.TITLE.getValue()).append(title.replace(" ", "+")); } else { throw new OMDBException(ApiExceptionType.INVALID_URL, "Must include a search or ID"); } // Append the year appendParam(params, Param.YEAR, sb); // Append the plot requirement if (params.has(Param.PLOT) && (PlotType) params.get(Param.PLOT) != PlotType.getDefault()) { appendParam(params, Param.PLOT, sb); } // Append the tomatoes requirement appendParam(params, Param.TOMATOES, sb); // Append the Type appendParam(params, Param.RESULT, sb); // Append the JSON request - This is not used by this API appendParam(params, Param.DATA, sb); // Append the version appendParam(params, Param.VERSION, sb); // Append the callback function - This is not used by this API appendParam(params, Param.CALLBACK, sb); LOG.trace("Created URL: {}", sb.toString()); return sb.toString(); }
[ "public", "static", "String", "create", "(", "final", "OmdbParameters", "params", ")", "throws", "OMDBException", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "BASE_URL", ")", ";", "sb", ".", "append", "(", "DELIMITER_FIRST", ")", ";", "//Add ...
Create the String representation of the URL for passed parameters @param params The parameters to use to create the URL @return String URL @throws OMDBException
[ "Create", "the", "String", "representation", "of", "the", "URL", "for", "passed", "parameters" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbUrlBuilder.java#L48-L101
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbUrlBuilder.java
OmdbUrlBuilder.appendParam
private static void appendParam(final OmdbParameters params, final Param key, StringBuilder sb) { if (params.has(key)) { sb.append(DELIMITER_SUBSEQUENT).append(key.getValue()).append(params.get(key)); } }
java
private static void appendParam(final OmdbParameters params, final Param key, StringBuilder sb) { if (params.has(key)) { sb.append(DELIMITER_SUBSEQUENT).append(key.getValue()).append(params.get(key)); } }
[ "private", "static", "void", "appendParam", "(", "final", "OmdbParameters", "params", ",", "final", "Param", "key", ",", "StringBuilder", "sb", ")", "{", "if", "(", "params", ".", "has", "(", "key", ")", ")", "{", "sb", ".", "append", "(", "DELIMITER_SUB...
Append a parameter and value to the URL line @param params The parameter list @param key The parameter to add @param sb The StringBuilder instance to use
[ "Append", "a", "parameter", "and", "value", "to", "the", "URL", "line" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbUrlBuilder.java#L121-L125
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbUrlBuilder.java
OmdbUrlBuilder.generateUrl
public static URL generateUrl(final String url) throws OMDBException { try { return new URL(url); } catch (MalformedURLException ex) { throw new OMDBException(ApiExceptionType.INVALID_URL, "Failed to create URL", url, ex); } }
java
public static URL generateUrl(final String url) throws OMDBException { try { return new URL(url); } catch (MalformedURLException ex) { throw new OMDBException(ApiExceptionType.INVALID_URL, "Failed to create URL", url, ex); } }
[ "public", "static", "URL", "generateUrl", "(", "final", "String", "url", ")", "throws", "OMDBException", "{", "try", "{", "return", "new", "URL", "(", "url", ")", ";", "}", "catch", "(", "MalformedURLException", "ex", ")", "{", "throw", "new", "OMDBExcepti...
Generate a URL object from a String URL @param url @return @throws OMDBException
[ "Generate", "a", "URL", "object", "from", "a", "String", "URL" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbUrlBuilder.java#L134-L140
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setSearchTerm
public OmdbBuilder setSearchTerm(final String searchTerm) throws OMDBException { if (StringUtils.isBlank(searchTerm)) { throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide a search term!"); } params.add(Param.SEARCH, searchTerm); return this; }
java
public OmdbBuilder setSearchTerm(final String searchTerm) throws OMDBException { if (StringUtils.isBlank(searchTerm)) { throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide a search term!"); } params.add(Param.SEARCH, searchTerm); return this; }
[ "public", "OmdbBuilder", "setSearchTerm", "(", "final", "String", "searchTerm", ")", "throws", "OMDBException", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "searchTerm", ")", ")", "{", "throw", "new", "OMDBException", "(", "ApiExceptionType", ".", "UNKNO...
Set the search term @param searchTerm The text to build for @return @throws com.omertron.omdbapi.OMDBException
[ "Set", "the", "search", "term" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L59-L65
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setImdbId
public OmdbBuilder setImdbId(final String imdbId) throws OMDBException { if (StringUtils.isBlank(imdbId)) { throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide an IMDB ID!"); } params.add(Param.IMDB, imdbId); return this; }
java
public OmdbBuilder setImdbId(final String imdbId) throws OMDBException { if (StringUtils.isBlank(imdbId)) { throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide an IMDB ID!"); } params.add(Param.IMDB, imdbId); return this; }
[ "public", "OmdbBuilder", "setImdbId", "(", "final", "String", "imdbId", ")", "throws", "OMDBException", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "imdbId", ")", ")", "{", "throw", "new", "OMDBException", "(", "ApiExceptionType", ".", "UNKNOWN_CAUSE", ...
A valid IMDb ID @param imdbId The IMDB ID @return @throws OMDBException
[ "A", "valid", "IMDb", "ID" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L74-L80
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setTitle
public OmdbBuilder setTitle(final String title) throws OMDBException { if (StringUtils.isBlank(title)) { throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide a title!"); } params.add(Param.TITLE, title); return this; }
java
public OmdbBuilder setTitle(final String title) throws OMDBException { if (StringUtils.isBlank(title)) { throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide a title!"); } params.add(Param.TITLE, title); return this; }
[ "public", "OmdbBuilder", "setTitle", "(", "final", "String", "title", ")", "throws", "OMDBException", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "title", ")", ")", "{", "throw", "new", "OMDBException", "(", "ApiExceptionType", ".", "UNKNOWN_CAUSE", ",...
The title to search for @param title @return @throws OMDBException
[ "The", "title", "to", "search", "for" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L89-L95
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setTypeMovie
public OmdbBuilder setTypeMovie() { if (!ResultType.isDefault(ResultType.MOVIE)) { params.add(Param.RESULT, ResultType.MOVIE); } return this; }
java
public OmdbBuilder setTypeMovie() { if (!ResultType.isDefault(ResultType.MOVIE)) { params.add(Param.RESULT, ResultType.MOVIE); } return this; }
[ "public", "OmdbBuilder", "setTypeMovie", "(", ")", "{", "if", "(", "!", "ResultType", ".", "isDefault", "(", "ResultType", ".", "MOVIE", ")", ")", "{", "params", ".", "add", "(", "Param", ".", "RESULT", ",", "ResultType", ".", "MOVIE", ")", ";", "}", ...
Limit the results to movies @return
[ "Limit", "the", "results", "to", "movies" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L128-L133
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setTypeSeries
public OmdbBuilder setTypeSeries() { if (!ResultType.isDefault(ResultType.SERIES)) { params.add(Param.RESULT, ResultType.SERIES); } return this; }
java
public OmdbBuilder setTypeSeries() { if (!ResultType.isDefault(ResultType.SERIES)) { params.add(Param.RESULT, ResultType.SERIES); } return this; }
[ "public", "OmdbBuilder", "setTypeSeries", "(", ")", "{", "if", "(", "!", "ResultType", ".", "isDefault", "(", "ResultType", ".", "SERIES", ")", ")", "{", "params", ".", "add", "(", "Param", ".", "RESULT", ",", "ResultType", ".", "SERIES", ")", ";", "}"...
Limit the results to series @return
[ "Limit", "the", "results", "to", "series" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L140-L145
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setTypeEpisode
public OmdbBuilder setTypeEpisode() { if (!ResultType.isDefault(ResultType.EPISODE)) { params.add(Param.RESULT, ResultType.EPISODE); } return this; }
java
public OmdbBuilder setTypeEpisode() { if (!ResultType.isDefault(ResultType.EPISODE)) { params.add(Param.RESULT, ResultType.EPISODE); } return this; }
[ "public", "OmdbBuilder", "setTypeEpisode", "(", ")", "{", "if", "(", "!", "ResultType", ".", "isDefault", "(", "ResultType", ".", "EPISODE", ")", ")", "{", "params", ".", "add", "(", "Param", ".", "RESULT", ",", "ResultType", ".", "EPISODE", ")", ";", ...
Limit the results to episodes @return
[ "Limit", "the", "results", "to", "episodes" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L152-L157
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setPlot
public OmdbBuilder setPlot(final PlotType plotType) { if (!PlotType.isDefault(plotType)) { params.add(Param.PLOT, plotType); } return this; }
java
public OmdbBuilder setPlot(final PlotType plotType) { if (!PlotType.isDefault(plotType)) { params.add(Param.PLOT, plotType); } return this; }
[ "public", "OmdbBuilder", "setPlot", "(", "final", "PlotType", "plotType", ")", "{", "if", "(", "!", "PlotType", ".", "isDefault", "(", "plotType", ")", ")", "{", "params", ".", "add", "(", "Param", ".", "PLOT", ",", "plotType", ")", ";", "}", "return",...
Return short or full plot. @param plotType The plot type to get @return
[ "Return", "short", "or", "full", "plot", "." ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L165-L170
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setPlotFull
public OmdbBuilder setPlotFull() { if (!PlotType.isDefault(PlotType.FULL)) { params.add(Param.PLOT, PlotType.FULL); } return this; }
java
public OmdbBuilder setPlotFull() { if (!PlotType.isDefault(PlotType.FULL)) { params.add(Param.PLOT, PlotType.FULL); } return this; }
[ "public", "OmdbBuilder", "setPlotFull", "(", ")", "{", "if", "(", "!", "PlotType", ".", "isDefault", "(", "PlotType", ".", "FULL", ")", ")", "{", "params", ".", "add", "(", "Param", ".", "PLOT", ",", "PlotType", ".", "FULL", ")", ";", "}", "return", ...
Return the long plot @return
[ "Return", "the", "long", "plot" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L188-L193
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setPlotShort
public OmdbBuilder setPlotShort() { if (!PlotType.isDefault(PlotType.SHORT)) { params.add(Param.PLOT, PlotType.SHORT); } return this; }
java
public OmdbBuilder setPlotShort() { if (!PlotType.isDefault(PlotType.SHORT)) { params.add(Param.PLOT, PlotType.SHORT); } return this; }
[ "public", "OmdbBuilder", "setPlotShort", "(", ")", "{", "if", "(", "!", "PlotType", ".", "isDefault", "(", "PlotType", ".", "SHORT", ")", ")", "{", "params", ".", "add", "(", "Param", ".", "PLOT", ",", "PlotType", ".", "SHORT", ")", ";", "}", "return...
Return the short plot @return
[ "Return", "the", "short", "plot" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L200-L205
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setTomatoes
public OmdbBuilder setTomatoes(boolean tomatoes) { if (DEFAULT_TOMATOES != tomatoes) { params.add(Param.TOMATOES, tomatoes); } return this; }
java
public OmdbBuilder setTomatoes(boolean tomatoes) { if (DEFAULT_TOMATOES != tomatoes) { params.add(Param.TOMATOES, tomatoes); } return this; }
[ "public", "OmdbBuilder", "setTomatoes", "(", "boolean", "tomatoes", ")", "{", "if", "(", "DEFAULT_TOMATOES", "!=", "tomatoes", ")", "{", "params", ".", "add", "(", "Param", ".", "TOMATOES", ",", "tomatoes", ")", ";", "}", "return", "this", ";", "}" ]
Include or exclude Rotten Tomatoes ratings. @param tomatoes @return
[ "Include", "or", "exclude", "Rotten", "Tomatoes", "ratings", "." ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L213-L218
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java
OmdbBuilder.setApiKey
public OmdbBuilder setApiKey(final String apiKey) throws OMDBException { if (StringUtils.isBlank(apiKey)) { throw new OMDBException(ApiExceptionType.AUTH_FAILURE, "Must provide an ApiKey"); } params.add(Param.APIKEY, apiKey); return this; }
java
public OmdbBuilder setApiKey(final String apiKey) throws OMDBException { if (StringUtils.isBlank(apiKey)) { throw new OMDBException(ApiExceptionType.AUTH_FAILURE, "Must provide an ApiKey"); } params.add(Param.APIKEY, apiKey); return this; }
[ "public", "OmdbBuilder", "setApiKey", "(", "final", "String", "apiKey", ")", "throws", "OMDBException", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "apiKey", ")", ")", "{", "throw", "new", "OMDBException", "(", "ApiExceptionType", ".", "AUTH_FAILURE", ...
Set the ApiKey @param apiKey The apikey needed for the contract @return @throws com.omertron.omdbapi.OMDBException
[ "Set", "the", "ApiKey" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbBuilder.java#L256-L262
train
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbParameters.java
OmdbParameters.add
public void add(Param key, Object value) { // check to see if we have a default value and skip it if (defaults.containsKey(key) && defaults.get(key).equals(value)) { // We already have this value, so skip it return; } parameters.put(key, value); }
java
public void add(Param key, Object value) { // check to see if we have a default value and skip it if (defaults.containsKey(key) && defaults.get(key).equals(value)) { // We already have this value, so skip it return; } parameters.put(key, value); }
[ "public", "void", "add", "(", "Param", "key", ",", "Object", "value", ")", "{", "// check to see if we have a default value and skip it", "if", "(", "defaults", ".", "containsKey", "(", "key", ")", "&&", "defaults", ".", "get", "(", "key", ")", ".", "equals", ...
Add a parameter to the collection @param key Parameter to add @param value The value to use
[ "Add", "a", "parameter", "to", "the", "collection" ]
acb506ded2d7b8a4159b48161ffab8cb5b7bad44
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbParameters.java#L58-L65
train
SilleBille/DynamicCalendar
library/src/main/java/com/kd/dynamic/calendar/generator/ImageGenerator.java
ImageGenerator.setDateTypeFace
public void setDateTypeFace(String fontName) { mDateTypeFace = Typeface.createFromAsset(mContext.getAssets(), "fonts/" + fontName); mDateTypeFaceSet = true; }
java
public void setDateTypeFace(String fontName) { mDateTypeFace = Typeface.createFromAsset(mContext.getAssets(), "fonts/" + fontName); mDateTypeFaceSet = true; }
[ "public", "void", "setDateTypeFace", "(", "String", "fontName", ")", "{", "mDateTypeFace", "=", "Typeface", ".", "createFromAsset", "(", "mContext", ".", "getAssets", "(", ")", ",", "\"fonts/\"", "+", "fontName", ")", ";", "mDateTypeFaceSet", "=", "true", ";",...
Apply the specified TypeFace to the date font OPTIONAL @param fontName Name of the date font to be generated
[ "Apply", "the", "specified", "TypeFace", "to", "the", "date", "font", "OPTIONAL" ]
887c16afc56655c9e591a26f3f04ed47f3d744be
https://github.com/SilleBille/DynamicCalendar/blob/887c16afc56655c9e591a26f3f04ed47f3d744be/library/src/main/java/com/kd/dynamic/calendar/generator/ImageGenerator.java#L157-L160
train
SilleBille/DynamicCalendar
library/src/main/java/com/kd/dynamic/calendar/generator/ImageGenerator.java
ImageGenerator.setMonthTypeFace
public void setMonthTypeFace(String fontName) { mMonthTypeFace = Typeface.createFromAsset(mContext.getAssets(), "fonts/" + fontName); mMonthTypeFaceSet = true; }
java
public void setMonthTypeFace(String fontName) { mMonthTypeFace = Typeface.createFromAsset(mContext.getAssets(), "fonts/" + fontName); mMonthTypeFaceSet = true; }
[ "public", "void", "setMonthTypeFace", "(", "String", "fontName", ")", "{", "mMonthTypeFace", "=", "Typeface", ".", "createFromAsset", "(", "mContext", ".", "getAssets", "(", ")", ",", "\"fonts/\"", "+", "fontName", ")", ";", "mMonthTypeFaceSet", "=", "true", "...
Apply the specified TypeFace to the month font OPTIONAL @param fontName Name of the month font to be generated
[ "Apply", "the", "specified", "TypeFace", "to", "the", "month", "font", "OPTIONAL" ]
887c16afc56655c9e591a26f3f04ed47f3d744be
https://github.com/SilleBille/DynamicCalendar/blob/887c16afc56655c9e591a26f3f04ed47f3d744be/library/src/main/java/com/kd/dynamic/calendar/generator/ImageGenerator.java#L168-L171
train
sababado/CircularView
library/src/main/java/com/sababado/circularview/CircularView.java
CircularView.getDefaultSize
public static int getDefaultSize(final int size, final int measureSpec) { final int result; final int specMode = MeasureSpec.getMode(measureSpec); final int specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.AT_MOST: result = Math.min(size, specSize); break; case MeasureSpec.EXACTLY: result = specSize; break; default: result = size; break; } return result; }
java
public static int getDefaultSize(final int size, final int measureSpec) { final int result; final int specMode = MeasureSpec.getMode(measureSpec); final int specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.AT_MOST: result = Math.min(size, specSize); break; case MeasureSpec.EXACTLY: result = specSize; break; default: result = size; break; } return result; }
[ "public", "static", "int", "getDefaultSize", "(", "final", "int", "size", ",", "final", "int", "measureSpec", ")", "{", "final", "int", "result", ";", "final", "int", "specMode", "=", "MeasureSpec", ".", "getMode", "(", "measureSpec", ")", ";", "final", "i...
Utility to return a default size. Uses the supplied size if the MeasureSpec imposed no constraints. Will get larger if allowed by the MeasureSpec. @param size Default size for this view @param measureSpec Constraints imposed by the parent @return The size this view should be.
[ "Utility", "to", "return", "a", "default", "size", ".", "Uses", "the", "supplied", "size", "if", "the", "MeasureSpec", "imposed", "no", "constraints", ".", "Will", "get", "larger", "if", "allowed", "by", "the", "MeasureSpec", "." ]
c9ab818d063bcc0796183616f8a82166a9b80aac
https://github.com/sababado/CircularView/blob/c9ab818d063bcc0796183616f8a82166a9b80aac/library/src/main/java/com/sababado/circularview/CircularView.java#L203-L220
train
sababado/CircularView
library/src/main/java/com/sababado/circularview/CircularView.java
CircularView.setAdapter
public void setAdapter(final BaseCircularViewAdapter adapter) { mAdapter = adapter; if (mAdapter != null) { mAdapter.registerDataSetObserver(mAdapterDataSetObserver); } postInvalidate(); }
java
public void setAdapter(final BaseCircularViewAdapter adapter) { mAdapter = adapter; if (mAdapter != null) { mAdapter.registerDataSetObserver(mAdapterDataSetObserver); } postInvalidate(); }
[ "public", "void", "setAdapter", "(", "final", "BaseCircularViewAdapter", "adapter", ")", "{", "mAdapter", "=", "adapter", ";", "if", "(", "mAdapter", "!=", "null", ")", "{", "mAdapter", ".", "registerDataSetObserver", "(", "mAdapterDataSetObserver", ")", ";", "}...
Set the adapter to use on this view. @param adapter Adapter to set.
[ "Set", "the", "adapter", "to", "use", "on", "this", "view", "." ]
c9ab818d063bcc0796183616f8a82166a9b80aac
https://github.com/sababado/CircularView/blob/c9ab818d063bcc0796183616f8a82166a9b80aac/library/src/main/java/com/sababado/circularview/CircularView.java#L366-L372
train
sababado/CircularView
library/src/main/java/com/sababado/circularview/CircularViewObject.java
CircularViewObject.distanceFromCenter
public double distanceFromCenter(final float x, final float y) { return Math.sqrt(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2)); }
java
public double distanceFromCenter(final float x, final float y) { return Math.sqrt(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2)); }
[ "public", "double", "distanceFromCenter", "(", "final", "float", "x", ",", "final", "float", "y", ")", "{", "return", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "x", "-", "this", ".", "x", ",", "2", ")", "+", "Math", ".", "pow", "(", "y",...
Get the distance from the given point to the center of this object. @param x X coordinate. @param y Y coordinate. @return Distance from the given point to the center of this object.
[ "Get", "the", "distance", "from", "the", "given", "point", "to", "the", "center", "of", "this", "object", "." ]
c9ab818d063bcc0796183616f8a82166a9b80aac
https://github.com/sababado/CircularView/blob/c9ab818d063bcc0796183616f8a82166a9b80aac/library/src/main/java/com/sababado/circularview/CircularViewObject.java#L153-L155
train
sababado/CircularView
library/src/main/java/com/sababado/circularview/CircularViewObject.java
CircularViewObject.updateDrawableState
public void updateDrawableState(int state, boolean flag) { final int oldState = mCombinedState; // Update the combined state flag if (flag) mCombinedState |= state; else mCombinedState &= ~state; // Set the combined state if (oldState != mCombinedState) { setState(VIEW_STATE_SETS[mCombinedState]); } }
java
public void updateDrawableState(int state, boolean flag) { final int oldState = mCombinedState; // Update the combined state flag if (flag) mCombinedState |= state; else mCombinedState &= ~state; // Set the combined state if (oldState != mCombinedState) { setState(VIEW_STATE_SETS[mCombinedState]); } }
[ "public", "void", "updateDrawableState", "(", "int", "state", ",", "boolean", "flag", ")", "{", "final", "int", "oldState", "=", "mCombinedState", ";", "// Update the combined state flag", "if", "(", "flag", ")", "mCombinedState", "|=", "state", ";", "else", "mC...
Either remove or add a state to the combined state. @param state State to add or remove. @param flag True to add, false to remove.
[ "Either", "remove", "or", "add", "a", "state", "to", "the", "combined", "state", "." ]
c9ab818d063bcc0796183616f8a82166a9b80aac
https://github.com/sababado/CircularView/blob/c9ab818d063bcc0796183616f8a82166a9b80aac/library/src/main/java/com/sababado/circularview/CircularViewObject.java#L230-L240
train
sababado/CircularView
library/src/main/java/com/sababado/circularview/CircularViewObject.java
CircularViewObject.setVisibility
public void setVisibility(int visibility) { if (this.visibility != visibility) { final boolean hasSpace = this.visibility == View.VISIBLE || this.visibility == View.INVISIBLE; final boolean removingSpace = visibility == View.GONE; final boolean change = hasSpace && removingSpace; this.visibility = visibility; // Only change the dataset if it is absolutely necessary if (change && mAdapterDataSetObserver != null) { mAdapterDataSetObserver.onChanged(); } else { invalidate(); } } }
java
public void setVisibility(int visibility) { if (this.visibility != visibility) { final boolean hasSpace = this.visibility == View.VISIBLE || this.visibility == View.INVISIBLE; final boolean removingSpace = visibility == View.GONE; final boolean change = hasSpace && removingSpace; this.visibility = visibility; // Only change the dataset if it is absolutely necessary if (change && mAdapterDataSetObserver != null) { mAdapterDataSetObserver.onChanged(); } else { invalidate(); } } }
[ "public", "void", "setVisibility", "(", "int", "visibility", ")", "{", "if", "(", "this", ".", "visibility", "!=", "visibility", ")", "{", "final", "boolean", "hasSpace", "=", "this", ".", "visibility", "==", "View", ".", "VISIBLE", "||", "this", ".", "v...
Set the enabled state of this view. @param visibility One of {@link View#VISIBLE}, {@link View#INVISIBLE}, or {@link View#GONE}.
[ "Set", "the", "enabled", "state", "of", "this", "view", "." ]
c9ab818d063bcc0796183616f8a82166a9b80aac
https://github.com/sababado/CircularView/blob/c9ab818d063bcc0796183616f8a82166a9b80aac/library/src/main/java/com/sababado/circularview/CircularViewObject.java#L387-L400
train
sababado/CircularView
library/src/main/java/com/sababado/circularview/CircularViewObject.java
CircularViewObject.onTouchEvent
public int onTouchEvent(final MotionEvent event) { int status = -2; if (visibility != View.GONE) { final int action = event.getAction(); final boolean isEventInCenterCircle = isInCenterCircle(event.getX(), event.getY()); if (action == MotionEvent.ACTION_DOWN) { // check if center if (isEventInCenterCircle) { updateDrawableState(VIEW_STATE_PRESSED, true); status = MotionEvent.ACTION_DOWN; } } else if (action == MotionEvent.ACTION_UP) { final boolean isPressed = (mCombinedState & VIEW_STATE_PRESSED) != 0; if (isPressed && isEventInCenterCircle) { updateDrawableState(VIEW_STATE_PRESSED, false); status = MotionEvent.ACTION_UP; } } else if (action == MotionEvent.ACTION_MOVE) { if (!isEventInCenterCircle) { updateDrawableState(VIEW_STATE_PRESSED, false); } } } return status; }
java
public int onTouchEvent(final MotionEvent event) { int status = -2; if (visibility != View.GONE) { final int action = event.getAction(); final boolean isEventInCenterCircle = isInCenterCircle(event.getX(), event.getY()); if (action == MotionEvent.ACTION_DOWN) { // check if center if (isEventInCenterCircle) { updateDrawableState(VIEW_STATE_PRESSED, true); status = MotionEvent.ACTION_DOWN; } } else if (action == MotionEvent.ACTION_UP) { final boolean isPressed = (mCombinedState & VIEW_STATE_PRESSED) != 0; if (isPressed && isEventInCenterCircle) { updateDrawableState(VIEW_STATE_PRESSED, false); status = MotionEvent.ACTION_UP; } } else if (action == MotionEvent.ACTION_MOVE) { if (!isEventInCenterCircle) { updateDrawableState(VIEW_STATE_PRESSED, false); } } } return status; }
[ "public", "int", "onTouchEvent", "(", "final", "MotionEvent", "event", ")", "{", "int", "status", "=", "-", "2", ";", "if", "(", "visibility", "!=", "View", ".", "GONE", ")", "{", "final", "int", "action", "=", "event", ".", "getAction", "(", ")", ";...
Act on a touch event. Returns a status based on what action was taken. @param event The motion event that was just received. @return Return a negative number if the event wasn't handled. Return a MotionEvent action code if it was handled.
[ "Act", "on", "a", "touch", "event", ".", "Returns", "a", "status", "based", "on", "what", "action", "was", "taken", "." ]
c9ab818d063bcc0796183616f8a82166a9b80aac
https://github.com/sababado/CircularView/blob/c9ab818d063bcc0796183616f8a82166a9b80aac/library/src/main/java/com/sababado/circularview/CircularViewObject.java#L408-L434
train
sualeh/credit_card_number
src/main/java/us/fatehi/creditcardnumber/ExpirationDate.java
ExpirationDate.getExpirationDateAsDate
public Date getExpirationDateAsDate() { if (hasExpirationDate()) { final LocalDateTime endOfMonth = expirationDate.atEndOfMonth() .atStartOfDay().plus(1, ChronoUnit.DAYS).minus(1, ChronoUnit.NANOS); final Instant instant = endOfMonth.atZone(ZoneId.systemDefault()) .toInstant(); final Date date = new Date(instant.toEpochMilli()); return date; } else { return null; } }
java
public Date getExpirationDateAsDate() { if (hasExpirationDate()) { final LocalDateTime endOfMonth = expirationDate.atEndOfMonth() .atStartOfDay().plus(1, ChronoUnit.DAYS).minus(1, ChronoUnit.NANOS); final Instant instant = endOfMonth.atZone(ZoneId.systemDefault()) .toInstant(); final Date date = new Date(instant.toEpochMilli()); return date; } else { return null; } }
[ "public", "Date", "getExpirationDateAsDate", "(", ")", "{", "if", "(", "hasExpirationDate", "(", ")", ")", "{", "final", "LocalDateTime", "endOfMonth", "=", "expirationDate", ".", "atEndOfMonth", "(", ")", ".", "atStartOfDay", "(", ")", ".", "plus", "(", "1"...
Gets the card expiration date, as a java.util.Date object. Returns null if no date is available. @return Card expiration date.
[ "Gets", "the", "card", "expiration", "date", "as", "a", "java", ".", "util", ".", "Date", "object", ".", "Returns", "null", "if", "no", "date", "is", "available", "." ]
75238a84bbfdfe9163a70fd5673cba627e8972b6
https://github.com/sualeh/credit_card_number/blob/75238a84bbfdfe9163a70fd5673cba627e8972b6/src/main/java/us/fatehi/creditcardnumber/ExpirationDate.java#L175-L190
train
sababado/CircularView
library/src/main/java/com/sababado/circularview/CircularViewCursorAdapter.java
CircularViewCursorAdapter.getItem
public Cursor getItem(int position) { if (mDataValid && mCursor != null) { mCursor.moveToPosition(position); return mCursor; } else { return null; } }
java
public Cursor getItem(int position) { if (mDataValid && mCursor != null) { mCursor.moveToPosition(position); return mCursor; } else { return null; } }
[ "public", "Cursor", "getItem", "(", "int", "position", ")", "{", "if", "(", "mDataValid", "&&", "mCursor", "!=", "null", ")", "{", "mCursor", ".", "moveToPosition", "(", "position", ")", ";", "return", "mCursor", ";", "}", "else", "{", "return", "null", ...
Returns a cursor pointed to the given position. @param position position to set on the cursor. @return a cursor set to the position.
[ "Returns", "a", "cursor", "pointed", "to", "the", "given", "position", "." ]
c9ab818d063bcc0796183616f8a82166a9b80aac
https://github.com/sababado/CircularView/blob/c9ab818d063bcc0796183616f8a82166a9b80aac/library/src/main/java/com/sababado/circularview/CircularViewCursorAdapter.java#L162-L169
train
francisdb/serviceloader-maven-plugin
src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java
ServiceloaderMojo.execute
public void execute() throws MojoExecutionException { if (skipProject()) { getLog().info("POM project detected; skipping"); }else { URLClassLoader classLoader = new URLClassLoader(generateClassPathUrls()); List<Class<?>> interfaceClasses = loadServiceClasses(classLoader); Map<String, List<String>> serviceImplementations = findImplementations(classLoader, interfaceClasses); writeServiceFiles(serviceImplementations); } }
java
public void execute() throws MojoExecutionException { if (skipProject()) { getLog().info("POM project detected; skipping"); }else { URLClassLoader classLoader = new URLClassLoader(generateClassPathUrls()); List<Class<?>> interfaceClasses = loadServiceClasses(classLoader); Map<String, List<String>> serviceImplementations = findImplementations(classLoader, interfaceClasses); writeServiceFiles(serviceImplementations); } }
[ "public", "void", "execute", "(", ")", "throws", "MojoExecutionException", "{", "if", "(", "skipProject", "(", ")", ")", "{", "getLog", "(", ")", ".", "info", "(", "\"POM project detected; skipping\"", ")", ";", "}", "else", "{", "URLClassLoader", "classLoader...
The main entry point for this Mojo. @throws MojoExecutionException
[ "The", "main", "entry", "point", "for", "this", "Mojo", "." ]
521a467ed5c00636749f6c6531be85ddf296565e
https://github.com/francisdb/serviceloader-maven-plugin/blob/521a467ed5c00636749f6c6531be85ddf296565e/src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java#L117-L126
train
francisdb/serviceloader-maven-plugin
src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java
ServiceloaderMojo.writeServiceFiles
private void writeServiceFiles( Map<String, List<String>> serviceImplementations) throws MojoExecutionException { // TODO give the user an option to write them to the source folder or // any other folder? File parentFolder = new File(getClassFolder(), "META-INF" + File.separator + "services"); if (!parentFolder.exists()) { parentFolder.mkdirs(); } for (Entry<String, List<String>> interfaceClassName : serviceImplementations.entrySet()) { File serviceFile = new File(parentFolder, interfaceClassName.getKey()); getLog().info("Generating service file " + serviceFile.getAbsolutePath()); FileWriter writer = null; try { writer = new FileWriter(serviceFile); for (String implementationClassName : interfaceClassName.getValue()) { getLog().info(" + " + implementationClassName); writer.write(implementationClassName); writer.write('\n'); } buildContext.refresh(serviceFile); } catch (IOException e) { throw new MojoExecutionException("Error creating file " + serviceFile, e); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { getLog().error(e); } } } } }
java
private void writeServiceFiles( Map<String, List<String>> serviceImplementations) throws MojoExecutionException { // TODO give the user an option to write them to the source folder or // any other folder? File parentFolder = new File(getClassFolder(), "META-INF" + File.separator + "services"); if (!parentFolder.exists()) { parentFolder.mkdirs(); } for (Entry<String, List<String>> interfaceClassName : serviceImplementations.entrySet()) { File serviceFile = new File(parentFolder, interfaceClassName.getKey()); getLog().info("Generating service file " + serviceFile.getAbsolutePath()); FileWriter writer = null; try { writer = new FileWriter(serviceFile); for (String implementationClassName : interfaceClassName.getValue()) { getLog().info(" + " + implementationClassName); writer.write(implementationClassName); writer.write('\n'); } buildContext.refresh(serviceFile); } catch (IOException e) { throw new MojoExecutionException("Error creating file " + serviceFile, e); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { getLog().error(e); } } } } }
[ "private", "void", "writeServiceFiles", "(", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "serviceImplementations", ")", "throws", "MojoExecutionException", "{", "// TODO give the user an option to write them to the source folder or", "// any other folder?", "F...
Writes the output for the service files to disk @param serviceImplementations @throws MojoExecutionException
[ "Writes", "the", "output", "for", "the", "service", "files", "to", "disk" ]
521a467ed5c00636749f6c6531be85ddf296565e
https://github.com/francisdb/serviceloader-maven-plugin/blob/521a467ed5c00636749f6c6531be85ddf296565e/src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java#L134-L167
train
francisdb/serviceloader-maven-plugin
src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java
ServiceloaderMojo.loadServiceClasses
private List<Class<?>> loadServiceClasses(ClassLoader loader) throws MojoExecutionException { List<Class<?>> serviceClasses = new ArrayList<Class<?>>(); for (String serviceClassName : getServices()) { try { Class<?> serviceClass = loader.loadClass(serviceClassName); serviceClasses.add(serviceClass); } catch (ClassNotFoundException ex) { throw new MojoExecutionException("Could not load class: " + serviceClassName, ex); } } return serviceClasses; }
java
private List<Class<?>> loadServiceClasses(ClassLoader loader) throws MojoExecutionException { List<Class<?>> serviceClasses = new ArrayList<Class<?>>(); for (String serviceClassName : getServices()) { try { Class<?> serviceClass = loader.loadClass(serviceClassName); serviceClasses.add(serviceClass); } catch (ClassNotFoundException ex) { throw new MojoExecutionException("Could not load class: " + serviceClassName, ex); } } return serviceClasses; }
[ "private", "List", "<", "Class", "<", "?", ">", ">", "loadServiceClasses", "(", "ClassLoader", "loader", ")", "throws", "MojoExecutionException", "{", "List", "<", "Class", "<", "?", ">", ">", "serviceClasses", "=", "new", "ArrayList", "<", "Class", "<", "...
Loads all interfaces using the provided ClassLoader @param loader the classloader @return thi List of Interface classes @throws MojoExecutionException is the interfaces are not interfaces or can not be found on the classpath
[ "Loads", "all", "interfaces", "using", "the", "provided", "ClassLoader" ]
521a467ed5c00636749f6c6531be85ddf296565e
https://github.com/francisdb/serviceloader-maven-plugin/blob/521a467ed5c00636749f6c6531be85ddf296565e/src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java#L178-L190
train
francisdb/serviceloader-maven-plugin
src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java
ServiceloaderMojo.findImplementations
private Map<String, List<String>> findImplementations(ClassLoader loader, List<Class<?>> interfaceClasses) throws MojoExecutionException { Map<String, List<String>> serviceImplementations = new HashMap<String, List<String>>(); for (String interfaceClassName : getServices()) { serviceImplementations.put(interfaceClassName, new ArrayList<String>()); } getLog().info("Scanning generated classes for implementations..."); File classFolder = getClassFolder(); List<String> classNames = listCompiledClasses(classFolder); // List<String> classNames = listCompiledClassesRegex( classFolder ); for (String className : classNames) { try { if(getLog().isDebugEnabled()){ getLog().debug("checking class: " + className); } Class<?> cls = loader.loadClass(className); int mods = cls.getModifiers(); if (!cls.isAnonymousClass() && !cls.isInterface() && !cls.isEnum() && !Modifier.isAbstract(mods) && Modifier.isPublic(mods)) { for (Class<?> interfaceCls : interfaceClasses) { if (!interfaceCls.equals(cls) && interfaceCls.isAssignableFrom(cls)) { // if the includes section isn't empty, we need to respect the choice and only include the items that are shown there. if (includes == null || includes.length == 0) { serviceImplementations.get(interfaceCls.getName()).add(className); } else { for ( String include : includes ) { if(SelectorUtils.match(include, className)) { serviceImplementations.get(interfaceCls.getName()).add(className); } } } } } } } catch (ClassNotFoundException e1) { getLog().warn(e1); } catch (NoClassDefFoundError e2) { getLog().warn(e2); } } // in the next iteration we start to process with the excludes if (excludes != null && excludes.length != 0) { Set<Entry<String,List<String>>> entrySet = serviceImplementations.entrySet(); for ( Entry<String, List<String>> entry : entrySet ) { classNames = entry.getValue(); ListIterator<String> classNamesIter = classNames.listIterator(); while ( classNamesIter.hasNext()) { String className = classNamesIter.next(); for ( String exclude : excludes ) { if(SelectorUtils.match(exclude, className)) { classNamesIter.remove(); break; } } } } } return serviceImplementations; }
java
private Map<String, List<String>> findImplementations(ClassLoader loader, List<Class<?>> interfaceClasses) throws MojoExecutionException { Map<String, List<String>> serviceImplementations = new HashMap<String, List<String>>(); for (String interfaceClassName : getServices()) { serviceImplementations.put(interfaceClassName, new ArrayList<String>()); } getLog().info("Scanning generated classes for implementations..."); File classFolder = getClassFolder(); List<String> classNames = listCompiledClasses(classFolder); // List<String> classNames = listCompiledClassesRegex( classFolder ); for (String className : classNames) { try { if(getLog().isDebugEnabled()){ getLog().debug("checking class: " + className); } Class<?> cls = loader.loadClass(className); int mods = cls.getModifiers(); if (!cls.isAnonymousClass() && !cls.isInterface() && !cls.isEnum() && !Modifier.isAbstract(mods) && Modifier.isPublic(mods)) { for (Class<?> interfaceCls : interfaceClasses) { if (!interfaceCls.equals(cls) && interfaceCls.isAssignableFrom(cls)) { // if the includes section isn't empty, we need to respect the choice and only include the items that are shown there. if (includes == null || includes.length == 0) { serviceImplementations.get(interfaceCls.getName()).add(className); } else { for ( String include : includes ) { if(SelectorUtils.match(include, className)) { serviceImplementations.get(interfaceCls.getName()).add(className); } } } } } } } catch (ClassNotFoundException e1) { getLog().warn(e1); } catch (NoClassDefFoundError e2) { getLog().warn(e2); } } // in the next iteration we start to process with the excludes if (excludes != null && excludes.length != 0) { Set<Entry<String,List<String>>> entrySet = serviceImplementations.entrySet(); for ( Entry<String, List<String>> entry : entrySet ) { classNames = entry.getValue(); ListIterator<String> classNamesIter = classNames.listIterator(); while ( classNamesIter.hasNext()) { String className = classNamesIter.next(); for ( String exclude : excludes ) { if(SelectorUtils.match(exclude, className)) { classNamesIter.remove(); break; } } } } } return serviceImplementations; }
[ "private", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "findImplementations", "(", "ClassLoader", "loader", ",", "List", "<", "Class", "<", "?", ">", ">", "interfaceClasses", ")", "throws", "MojoExecutionException", "{", "Map", "<", "String",...
Finds all implementations of interfaces in a folder @param loader @param interfaceClasses @return @throws MojoExecutionException
[ "Finds", "all", "implementations", "of", "interfaces", "in", "a", "folder" ]
521a467ed5c00636749f6c6531be85ddf296565e
https://github.com/francisdb/serviceloader-maven-plugin/blob/521a467ed5c00636749f6c6531be85ddf296565e/src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java#L200-L268
train
francisdb/serviceloader-maven-plugin
src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java
ServiceloaderMojo.listCompiledClasses
List<String> listCompiledClasses(final File classFolder) { List<String> classNames = new ArrayList<String>(); if (!classFolder.exists()) { getLog().info("Class folder does not exist; skipping scan"); return classNames; } final String extension = ".class"; final DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(classFolder); directoryScanner.setIncludes(new String[] { "**" + File.separator + "*" + extension }); directoryScanner.scan(); String[] files = directoryScanner.getIncludedFiles(); String className; for (String file : files) { className = file.substring(0, file.length() - extension.length()).replace(File.separator, "."); classNames.add(className); } return classNames; }
java
List<String> listCompiledClasses(final File classFolder) { List<String> classNames = new ArrayList<String>(); if (!classFolder.exists()) { getLog().info("Class folder does not exist; skipping scan"); return classNames; } final String extension = ".class"; final DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(classFolder); directoryScanner.setIncludes(new String[] { "**" + File.separator + "*" + extension }); directoryScanner.scan(); String[] files = directoryScanner.getIncludedFiles(); String className; for (String file : files) { className = file.substring(0, file.length() - extension.length()).replace(File.separator, "."); classNames.add(className); } return classNames; }
[ "List", "<", "String", ">", "listCompiledClasses", "(", "final", "File", "classFolder", ")", "{", "List", "<", "String", ">", "classNames", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "if", "(", "!", "classFolder", ".", "exists", "(", "...
Walks the classFolder and finds all classes @param classFolder the folder to scan for .class files @return the list of available class names
[ "Walks", "the", "classFolder", "and", "finds", "all", "classes" ]
521a467ed5c00636749f6c6531be85ddf296565e
https://github.com/francisdb/serviceloader-maven-plugin/blob/521a467ed5c00636749f6c6531be85ddf296565e/src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java#L276-L296
train
francisdb/serviceloader-maven-plugin
src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java
ServiceloaderMojo.listCompiledClassesRegex
private List<String> listCompiledClassesRegex(File classFolder) { List<String> classNames = new ArrayList<String>(); Stack<File> todo = new Stack<File>(); todo.push(classFolder); String classFolderPath = classFolder.getAbsolutePath(); getLog().info("ClassFolderPath=" + classFolderPath); Pattern pat = Pattern.compile(classFolderPath + File.separator + "(.*).class"); File workDir; String name; while (!todo.isEmpty()) { workDir = todo.pop(); for (File file : workDir.listFiles()) { if (file.isDirectory()) { todo.push(file); } else { if (file.getName().endsWith(".class")) { name = file.getAbsolutePath(); name = pat.matcher(name).group(1); name = name.replace(File.separator, "."); getLog().debug("Found class: " + name); classNames.add(name); } } } } return classNames; }
java
private List<String> listCompiledClassesRegex(File classFolder) { List<String> classNames = new ArrayList<String>(); Stack<File> todo = new Stack<File>(); todo.push(classFolder); String classFolderPath = classFolder.getAbsolutePath(); getLog().info("ClassFolderPath=" + classFolderPath); Pattern pat = Pattern.compile(classFolderPath + File.separator + "(.*).class"); File workDir; String name; while (!todo.isEmpty()) { workDir = todo.pop(); for (File file : workDir.listFiles()) { if (file.isDirectory()) { todo.push(file); } else { if (file.getName().endsWith(".class")) { name = file.getAbsolutePath(); name = pat.matcher(name).group(1); name = name.replace(File.separator, "."); getLog().debug("Found class: " + name); classNames.add(name); } } } } return classNames; }
[ "private", "List", "<", "String", ">", "listCompiledClassesRegex", "(", "File", "classFolder", ")", "{", "List", "<", "String", ">", "classNames", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "Stack", "<", "File", ">", "todo", "=", "new", ...
Walks the classFolder and finds all .class files @param classFolder @return the list of available class names
[ "Walks", "the", "classFolder", "and", "finds", "all", ".", "class", "files" ]
521a467ed5c00636749f6c6531be85ddf296565e
https://github.com/francisdb/serviceloader-maven-plugin/blob/521a467ed5c00636749f6c6531be85ddf296565e/src/main/java/eu/somatik/maven/serviceloader/ServiceloaderMojo.java#L304-L333
train
kpelykh/docker-java
src/main/java/com/kpelykh/docker/client/DockerClient.java
DockerClient.auth
public void auth() throws DockerException { try { client.resource(restEndpointUrl + "/auth") .header("Content-Type", MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(authConfig()); } catch (UniformInterfaceException e) { throw new DockerException(e); } }
java
public void auth() throws DockerException { try { client.resource(restEndpointUrl + "/auth") .header("Content-Type", MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(authConfig()); } catch (UniformInterfaceException e) { throw new DockerException(e); } }
[ "public", "void", "auth", "(", ")", "throws", "DockerException", "{", "try", "{", "client", ".", "resource", "(", "restEndpointUrl", "+", "\"/auth\"", ")", ".", "header", "(", "\"Content-Type\"", ",", "MediaType", ".", "APPLICATION_JSON", ")", ".", "accept", ...
Authenticate with the server, useful for checking authentication.
[ "Authenticate", "with", "the", "server", "useful", "for", "checking", "authentication", "." ]
26b4069bb1985a8c293a016aaf9b56979771d75b
https://github.com/kpelykh/docker-java/blob/26b4069bb1985a8c293a016aaf9b56979771d75b/src/main/java/com/kpelykh/docker/client/DockerClient.java#L118-L127
train
kpelykh/docker-java
src/main/java/com/kpelykh/docker/client/DockerClient.java
DockerClient.push
public ClientResponse push(final String name) throws DockerException { if (name == null) { throw new IllegalArgumentException("name is null"); } try { final String registryAuth = registryAuth(); return client.resource(restEndpointUrl + "/images/" + name(name) + "/push") .header("X-Registry-Auth", registryAuth) .accept(MediaType.APPLICATION_JSON) .post(ClientResponse.class); } catch (UniformInterfaceException e) { throw new DockerException(e); } }
java
public ClientResponse push(final String name) throws DockerException { if (name == null) { throw new IllegalArgumentException("name is null"); } try { final String registryAuth = registryAuth(); return client.resource(restEndpointUrl + "/images/" + name(name) + "/push") .header("X-Registry-Auth", registryAuth) .accept(MediaType.APPLICATION_JSON) .post(ClientResponse.class); } catch (UniformInterfaceException e) { throw new DockerException(e); } }
[ "public", "ClientResponse", "push", "(", "final", "String", "name", ")", "throws", "DockerException", "{", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"name is null\"", ")", ";", "}", "try", "{", "final", "St...
Push the latest image to the repository. @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null.
[ "Push", "the", "latest", "image", "to", "the", "repository", "." ]
26b4069bb1985a8c293a016aaf9b56979771d75b
https://github.com/kpelykh/docker-java/blob/26b4069bb1985a8c293a016aaf9b56979771d75b/src/main/java/com/kpelykh/docker/client/DockerClient.java#L277-L290
train
kpelykh/docker-java
src/main/java/com/kpelykh/docker/client/DockerClient.java
DockerClient.tag
public int tag(String image, String repository, String tag, boolean force) throws DockerException { Preconditions.checkNotNull(image, "image was not specified"); Preconditions.checkNotNull(repository, "repository was not specified"); Preconditions.checkNotNull(tag, " tag was not provided"); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("repo", repository); params.add("tag", tag); params.add("force", String.valueOf(force)); WebResource webResource = client.resource(restEndpointUrl + "/images/" + image + "/tag").queryParams(params); try { LOGGER.trace("POST: {}", webResource); ClientResponse resp = webResource.post(ClientResponse.class); return resp.getStatus(); } catch (UniformInterfaceException exception) { throw new DockerException(exception); } }
java
public int tag(String image, String repository, String tag, boolean force) throws DockerException { Preconditions.checkNotNull(image, "image was not specified"); Preconditions.checkNotNull(repository, "repository was not specified"); Preconditions.checkNotNull(tag, " tag was not provided"); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("repo", repository); params.add("tag", tag); params.add("force", String.valueOf(force)); WebResource webResource = client.resource(restEndpointUrl + "/images/" + image + "/tag").queryParams(params); try { LOGGER.trace("POST: {}", webResource); ClientResponse resp = webResource.post(ClientResponse.class); return resp.getStatus(); } catch (UniformInterfaceException exception) { throw new DockerException(exception); } }
[ "public", "int", "tag", "(", "String", "image", ",", "String", "repository", ",", "String", "tag", ",", "boolean", "force", ")", "throws", "DockerException", "{", "Preconditions", ".", "checkNotNull", "(", "image", ",", "\"image was not specified\"", ")", ";", ...
Tag an image into a repository @param image the local image to tag (either a name or an id) @param repository the repository to tag in @param tag any tag for this image @param force (not documented) @return the HTTP status code (201 for success)
[ "Tag", "an", "image", "into", "a", "repository" ]
26b4069bb1985a8c293a016aaf9b56979771d75b
https://github.com/kpelykh/docker-java/blob/26b4069bb1985a8c293a016aaf9b56979771d75b/src/main/java/com/kpelykh/docker/client/DockerClient.java#L305-L324
train