id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
28,200
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java
LogRequestor.fetchLogs
public void fetchLogs() { try { callback.open(); this.request = getLogRequest(false); final HttpResponse response = client.execute(request); parseResponse(response); } catch (LogCallback.DoneException e) { // Signifies we're finished with the log stream. } catch (IOException exp) { callback.error(exp.getMessage()); } finally { callback.close(); } }
java
public void fetchLogs() { try { callback.open(); this.request = getLogRequest(false); final HttpResponse response = client.execute(request); parseResponse(response); } catch (LogCallback.DoneException e) { // Signifies we're finished with the log stream. } catch (IOException exp) { callback.error(exp.getMessage()); } finally { callback.close(); } }
[ "public", "void", "fetchLogs", "(", ")", "{", "try", "{", "callback", ".", "open", "(", ")", ";", "this", ".", "request", "=", "getLogRequest", "(", "false", ")", ";", "final", "HttpResponse", "response", "=", "client", ".", "execute", "(", "request", ")", ";", "parseResponse", "(", "response", ")", ";", "}", "catch", "(", "LogCallback", ".", "DoneException", "e", ")", "{", "// Signifies we're finished with the log stream.", "}", "catch", "(", "IOException", "exp", ")", "{", "callback", ".", "error", "(", "exp", ".", "getMessage", "(", ")", ")", ";", "}", "finally", "{", "callback", ".", "close", "(", ")", ";", "}", "}" ]
Get logs and feed a callback with the content
[ "Get", "logs", "and", "feed", "a", "callback", "with", "the", "content" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java#L82-L95
28,201
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java
LogRequestor.run
public void run() { try { callback.open(); this.request = getLogRequest(true); final HttpResponse response = client.execute(request); parseResponse(response); } catch (LogCallback.DoneException e) { // Signifies we're finished with the log stream. } catch (IOException e) { callback.error("IO Error while requesting logs: " + e + " " + Thread.currentThread().getName()); } finally { callback.close(); } }
java
public void run() { try { callback.open(); this.request = getLogRequest(true); final HttpResponse response = client.execute(request); parseResponse(response); } catch (LogCallback.DoneException e) { // Signifies we're finished with the log stream. } catch (IOException e) { callback.error("IO Error while requesting logs: " + e + " " + Thread.currentThread().getName()); } finally { callback.close(); } }
[ "public", "void", "run", "(", ")", "{", "try", "{", "callback", ".", "open", "(", ")", ";", "this", ".", "request", "=", "getLogRequest", "(", "true", ")", ";", "final", "HttpResponse", "response", "=", "client", ".", "execute", "(", "request", ")", ";", "parseResponse", "(", "response", ")", ";", "}", "catch", "(", "LogCallback", ".", "DoneException", "e", ")", "{", "// Signifies we're finished with the log stream.", "}", "catch", "(", "IOException", "e", ")", "{", "callback", ".", "error", "(", "\"IO Error while requesting logs: \"", "+", "e", "+", "\" \"", "+", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "finally", "{", "callback", ".", "close", "(", ")", ";", "}", "}" ]
Fetch log asynchronously as stream and follow stream
[ "Fetch", "log", "asynchronously", "as", "stream", "and", "follow", "stream" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java#L98-L111
28,202
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/DockerAssemblyConfigurationSource.java
DockerAssemblyConfigurationSource.mainProjectInterpolator
private FixedStringSearchInterpolator mainProjectInterpolator(MavenProject mainProject) { if (mainProject != null) { // 5 return FixedStringSearchInterpolator.create( new org.codehaus.plexus.interpolation.fixed.PrefixedObjectValueSource( InterpolationConstants.PROJECT_PREFIXES, mainProject, true ), // 6 new org.codehaus.plexus.interpolation.fixed.PrefixedPropertiesValueSource( InterpolationConstants.PROJECT_PROPERTIES_PREFIXES, mainProject.getProperties(), true ) ); } else { return FixedStringSearchInterpolator.empty(); } }
java
private FixedStringSearchInterpolator mainProjectInterpolator(MavenProject mainProject) { if (mainProject != null) { // 5 return FixedStringSearchInterpolator.create( new org.codehaus.plexus.interpolation.fixed.PrefixedObjectValueSource( InterpolationConstants.PROJECT_PREFIXES, mainProject, true ), // 6 new org.codehaus.plexus.interpolation.fixed.PrefixedPropertiesValueSource( InterpolationConstants.PROJECT_PROPERTIES_PREFIXES, mainProject.getProperties(), true ) ); } else { return FixedStringSearchInterpolator.empty(); } }
[ "private", "FixedStringSearchInterpolator", "mainProjectInterpolator", "(", "MavenProject", "mainProject", ")", "{", "if", "(", "mainProject", "!=", "null", ")", "{", "// 5", "return", "FixedStringSearchInterpolator", ".", "create", "(", "new", "org", ".", "codehaus", ".", "plexus", ".", "interpolation", ".", "fixed", ".", "PrefixedObjectValueSource", "(", "InterpolationConstants", ".", "PROJECT_PREFIXES", ",", "mainProject", ",", "true", ")", ",", "// 6", "new", "org", ".", "codehaus", ".", "plexus", ".", "interpolation", ".", "fixed", ".", "PrefixedPropertiesValueSource", "(", "InterpolationConstants", ".", "PROJECT_PROPERTIES_PREFIXES", ",", "mainProject", ".", "getProperties", "(", ")", ",", "true", ")", ")", ";", "}", "else", "{", "return", "FixedStringSearchInterpolator", ".", "empty", "(", ")", ";", "}", "}" ]
Taken from AbstractAssemblyMojo
[ "Taken", "from", "AbstractAssemblyMojo" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/DockerAssemblyConfigurationSource.java#L280-L295
28,203
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/NamePatternUtil.java
NamePatternUtil.convertImageNamePattern
public static String convertImageNamePattern(String pattern) { final String REGEX_PREFIX = "%regex[", ANT_PREFIX = "%ant[", PATTERN_SUFFIX="]"; if(pattern.startsWith(REGEX_PREFIX) && pattern.endsWith(PATTERN_SUFFIX)) { return pattern.substring(REGEX_PREFIX.length(), pattern.length() - PATTERN_SUFFIX.length()); } if(pattern.startsWith(ANT_PREFIX) && pattern.endsWith(PATTERN_SUFFIX)) { pattern = pattern.substring(ANT_PREFIX.length(), pattern.length() - PATTERN_SUFFIX.length()); } String[] parts = pattern.split("((?=[/:?*])|(?<=[/:?*]))"); Matcher matcher = Pattern.compile("[A-Za-z0-9-]+").matcher(""); StringBuilder builder = new StringBuilder("^"); for(int i = 0; i < parts.length; ++i) { if("?".equals(parts[i])) { builder.append("[^/:]"); } else if("*".equals(parts[i])) { if (i + 1 < parts.length && "*".equals(parts[i + 1])) { builder.append("([^:]|:(?=.*:))*"); ++i; if (i + 1 < parts.length && "/".equals(parts[i + 1])) { builder.append("(?<![^/])"); ++i; } } else { builder.append("([^/:]|:(?=.*:))*"); } } else if("/".equals(parts[i]) || ":".equals(parts[i]) || matcher.reset(parts[i]).matches()) { builder.append(parts[i]); } else if(parts[i].length() > 0) { builder.append(Pattern.quote(parts[i])); } } builder.append("$"); return builder.toString(); }
java
public static String convertImageNamePattern(String pattern) { final String REGEX_PREFIX = "%regex[", ANT_PREFIX = "%ant[", PATTERN_SUFFIX="]"; if(pattern.startsWith(REGEX_PREFIX) && pattern.endsWith(PATTERN_SUFFIX)) { return pattern.substring(REGEX_PREFIX.length(), pattern.length() - PATTERN_SUFFIX.length()); } if(pattern.startsWith(ANT_PREFIX) && pattern.endsWith(PATTERN_SUFFIX)) { pattern = pattern.substring(ANT_PREFIX.length(), pattern.length() - PATTERN_SUFFIX.length()); } String[] parts = pattern.split("((?=[/:?*])|(?<=[/:?*]))"); Matcher matcher = Pattern.compile("[A-Za-z0-9-]+").matcher(""); StringBuilder builder = new StringBuilder("^"); for(int i = 0; i < parts.length; ++i) { if("?".equals(parts[i])) { builder.append("[^/:]"); } else if("*".equals(parts[i])) { if (i + 1 < parts.length && "*".equals(parts[i + 1])) { builder.append("([^:]|:(?=.*:))*"); ++i; if (i + 1 < parts.length && "/".equals(parts[i + 1])) { builder.append("(?<![^/])"); ++i; } } else { builder.append("([^/:]|:(?=.*:))*"); } } else if("/".equals(parts[i]) || ":".equals(parts[i]) || matcher.reset(parts[i]).matches()) { builder.append(parts[i]); } else if(parts[i].length() > 0) { builder.append(Pattern.quote(parts[i])); } } builder.append("$"); return builder.toString(); }
[ "public", "static", "String", "convertImageNamePattern", "(", "String", "pattern", ")", "{", "final", "String", "REGEX_PREFIX", "=", "\"%regex[\"", ",", "ANT_PREFIX", "=", "\"%ant[\"", ",", "PATTERN_SUFFIX", "=", "\"]\"", ";", "if", "(", "pattern", ".", "startsWith", "(", "REGEX_PREFIX", ")", "&&", "pattern", ".", "endsWith", "(", "PATTERN_SUFFIX", ")", ")", "{", "return", "pattern", ".", "substring", "(", "REGEX_PREFIX", ".", "length", "(", ")", ",", "pattern", ".", "length", "(", ")", "-", "PATTERN_SUFFIX", ".", "length", "(", ")", ")", ";", "}", "if", "(", "pattern", ".", "startsWith", "(", "ANT_PREFIX", ")", "&&", "pattern", ".", "endsWith", "(", "PATTERN_SUFFIX", ")", ")", "{", "pattern", "=", "pattern", ".", "substring", "(", "ANT_PREFIX", ".", "length", "(", ")", ",", "pattern", ".", "length", "(", ")", "-", "PATTERN_SUFFIX", ".", "length", "(", ")", ")", ";", "}", "String", "[", "]", "parts", "=", "pattern", ".", "split", "(", "\"((?=[/:?*])|(?<=[/:?*]))\"", ")", ";", "Matcher", "matcher", "=", "Pattern", ".", "compile", "(", "\"[A-Za-z0-9-]+\"", ")", ".", "matcher", "(", "\"\"", ")", ";", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", "\"^\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "++", "i", ")", "{", "if", "(", "\"?\"", ".", "equals", "(", "parts", "[", "i", "]", ")", ")", "{", "builder", ".", "append", "(", "\"[^/:]\"", ")", ";", "}", "else", "if", "(", "\"*\"", ".", "equals", "(", "parts", "[", "i", "]", ")", ")", "{", "if", "(", "i", "+", "1", "<", "parts", ".", "length", "&&", "\"*\"", ".", "equals", "(", "parts", "[", "i", "+", "1", "]", ")", ")", "{", "builder", ".", "append", "(", "\"([^:]|:(?=.*:))*\"", ")", ";", "++", "i", ";", "if", "(", "i", "+", "1", "<", "parts", ".", "length", "&&", "\"/\"", ".", "equals", "(", "parts", "[", "i", "+", "1", "]", ")", ")", "{", "builder", ".", "append", "(", "\"(?<![^/])\"", ")", ";", "++", "i", ";", "}", "}", "else", "{", "builder", ".", "append", "(", "\"([^/:]|:(?=.*:))*\"", ")", ";", "}", "}", "else", "if", "(", "\"/\"", ".", "equals", "(", "parts", "[", "i", "]", ")", "||", "\":\"", ".", "equals", "(", "parts", "[", "i", "]", ")", "||", "matcher", ".", "reset", "(", "parts", "[", "i", "]", ")", ".", "matches", "(", ")", ")", "{", "builder", ".", "append", "(", "parts", "[", "i", "]", ")", ";", "}", "else", "if", "(", "parts", "[", "i", "]", ".", "length", "(", ")", ">", "0", ")", "{", "builder", ".", "append", "(", "Pattern", ".", "quote", "(", "parts", "[", "i", "]", ")", ")", ";", "}", "}", "builder", ".", "append", "(", "\"$\"", ")", ";", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Accepts an Ant-ish or regular expression pattern and compiles to a regular expression. This is similar to SelectorUtils in the Maven codebase, but there the code uses the platform File.separator, while here we always want to work with forward slashes. Also, for a more natural fit with repository tags, both * and ** should stop at the colon that precedes the tag. Like SelectorUtils, wrapping a pattern in %regex[pattern] will create a regex from the pattern provided without translation. Otherwise, or if wrapped in %ant[pattern], then a regular expression will be created that is anchored at beginning and end, converts ? to [^/:], * to ([^/:]|:(?=.*:)) and ** to ([^:]|:(?=.*:))*. If ** is followed by /, the / is converted to a negative lookbehind for anything apart from a slash. @return a regular expression pattern created from the input pattern
[ "Accepts", "an", "Ant", "-", "ish", "or", "regular", "expression", "pattern", "and", "compiles", "to", "a", "regular", "expression", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/NamePatternUtil.java#L29-L69
28,204
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/ecr/AwsSigner4.java
AwsSigner4.sign
void sign(HttpRequest request, AuthConfig credentials, Date signingTime) { AwsSigner4Request sr = new AwsSigner4Request(region, service, request, signingTime); if(!request.containsHeader("X-Amz-Date")) { request.addHeader("X-Amz-Date", sr.getSigningDateTime()); } request.addHeader("Authorization", task4(sr, credentials)); final String securityToken = credentials.getAuth(); if (StringUtils.isNotEmpty(securityToken)) { request.addHeader("X-Amz-Security-Token", securityToken); } }
java
void sign(HttpRequest request, AuthConfig credentials, Date signingTime) { AwsSigner4Request sr = new AwsSigner4Request(region, service, request, signingTime); if(!request.containsHeader("X-Amz-Date")) { request.addHeader("X-Amz-Date", sr.getSigningDateTime()); } request.addHeader("Authorization", task4(sr, credentials)); final String securityToken = credentials.getAuth(); if (StringUtils.isNotEmpty(securityToken)) { request.addHeader("X-Amz-Security-Token", securityToken); } }
[ "void", "sign", "(", "HttpRequest", "request", ",", "AuthConfig", "credentials", ",", "Date", "signingTime", ")", "{", "AwsSigner4Request", "sr", "=", "new", "AwsSigner4Request", "(", "region", ",", "service", ",", "request", ",", "signingTime", ")", ";", "if", "(", "!", "request", ".", "containsHeader", "(", "\"X-Amz-Date\"", ")", ")", "{", "request", ".", "addHeader", "(", "\"X-Amz-Date\"", ",", "sr", ".", "getSigningDateTime", "(", ")", ")", ";", "}", "request", ".", "addHeader", "(", "\"Authorization\"", ",", "task4", "(", "sr", ",", "credentials", ")", ")", ";", "final", "String", "securityToken", "=", "credentials", ".", "getAuth", "(", ")", ";", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "securityToken", ")", ")", "{", "request", ".", "addHeader", "(", "\"X-Amz-Security-Token\"", ",", "securityToken", ")", ";", "}", "}" ]
Sign a request. Add the headers that authenticate the request. @param request The request to sign. @param credentials The credentials to use when signing. @param signingTime The invocation time to use;
[ "Sign", "a", "request", ".", "Add", "the", "headers", "that", "authenticate", "the", "request", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/ecr/AwsSigner4.java#L55-L65
28,205
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/config/handler/property/PropertyConfigHandler.java
PropertyConfigHandler.buildConfigured
private boolean buildConfigured(BuildImageConfiguration config, ValueProvider valueProvider, MavenProject project) { if (isStringValueNull(valueProvider, config, FROM, () -> config.getFrom())) { return true; } if (valueProvider.getMap(FROM_EXT, config == null ? null : config.getFromExt()) != null) { return true; } if (isStringValueNull(valueProvider, config, DOCKER_FILE, () -> config.getDockerFileRaw() )) { return true; } if (isStringValueNull(valueProvider, config, DOCKER_ARCHIVE, () -> config.getDockerArchiveRaw())) { return true; } if (isStringValueNull(valueProvider, config, CONTEXT_DIR, () -> config.getContextDirRaw())) { return true; } if (isStringValueNull(valueProvider, config, DOCKER_FILE_DIR, () -> config.getDockerFileDirRaw())) { return true; } // Simple Dockerfile mode return new File(project.getBasedir(),"Dockerfile").exists(); }
java
private boolean buildConfigured(BuildImageConfiguration config, ValueProvider valueProvider, MavenProject project) { if (isStringValueNull(valueProvider, config, FROM, () -> config.getFrom())) { return true; } if (valueProvider.getMap(FROM_EXT, config == null ? null : config.getFromExt()) != null) { return true; } if (isStringValueNull(valueProvider, config, DOCKER_FILE, () -> config.getDockerFileRaw() )) { return true; } if (isStringValueNull(valueProvider, config, DOCKER_ARCHIVE, () -> config.getDockerArchiveRaw())) { return true; } if (isStringValueNull(valueProvider, config, CONTEXT_DIR, () -> config.getContextDirRaw())) { return true; } if (isStringValueNull(valueProvider, config, DOCKER_FILE_DIR, () -> config.getDockerFileDirRaw())) { return true; } // Simple Dockerfile mode return new File(project.getBasedir(),"Dockerfile").exists(); }
[ "private", "boolean", "buildConfigured", "(", "BuildImageConfiguration", "config", ",", "ValueProvider", "valueProvider", ",", "MavenProject", "project", ")", "{", "if", "(", "isStringValueNull", "(", "valueProvider", ",", "config", ",", "FROM", ",", "(", ")", "->", "config", ".", "getFrom", "(", ")", ")", ")", "{", "return", "true", ";", "}", "if", "(", "valueProvider", ".", "getMap", "(", "FROM_EXT", ",", "config", "==", "null", "?", "null", ":", "config", ".", "getFromExt", "(", ")", ")", "!=", "null", ")", "{", "return", "true", ";", "}", "if", "(", "isStringValueNull", "(", "valueProvider", ",", "config", ",", "DOCKER_FILE", ",", "(", ")", "->", "config", ".", "getDockerFileRaw", "(", ")", ")", ")", "{", "return", "true", ";", "}", "if", "(", "isStringValueNull", "(", "valueProvider", ",", "config", ",", "DOCKER_ARCHIVE", ",", "(", ")", "->", "config", ".", "getDockerArchiveRaw", "(", ")", ")", ")", "{", "return", "true", ";", "}", "if", "(", "isStringValueNull", "(", "valueProvider", ",", "config", ",", "CONTEXT_DIR", ",", "(", ")", "->", "config", ".", "getContextDirRaw", "(", ")", ")", ")", "{", "return", "true", ";", "}", "if", "(", "isStringValueNull", "(", "valueProvider", ",", "config", ",", "DOCKER_FILE_DIR", ",", "(", ")", "->", "config", ".", "getDockerFileDirRaw", "(", ")", ")", ")", "{", "return", "true", ";", "}", "// Simple Dockerfile mode", "return", "new", "File", "(", "project", ".", "getBasedir", "(", ")", ",", "\"Dockerfile\"", ")", ".", "exists", "(", ")", ";", "}" ]
Enable build config only when a `.from.`, `.dockerFile.`, or `.dockerFileDir.` is configured
[ "Enable", "build", "config", "only", "when", "a", ".", "from", ".", ".", "dockerFile", ".", "or", ".", "dockerFileDir", ".", "is", "configured" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/config/handler/property/PropertyConfigHandler.java#L96-L123
28,206
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/config/handler/property/PropertyConfigHandler.java
PropertyConfigHandler.extractPortValues
private List<String> extractPortValues(List<String> config, ValueProvider valueProvider) { List<String> ret = new ArrayList<>(); List<String> ports = valueProvider.getList(PORTS, config); if (ports == null) { return null; } List<String[]> parsedPorts = EnvUtil.splitOnLastColon(ports); for (String[] port : parsedPorts) { ret.add(port[1]); } return ret; }
java
private List<String> extractPortValues(List<String> config, ValueProvider valueProvider) { List<String> ret = new ArrayList<>(); List<String> ports = valueProvider.getList(PORTS, config); if (ports == null) { return null; } List<String[]> parsedPorts = EnvUtil.splitOnLastColon(ports); for (String[] port : parsedPorts) { ret.add(port[1]); } return ret; }
[ "private", "List", "<", "String", ">", "extractPortValues", "(", "List", "<", "String", ">", "config", ",", "ValueProvider", "valueProvider", ")", "{", "List", "<", "String", ">", "ret", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "String", ">", "ports", "=", "valueProvider", ".", "getList", "(", "PORTS", ",", "config", ")", ";", "if", "(", "ports", "==", "null", ")", "{", "return", "null", ";", "}", "List", "<", "String", "[", "]", ">", "parsedPorts", "=", "EnvUtil", ".", "splitOnLastColon", "(", "ports", ")", ";", "for", "(", "String", "[", "]", "port", ":", "parsedPorts", ")", "{", "ret", ".", "add", "(", "port", "[", "1", "]", ")", ";", "}", "return", "ret", ";", "}" ]
Extract only the values of the port mapping
[ "Extract", "only", "the", "values", "of", "the", "port", "mapping" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/config/handler/property/PropertyConfigHandler.java#L265-L276
28,207
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/BuildMojo.java
BuildMojo.processImageConfig
private void processImageConfig(ServiceHub hub, ImageConfiguration aImageConfig) throws IOException, MojoExecutionException { BuildImageConfiguration buildConfig = aImageConfig.getBuildConfiguration(); if (buildConfig != null) { if(buildConfig.skip()) { log.info("%s : Skipped building", aImageConfig.getDescription()); } else { buildAndTag(hub, aImageConfig); } } }
java
private void processImageConfig(ServiceHub hub, ImageConfiguration aImageConfig) throws IOException, MojoExecutionException { BuildImageConfiguration buildConfig = aImageConfig.getBuildConfiguration(); if (buildConfig != null) { if(buildConfig.skip()) { log.info("%s : Skipped building", aImageConfig.getDescription()); } else { buildAndTag(hub, aImageConfig); } } }
[ "private", "void", "processImageConfig", "(", "ServiceHub", "hub", ",", "ImageConfiguration", "aImageConfig", ")", "throws", "IOException", ",", "MojoExecutionException", "{", "BuildImageConfiguration", "buildConfig", "=", "aImageConfig", ".", "getBuildConfiguration", "(", ")", ";", "if", "(", "buildConfig", "!=", "null", ")", "{", "if", "(", "buildConfig", ".", "skip", "(", ")", ")", "{", "log", ".", "info", "(", "\"%s : Skipped building\"", ",", "aImageConfig", ".", "getDescription", "(", ")", ")", ";", "}", "else", "{", "buildAndTag", "(", "hub", ",", "aImageConfig", ")", ";", "}", "}", "}" ]
Helper method to process an ImageConfiguration. @param hub ServiceHub @param aImageConfig ImageConfiguration that would be forwarded to build and tag @throws DockerAccessException @throws MojoExecutionException
[ "Helper", "method", "to", "process", "an", "ImageConfiguration", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/BuildMojo.java#L98-L108
28,208
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/UrlBuilder.java
UrlBuilder.u
private Builder u(String format, String ... args) { return new Builder(createUrl(String.format(format, (Object[]) encodeArgs(args)))); }
java
private Builder u(String format, String ... args) { return new Builder(createUrl(String.format(format, (Object[]) encodeArgs(args)))); }
[ "private", "Builder", "u", "(", "String", "format", ",", "String", "...", "args", ")", "{", "return", "new", "Builder", "(", "createUrl", "(", "String", ".", "format", "(", "format", ",", "(", "Object", "[", "]", ")", "encodeArgs", "(", "args", ")", ")", ")", ")", ";", "}" ]
Entry point for builder
[ "Entry", "point", "for", "builder" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/UrlBuilder.java#L199-L201
28,209
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/ImageName.java
ImageName.getSimpleName
public String getSimpleName() { String prefix = user + "/"; return repository.startsWith(prefix) ? repository.substring(prefix.length()) : repository; }
java
public String getSimpleName() { String prefix = user + "/"; return repository.startsWith(prefix) ? repository.substring(prefix.length()) : repository; }
[ "public", "String", "getSimpleName", "(", ")", "{", "String", "prefix", "=", "user", "+", "\"/\"", ";", "return", "repository", ".", "startsWith", "(", "prefix", ")", "?", "repository", ".", "substring", "(", "prefix", ".", "length", "(", ")", ")", ":", "repository", ";", "}" ]
Get the simple name of the image, which is the repository sans the user parts. @return simple name of the image
[ "Get", "the", "simple", "name", "of", "the", "image", "which", "is", "the", "repository", "sans", "the", "user", "parts", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/ImageName.java#L210-L213
28,210
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/ImageName.java
ImageName.doValidate
private void doValidate() { List<String> errors = new ArrayList<>(); // Strip off user from repository name String image = user != null ? repository.substring(user.length() + 1) : repository; Object[] checks = new Object[] { "registry", DOMAIN_REGEXP, registry, "image", IMAGE_NAME_REGEXP, image, "user", NAME_COMP_REGEXP, user, "tag", TAG_REGEXP, tag, "digest", DIGEST_REGEXP, digest }; for (int i = 0; i < checks.length; i +=3) { String value = (String) checks[i + 2]; Pattern checkPattern = (Pattern) checks[i + 1]; if (value != null && !checkPattern.matcher(value).matches()) { errors.add(String.format("%s part '%s' doesn't match allowed pattern '%s'", checks[i], value, checkPattern.pattern())); } } if (errors.size() > 0) { StringBuilder buf = new StringBuilder(); buf.append(String.format("Given Docker name '%s' is invalid:\n", getFullName())); for (String error : errors) { buf.append(String.format(" * %s\n",error)); } buf.append("See http://bit.ly/docker_image_fmt for more details"); throw new IllegalArgumentException(buf.toString()); } }
java
private void doValidate() { List<String> errors = new ArrayList<>(); // Strip off user from repository name String image = user != null ? repository.substring(user.length() + 1) : repository; Object[] checks = new Object[] { "registry", DOMAIN_REGEXP, registry, "image", IMAGE_NAME_REGEXP, image, "user", NAME_COMP_REGEXP, user, "tag", TAG_REGEXP, tag, "digest", DIGEST_REGEXP, digest }; for (int i = 0; i < checks.length; i +=3) { String value = (String) checks[i + 2]; Pattern checkPattern = (Pattern) checks[i + 1]; if (value != null && !checkPattern.matcher(value).matches()) { errors.add(String.format("%s part '%s' doesn't match allowed pattern '%s'", checks[i], value, checkPattern.pattern())); } } if (errors.size() > 0) { StringBuilder buf = new StringBuilder(); buf.append(String.format("Given Docker name '%s' is invalid:\n", getFullName())); for (String error : errors) { buf.append(String.format(" * %s\n",error)); } buf.append("See http://bit.ly/docker_image_fmt for more details"); throw new IllegalArgumentException(buf.toString()); } }
[ "private", "void", "doValidate", "(", ")", "{", "List", "<", "String", ">", "errors", "=", "new", "ArrayList", "<>", "(", ")", ";", "// Strip off user from repository name", "String", "image", "=", "user", "!=", "null", "?", "repository", ".", "substring", "(", "user", ".", "length", "(", ")", "+", "1", ")", ":", "repository", ";", "Object", "[", "]", "checks", "=", "new", "Object", "[", "]", "{", "\"registry\"", ",", "DOMAIN_REGEXP", ",", "registry", ",", "\"image\"", ",", "IMAGE_NAME_REGEXP", ",", "image", ",", "\"user\"", ",", "NAME_COMP_REGEXP", ",", "user", ",", "\"tag\"", ",", "TAG_REGEXP", ",", "tag", ",", "\"digest\"", ",", "DIGEST_REGEXP", ",", "digest", "}", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "checks", ".", "length", ";", "i", "+=", "3", ")", "{", "String", "value", "=", "(", "String", ")", "checks", "[", "i", "+", "2", "]", ";", "Pattern", "checkPattern", "=", "(", "Pattern", ")", "checks", "[", "i", "+", "1", "]", ";", "if", "(", "value", "!=", "null", "&&", "!", "checkPattern", ".", "matcher", "(", "value", ")", ".", "matches", "(", ")", ")", "{", "errors", ".", "add", "(", "String", ".", "format", "(", "\"%s part '%s' doesn't match allowed pattern '%s'\"", ",", "checks", "[", "i", "]", ",", "value", ",", "checkPattern", ".", "pattern", "(", ")", ")", ")", ";", "}", "}", "if", "(", "errors", ".", "size", "(", ")", ">", "0", ")", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", ")", ";", "buf", ".", "append", "(", "String", ".", "format", "(", "\"Given Docker name '%s' is invalid:\\n\"", ",", "getFullName", "(", ")", ")", ")", ";", "for", "(", "String", "error", ":", "errors", ")", "{", "buf", ".", "append", "(", "String", ".", "format", "(", "\" * %s\\n\"", ",", "error", ")", ")", ";", "}", "buf", ".", "append", "(", "\"See http://bit.ly/docker_image_fmt for more details\"", ")", ";", "throw", "new", "IllegalArgumentException", "(", "buf", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Validate parts and throw an IllegalArgumentException if a part is not valid
[ "Validate", "parts", "and", "throw", "an", "IllegalArgumentException", "if", "a", "part", "is", "not", "valid" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/ImageName.java#L227-L256
28,211
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/ImageArchiveUtil.java
ImageArchiveUtil.findEntryByRepoTag
public static ImageArchiveManifestEntry findEntryByRepoTag(String repoTag, ImageArchiveManifest manifest) { if(repoTag == null || manifest == null) { return null; } for(ImageArchiveManifestEntry entry : manifest.getEntries()) { for(String entryRepoTag : entry.getRepoTags()) { if(repoTag.equals(entryRepoTag)) { return entry; } } } return null; }
java
public static ImageArchiveManifestEntry findEntryByRepoTag(String repoTag, ImageArchiveManifest manifest) { if(repoTag == null || manifest == null) { return null; } for(ImageArchiveManifestEntry entry : manifest.getEntries()) { for(String entryRepoTag : entry.getRepoTags()) { if(repoTag.equals(entryRepoTag)) { return entry; } } } return null; }
[ "public", "static", "ImageArchiveManifestEntry", "findEntryByRepoTag", "(", "String", "repoTag", ",", "ImageArchiveManifest", "manifest", ")", "{", "if", "(", "repoTag", "==", "null", "||", "manifest", "==", "null", ")", "{", "return", "null", ";", "}", "for", "(", "ImageArchiveManifestEntry", "entry", ":", "manifest", ".", "getEntries", "(", ")", ")", "{", "for", "(", "String", "entryRepoTag", ":", "entry", ".", "getRepoTags", "(", ")", ")", "{", "if", "(", "repoTag", ".", "equals", "(", "entryRepoTag", ")", ")", "{", "return", "entry", ";", "}", "}", "}", "return", "null", ";", "}" ]
Search the manifest for an entry that has the repository and tag provided. @param repoTag the repository and tag to search (e.g. busybox:latest). @param manifest the manifest to be searched @return the entry found, or null if no match.
[ "Search", "the", "manifest", "for", "an", "entry", "that", "has", "the", "repository", "and", "tag", "provided", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/ImageArchiveUtil.java#L124-L138
28,212
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/ImageArchiveUtil.java
ImageArchiveUtil.mapEntriesById
public static Map<String, ImageArchiveManifestEntry> mapEntriesById(Iterable<ImageArchiveManifestEntry> entries) { Map<String, ImageArchiveManifestEntry> mapped = new LinkedHashMap<>(); for(ImageArchiveManifestEntry entry : entries) { mapped.put(entry.getId(), entry); } return mapped; }
java
public static Map<String, ImageArchiveManifestEntry> mapEntriesById(Iterable<ImageArchiveManifestEntry> entries) { Map<String, ImageArchiveManifestEntry> mapped = new LinkedHashMap<>(); for(ImageArchiveManifestEntry entry : entries) { mapped.put(entry.getId(), entry); } return mapped; }
[ "public", "static", "Map", "<", "String", ",", "ImageArchiveManifestEntry", ">", "mapEntriesById", "(", "Iterable", "<", "ImageArchiveManifestEntry", ">", "entries", ")", "{", "Map", "<", "String", ",", "ImageArchiveManifestEntry", ">", "mapped", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "for", "(", "ImageArchiveManifestEntry", "entry", ":", "entries", ")", "{", "mapped", ".", "put", "(", "entry", ".", "getId", "(", ")", ",", "entry", ")", ";", "}", "return", "mapped", ";", "}" ]
Build a map of entries by id from an iterable of entries. @param entries @return a map of entries by id
[ "Build", "a", "map", "of", "entries", "by", "id", "from", "an", "iterable", "of", "entries", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/ImageArchiveUtil.java#L220-L228
28,213
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/StartMojo.java
StartMojo.hasBeenAllImagesStarted
private boolean hasBeenAllImagesStarted(Queue<ImageConfiguration> imagesWaitingToStart, Queue<ImageConfiguration> imagesStarting) { return imagesWaitingToStart.isEmpty() && imagesStarting.isEmpty(); }
java
private boolean hasBeenAllImagesStarted(Queue<ImageConfiguration> imagesWaitingToStart, Queue<ImageConfiguration> imagesStarting) { return imagesWaitingToStart.isEmpty() && imagesStarting.isEmpty(); }
[ "private", "boolean", "hasBeenAllImagesStarted", "(", "Queue", "<", "ImageConfiguration", ">", "imagesWaitingToStart", ",", "Queue", "<", "ImageConfiguration", ">", "imagesStarting", ")", "{", "return", "imagesWaitingToStart", ".", "isEmpty", "(", ")", "&&", "imagesStarting", ".", "isEmpty", "(", ")", ";", "}" ]
Check if we are done
[ "Check", "if", "we", "are", "done" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/StartMojo.java#L229-L231
28,214
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/StartMojo.java
StartMojo.getImagesWhoseDependenciesHasStarted
private List<ImageConfiguration> getImagesWhoseDependenciesHasStarted(Queue<ImageConfiguration> imagesRemaining, Set<String> containersStarted, Set<String> aliases) { final List<ImageConfiguration> ret = new ArrayList<>(); // Check for all images which can be already started for (ImageConfiguration imageWaitingToStart : imagesRemaining) { List<String> allDependencies = imageWaitingToStart.getDependencies(); List<String> aliasDependencies = filterOutNonAliases(aliases, allDependencies); if (containersStarted.containsAll(aliasDependencies)) { ret.add(imageWaitingToStart); } } return ret; }
java
private List<ImageConfiguration> getImagesWhoseDependenciesHasStarted(Queue<ImageConfiguration> imagesRemaining, Set<String> containersStarted, Set<String> aliases) { final List<ImageConfiguration> ret = new ArrayList<>(); // Check for all images which can be already started for (ImageConfiguration imageWaitingToStart : imagesRemaining) { List<String> allDependencies = imageWaitingToStart.getDependencies(); List<String> aliasDependencies = filterOutNonAliases(aliases, allDependencies); if (containersStarted.containsAll(aliasDependencies)) { ret.add(imageWaitingToStart); } } return ret; }
[ "private", "List", "<", "ImageConfiguration", ">", "getImagesWhoseDependenciesHasStarted", "(", "Queue", "<", "ImageConfiguration", ">", "imagesRemaining", ",", "Set", "<", "String", ">", "containersStarted", ",", "Set", "<", "String", ">", "aliases", ")", "{", "final", "List", "<", "ImageConfiguration", ">", "ret", "=", "new", "ArrayList", "<>", "(", ")", ";", "// Check for all images which can be already started", "for", "(", "ImageConfiguration", "imageWaitingToStart", ":", "imagesRemaining", ")", "{", "List", "<", "String", ">", "allDependencies", "=", "imageWaitingToStart", ".", "getDependencies", "(", ")", ";", "List", "<", "String", ">", "aliasDependencies", "=", "filterOutNonAliases", "(", "aliases", ",", "allDependencies", ")", ";", "if", "(", "containersStarted", ".", "containsAll", "(", "aliasDependencies", ")", ")", "{", "ret", ".", "add", "(", "imageWaitingToStart", ")", ";", "}", "}", "return", "ret", ";", "}" ]
Pick out all images who can be started right now because all their dependencies has been started
[ "Pick", "out", "all", "images", "who", "can", "be", "started", "right", "now", "because", "all", "their", "dependencies", "has", "been", "started" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/StartMojo.java#L311-L325
28,215
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/StartMojo.java
StartMojo.prepareStart
private Queue<ImageConfiguration> prepareStart(ServiceHub hub, QueryService queryService, RunService runService, Set<String> imageAliases) throws DockerAccessException, MojoExecutionException { final Queue<ImageConfiguration> imagesWaitingToStart = new ArrayDeque<>(); for (StartOrderResolver.Resolvable resolvable : runService.getImagesConfigsInOrder(queryService, getResolvedImages())) { final ImageConfiguration imageConfig = (ImageConfiguration) resolvable; // Still to check: How to work with linking, volumes, etc .... //String imageName = new ImageName(imageConfig.getName()).getFullNameWithTag(registry); RunImageConfiguration runConfig = imageConfig.getRunConfiguration(); RegistryService.RegistryConfig registryConfig = getRegistryConfig(pullRegistry); ImagePullManager pullManager = getImagePullManager(determinePullPolicy(runConfig), autoPull); hub.getRegistryService().pullImageWithPolicy(imageConfig.getName(), pullManager, registryConfig, queryService.hasImage(imageConfig.getName())); NetworkConfig config = runConfig.getNetworkingConfig(); List<String> bindMounts = extractBindMounts(runConfig.getVolumeConfiguration()); List<VolumeConfiguration> volumes = getVolumes(); if(!bindMounts.isEmpty() && volumes != null) { runService.createVolumesAsPerVolumeBinds(hub, bindMounts, volumes); } if (autoCreateCustomNetworks && config.isCustomNetwork()) { runService.createCustomNetworkIfNotExistant(config.getCustomNetwork()); } imagesWaitingToStart.add(imageConfig); updateAliasesSet(imageAliases, imageConfig.getAlias()); } return imagesWaitingToStart; }
java
private Queue<ImageConfiguration> prepareStart(ServiceHub hub, QueryService queryService, RunService runService, Set<String> imageAliases) throws DockerAccessException, MojoExecutionException { final Queue<ImageConfiguration> imagesWaitingToStart = new ArrayDeque<>(); for (StartOrderResolver.Resolvable resolvable : runService.getImagesConfigsInOrder(queryService, getResolvedImages())) { final ImageConfiguration imageConfig = (ImageConfiguration) resolvable; // Still to check: How to work with linking, volumes, etc .... //String imageName = new ImageName(imageConfig.getName()).getFullNameWithTag(registry); RunImageConfiguration runConfig = imageConfig.getRunConfiguration(); RegistryService.RegistryConfig registryConfig = getRegistryConfig(pullRegistry); ImagePullManager pullManager = getImagePullManager(determinePullPolicy(runConfig), autoPull); hub.getRegistryService().pullImageWithPolicy(imageConfig.getName(), pullManager, registryConfig, queryService.hasImage(imageConfig.getName())); NetworkConfig config = runConfig.getNetworkingConfig(); List<String> bindMounts = extractBindMounts(runConfig.getVolumeConfiguration()); List<VolumeConfiguration> volumes = getVolumes(); if(!bindMounts.isEmpty() && volumes != null) { runService.createVolumesAsPerVolumeBinds(hub, bindMounts, volumes); } if (autoCreateCustomNetworks && config.isCustomNetwork()) { runService.createCustomNetworkIfNotExistant(config.getCustomNetwork()); } imagesWaitingToStart.add(imageConfig); updateAliasesSet(imageAliases, imageConfig.getAlias()); } return imagesWaitingToStart; }
[ "private", "Queue", "<", "ImageConfiguration", ">", "prepareStart", "(", "ServiceHub", "hub", ",", "QueryService", "queryService", ",", "RunService", "runService", ",", "Set", "<", "String", ">", "imageAliases", ")", "throws", "DockerAccessException", ",", "MojoExecutionException", "{", "final", "Queue", "<", "ImageConfiguration", ">", "imagesWaitingToStart", "=", "new", "ArrayDeque", "<>", "(", ")", ";", "for", "(", "StartOrderResolver", ".", "Resolvable", "resolvable", ":", "runService", ".", "getImagesConfigsInOrder", "(", "queryService", ",", "getResolvedImages", "(", ")", ")", ")", "{", "final", "ImageConfiguration", "imageConfig", "=", "(", "ImageConfiguration", ")", "resolvable", ";", "// Still to check: How to work with linking, volumes, etc ....", "//String imageName = new ImageName(imageConfig.getName()).getFullNameWithTag(registry);", "RunImageConfiguration", "runConfig", "=", "imageConfig", ".", "getRunConfiguration", "(", ")", ";", "RegistryService", ".", "RegistryConfig", "registryConfig", "=", "getRegistryConfig", "(", "pullRegistry", ")", ";", "ImagePullManager", "pullManager", "=", "getImagePullManager", "(", "determinePullPolicy", "(", "runConfig", ")", ",", "autoPull", ")", ";", "hub", ".", "getRegistryService", "(", ")", ".", "pullImageWithPolicy", "(", "imageConfig", ".", "getName", "(", ")", ",", "pullManager", ",", "registryConfig", ",", "queryService", ".", "hasImage", "(", "imageConfig", ".", "getName", "(", ")", ")", ")", ";", "NetworkConfig", "config", "=", "runConfig", ".", "getNetworkingConfig", "(", ")", ";", "List", "<", "String", ">", "bindMounts", "=", "extractBindMounts", "(", "runConfig", ".", "getVolumeConfiguration", "(", ")", ")", ";", "List", "<", "VolumeConfiguration", ">", "volumes", "=", "getVolumes", "(", ")", ";", "if", "(", "!", "bindMounts", ".", "isEmpty", "(", ")", "&&", "volumes", "!=", "null", ")", "{", "runService", ".", "createVolumesAsPerVolumeBinds", "(", "hub", ",", "bindMounts", ",", "volumes", ")", ";", "}", "if", "(", "autoCreateCustomNetworks", "&&", "config", ".", "isCustomNetwork", "(", ")", ")", "{", "runService", ".", "createCustomNetworkIfNotExistant", "(", "config", ".", "getCustomNetwork", "(", ")", ")", ";", "}", "imagesWaitingToStart", ".", "add", "(", "imageConfig", ")", ";", "updateAliasesSet", "(", "imageAliases", ",", "imageConfig", ".", "getAlias", "(", ")", ")", ";", "}", "return", "imagesWaitingToStart", ";", "}" ]
to start in the correct order
[ "to", "start", "in", "the", "correct", "order" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/StartMojo.java#L329-L358
28,216
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java
DockerFileUtil.extractLines
public static List<String[]> extractLines(File dockerFile, String keyword, FixedStringSearchInterpolator interpolator) throws IOException { List<String[]> ret = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(dockerFile))) { String line; while ((line = reader.readLine()) != null) { String lineInterpolated = interpolator.interpolate(line); String[] lineParts = lineInterpolated.split("\\s+"); if (lineParts.length > 0 && lineParts[0].equalsIgnoreCase(keyword)) { ret.add(lineParts); } } } return ret; }
java
public static List<String[]> extractLines(File dockerFile, String keyword, FixedStringSearchInterpolator interpolator) throws IOException { List<String[]> ret = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(dockerFile))) { String line; while ((line = reader.readLine()) != null) { String lineInterpolated = interpolator.interpolate(line); String[] lineParts = lineInterpolated.split("\\s+"); if (lineParts.length > 0 && lineParts[0].equalsIgnoreCase(keyword)) { ret.add(lineParts); } } } return ret; }
[ "public", "static", "List", "<", "String", "[", "]", ">", "extractLines", "(", "File", "dockerFile", ",", "String", "keyword", ",", "FixedStringSearchInterpolator", "interpolator", ")", "throws", "IOException", "{", "List", "<", "String", "[", "]", ">", "ret", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "(", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "FileReader", "(", "dockerFile", ")", ")", ")", "{", "String", "line", ";", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "String", "lineInterpolated", "=", "interpolator", ".", "interpolate", "(", "line", ")", ";", "String", "[", "]", "lineParts", "=", "lineInterpolated", ".", "split", "(", "\"\\\\s+\"", ")", ";", "if", "(", "lineParts", ".", "length", ">", "0", "&&", "lineParts", "[", "0", "]", ".", "equalsIgnoreCase", "(", "keyword", ")", ")", "{", "ret", ".", "add", "(", "lineParts", ")", ";", "}", "}", "}", "return", "ret", ";", "}" ]
Extract all lines containing the given keyword @param dockerFile dockerfile to examine @param keyword keyword to extract the lines for @param interpolator interpolator for replacing properties @return list of matched lines or an empty list
[ "Extract", "all", "lines", "containing", "the", "given", "keyword" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java#L72-L85
28,217
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java
DockerFileUtil.interpolate
public static String interpolate(File dockerFile, FixedStringSearchInterpolator interpolator) throws IOException { StringBuilder ret = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(dockerFile))) { String line; while ((line = reader.readLine()) != null) { ret.append(interpolator.interpolate(line)).append(System.lineSeparator()); } } return ret.toString(); }
java
public static String interpolate(File dockerFile, FixedStringSearchInterpolator interpolator) throws IOException { StringBuilder ret = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(dockerFile))) { String line; while ((line = reader.readLine()) != null) { ret.append(interpolator.interpolate(line)).append(System.lineSeparator()); } } return ret.toString(); }
[ "public", "static", "String", "interpolate", "(", "File", "dockerFile", ",", "FixedStringSearchInterpolator", "interpolator", ")", "throws", "IOException", "{", "StringBuilder", "ret", "=", "new", "StringBuilder", "(", ")", ";", "try", "(", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "FileReader", "(", "dockerFile", ")", ")", ")", "{", "String", "line", ";", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "ret", ".", "append", "(", "interpolator", ".", "interpolate", "(", "line", ")", ")", ".", "append", "(", "System", ".", "lineSeparator", "(", ")", ")", ";", "}", "}", "return", "ret", ".", "toString", "(", ")", ";", "}" ]
Interpolate a docker file with the given properties and filter @param dockerFile docker file to interpolate @param interpolator interpolator for replacing properties @return The interpolated contents of the file. @throws IOException
[ "Interpolate", "a", "docker", "file", "with", "the", "given", "properties", "and", "filter" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java#L95-L104
28,218
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java
DockerFileUtil.createInterpolator
public static FixedStringSearchInterpolator createInterpolator(MojoParameters params, String filter) { String[] delimiters = extractDelimiters(filter); if (delimiters == null) { // Don't interpolate anything return FixedStringSearchInterpolator.create(); } DockerAssemblyConfigurationSource configSource = new DockerAssemblyConfigurationSource(params, null, null); // Patterned after org.apache.maven.plugins.assembly.interpolation.AssemblyExpressionEvaluator return AssemblyInterpolator .fullInterpolator(params.getProject(), DefaultAssemblyReader.createProjectInterpolator(params.getProject()) .withExpressionMarkers(delimiters[0], delimiters[1]), configSource) .withExpressionMarkers(delimiters[0], delimiters[1]); }
java
public static FixedStringSearchInterpolator createInterpolator(MojoParameters params, String filter) { String[] delimiters = extractDelimiters(filter); if (delimiters == null) { // Don't interpolate anything return FixedStringSearchInterpolator.create(); } DockerAssemblyConfigurationSource configSource = new DockerAssemblyConfigurationSource(params, null, null); // Patterned after org.apache.maven.plugins.assembly.interpolation.AssemblyExpressionEvaluator return AssemblyInterpolator .fullInterpolator(params.getProject(), DefaultAssemblyReader.createProjectInterpolator(params.getProject()) .withExpressionMarkers(delimiters[0], delimiters[1]), configSource) .withExpressionMarkers(delimiters[0], delimiters[1]); }
[ "public", "static", "FixedStringSearchInterpolator", "createInterpolator", "(", "MojoParameters", "params", ",", "String", "filter", ")", "{", "String", "[", "]", "delimiters", "=", "extractDelimiters", "(", "filter", ")", ";", "if", "(", "delimiters", "==", "null", ")", "{", "// Don't interpolate anything", "return", "FixedStringSearchInterpolator", ".", "create", "(", ")", ";", "}", "DockerAssemblyConfigurationSource", "configSource", "=", "new", "DockerAssemblyConfigurationSource", "(", "params", ",", "null", ",", "null", ")", ";", "// Patterned after org.apache.maven.plugins.assembly.interpolation.AssemblyExpressionEvaluator", "return", "AssemblyInterpolator", ".", "fullInterpolator", "(", "params", ".", "getProject", "(", ")", ",", "DefaultAssemblyReader", ".", "createProjectInterpolator", "(", "params", ".", "getProject", "(", ")", ")", ".", "withExpressionMarkers", "(", "delimiters", "[", "0", "]", ",", "delimiters", "[", "1", "]", ")", ",", "configSource", ")", ".", "withExpressionMarkers", "(", "delimiters", "[", "0", "]", ",", "delimiters", "[", "1", "]", ")", ";", "}" ]
Create an interpolator for the given maven parameters and filter configuration. @param params The maven parameters. @param filter The filter configuration. @return An interpolator for replacing maven properties.
[ "Create", "an", "interpolator", "for", "the", "given", "maven", "parameters", "and", "filter", "configuration", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java#L113-L127
28,219
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogicMap.java
FieldScopeLogicMap.with
public FieldScopeLogicMap<V> with(FieldScopeLogic fieldScopeLogic, V value) { ImmutableList.Builder<Entry<V>> newEntries = ImmutableList.builder(); // Earlier entries override later ones, so we insert the new one at the front of the list. newEntries.add(Entry.of(fieldScopeLogic, value)); newEntries.addAll(entries); return new FieldScopeLogicMap<>(newEntries.build()); }
java
public FieldScopeLogicMap<V> with(FieldScopeLogic fieldScopeLogic, V value) { ImmutableList.Builder<Entry<V>> newEntries = ImmutableList.builder(); // Earlier entries override later ones, so we insert the new one at the front of the list. newEntries.add(Entry.of(fieldScopeLogic, value)); newEntries.addAll(entries); return new FieldScopeLogicMap<>(newEntries.build()); }
[ "public", "FieldScopeLogicMap", "<", "V", ">", "with", "(", "FieldScopeLogic", "fieldScopeLogic", ",", "V", "value", ")", "{", "ImmutableList", ".", "Builder", "<", "Entry", "<", "V", ">>", "newEntries", "=", "ImmutableList", ".", "builder", "(", ")", ";", "// Earlier entries override later ones, so we insert the new one at the front of the list.", "newEntries", ".", "add", "(", "Entry", ".", "of", "(", "fieldScopeLogic", ",", "value", ")", ")", ";", "newEntries", ".", "addAll", "(", "entries", ")", ";", "return", "new", "FieldScopeLogicMap", "<>", "(", "newEntries", ".", "build", "(", ")", ")", ";", "}" ]
Returns a new immutable map that adds the given fields -> value mapping.
[ "Returns", "a", "new", "immutable", "map", "that", "adds", "the", "given", "fields", "-", ">", "value", "mapping", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogicMap.java#L76-L82
28,220
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogicMap.java
FieldScopeLogicMap.defaultValue
public static <V> FieldScopeLogicMap<V> defaultValue(V value) { return new FieldScopeLogicMap<>(ImmutableList.of(Entry.of(FieldScopeLogic.all(), value))); }
java
public static <V> FieldScopeLogicMap<V> defaultValue(V value) { return new FieldScopeLogicMap<>(ImmutableList.of(Entry.of(FieldScopeLogic.all(), value))); }
[ "public", "static", "<", "V", ">", "FieldScopeLogicMap", "<", "V", ">", "defaultValue", "(", "V", "value", ")", "{", "return", "new", "FieldScopeLogicMap", "<>", "(", "ImmutableList", ".", "of", "(", "Entry", ".", "of", "(", "FieldScopeLogic", ".", "all", "(", ")", ",", "value", ")", ")", ")", ";", "}" ]
Returns a map which maps all fields to the given value by default.
[ "Returns", "a", "map", "which", "maps", "all", "fields", "to", "the", "given", "value", "by", "default", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogicMap.java#L112-L114
28,221
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeUtil.java
FieldScopeUtil.fieldNumbersFunction
static Function<Optional<Descriptor>, String> fieldNumbersFunction( final String fmt, final Iterable<Integer> fieldNumbers) { return new Function<Optional<Descriptor>, String>() { @Override public String apply(Optional<Descriptor> optDescriptor) { return resolveFieldNumbers(optDescriptor, fmt, fieldNumbers); } }; }
java
static Function<Optional<Descriptor>, String> fieldNumbersFunction( final String fmt, final Iterable<Integer> fieldNumbers) { return new Function<Optional<Descriptor>, String>() { @Override public String apply(Optional<Descriptor> optDescriptor) { return resolveFieldNumbers(optDescriptor, fmt, fieldNumbers); } }; }
[ "static", "Function", "<", "Optional", "<", "Descriptor", ">", ",", "String", ">", "fieldNumbersFunction", "(", "final", "String", "fmt", ",", "final", "Iterable", "<", "Integer", ">", "fieldNumbers", ")", "{", "return", "new", "Function", "<", "Optional", "<", "Descriptor", ">", ",", "String", ">", "(", ")", "{", "@", "Override", "public", "String", "apply", "(", "Optional", "<", "Descriptor", ">", "optDescriptor", ")", "{", "return", "resolveFieldNumbers", "(", "optDescriptor", ",", "fmt", ",", "fieldNumbers", ")", ";", "}", "}", ";", "}" ]
Returns a function which translates integer field numbers into field names using the Descriptor if available. @param fmt Format string that must contain exactly one '%s' and no other format parameters.
[ "Returns", "a", "function", "which", "translates", "integer", "field", "numbers", "into", "field", "names", "using", "the", "Descriptor", "if", "available", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeUtil.java#L36-L44
28,222
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeUtil.java
FieldScopeUtil.fieldScopeFunction
static Function<Optional<Descriptor>, String> fieldScopeFunction( final String fmt, final FieldScope fieldScope) { return new Function<Optional<Descriptor>, String>() { @Override public String apply(Optional<Descriptor> optDescriptor) { return String.format(fmt, fieldScope.usingCorrespondenceString(optDescriptor)); } }; }
java
static Function<Optional<Descriptor>, String> fieldScopeFunction( final String fmt, final FieldScope fieldScope) { return new Function<Optional<Descriptor>, String>() { @Override public String apply(Optional<Descriptor> optDescriptor) { return String.format(fmt, fieldScope.usingCorrespondenceString(optDescriptor)); } }; }
[ "static", "Function", "<", "Optional", "<", "Descriptor", ">", ",", "String", ">", "fieldScopeFunction", "(", "final", "String", "fmt", ",", "final", "FieldScope", "fieldScope", ")", "{", "return", "new", "Function", "<", "Optional", "<", "Descriptor", ">", ",", "String", ">", "(", ")", "{", "@", "Override", "public", "String", "apply", "(", "Optional", "<", "Descriptor", ">", "optDescriptor", ")", "{", "return", "String", ".", "format", "(", "fmt", ",", "fieldScope", ".", "usingCorrespondenceString", "(", "optDescriptor", ")", ")", ";", "}", "}", ";", "}" ]
Returns a function which formats the given string by getting the usingCorrespondenceString from the given FieldScope with the argument descriptor. @param fmt Format string that must contain exactly one '%s' and no other format parameters.
[ "Returns", "a", "function", "which", "formats", "the", "given", "string", "by", "getting", "the", "usingCorrespondenceString", "from", "the", "given", "FieldScope", "with", "the", "argument", "descriptor", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeUtil.java#L52-L60
28,223
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeUtil.java
FieldScopeUtil.concat
static Function<Optional<Descriptor>, String> concat( final Function<? super Optional<Descriptor>, String> function1, final Function<? super Optional<Descriptor>, String> function2) { return new Function<Optional<Descriptor>, String>() { @Override public String apply(Optional<Descriptor> optDescriptor) { return function1.apply(optDescriptor) + function2.apply(optDescriptor); } }; }
java
static Function<Optional<Descriptor>, String> concat( final Function<? super Optional<Descriptor>, String> function1, final Function<? super Optional<Descriptor>, String> function2) { return new Function<Optional<Descriptor>, String>() { @Override public String apply(Optional<Descriptor> optDescriptor) { return function1.apply(optDescriptor) + function2.apply(optDescriptor); } }; }
[ "static", "Function", "<", "Optional", "<", "Descriptor", ">", ",", "String", ">", "concat", "(", "final", "Function", "<", "?", "super", "Optional", "<", "Descriptor", ">", ",", "String", ">", "function1", ",", "final", "Function", "<", "?", "super", "Optional", "<", "Descriptor", ">", ",", "String", ">", "function2", ")", "{", "return", "new", "Function", "<", "Optional", "<", "Descriptor", ">", ",", "String", ">", "(", ")", "{", "@", "Override", "public", "String", "apply", "(", "Optional", "<", "Descriptor", ">", "optDescriptor", ")", "{", "return", "function1", ".", "apply", "(", "optDescriptor", ")", "+", "function2", ".", "apply", "(", "optDescriptor", ")", ";", "}", "}", ";", "}" ]
Returns a function which concatenates the outputs of the two input functions.
[ "Returns", "a", "function", "which", "concatenates", "the", "outputs", "of", "the", "two", "input", "functions", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeUtil.java#L63-L72
28,224
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeUtil.java
FieldScopeUtil.getSingleDescriptor
static Optional<Descriptor> getSingleDescriptor(Iterable<? extends Message> messages) { Optional<Descriptor> optDescriptor = Optional.absent(); for (Message message : messages) { if (message != null) { Descriptor descriptor = message.getDescriptorForType(); if (!optDescriptor.isPresent()) { optDescriptor = Optional.of(descriptor); } else if (descriptor != optDescriptor.get()) { // Two different descriptors - abandon ship. return Optional.absent(); } } } return optDescriptor; }
java
static Optional<Descriptor> getSingleDescriptor(Iterable<? extends Message> messages) { Optional<Descriptor> optDescriptor = Optional.absent(); for (Message message : messages) { if (message != null) { Descriptor descriptor = message.getDescriptorForType(); if (!optDescriptor.isPresent()) { optDescriptor = Optional.of(descriptor); } else if (descriptor != optDescriptor.get()) { // Two different descriptors - abandon ship. return Optional.absent(); } } } return optDescriptor; }
[ "static", "Optional", "<", "Descriptor", ">", "getSingleDescriptor", "(", "Iterable", "<", "?", "extends", "Message", ">", "messages", ")", "{", "Optional", "<", "Descriptor", ">", "optDescriptor", "=", "Optional", ".", "absent", "(", ")", ";", "for", "(", "Message", "message", ":", "messages", ")", "{", "if", "(", "message", "!=", "null", ")", "{", "Descriptor", "descriptor", "=", "message", ".", "getDescriptorForType", "(", ")", ";", "if", "(", "!", "optDescriptor", ".", "isPresent", "(", ")", ")", "{", "optDescriptor", "=", "Optional", ".", "of", "(", "descriptor", ")", ";", "}", "else", "if", "(", "descriptor", "!=", "optDescriptor", ".", "get", "(", ")", ")", "{", "// Two different descriptors - abandon ship.", "return", "Optional", ".", "absent", "(", ")", ";", "}", "}", "}", "return", "optDescriptor", ";", "}" ]
Returns the singular descriptor used by all non-null messages in the list. <p>If there is no descriptor, or more than one, returns {@code Optional.absent()}.
[ "Returns", "the", "singular", "descriptor", "used", "by", "all", "non", "-", "null", "messages", "in", "the", "list", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeUtil.java#L79-L93
28,225
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
MultimapSubject.containsExactly
@CanIgnoreReturnValue public Ordered containsExactly() { return check().about(iterableEntries()).that(actual().entries()).containsExactly(); }
java
@CanIgnoreReturnValue public Ordered containsExactly() { return check().about(iterableEntries()).that(actual().entries()).containsExactly(); }
[ "@", "CanIgnoreReturnValue", "public", "Ordered", "containsExactly", "(", ")", "{", "return", "check", "(", ")", ".", "about", "(", "iterableEntries", "(", ")", ")", ".", "that", "(", "actual", "(", ")", ".", "entries", "(", ")", ")", ".", "containsExactly", "(", ")", ";", "}" ]
Fails if the multimap is not empty.
[ "Fails", "if", "the", "multimap", "is", "not", "empty", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/MultimapSubject.java#L285-L288
28,226
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
MultimapSubject.advanceToFind
private static boolean advanceToFind(Iterator<?> iterator, Object value) { while (iterator.hasNext()) { if (Objects.equal(iterator.next(), value)) { return true; } } return false; }
java
private static boolean advanceToFind(Iterator<?> iterator, Object value) { while (iterator.hasNext()) { if (Objects.equal(iterator.next(), value)) { return true; } } return false; }
[ "private", "static", "boolean", "advanceToFind", "(", "Iterator", "<", "?", ">", "iterator", ",", "Object", "value", ")", "{", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "if", "(", "Objects", ".", "equal", "(", "iterator", ".", "next", "(", ")", ",", "value", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Advances the iterator until it either returns value, or has no more elements. <p>Returns true if the value was found, false if the end was reached before finding it. <p>This is basically the same as {@link Iterables#contains}, but where the contract explicitly states that the iterator isn't advanced beyond the value if the value is found.
[ "Advances", "the", "iterator", "until", "it", "either", "returns", "value", "or", "has", "no", "more", "elements", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/MultimapSubject.java#L425-L432
28,227
google/truth
core/src/main/java/com/google/common/truth/TruthFailureSubject.java
TruthFailureSubject.factKeys
public IterableSubject factKeys() { if (!(actual() instanceof ErrorWithFacts)) { failWithActual(simpleFact("expected a failure thrown by Truth's new failure API")); return ignoreCheck().that(ImmutableList.of()); } ErrorWithFacts error = (ErrorWithFacts) actual(); return check("factKeys()").that(getFactKeys(error)); }
java
public IterableSubject factKeys() { if (!(actual() instanceof ErrorWithFacts)) { failWithActual(simpleFact("expected a failure thrown by Truth's new failure API")); return ignoreCheck().that(ImmutableList.of()); } ErrorWithFacts error = (ErrorWithFacts) actual(); return check("factKeys()").that(getFactKeys(error)); }
[ "public", "IterableSubject", "factKeys", "(", ")", "{", "if", "(", "!", "(", "actual", "(", ")", "instanceof", "ErrorWithFacts", ")", ")", "{", "failWithActual", "(", "simpleFact", "(", "\"expected a failure thrown by Truth's new failure API\"", ")", ")", ";", "return", "ignoreCheck", "(", ")", ".", "that", "(", "ImmutableList", ".", "of", "(", ")", ")", ";", "}", "ErrorWithFacts", "error", "=", "(", "ErrorWithFacts", ")", "actual", "(", ")", ";", "return", "check", "(", "\"factKeys()\"", ")", ".", "that", "(", "getFactKeys", "(", "error", ")", ")", ";", "}" ]
Returns a subject for the list of fact keys.
[ "Returns", "a", "subject", "for", "the", "list", "of", "fact", "keys", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/TruthFailureSubject.java#L77-L84
28,228
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MapWithProtoValuesSubject.java
MapWithProtoValuesSubject.usingFloatToleranceForFieldDescriptorsForValues
public MapWithProtoValuesFluentAssertion<M> usingFloatToleranceForFieldDescriptorsForValues( float tolerance, FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return usingConfig( config.usingFloatToleranceForFieldDescriptors( tolerance, asList(firstFieldDescriptor, rest))); }
java
public MapWithProtoValuesFluentAssertion<M> usingFloatToleranceForFieldDescriptorsForValues( float tolerance, FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return usingConfig( config.usingFloatToleranceForFieldDescriptors( tolerance, asList(firstFieldDescriptor, rest))); }
[ "public", "MapWithProtoValuesFluentAssertion", "<", "M", ">", "usingFloatToleranceForFieldDescriptorsForValues", "(", "float", "tolerance", ",", "FieldDescriptor", "firstFieldDescriptor", ",", "FieldDescriptor", "...", "rest", ")", "{", "return", "usingConfig", "(", "config", ".", "usingFloatToleranceForFieldDescriptors", "(", "tolerance", ",", "asList", "(", "firstFieldDescriptor", ",", "rest", ")", ")", ")", ";", "}" ]
Compares float fields with these explicitly specified fields using the provided absolute tolerance. @param tolerance A finite, non-negative tolerance.
[ "Compares", "float", "fields", "with", "these", "explicitly", "specified", "fields", "using", "the", "provided", "absolute", "tolerance", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MapWithProtoValuesSubject.java#L596-L601
28,229
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogic.java
FieldScopeLogic.ignoringFields
FieldScopeLogic ignoringFields(Iterable<Integer> fieldNumbers) { if (isEmpty(fieldNumbers)) { return this; } return and( this, new NegationFieldScopeLogic(new FieldNumbersLogic(fieldNumbers, /* isRecursive = */ true))); }
java
FieldScopeLogic ignoringFields(Iterable<Integer> fieldNumbers) { if (isEmpty(fieldNumbers)) { return this; } return and( this, new NegationFieldScopeLogic(new FieldNumbersLogic(fieldNumbers, /* isRecursive = */ true))); }
[ "FieldScopeLogic", "ignoringFields", "(", "Iterable", "<", "Integer", ">", "fieldNumbers", ")", "{", "if", "(", "isEmpty", "(", "fieldNumbers", ")", ")", "{", "return", "this", ";", "}", "return", "and", "(", "this", ",", "new", "NegationFieldScopeLogic", "(", "new", "FieldNumbersLogic", "(", "fieldNumbers", ",", "/* isRecursive = */", "true", ")", ")", ")", ";", "}" ]
something else that doesn't tightly couple FieldScopeLogic to the 'ignore' concept.
[ "something", "else", "that", "doesn", "t", "tightly", "couple", "FieldScopeLogic", "to", "the", "ignore", "concept", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogic.java#L116-L123
28,230
google/truth
extensions/java8/src/main/java/com/google/common/truth/IntStreamSubject.java
IntStreamSubject.containsAnyOf
@SuppressWarnings("GoodTime") // false positive; b/122617528 public void containsAnyOf(int first, int second, int... rest) { check().that(actualList).containsAnyOf(first, second, box(rest)); }
java
@SuppressWarnings("GoodTime") // false positive; b/122617528 public void containsAnyOf(int first, int second, int... rest) { check().that(actualList).containsAnyOf(first, second, box(rest)); }
[ "@", "SuppressWarnings", "(", "\"GoodTime\"", ")", "// false positive; b/122617528", "public", "void", "containsAnyOf", "(", "int", "first", ",", "int", "second", ",", "int", "...", "rest", ")", "{", "check", "(", ")", ".", "that", "(", "actualList", ")", ".", "containsAnyOf", "(", "first", ",", "second", ",", "box", "(", "rest", ")", ")", ";", "}" ]
Fails if the subject does not contain at least one of the given elements.
[ "Fails", "if", "the", "subject", "does", "not", "contain", "at", "least", "one", "of", "the", "given", "elements", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/java8/src/main/java/com/google/common/truth/IntStreamSubject.java#L98-L101
28,231
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
StringSubject.hasLength
public void hasLength(int expectedLength) { checkArgument(expectedLength >= 0, "expectedLength(%s) must be >= 0", expectedLength); check("length()").that(actual().length()).isEqualTo(expectedLength); }
java
public void hasLength(int expectedLength) { checkArgument(expectedLength >= 0, "expectedLength(%s) must be >= 0", expectedLength); check("length()").that(actual().length()).isEqualTo(expectedLength); }
[ "public", "void", "hasLength", "(", "int", "expectedLength", ")", "{", "checkArgument", "(", "expectedLength", ">=", "0", ",", "\"expectedLength(%s) must be >= 0\"", ",", "expectedLength", ")", ";", "check", "(", "\"length()\"", ")", ".", "that", "(", "actual", "(", ")", ".", "length", "(", ")", ")", ".", "isEqualTo", "(", "expectedLength", ")", ";", "}" ]
Fails if the string does not have the given length.
[ "Fails", "if", "the", "string", "does", "not", "have", "the", "given", "length", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/StringSubject.java#L53-L56
28,232
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
StringSubject.contains
public void contains(CharSequence string) { checkNotNull(string); if (actual() == null) { failWithActual("expected a string that contains", string); } else if (!actual().contains(string)) { failWithActual("expected to contain", string); } }
java
public void contains(CharSequence string) { checkNotNull(string); if (actual() == null) { failWithActual("expected a string that contains", string); } else if (!actual().contains(string)) { failWithActual("expected to contain", string); } }
[ "public", "void", "contains", "(", "CharSequence", "string", ")", "{", "checkNotNull", "(", "string", ")", ";", "if", "(", "actual", "(", ")", "==", "null", ")", "{", "failWithActual", "(", "\"expected a string that contains\"", ",", "string", ")", ";", "}", "else", "if", "(", "!", "actual", "(", ")", ".", "contains", "(", "string", ")", ")", "{", "failWithActual", "(", "\"expected to contain\"", ",", "string", ")", ";", "}", "}" ]
Fails if the string does not contain the given sequence.
[ "Fails", "if", "the", "string", "does", "not", "contain", "the", "given", "sequence", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/StringSubject.java#L77-L84
28,233
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
StringSubject.startsWith
public void startsWith(String string) { checkNotNull(string); if (actual() == null) { failWithActual("expected a string that starts with", string); } else if (!actual().startsWith(string)) { failWithActual("expected to start with", string); } }
java
public void startsWith(String string) { checkNotNull(string); if (actual() == null) { failWithActual("expected a string that starts with", string); } else if (!actual().startsWith(string)) { failWithActual("expected to start with", string); } }
[ "public", "void", "startsWith", "(", "String", "string", ")", "{", "checkNotNull", "(", "string", ")", ";", "if", "(", "actual", "(", ")", "==", "null", ")", "{", "failWithActual", "(", "\"expected a string that starts with\"", ",", "string", ")", ";", "}", "else", "if", "(", "!", "actual", "(", ")", ".", "startsWith", "(", "string", ")", ")", "{", "failWithActual", "(", "\"expected to start with\"", ",", "string", ")", ";", "}", "}" ]
Fails if the string does not start with the given string.
[ "Fails", "if", "the", "string", "does", "not", "start", "with", "the", "given", "string", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/StringSubject.java#L97-L104
28,234
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
StringSubject.endsWith
public void endsWith(String string) { checkNotNull(string); if (actual() == null) { failWithActual("expected a string that ends with", string); } else if (!actual().endsWith(string)) { failWithActual("expected to end with", string); } }
java
public void endsWith(String string) { checkNotNull(string); if (actual() == null) { failWithActual("expected a string that ends with", string); } else if (!actual().endsWith(string)) { failWithActual("expected to end with", string); } }
[ "public", "void", "endsWith", "(", "String", "string", ")", "{", "checkNotNull", "(", "string", ")", ";", "if", "(", "actual", "(", ")", "==", "null", ")", "{", "failWithActual", "(", "\"expected a string that ends with\"", ",", "string", ")", ";", "}", "else", "if", "(", "!", "actual", "(", ")", ".", "endsWith", "(", "string", ")", ")", "{", "failWithActual", "(", "\"expected to end with\"", ",", "string", ")", ";", "}", "}" ]
Fails if the string does not end with the given string.
[ "Fails", "if", "the", "string", "does", "not", "end", "with", "the", "given", "string", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/StringSubject.java#L107-L114
28,235
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
StringSubject.matches
@GwtIncompatible("java.util.regex.Pattern") public void matches(Pattern regex) { if (!regex.matcher(actual()).matches()) { failWithActual("expected to match", regex); } }
java
@GwtIncompatible("java.util.regex.Pattern") public void matches(Pattern regex) { if (!regex.matcher(actual()).matches()) { failWithActual("expected to match", regex); } }
[ "@", "GwtIncompatible", "(", "\"java.util.regex.Pattern\"", ")", "public", "void", "matches", "(", "Pattern", "regex", ")", "{", "if", "(", "!", "regex", ".", "matcher", "(", "actual", "(", ")", ")", ".", "matches", "(", ")", ")", "{", "failWithActual", "(", "\"expected to match\"", ",", "regex", ")", ";", "}", "}" ]
Fails if the string does not match the given regex.
[ "Fails", "if", "the", "string", "does", "not", "match", "the", "given", "regex", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/StringSubject.java#L126-L131
28,236
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
StringSubject.containsMatch
@GwtIncompatible("java.util.regex.Pattern") public void containsMatch(Pattern regex) { if (!regex.matcher(actual()).find()) { failWithActual("expected to contain a match for", regex); } }
java
@GwtIncompatible("java.util.regex.Pattern") public void containsMatch(Pattern regex) { if (!regex.matcher(actual()).find()) { failWithActual("expected to contain a match for", regex); } }
[ "@", "GwtIncompatible", "(", "\"java.util.regex.Pattern\"", ")", "public", "void", "containsMatch", "(", "Pattern", "regex", ")", "{", "if", "(", "!", "regex", ".", "matcher", "(", "actual", "(", ")", ")", ".", "find", "(", ")", ")", "{", "failWithActual", "(", "\"expected to contain a match for\"", ",", "regex", ")", ";", "}", "}" ]
Fails if the string does not contain a match on the given regex.
[ "Fails", "if", "the", "string", "does", "not", "contain", "a", "match", "on", "the", "given", "regex", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/StringSubject.java#L149-L154
28,237
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
StringSubject.doesNotContainMatch
@GwtIncompatible("java.util.regex.Pattern") public void doesNotContainMatch(Pattern regex) { Matcher matcher = regex.matcher(actual()); if (matcher.find()) { failWithoutActual( fact("expected not to contain a match for", regex), fact("but contained", matcher.group()), fact("full string", actualCustomStringRepresentationForPackageMembersToCall())); } }
java
@GwtIncompatible("java.util.regex.Pattern") public void doesNotContainMatch(Pattern regex) { Matcher matcher = regex.matcher(actual()); if (matcher.find()) { failWithoutActual( fact("expected not to contain a match for", regex), fact("but contained", matcher.group()), fact("full string", actualCustomStringRepresentationForPackageMembersToCall())); } }
[ "@", "GwtIncompatible", "(", "\"java.util.regex.Pattern\"", ")", "public", "void", "doesNotContainMatch", "(", "Pattern", "regex", ")", "{", "Matcher", "matcher", "=", "regex", ".", "matcher", "(", "actual", "(", ")", ")", ";", "if", "(", "matcher", ".", "find", "(", ")", ")", "{", "failWithoutActual", "(", "fact", "(", "\"expected not to contain a match for\"", ",", "regex", ")", ",", "fact", "(", "\"but contained\"", ",", "matcher", ".", "group", "(", ")", ")", ",", "fact", "(", "\"full string\"", ",", "actualCustomStringRepresentationForPackageMembersToCall", "(", ")", ")", ")", ";", "}", "}" ]
Fails if the string contains a match on the given regex.
[ "Fails", "if", "the", "string", "contains", "a", "match", "on", "the", "given", "regex", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/StringSubject.java#L164-L173
28,238
google/truth
core/src/main/java/com/google/common/truth/Platform.java
Platform.containsMatch
static boolean containsMatch(String actual, String regex) { return Pattern.compile(regex).matcher(actual).find(); }
java
static boolean containsMatch(String actual, String regex) { return Pattern.compile(regex).matcher(actual).find(); }
[ "static", "boolean", "containsMatch", "(", "String", "actual", ",", "String", "regex", ")", "{", "return", "Pattern", ".", "compile", "(", "regex", ")", ".", "matcher", "(", "actual", ")", ".", "find", "(", ")", ";", "}" ]
Determines if the given subject contains a match for the given regex.
[ "Determines", "if", "the", "given", "subject", "contains", "a", "match", "for", "the", "given", "regex", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/Platform.java#L50-L52
28,239
google/truth
core/src/main/java/com/google/common/truth/Correspondence.java
Correspondence.formattingDiffsUsing
public Correspondence<A, E> formattingDiffsUsing(DiffFormatter<? super A, ? super E> formatter) { return new FormattingDiffs<>(this, formatter); }
java
public Correspondence<A, E> formattingDiffsUsing(DiffFormatter<? super A, ? super E> formatter) { return new FormattingDiffs<>(this, formatter); }
[ "public", "Correspondence", "<", "A", ",", "E", ">", "formattingDiffsUsing", "(", "DiffFormatter", "<", "?", "super", "A", ",", "?", "super", "E", ">", "formatter", ")", "{", "return", "new", "FormattingDiffs", "<>", "(", "this", ",", "formatter", ")", ";", "}" ]
Returns a new correspondence which is like this one, except that the given formatter may be used to format the difference between a pair of elements that do not correspond. <p>Note that, if you the data you are asserting about contains null actual or expected values, the formatter may be invoked with a null argument. If this causes it to throw a {@link NullPointerException}, that will be taken to indicate that the values cannot be diffed. (See {@link Correspondence#formatDiff} for more detail on how exceptions are handled.) If you think null values are likely, it is slightly cleaner to have the formatter return null in that case instead of throwing. <p>Example: <pre>{@code class MyRecordTestHelper { static final Correspondence<MyRecord, MyRecord> EQUIVALENCE = Correspondence.from(MyRecordTestHelper::recordsEquivalent, "is equivalent to") .formattingDiffsUsing(MyRecordTestHelper::formatRecordDiff); static boolean recordsEquivalent(@Nullable MyRecord actual, @Nullable MyRecord expected) { // code to check whether records should be considered equivalent for testing purposes } static String formatRecordDiff(@Nullable MyRecord actual, @Nullable MyRecord expected) { // code to format the diff between the records } } }</pre>
[ "Returns", "a", "new", "correspondence", "which", "is", "like", "this", "one", "except", "that", "the", "given", "formatter", "may", "be", "used", "to", "format", "the", "difference", "between", "a", "pair", "of", "elements", "that", "do", "not", "correspond", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/Correspondence.java#L350-L352
28,240
google/truth
core/src/main/java/com/google/common/truth/ComparisonFailureWithFacts.java
ComparisonFailureWithFacts.formatExpectedAndActual
@VisibleForTesting static ImmutableList<Fact> formatExpectedAndActual(String expected, String actual) { ImmutableList<Fact> result; // TODO(cpovirk): Call attention to differences in trailing whitespace. // TODO(cpovirk): And changes in the *kind* of whitespace characters in the middle of the line. result = Platform.makeDiff(expected, actual); if (result != null) { return result; } result = removeCommonPrefixAndSuffix(expected, actual); if (result != null) { return result; } return ImmutableList.of(fact("expected", expected), fact("but was", actual)); }
java
@VisibleForTesting static ImmutableList<Fact> formatExpectedAndActual(String expected, String actual) { ImmutableList<Fact> result; // TODO(cpovirk): Call attention to differences in trailing whitespace. // TODO(cpovirk): And changes in the *kind* of whitespace characters in the middle of the line. result = Platform.makeDiff(expected, actual); if (result != null) { return result; } result = removeCommonPrefixAndSuffix(expected, actual); if (result != null) { return result; } return ImmutableList.of(fact("expected", expected), fact("but was", actual)); }
[ "@", "VisibleForTesting", "static", "ImmutableList", "<", "Fact", ">", "formatExpectedAndActual", "(", "String", "expected", ",", "String", "actual", ")", "{", "ImmutableList", "<", "Fact", ">", "result", ";", "// TODO(cpovirk): Call attention to differences in trailing whitespace.", "// TODO(cpovirk): And changes in the *kind* of whitespace characters in the middle of the line.", "result", "=", "Platform", ".", "makeDiff", "(", "expected", ",", "actual", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "result", "=", "removeCommonPrefixAndSuffix", "(", "expected", ",", "actual", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "return", "ImmutableList", ".", "of", "(", "fact", "(", "\"expected\"", ",", "expected", ")", ",", "fact", "(", "\"but was\"", ",", "actual", ")", ")", ";", "}" ]
Returns one or more facts describing the difference between the given expected and actual values. <p>Currently, that means either 2 facts (one each for expected and actual) or 1 fact with a diff-like (but much simpler) view. <p>In the case of 2 facts, the facts contain either the full expected and actual values or, if the values have a long prefix or suffix in common, abbreviated values with "…" at the beginning or end.
[ "Returns", "one", "or", "more", "facts", "describing", "the", "difference", "between", "the", "given", "expected", "and", "actual", "values", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/ComparisonFailureWithFacts.java#L88-L106
28,241
google/truth
core/src/main/java/com/google/common/truth/ComparisonFailureWithFacts.java
ComparisonFailureWithFacts.validSurrogatePairAt
private static boolean validSurrogatePairAt(CharSequence string, int index) { return index >= 0 && index <= (string.length() - 2) && isHighSurrogate(string.charAt(index)) && isLowSurrogate(string.charAt(index + 1)); }
java
private static boolean validSurrogatePairAt(CharSequence string, int index) { return index >= 0 && index <= (string.length() - 2) && isHighSurrogate(string.charAt(index)) && isLowSurrogate(string.charAt(index + 1)); }
[ "private", "static", "boolean", "validSurrogatePairAt", "(", "CharSequence", "string", ",", "int", "index", ")", "{", "return", "index", ">=", "0", "&&", "index", "<=", "(", "string", ".", "length", "(", ")", "-", "2", ")", "&&", "isHighSurrogate", "(", "string", ".", "charAt", "(", "index", ")", ")", "&&", "isLowSurrogate", "(", "string", ".", "charAt", "(", "index", "+", "1", ")", ")", ";", "}" ]
From c.g.c.base.Strings.
[ "From", "c", ".", "g", ".", "c", ".", "base", ".", "Strings", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/ComparisonFailureWithFacts.java#L154-L159
28,242
google/truth
core/src/main/java/com/google/common/truth/super/com/google/common/truth/Platform.java
Platform.isInstanceOfType
static boolean isInstanceOfType(Object instance, Class<?> clazz) { if (clazz.isInterface()) { throw new UnsupportedOperationException( "Under GWT, we can't determine whether an object is an instance of an interface Class"); } for (Class<?> current = instance.getClass(); current != null; current = current.getSuperclass()) { if (current.equals(clazz)) { return true; } } return false; }
java
static boolean isInstanceOfType(Object instance, Class<?> clazz) { if (clazz.isInterface()) { throw new UnsupportedOperationException( "Under GWT, we can't determine whether an object is an instance of an interface Class"); } for (Class<?> current = instance.getClass(); current != null; current = current.getSuperclass()) { if (current.equals(clazz)) { return true; } } return false; }
[ "static", "boolean", "isInstanceOfType", "(", "Object", "instance", ",", "Class", "<", "?", ">", "clazz", ")", "{", "if", "(", "clazz", ".", "isInterface", "(", ")", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Under GWT, we can't determine whether an object is an instance of an interface Class\"", ")", ";", "}", "for", "(", "Class", "<", "?", ">", "current", "=", "instance", ".", "getClass", "(", ")", ";", "current", "!=", "null", ";", "current", "=", "current", ".", "getSuperclass", "(", ")", ")", "{", "if", "(", "current", ".", "equals", "(", "clazz", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if the instance is assignable to the type Clazz.
[ "Returns", "true", "if", "the", "instance", "is", "assignable", "to", "the", "type", "Clazz", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/super/com/google/common/truth/Platform.java#L37-L51
28,243
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/ProtoTruthMessageDifferencer.java
ProtoTruthMessageDifferencer.diffMessages
DiffResult diffMessages(Message actual, Message expected) { checkNotNull(actual); checkNotNull(expected); checkArgument( actual.getDescriptorForType() == expected.getDescriptorForType(), "The actual [%s] and expected [%s] message descriptors do not match.", actual.getDescriptorForType(), expected.getDescriptorForType()); return diffMessages(actual, expected, rootConfig); }
java
DiffResult diffMessages(Message actual, Message expected) { checkNotNull(actual); checkNotNull(expected); checkArgument( actual.getDescriptorForType() == expected.getDescriptorForType(), "The actual [%s] and expected [%s] message descriptors do not match.", actual.getDescriptorForType(), expected.getDescriptorForType()); return diffMessages(actual, expected, rootConfig); }
[ "DiffResult", "diffMessages", "(", "Message", "actual", ",", "Message", "expected", ")", "{", "checkNotNull", "(", "actual", ")", ";", "checkNotNull", "(", "expected", ")", ";", "checkArgument", "(", "actual", ".", "getDescriptorForType", "(", ")", "==", "expected", ".", "getDescriptorForType", "(", ")", ",", "\"The actual [%s] and expected [%s] message descriptors do not match.\"", ",", "actual", ".", "getDescriptorForType", "(", ")", ",", "expected", ".", "getDescriptorForType", "(", ")", ")", ";", "return", "diffMessages", "(", "actual", ",", "expected", ",", "rootConfig", ")", ";", "}" ]
Compare the two non-null messages, and return a detailed comparison report.
[ "Compare", "the", "two", "non", "-", "null", "messages", "and", "return", "a", "detailed", "comparison", "report", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/ProtoTruthMessageDifferencer.java#L79-L89
28,244
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/ProtoTruthMessageDifferencer.java
ProtoTruthMessageDifferencer.findMatchingPairResult
@NullableDecl private RepeatedField.PairResult findMatchingPairResult( Deque<Integer> actualIndices, List<?> actualValues, int expectedIndex, Object expectedValue, boolean excludeNonRecursive, FieldDescriptor fieldDescriptor, FluentEqualityConfig config) { Iterator<Integer> actualIndexIter = actualIndices.iterator(); while (actualIndexIter.hasNext()) { int actualIndex = actualIndexIter.next(); RepeatedField.PairResult pairResult = compareRepeatedFieldElementPair( actualValues.get(actualIndex), expectedValue, excludeNonRecursive, fieldDescriptor, actualIndex, expectedIndex, config); if (pairResult.isMatched()) { actualIndexIter.remove(); return pairResult; } } return null; }
java
@NullableDecl private RepeatedField.PairResult findMatchingPairResult( Deque<Integer> actualIndices, List<?> actualValues, int expectedIndex, Object expectedValue, boolean excludeNonRecursive, FieldDescriptor fieldDescriptor, FluentEqualityConfig config) { Iterator<Integer> actualIndexIter = actualIndices.iterator(); while (actualIndexIter.hasNext()) { int actualIndex = actualIndexIter.next(); RepeatedField.PairResult pairResult = compareRepeatedFieldElementPair( actualValues.get(actualIndex), expectedValue, excludeNonRecursive, fieldDescriptor, actualIndex, expectedIndex, config); if (pairResult.isMatched()) { actualIndexIter.remove(); return pairResult; } } return null; }
[ "@", "NullableDecl", "private", "RepeatedField", ".", "PairResult", "findMatchingPairResult", "(", "Deque", "<", "Integer", ">", "actualIndices", ",", "List", "<", "?", ">", "actualValues", ",", "int", "expectedIndex", ",", "Object", "expectedValue", ",", "boolean", "excludeNonRecursive", ",", "FieldDescriptor", "fieldDescriptor", ",", "FluentEqualityConfig", "config", ")", "{", "Iterator", "<", "Integer", ">", "actualIndexIter", "=", "actualIndices", ".", "iterator", "(", ")", ";", "while", "(", "actualIndexIter", ".", "hasNext", "(", ")", ")", "{", "int", "actualIndex", "=", "actualIndexIter", ".", "next", "(", ")", ";", "RepeatedField", ".", "PairResult", "pairResult", "=", "compareRepeatedFieldElementPair", "(", "actualValues", ".", "get", "(", "actualIndex", ")", ",", "expectedValue", ",", "excludeNonRecursive", ",", "fieldDescriptor", ",", "actualIndex", ",", "expectedIndex", ",", "config", ")", ";", "if", "(", "pairResult", ".", "isMatched", "(", ")", ")", "{", "actualIndexIter", ".", "remove", "(", ")", ";", "return", "pairResult", ";", "}", "}", "return", "null", ";", "}" ]
If there is no match, returns null.
[ "If", "there", "is", "no", "match", "returns", "null", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/ProtoTruthMessageDifferencer.java#L435-L463
28,245
google/truth
core/src/main/java/com/google/common/truth/SubjectUtils.java
SubjectUtils.annotateEmptyStrings
static <T> Iterable<T> annotateEmptyStrings(Iterable<T> items) { if (Iterables.contains(items, "")) { List<T> annotatedItems = Lists.newArrayList(); for (T item : items) { if (Objects.equal(item, "")) { // This is a safe cast because know that at least one instance of T (this item) is a // String. @SuppressWarnings("unchecked") T newItem = (T) HUMAN_UNDERSTANDABLE_EMPTY_STRING; annotatedItems.add(newItem); } else { annotatedItems.add(item); } } return annotatedItems; } else { return items; } }
java
static <T> Iterable<T> annotateEmptyStrings(Iterable<T> items) { if (Iterables.contains(items, "")) { List<T> annotatedItems = Lists.newArrayList(); for (T item : items) { if (Objects.equal(item, "")) { // This is a safe cast because know that at least one instance of T (this item) is a // String. @SuppressWarnings("unchecked") T newItem = (T) HUMAN_UNDERSTANDABLE_EMPTY_STRING; annotatedItems.add(newItem); } else { annotatedItems.add(item); } } return annotatedItems; } else { return items; } }
[ "static", "<", "T", ">", "Iterable", "<", "T", ">", "annotateEmptyStrings", "(", "Iterable", "<", "T", ">", "items", ")", "{", "if", "(", "Iterables", ".", "contains", "(", "items", ",", "\"\"", ")", ")", "{", "List", "<", "T", ">", "annotatedItems", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "T", "item", ":", "items", ")", "{", "if", "(", "Objects", ".", "equal", "(", "item", ",", "\"\"", ")", ")", "{", "// This is a safe cast because know that at least one instance of T (this item) is a", "// String.", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "T", "newItem", "=", "(", "T", ")", "HUMAN_UNDERSTANDABLE_EMPTY_STRING", ";", "annotatedItems", ".", "add", "(", "newItem", ")", ";", "}", "else", "{", "annotatedItems", ".", "add", "(", "item", ")", ";", "}", "}", "return", "annotatedItems", ";", "}", "else", "{", "return", "items", ";", "}", "}" ]
Returns an iterable with all empty strings replaced by a non-empty human understandable indicator for an empty string. <p>Returns the given iterable if it contains no empty strings.
[ "Returns", "an", "iterable", "with", "all", "empty", "strings", "replaced", "by", "a", "non", "-", "empty", "human", "understandable", "indicator", "for", "an", "empty", "string", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/SubjectUtils.java#L367-L385
28,246
google/truth
core/src/main/java/com/google/common/truth/FailureMetadata.java
FailureMetadata.description
private ImmutableList<Fact> description() { String description = null; boolean descriptionWasDerived = false; for (Step step : steps) { if (step.isCheckCall()) { checkState(description != null); if (step.descriptionUpdate == null) { description = null; descriptionWasDerived = false; } else { description = verifyNotNull(step.descriptionUpdate.apply(description)); descriptionWasDerived = true; } continue; } if (description == null) { description = firstNonNull(step.subject.internalCustomName(), step.subject.typeDescription()); } } return descriptionWasDerived ? ImmutableList.of(fact("value of", description)) : ImmutableList.<Fact>of(); }
java
private ImmutableList<Fact> description() { String description = null; boolean descriptionWasDerived = false; for (Step step : steps) { if (step.isCheckCall()) { checkState(description != null); if (step.descriptionUpdate == null) { description = null; descriptionWasDerived = false; } else { description = verifyNotNull(step.descriptionUpdate.apply(description)); descriptionWasDerived = true; } continue; } if (description == null) { description = firstNonNull(step.subject.internalCustomName(), step.subject.typeDescription()); } } return descriptionWasDerived ? ImmutableList.of(fact("value of", description)) : ImmutableList.<Fact>of(); }
[ "private", "ImmutableList", "<", "Fact", ">", "description", "(", ")", "{", "String", "description", "=", "null", ";", "boolean", "descriptionWasDerived", "=", "false", ";", "for", "(", "Step", "step", ":", "steps", ")", "{", "if", "(", "step", ".", "isCheckCall", "(", ")", ")", "{", "checkState", "(", "description", "!=", "null", ")", ";", "if", "(", "step", ".", "descriptionUpdate", "==", "null", ")", "{", "description", "=", "null", ";", "descriptionWasDerived", "=", "false", ";", "}", "else", "{", "description", "=", "verifyNotNull", "(", "step", ".", "descriptionUpdate", ".", "apply", "(", "description", ")", ")", ";", "descriptionWasDerived", "=", "true", ";", "}", "continue", ";", "}", "if", "(", "description", "==", "null", ")", "{", "description", "=", "firstNonNull", "(", "step", ".", "subject", ".", "internalCustomName", "(", ")", ",", "step", ".", "subject", ".", "typeDescription", "(", ")", ")", ";", "}", "}", "return", "descriptionWasDerived", "?", "ImmutableList", ".", "of", "(", "fact", "(", "\"value of\"", ",", "description", ")", ")", ":", "ImmutableList", ".", "<", "Fact", ">", "of", "(", ")", ";", "}" ]
Returns a description of how the final actual value was derived from earlier actual values in the chain, if the chain ends with at least one derivation that we have a name for. <p>We don't want to say: "value of string: expected [foo] but was [bar]" (OK, we might still decide to say this, but for now, we don't.) <p>We do want to say: "value of throwable.getMessage(): expected [foo] but was [bar]" <p>To support that, {@code descriptionWasDerived} tracks whether we've been given context through {@code check} calls <i>that include names</i>. <p>If we're missing a naming function halfway through, we have to reset: We don't want to claim that the value is "foo.bar.baz" when it's "foo.bar.somethingelse.baz." We have to go back to "object.baz." (But note that {@link #rootUnlessThrowable} will still provide the value of the root foo to the user as long as we had at least one naming function: We might not know the root's exact relationship to the final object, but we know it's some object "different enough" to be worth displaying.)
[ "Returns", "a", "description", "of", "how", "the", "final", "actual", "value", "was", "derived", "from", "earlier", "actual", "values", "in", "the", "chain", "if", "the", "chain", "ends", "with", "at", "least", "one", "derivation", "that", "we", "have", "a", "name", "for", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/FailureMetadata.java#L219-L243
28,247
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
MapSubject.containsExactlyEntriesIn
@CanIgnoreReturnValue public Ordered containsExactlyEntriesIn(Map<?, ?> expectedMap) { if (expectedMap.isEmpty()) { if (actual().isEmpty()) { return IN_ORDER; } else { isEmpty(); // fails return ALREADY_FAILED; } } boolean containsAnyOrder = containsEntriesInAnyOrder(expectedMap, "contains exactly", /* allowUnexpected= */ false); if (containsAnyOrder) { return new MapInOrder(expectedMap, "contains exactly these entries in order"); } else { return ALREADY_FAILED; } }
java
@CanIgnoreReturnValue public Ordered containsExactlyEntriesIn(Map<?, ?> expectedMap) { if (expectedMap.isEmpty()) { if (actual().isEmpty()) { return IN_ORDER; } else { isEmpty(); // fails return ALREADY_FAILED; } } boolean containsAnyOrder = containsEntriesInAnyOrder(expectedMap, "contains exactly", /* allowUnexpected= */ false); if (containsAnyOrder) { return new MapInOrder(expectedMap, "contains exactly these entries in order"); } else { return ALREADY_FAILED; } }
[ "@", "CanIgnoreReturnValue", "public", "Ordered", "containsExactlyEntriesIn", "(", "Map", "<", "?", ",", "?", ">", "expectedMap", ")", "{", "if", "(", "expectedMap", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "actual", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "IN_ORDER", ";", "}", "else", "{", "isEmpty", "(", ")", ";", "// fails", "return", "ALREADY_FAILED", ";", "}", "}", "boolean", "containsAnyOrder", "=", "containsEntriesInAnyOrder", "(", "expectedMap", ",", "\"contains exactly\"", ",", "/* allowUnexpected= */", "false", ")", ";", "if", "(", "containsAnyOrder", ")", "{", "return", "new", "MapInOrder", "(", "expectedMap", ",", "\"contains exactly these entries in order\"", ")", ";", "}", "else", "{", "return", "ALREADY_FAILED", ";", "}", "}" ]
Fails if the map does not contain exactly the given set of entries in the given map.
[ "Fails", "if", "the", "map", "does", "not", "contain", "exactly", "the", "given", "set", "of", "entries", "in", "the", "given", "map", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/MapSubject.java#L231-L248
28,248
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
MapSubject.containsAtLeastEntriesIn
@CanIgnoreReturnValue public Ordered containsAtLeastEntriesIn(Map<?, ?> expectedMap) { if (expectedMap.isEmpty()) { return IN_ORDER; } boolean containsAnyOrder = containsEntriesInAnyOrder(expectedMap, "contains at least", /* allowUnexpected= */ true); if (containsAnyOrder) { return new MapInOrder(expectedMap, "contains at least these entries in order"); } else { return ALREADY_FAILED; } }
java
@CanIgnoreReturnValue public Ordered containsAtLeastEntriesIn(Map<?, ?> expectedMap) { if (expectedMap.isEmpty()) { return IN_ORDER; } boolean containsAnyOrder = containsEntriesInAnyOrder(expectedMap, "contains at least", /* allowUnexpected= */ true); if (containsAnyOrder) { return new MapInOrder(expectedMap, "contains at least these entries in order"); } else { return ALREADY_FAILED; } }
[ "@", "CanIgnoreReturnValue", "public", "Ordered", "containsAtLeastEntriesIn", "(", "Map", "<", "?", ",", "?", ">", "expectedMap", ")", "{", "if", "(", "expectedMap", ".", "isEmpty", "(", ")", ")", "{", "return", "IN_ORDER", ";", "}", "boolean", "containsAnyOrder", "=", "containsEntriesInAnyOrder", "(", "expectedMap", ",", "\"contains at least\"", ",", "/* allowUnexpected= */", "true", ")", ";", "if", "(", "containsAnyOrder", ")", "{", "return", "new", "MapInOrder", "(", "expectedMap", ",", "\"contains at least these entries in order\"", ")", ";", "}", "else", "{", "return", "ALREADY_FAILED", ";", "}", "}" ]
Fails if the map does not contain at least the given set of entries in the given map.
[ "Fails", "if", "the", "map", "does", "not", "contain", "at", "least", "the", "given", "set", "of", "entries", "in", "the", "given", "map", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/MapSubject.java#L251-L263
28,249
google/truth
core/src/main/java/com/google/common/truth/Fact.java
Fact.makeMessage
static String makeMessage(ImmutableList<String> messages, ImmutableList<Fact> facts) { int longestKeyLength = 0; boolean seenNewlineInValue = false; for (Fact fact : facts) { if (fact.value != null) { longestKeyLength = max(longestKeyLength, fact.key.length()); // TODO(cpovirk): Look for other kinds of newlines. seenNewlineInValue |= fact.value.contains("\n"); } } StringBuilder builder = new StringBuilder(); for (String message : messages) { builder.append(message); builder.append('\n'); } /* * *Usually* the first fact is printed at the beginning of a new line. However, when this * exception is the cause of another exception, that exception will print it starting after * "Caused by: " on the same line. The other exception sometimes also reuses this message as its * own message. In both of those scenarios, the first line doesn't start at column 0, so the * horizontal alignment is thrown off. * * There's not much we can do about this, short of always starting with a newline (which would * leave a blank line at the beginning of the message in the normal case). */ for (Fact fact : facts) { if (fact.value == null) { builder.append(fact.key); } else if (seenNewlineInValue) { builder.append(fact.key); builder.append(":\n"); builder.append(indent(fact.value)); } else { builder.append(padEnd(fact.key, longestKeyLength, ' ')); builder.append(": "); builder.append(fact.value); } builder.append('\n'); } builder.setLength(builder.length() - 1); // remove trailing \n return builder.toString(); }
java
static String makeMessage(ImmutableList<String> messages, ImmutableList<Fact> facts) { int longestKeyLength = 0; boolean seenNewlineInValue = false; for (Fact fact : facts) { if (fact.value != null) { longestKeyLength = max(longestKeyLength, fact.key.length()); // TODO(cpovirk): Look for other kinds of newlines. seenNewlineInValue |= fact.value.contains("\n"); } } StringBuilder builder = new StringBuilder(); for (String message : messages) { builder.append(message); builder.append('\n'); } /* * *Usually* the first fact is printed at the beginning of a new line. However, when this * exception is the cause of another exception, that exception will print it starting after * "Caused by: " on the same line. The other exception sometimes also reuses this message as its * own message. In both of those scenarios, the first line doesn't start at column 0, so the * horizontal alignment is thrown off. * * There's not much we can do about this, short of always starting with a newline (which would * leave a blank line at the beginning of the message in the normal case). */ for (Fact fact : facts) { if (fact.value == null) { builder.append(fact.key); } else if (seenNewlineInValue) { builder.append(fact.key); builder.append(":\n"); builder.append(indent(fact.value)); } else { builder.append(padEnd(fact.key, longestKeyLength, ' ')); builder.append(": "); builder.append(fact.value); } builder.append('\n'); } builder.setLength(builder.length() - 1); // remove trailing \n return builder.toString(); }
[ "static", "String", "makeMessage", "(", "ImmutableList", "<", "String", ">", "messages", ",", "ImmutableList", "<", "Fact", ">", "facts", ")", "{", "int", "longestKeyLength", "=", "0", ";", "boolean", "seenNewlineInValue", "=", "false", ";", "for", "(", "Fact", "fact", ":", "facts", ")", "{", "if", "(", "fact", ".", "value", "!=", "null", ")", "{", "longestKeyLength", "=", "max", "(", "longestKeyLength", ",", "fact", ".", "key", ".", "length", "(", ")", ")", ";", "// TODO(cpovirk): Look for other kinds of newlines.", "seenNewlineInValue", "|=", "fact", ".", "value", ".", "contains", "(", "\"\\n\"", ")", ";", "}", "}", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "message", ":", "messages", ")", "{", "builder", ".", "append", "(", "message", ")", ";", "builder", ".", "append", "(", "'", "'", ")", ";", "}", "/*\n * *Usually* the first fact is printed at the beginning of a new line. However, when this\n * exception is the cause of another exception, that exception will print it starting after\n * \"Caused by: \" on the same line. The other exception sometimes also reuses this message as its\n * own message. In both of those scenarios, the first line doesn't start at column 0, so the\n * horizontal alignment is thrown off.\n *\n * There's not much we can do about this, short of always starting with a newline (which would\n * leave a blank line at the beginning of the message in the normal case).\n */", "for", "(", "Fact", "fact", ":", "facts", ")", "{", "if", "(", "fact", ".", "value", "==", "null", ")", "{", "builder", ".", "append", "(", "fact", ".", "key", ")", ";", "}", "else", "if", "(", "seenNewlineInValue", ")", "{", "builder", ".", "append", "(", "fact", ".", "key", ")", ";", "builder", ".", "append", "(", "\":\\n\"", ")", ";", "builder", ".", "append", "(", "indent", "(", "fact", ".", "value", ")", ")", ";", "}", "else", "{", "builder", ".", "append", "(", "padEnd", "(", "fact", ".", "key", ",", "longestKeyLength", ",", "'", "'", ")", ")", ";", "builder", ".", "append", "(", "\": \"", ")", ";", "builder", ".", "append", "(", "fact", ".", "value", ")", ";", "}", "builder", ".", "append", "(", "'", "'", ")", ";", "}", "builder", ".", "setLength", "(", "builder", ".", "length", "(", ")", "-", "1", ")", ";", "// remove trailing \\n", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Formats the given messages and facts into a string for use as the message of a test failure. In particular, this method horizontally aligns the beginning of fact values.
[ "Formats", "the", "given", "messages", "and", "facts", "into", "a", "string", "for", "use", "as", "the", "message", "of", "a", "test", "failure", ".", "In", "particular", "this", "method", "horizontally", "aligns", "the", "beginning", "of", "fact", "values", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/Fact.java#L84-L127
28,250
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldDescriptorOrUnknown.java
FieldDescriptorOrUnknown.shortName
final String shortName() { if (fieldDescriptor().isPresent()) { return fieldDescriptor().get().isExtension() ? "[" + fieldDescriptor().get() + "]" : fieldDescriptor().get().getName(); } else { return String.valueOf(unknownFieldDescriptor().get().fieldNumber()); } }
java
final String shortName() { if (fieldDescriptor().isPresent()) { return fieldDescriptor().get().isExtension() ? "[" + fieldDescriptor().get() + "]" : fieldDescriptor().get().getName(); } else { return String.valueOf(unknownFieldDescriptor().get().fieldNumber()); } }
[ "final", "String", "shortName", "(", ")", "{", "if", "(", "fieldDescriptor", "(", ")", ".", "isPresent", "(", ")", ")", "{", "return", "fieldDescriptor", "(", ")", ".", "get", "(", ")", ".", "isExtension", "(", ")", "?", "\"[\"", "+", "fieldDescriptor", "(", ")", ".", "get", "(", ")", "+", "\"]\"", ":", "fieldDescriptor", "(", ")", ".", "get", "(", ")", ".", "getName", "(", ")", ";", "}", "else", "{", "return", "String", ".", "valueOf", "(", "unknownFieldDescriptor", "(", ")", ".", "get", "(", ")", ".", "fieldNumber", "(", ")", ")", ";", "}", "}" ]
Returns a short, human-readable version of this identifier.
[ "Returns", "a", "short", "human", "-", "readable", "version", "of", "this", "identifier", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldDescriptorOrUnknown.java#L41-L49
28,251
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
IterableSubject.hasSize
public final void hasSize(int expectedSize) { checkArgument(expectedSize >= 0, "expectedSize(%s) must be >= 0", expectedSize); int actualSize = size(actual()); check("size()").that(actualSize).isEqualTo(expectedSize); }
java
public final void hasSize(int expectedSize) { checkArgument(expectedSize >= 0, "expectedSize(%s) must be >= 0", expectedSize); int actualSize = size(actual()); check("size()").that(actualSize).isEqualTo(expectedSize); }
[ "public", "final", "void", "hasSize", "(", "int", "expectedSize", ")", "{", "checkArgument", "(", "expectedSize", ">=", "0", ",", "\"expectedSize(%s) must be >= 0\"", ",", "expectedSize", ")", ";", "int", "actualSize", "=", "size", "(", "actual", "(", ")", ")", ";", "check", "(", "\"size()\"", ")", ".", "that", "(", "actualSize", ")", ".", "isEqualTo", "(", "expectedSize", ")", ";", "}" ]
Fails if the subject does not have the given size.
[ "Fails", "if", "the", "subject", "does", "not", "have", "the", "given", "size", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/IterableSubject.java#L133-L137
28,252
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
IterableSubject.containsNoDuplicates
public final void containsNoDuplicates() { List<Entry<?>> duplicates = newArrayList(); for (Multiset.Entry<?> entry : LinkedHashMultiset.create(actual()).entrySet()) { if (entry.getCount() > 1) { duplicates.add(entry); } } if (!duplicates.isEmpty()) { failWithoutActual( simpleFact("expected not to contain duplicates"), fact("but contained", duplicates), fullContents()); } }
java
public final void containsNoDuplicates() { List<Entry<?>> duplicates = newArrayList(); for (Multiset.Entry<?> entry : LinkedHashMultiset.create(actual()).entrySet()) { if (entry.getCount() > 1) { duplicates.add(entry); } } if (!duplicates.isEmpty()) { failWithoutActual( simpleFact("expected not to contain duplicates"), fact("but contained", duplicates), fullContents()); } }
[ "public", "final", "void", "containsNoDuplicates", "(", ")", "{", "List", "<", "Entry", "<", "?", ">", ">", "duplicates", "=", "newArrayList", "(", ")", ";", "for", "(", "Multiset", ".", "Entry", "<", "?", ">", "entry", ":", "LinkedHashMultiset", ".", "create", "(", "actual", "(", ")", ")", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getCount", "(", ")", ">", "1", ")", "{", "duplicates", ".", "add", "(", "entry", ")", ";", "}", "}", "if", "(", "!", "duplicates", ".", "isEmpty", "(", ")", ")", "{", "failWithoutActual", "(", "simpleFact", "(", "\"expected not to contain duplicates\"", ")", ",", "fact", "(", "\"but contained\"", ",", "duplicates", ")", ",", "fullContents", "(", ")", ")", ";", "}", "}" ]
Checks that the subject does not contain duplicate elements.
[ "Checks", "that", "the", "subject", "does", "not", "contain", "duplicate", "elements", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/IterableSubject.java#L167-L180
28,253
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
IterableSubject.containsAtLeastElementsIn
@CanIgnoreReturnValue public final Ordered containsAtLeastElementsIn(Iterable<?> expectedIterable) { List<?> actual = Lists.newLinkedList(actual()); final Collection<?> expected = iterableToCollection(expectedIterable); List<Object> missing = newArrayList(); List<Object> actualNotInOrder = newArrayList(); boolean ordered = true; // step through the expected elements... for (Object e : expected) { int index = actual.indexOf(e); if (index != -1) { // if we find the element in the actual list... // drain all the elements that come before that element into actualNotInOrder moveElements(actual, actualNotInOrder, index); // and remove the element from the actual list actual.remove(0); } else { // otherwise try removing it from actualNotInOrder... if (actualNotInOrder.remove(e)) { // if it was in actualNotInOrder, we're not in order ordered = false; } else { // if it's not in actualNotInOrder, we're missing an expected element missing.add(e); } } } // if we have any missing expected elements, fail if (!missing.isEmpty()) { return failAtLeast(expected, missing); } /* * TODO(cpovirk): In the NotInOrder case, also include a Fact that shows _only_ the required * elements (that is, without any extras) but in the order they were actually found. That should * make it easier for users to compare the actual order of the required elements to the expected * order. Or, if that's too much trouble, at least try to find a better title for the full * actual iterable than the default of "but was," which may _sound_ like it should show only the * required elements, rather than the full actual iterable. */ return ordered ? IN_ORDER : new Ordered() { @Override public void inOrder() { failWithActual( simpleFact("required elements were all found, but order was wrong"), fact("expected order for required elements", expected)); } }; }
java
@CanIgnoreReturnValue public final Ordered containsAtLeastElementsIn(Iterable<?> expectedIterable) { List<?> actual = Lists.newLinkedList(actual()); final Collection<?> expected = iterableToCollection(expectedIterable); List<Object> missing = newArrayList(); List<Object> actualNotInOrder = newArrayList(); boolean ordered = true; // step through the expected elements... for (Object e : expected) { int index = actual.indexOf(e); if (index != -1) { // if we find the element in the actual list... // drain all the elements that come before that element into actualNotInOrder moveElements(actual, actualNotInOrder, index); // and remove the element from the actual list actual.remove(0); } else { // otherwise try removing it from actualNotInOrder... if (actualNotInOrder.remove(e)) { // if it was in actualNotInOrder, we're not in order ordered = false; } else { // if it's not in actualNotInOrder, we're missing an expected element missing.add(e); } } } // if we have any missing expected elements, fail if (!missing.isEmpty()) { return failAtLeast(expected, missing); } /* * TODO(cpovirk): In the NotInOrder case, also include a Fact that shows _only_ the required * elements (that is, without any extras) but in the order they were actually found. That should * make it easier for users to compare the actual order of the required elements to the expected * order. Or, if that's too much trouble, at least try to find a better title for the full * actual iterable than the default of "but was," which may _sound_ like it should show only the * required elements, rather than the full actual iterable. */ return ordered ? IN_ORDER : new Ordered() { @Override public void inOrder() { failWithActual( simpleFact("required elements were all found, but order was wrong"), fact("expected order for required elements", expected)); } }; }
[ "@", "CanIgnoreReturnValue", "public", "final", "Ordered", "containsAtLeastElementsIn", "(", "Iterable", "<", "?", ">", "expectedIterable", ")", "{", "List", "<", "?", ">", "actual", "=", "Lists", ".", "newLinkedList", "(", "actual", "(", ")", ")", ";", "final", "Collection", "<", "?", ">", "expected", "=", "iterableToCollection", "(", "expectedIterable", ")", ";", "List", "<", "Object", ">", "missing", "=", "newArrayList", "(", ")", ";", "List", "<", "Object", ">", "actualNotInOrder", "=", "newArrayList", "(", ")", ";", "boolean", "ordered", "=", "true", ";", "// step through the expected elements...", "for", "(", "Object", "e", ":", "expected", ")", "{", "int", "index", "=", "actual", ".", "indexOf", "(", "e", ")", ";", "if", "(", "index", "!=", "-", "1", ")", "{", "// if we find the element in the actual list...", "// drain all the elements that come before that element into actualNotInOrder", "moveElements", "(", "actual", ",", "actualNotInOrder", ",", "index", ")", ";", "// and remove the element from the actual list", "actual", ".", "remove", "(", "0", ")", ";", "}", "else", "{", "// otherwise try removing it from actualNotInOrder...", "if", "(", "actualNotInOrder", ".", "remove", "(", "e", ")", ")", "{", "// if it was in actualNotInOrder, we're not in order", "ordered", "=", "false", ";", "}", "else", "{", "// if it's not in actualNotInOrder, we're missing an expected element", "missing", ".", "add", "(", "e", ")", ";", "}", "}", "}", "// if we have any missing expected elements, fail", "if", "(", "!", "missing", ".", "isEmpty", "(", ")", ")", "{", "return", "failAtLeast", "(", "expected", ",", "missing", ")", ";", "}", "/*\n * TODO(cpovirk): In the NotInOrder case, also include a Fact that shows _only_ the required\n * elements (that is, without any extras) but in the order they were actually found. That should\n * make it easier for users to compare the actual order of the required elements to the expected\n * order. Or, if that's too much trouble, at least try to find a better title for the full\n * actual iterable than the default of \"but was,\" which may _sound_ like it should show only the\n * required elements, rather than the full actual iterable.\n */", "return", "ordered", "?", "IN_ORDER", ":", "new", "Ordered", "(", ")", "{", "@", "Override", "public", "void", "inOrder", "(", ")", "{", "failWithActual", "(", "simpleFact", "(", "\"required elements were all found, but order was wrong\"", ")", ",", "fact", "(", "\"expected order for required elements\"", ",", "expected", ")", ")", ";", "}", "}", ";", "}" ]
Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()} on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive.
[ "Checks", "that", "the", "actual", "iterable", "contains", "at", "least", "all", "of", "the", "expected", "elements", "or", "fails", ".", "If", "an", "element", "appears", "more", "than", "once", "in", "the", "expected", "elements", "then", "it", "must", "appear", "at", "least", "that", "number", "of", "times", "in", "the", "actual", "elements", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/IterableSubject.java#L299-L347
28,254
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
IterableSubject.moveElements
private static void moveElements(List<?> input, Collection<Object> output, int maxElements) { for (int i = 0; i < maxElements; i++) { output.add(input.remove(0)); } }
java
private static void moveElements(List<?> input, Collection<Object> output, int maxElements) { for (int i = 0; i < maxElements; i++) { output.add(input.remove(0)); } }
[ "private", "static", "void", "moveElements", "(", "List", "<", "?", ">", "input", ",", "Collection", "<", "Object", ">", "output", ",", "int", "maxElements", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "maxElements", ";", "i", "++", ")", "{", "output", ".", "add", "(", "input", ".", "remove", "(", "0", ")", ")", ";", "}", "}" ]
Removes at most the given number of available elements from the input list and adds them to the given output collection.
[ "Removes", "at", "most", "the", "given", "number", "of", "available", "elements", "from", "the", "input", "list", "and", "adds", "them", "to", "the", "given", "output", "collection", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/IterableSubject.java#L390-L394
28,255
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/RecursableDiffEntity.java
RecursableDiffEntity.isAnyChildMatched
final boolean isAnyChildMatched() { if (isAnyChildMatched == null) { isAnyChildMatched = false; for (RecursableDiffEntity entity : childEntities()) { if ((entity.isMatched() && !entity.isContentEmpty()) || entity.isAnyChildMatched()) { isAnyChildMatched = true; break; } } } return isAnyChildMatched; }
java
final boolean isAnyChildMatched() { if (isAnyChildMatched == null) { isAnyChildMatched = false; for (RecursableDiffEntity entity : childEntities()) { if ((entity.isMatched() && !entity.isContentEmpty()) || entity.isAnyChildMatched()) { isAnyChildMatched = true; break; } } } return isAnyChildMatched; }
[ "final", "boolean", "isAnyChildMatched", "(", ")", "{", "if", "(", "isAnyChildMatched", "==", "null", ")", "{", "isAnyChildMatched", "=", "false", ";", "for", "(", "RecursableDiffEntity", "entity", ":", "childEntities", "(", ")", ")", "{", "if", "(", "(", "entity", ".", "isMatched", "(", ")", "&&", "!", "entity", ".", "isContentEmpty", "(", ")", ")", "||", "entity", ".", "isAnyChildMatched", "(", ")", ")", "{", "isAnyChildMatched", "=", "true", ";", "break", ";", "}", "}", "}", "return", "isAnyChildMatched", ";", "}" ]
Returns true if some child entity matched. <p>Caches the result for future calls.
[ "Returns", "true", "if", "some", "child", "entity", "matched", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/RecursableDiffEntity.java#L69-L80
28,256
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/RecursableDiffEntity.java
RecursableDiffEntity.isAnyChildIgnored
final boolean isAnyChildIgnored() { if (isAnyChildIgnored == null) { isAnyChildIgnored = false; for (RecursableDiffEntity entity : childEntities()) { if ((entity.isIgnored() && !entity.isContentEmpty()) || entity.isAnyChildIgnored()) { isAnyChildIgnored = true; break; } } } return isAnyChildIgnored; }
java
final boolean isAnyChildIgnored() { if (isAnyChildIgnored == null) { isAnyChildIgnored = false; for (RecursableDiffEntity entity : childEntities()) { if ((entity.isIgnored() && !entity.isContentEmpty()) || entity.isAnyChildIgnored()) { isAnyChildIgnored = true; break; } } } return isAnyChildIgnored; }
[ "final", "boolean", "isAnyChildIgnored", "(", ")", "{", "if", "(", "isAnyChildIgnored", "==", "null", ")", "{", "isAnyChildIgnored", "=", "false", ";", "for", "(", "RecursableDiffEntity", "entity", ":", "childEntities", "(", ")", ")", "{", "if", "(", "(", "entity", ".", "isIgnored", "(", ")", "&&", "!", "entity", ".", "isContentEmpty", "(", ")", ")", "||", "entity", ".", "isAnyChildIgnored", "(", ")", ")", "{", "isAnyChildIgnored", "=", "true", ";", "break", ";", "}", "}", "}", "return", "isAnyChildIgnored", ";", "}" ]
Returns true if some child entity was ignored. <p>Caches the result for future calls.
[ "Returns", "true", "if", "some", "child", "entity", "was", "ignored", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/RecursableDiffEntity.java#L87-L98
28,257
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
StackTraceCleaner.addToStreak
private void addToStreak(StackTraceElementWrapper stackTraceElementWrapper) { if (stackTraceElementWrapper.getStackFrameType() != currentStreakType) { endStreak(); currentStreakType = stackTraceElementWrapper.getStackFrameType(); currentStreakLength = 1; } else { currentStreakLength++; } }
java
private void addToStreak(StackTraceElementWrapper stackTraceElementWrapper) { if (stackTraceElementWrapper.getStackFrameType() != currentStreakType) { endStreak(); currentStreakType = stackTraceElementWrapper.getStackFrameType(); currentStreakLength = 1; } else { currentStreakLength++; } }
[ "private", "void", "addToStreak", "(", "StackTraceElementWrapper", "stackTraceElementWrapper", ")", "{", "if", "(", "stackTraceElementWrapper", ".", "getStackFrameType", "(", ")", "!=", "currentStreakType", ")", "{", "endStreak", "(", ")", ";", "currentStreakType", "=", "stackTraceElementWrapper", ".", "getStackFrameType", "(", ")", ";", "currentStreakLength", "=", "1", ";", "}", "else", "{", "currentStreakLength", "++", ";", "}", "}" ]
Either adds the given frame to the running streak or closes out the running streak and starts a new one.
[ "Either", "adds", "the", "given", "frame", "to", "the", "running", "streak", "or", "closes", "out", "the", "running", "streak", "and", "starts", "a", "new", "one", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/StackTraceCleaner.java#L161-L169
28,258
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
StackTraceCleaner.endStreak
private void endStreak() { if (currentStreakLength == 0) { return; } if (currentStreakLength == 1) { // A single frame isn't a streak. Just include the frame as-is in the result. cleanedStackTrace.add(lastStackFrameElementWrapper); } else { // Add a single frame to the result summarizing the streak of framework frames cleanedStackTrace.add(createStreakReplacementFrame(currentStreakType, currentStreakLength)); } clearStreak(); }
java
private void endStreak() { if (currentStreakLength == 0) { return; } if (currentStreakLength == 1) { // A single frame isn't a streak. Just include the frame as-is in the result. cleanedStackTrace.add(lastStackFrameElementWrapper); } else { // Add a single frame to the result summarizing the streak of framework frames cleanedStackTrace.add(createStreakReplacementFrame(currentStreakType, currentStreakLength)); } clearStreak(); }
[ "private", "void", "endStreak", "(", ")", "{", "if", "(", "currentStreakLength", "==", "0", ")", "{", "return", ";", "}", "if", "(", "currentStreakLength", "==", "1", ")", "{", "// A single frame isn't a streak. Just include the frame as-is in the result.", "cleanedStackTrace", ".", "add", "(", "lastStackFrameElementWrapper", ")", ";", "}", "else", "{", "// Add a single frame to the result summarizing the streak of framework frames", "cleanedStackTrace", ".", "add", "(", "createStreakReplacementFrame", "(", "currentStreakType", ",", "currentStreakLength", ")", ")", ";", "}", "clearStreak", "(", ")", ";", "}" ]
Ends the current streak, adding a summary frame to the result. Resets the streak counter.
[ "Ends", "the", "current", "streak", "adding", "a", "summary", "frame", "to", "the", "result", ".", "Resets", "the", "streak", "counter", "." ]
60eceffd2e8c3297655d33ed87d965cf5af51108
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/StackTraceCleaner.java#L172-L186
28,259
mapsforge/mapsforge
mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/MapFileWriter.java
MapFileWriter.writeFile
public static void writeFile(MapWriterConfiguration configuration, TileBasedDataProcessor dataProcessor) throws IOException { EXECUTOR_SERVICE = Executors.newFixedThreadPool(configuration.getThreads()); RandomAccessFile randomAccessFile = new RandomAccessFile(configuration.getOutputFile(), "rw"); int amountOfZoomIntervals = dataProcessor.getZoomIntervalConfiguration().getNumberOfZoomIntervals(); ByteBuffer containerHeaderBuffer = ByteBuffer.allocate(HEADER_BUFFER_SIZE); // CONTAINER HEADER int totalHeaderSize = writeHeaderBuffer(configuration, dataProcessor, containerHeaderBuffer); // set to mark where zoomIntervalConfig starts containerHeaderBuffer.reset(); final LoadingCache<TDWay, Geometry> jtsGeometryCache = CacheBuilder.newBuilder() .maximumSize(JTS_GEOMETRY_CACHE_SIZE).concurrencyLevel(Runtime.getRuntime().availableProcessors() * 2) .build(new JTSGeometryCacheLoader(dataProcessor)); // SUB FILES // for each zoom interval write a sub file long currentFileSize = totalHeaderSize; for (int i = 0; i < amountOfZoomIntervals; i++) { // SUB FILE INDEX AND DATA long subfileSize = writeSubfile(currentFileSize, i, dataProcessor, jtsGeometryCache, randomAccessFile, configuration); // SUB FILE META DATA IN CONTAINER HEADER writeSubfileMetaDataToContainerHeader(dataProcessor.getZoomIntervalConfiguration(), i, currentFileSize, subfileSize, containerHeaderBuffer); currentFileSize += subfileSize; } randomAccessFile.seek(0); randomAccessFile.write(containerHeaderBuffer.array(), 0, totalHeaderSize); // WRITE FILE SIZE TO HEADER long fileSize = randomAccessFile.length(); randomAccessFile.seek(OFFSET_FILE_SIZE); randomAccessFile.writeLong(fileSize); randomAccessFile.close(); CacheStats stats = jtsGeometryCache.stats(); LOGGER.fine("Tag values stats:\n" + OSMUtils.logValueTypeCount()); LOGGER.info("JTS Geometry cache hit rate: " + stats.hitRate()); LOGGER.info("JTS Geometry total load time: " + stats.totalLoadTime() / 1000); LOGGER.info("Finished writing file."); }
java
public static void writeFile(MapWriterConfiguration configuration, TileBasedDataProcessor dataProcessor) throws IOException { EXECUTOR_SERVICE = Executors.newFixedThreadPool(configuration.getThreads()); RandomAccessFile randomAccessFile = new RandomAccessFile(configuration.getOutputFile(), "rw"); int amountOfZoomIntervals = dataProcessor.getZoomIntervalConfiguration().getNumberOfZoomIntervals(); ByteBuffer containerHeaderBuffer = ByteBuffer.allocate(HEADER_BUFFER_SIZE); // CONTAINER HEADER int totalHeaderSize = writeHeaderBuffer(configuration, dataProcessor, containerHeaderBuffer); // set to mark where zoomIntervalConfig starts containerHeaderBuffer.reset(); final LoadingCache<TDWay, Geometry> jtsGeometryCache = CacheBuilder.newBuilder() .maximumSize(JTS_GEOMETRY_CACHE_SIZE).concurrencyLevel(Runtime.getRuntime().availableProcessors() * 2) .build(new JTSGeometryCacheLoader(dataProcessor)); // SUB FILES // for each zoom interval write a sub file long currentFileSize = totalHeaderSize; for (int i = 0; i < amountOfZoomIntervals; i++) { // SUB FILE INDEX AND DATA long subfileSize = writeSubfile(currentFileSize, i, dataProcessor, jtsGeometryCache, randomAccessFile, configuration); // SUB FILE META DATA IN CONTAINER HEADER writeSubfileMetaDataToContainerHeader(dataProcessor.getZoomIntervalConfiguration(), i, currentFileSize, subfileSize, containerHeaderBuffer); currentFileSize += subfileSize; } randomAccessFile.seek(0); randomAccessFile.write(containerHeaderBuffer.array(), 0, totalHeaderSize); // WRITE FILE SIZE TO HEADER long fileSize = randomAccessFile.length(); randomAccessFile.seek(OFFSET_FILE_SIZE); randomAccessFile.writeLong(fileSize); randomAccessFile.close(); CacheStats stats = jtsGeometryCache.stats(); LOGGER.fine("Tag values stats:\n" + OSMUtils.logValueTypeCount()); LOGGER.info("JTS Geometry cache hit rate: " + stats.hitRate()); LOGGER.info("JTS Geometry total load time: " + stats.totalLoadTime() / 1000); LOGGER.info("Finished writing file."); }
[ "public", "static", "void", "writeFile", "(", "MapWriterConfiguration", "configuration", ",", "TileBasedDataProcessor", "dataProcessor", ")", "throws", "IOException", "{", "EXECUTOR_SERVICE", "=", "Executors", ".", "newFixedThreadPool", "(", "configuration", ".", "getThreads", "(", ")", ")", ";", "RandomAccessFile", "randomAccessFile", "=", "new", "RandomAccessFile", "(", "configuration", ".", "getOutputFile", "(", ")", ",", "\"rw\"", ")", ";", "int", "amountOfZoomIntervals", "=", "dataProcessor", ".", "getZoomIntervalConfiguration", "(", ")", ".", "getNumberOfZoomIntervals", "(", ")", ";", "ByteBuffer", "containerHeaderBuffer", "=", "ByteBuffer", ".", "allocate", "(", "HEADER_BUFFER_SIZE", ")", ";", "// CONTAINER HEADER", "int", "totalHeaderSize", "=", "writeHeaderBuffer", "(", "configuration", ",", "dataProcessor", ",", "containerHeaderBuffer", ")", ";", "// set to mark where zoomIntervalConfig starts", "containerHeaderBuffer", ".", "reset", "(", ")", ";", "final", "LoadingCache", "<", "TDWay", ",", "Geometry", ">", "jtsGeometryCache", "=", "CacheBuilder", ".", "newBuilder", "(", ")", ".", "maximumSize", "(", "JTS_GEOMETRY_CACHE_SIZE", ")", ".", "concurrencyLevel", "(", "Runtime", ".", "getRuntime", "(", ")", ".", "availableProcessors", "(", ")", "*", "2", ")", ".", "build", "(", "new", "JTSGeometryCacheLoader", "(", "dataProcessor", ")", ")", ";", "// SUB FILES", "// for each zoom interval write a sub file", "long", "currentFileSize", "=", "totalHeaderSize", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "amountOfZoomIntervals", ";", "i", "++", ")", "{", "// SUB FILE INDEX AND DATA", "long", "subfileSize", "=", "writeSubfile", "(", "currentFileSize", ",", "i", ",", "dataProcessor", ",", "jtsGeometryCache", ",", "randomAccessFile", ",", "configuration", ")", ";", "// SUB FILE META DATA IN CONTAINER HEADER", "writeSubfileMetaDataToContainerHeader", "(", "dataProcessor", ".", "getZoomIntervalConfiguration", "(", ")", ",", "i", ",", "currentFileSize", ",", "subfileSize", ",", "containerHeaderBuffer", ")", ";", "currentFileSize", "+=", "subfileSize", ";", "}", "randomAccessFile", ".", "seek", "(", "0", ")", ";", "randomAccessFile", ".", "write", "(", "containerHeaderBuffer", ".", "array", "(", ")", ",", "0", ",", "totalHeaderSize", ")", ";", "// WRITE FILE SIZE TO HEADER", "long", "fileSize", "=", "randomAccessFile", ".", "length", "(", ")", ";", "randomAccessFile", ".", "seek", "(", "OFFSET_FILE_SIZE", ")", ";", "randomAccessFile", ".", "writeLong", "(", "fileSize", ")", ";", "randomAccessFile", ".", "close", "(", ")", ";", "CacheStats", "stats", "=", "jtsGeometryCache", ".", "stats", "(", ")", ";", "LOGGER", ".", "fine", "(", "\"Tag values stats:\\n\"", "+", "OSMUtils", ".", "logValueTypeCount", "(", ")", ")", ";", "LOGGER", ".", "info", "(", "\"JTS Geometry cache hit rate: \"", "+", "stats", ".", "hitRate", "(", ")", ")", ";", "LOGGER", ".", "info", "(", "\"JTS Geometry total load time: \"", "+", "stats", ".", "totalLoadTime", "(", ")", "/", "1000", ")", ";", "LOGGER", ".", "info", "(", "\"Finished writing file.\"", ")", ";", "}" ]
Writes the map file according to the given configuration using the given data processor. @param configuration the configuration @param dataProcessor the data processor @throws IOException thrown if any IO error occurs
[ "Writes", "the", "map", "file", "according", "to", "the", "given", "configuration", "using", "the", "given", "data", "processor", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/MapFileWriter.java#L353-L399
28,260
mapsforge/mapsforge
mapsforge-poi/src/main/java/org/mapsforge/poi/storage/AbstractPoiPersistenceManager.java
AbstractPoiPersistenceManager.stringToTags
protected static Set<Tag> stringToTags(String data) { Set<Tag> tags = new HashSet<>(); String[] split = data.split("\r"); for (String s : split) { if (s.indexOf(Tag.KEY_VALUE_SEPARATOR) > -1) { String[] keyValue = s.split(String.valueOf(Tag.KEY_VALUE_SEPARATOR)); if (keyValue.length == 2) { tags.add(new Tag(keyValue[0], keyValue[1])); } } } return tags; }
java
protected static Set<Tag> stringToTags(String data) { Set<Tag> tags = new HashSet<>(); String[] split = data.split("\r"); for (String s : split) { if (s.indexOf(Tag.KEY_VALUE_SEPARATOR) > -1) { String[] keyValue = s.split(String.valueOf(Tag.KEY_VALUE_SEPARATOR)); if (keyValue.length == 2) { tags.add(new Tag(keyValue[0], keyValue[1])); } } } return tags; }
[ "protected", "static", "Set", "<", "Tag", ">", "stringToTags", "(", "String", "data", ")", "{", "Set", "<", "Tag", ">", "tags", "=", "new", "HashSet", "<>", "(", ")", ";", "String", "[", "]", "split", "=", "data", ".", "split", "(", "\"\\r\"", ")", ";", "for", "(", "String", "s", ":", "split", ")", "{", "if", "(", "s", ".", "indexOf", "(", "Tag", ".", "KEY_VALUE_SEPARATOR", ")", ">", "-", "1", ")", "{", "String", "[", "]", "keyValue", "=", "s", ".", "split", "(", "String", ".", "valueOf", "(", "Tag", ".", "KEY_VALUE_SEPARATOR", ")", ")", ";", "if", "(", "keyValue", ".", "length", "==", "2", ")", "{", "tags", ".", "add", "(", "new", "Tag", "(", "keyValue", "[", "0", "]", ",", "keyValue", "[", "1", "]", ")", ")", ";", "}", "}", "}", "return", "tags", ";", "}" ]
Convert tags string representation with '\r' delimiter to collection.
[ "Convert", "tags", "string", "representation", "with", "\\", "r", "delimiter", "to", "collection", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi/src/main/java/org/mapsforge/poi/storage/AbstractPoiPersistenceManager.java#L124-L136
28,261
mapsforge/mapsforge
mapsforge-poi/src/main/java/org/mapsforge/poi/storage/AbstractPoiPersistenceManager.java
AbstractPoiPersistenceManager.tagsToString
protected static String tagsToString(Set<Tag> tags) { StringBuilder sb = new StringBuilder(); for (Tag tag : tags) { if (sb.length() > 0) { sb.append('\r'); } sb.append(tag.key).append(Tag.KEY_VALUE_SEPARATOR).append(tag.value); } return sb.toString(); }
java
protected static String tagsToString(Set<Tag> tags) { StringBuilder sb = new StringBuilder(); for (Tag tag : tags) { if (sb.length() > 0) { sb.append('\r'); } sb.append(tag.key).append(Tag.KEY_VALUE_SEPARATOR).append(tag.value); } return sb.toString(); }
[ "protected", "static", "String", "tagsToString", "(", "Set", "<", "Tag", ">", "tags", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Tag", "tag", ":", "tags", ")", "{", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "sb", ".", "append", "(", "tag", ".", "key", ")", ".", "append", "(", "Tag", ".", "KEY_VALUE_SEPARATOR", ")", ".", "append", "(", "tag", ".", "value", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Convert tags collection to string representation with '\r' delimiter.
[ "Convert", "tags", "collection", "to", "string", "representation", "with", "\\", "r", "delimiter", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi/src/main/java/org/mapsforge/poi/storage/AbstractPoiPersistenceManager.java#L141-L150
28,262
mapsforge/mapsforge
mapsforge-map/src/main/java/org/mapsforge/map/layer/cache/FileSystemTileCache.java
FileSystemTileCache.storeData
private void storeData(Job key, TileBitmap bitmap) { OutputStream outputStream = null; try { File file = getOutputFile(key); if (file == null) { // if the file cannot be written, silently return return; } outputStream = new FileOutputStream(file); bitmap.compress(outputStream); try { lock.writeLock().lock(); if (this.lruCache.put(key.getKey(), file) != null) { LOGGER.warning("overwriting cached entry: " + key.getKey()); } } finally { lock.writeLock().unlock(); } } catch (Exception e) { // we are catching now any exception and then disable the file cache // this should ensure that no exception in the storage thread will // ever crash the main app. If there is a runtime exception, the thread // will exit (via destroy). LOGGER.log(Level.SEVERE, "Disabling filesystem cache", e); // most likely cause is that the disk is full, just disable the // cache otherwise // more and more exceptions will be thrown. this.destroy(); try { lock.writeLock().lock(); this.lruCache = new FileWorkingSetCache<String>(0); } finally { lock.writeLock().unlock(); } } finally { IOUtils.closeQuietly(outputStream); } }
java
private void storeData(Job key, TileBitmap bitmap) { OutputStream outputStream = null; try { File file = getOutputFile(key); if (file == null) { // if the file cannot be written, silently return return; } outputStream = new FileOutputStream(file); bitmap.compress(outputStream); try { lock.writeLock().lock(); if (this.lruCache.put(key.getKey(), file) != null) { LOGGER.warning("overwriting cached entry: " + key.getKey()); } } finally { lock.writeLock().unlock(); } } catch (Exception e) { // we are catching now any exception and then disable the file cache // this should ensure that no exception in the storage thread will // ever crash the main app. If there is a runtime exception, the thread // will exit (via destroy). LOGGER.log(Level.SEVERE, "Disabling filesystem cache", e); // most likely cause is that the disk is full, just disable the // cache otherwise // more and more exceptions will be thrown. this.destroy(); try { lock.writeLock().lock(); this.lruCache = new FileWorkingSetCache<String>(0); } finally { lock.writeLock().unlock(); } } finally { IOUtils.closeQuietly(outputStream); } }
[ "private", "void", "storeData", "(", "Job", "key", ",", "TileBitmap", "bitmap", ")", "{", "OutputStream", "outputStream", "=", "null", ";", "try", "{", "File", "file", "=", "getOutputFile", "(", "key", ")", ";", "if", "(", "file", "==", "null", ")", "{", "// if the file cannot be written, silently return", "return", ";", "}", "outputStream", "=", "new", "FileOutputStream", "(", "file", ")", ";", "bitmap", ".", "compress", "(", "outputStream", ")", ";", "try", "{", "lock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", "if", "(", "this", ".", "lruCache", ".", "put", "(", "key", ".", "getKey", "(", ")", ",", "file", ")", "!=", "null", ")", "{", "LOGGER", ".", "warning", "(", "\"overwriting cached entry: \"", "+", "key", ".", "getKey", "(", ")", ")", ";", "}", "}", "finally", "{", "lock", ".", "writeLock", "(", ")", ".", "unlock", "(", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "// we are catching now any exception and then disable the file cache", "// this should ensure that no exception in the storage thread will", "// ever crash the main app. If there is a runtime exception, the thread", "// will exit (via destroy).", "LOGGER", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Disabling filesystem cache\"", ",", "e", ")", ";", "// most likely cause is that the disk is full, just disable the", "// cache otherwise", "// more and more exceptions will be thrown.", "this", ".", "destroy", "(", ")", ";", "try", "{", "lock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", "this", ".", "lruCache", "=", "new", "FileWorkingSetCache", "<", "String", ">", "(", "0", ")", ";", "}", "finally", "{", "lock", ".", "writeLock", "(", ")", ".", "unlock", "(", ")", ";", "}", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "outputStream", ")", ";", "}", "}" ]
stores the bitmap data on disk with filename key @param key filename @param bitmap tile image
[ "stores", "the", "bitmap", "data", "on", "disk", "with", "filename", "key" ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/layer/cache/FileSystemTileCache.java#L387-L425
28,263
mapsforge/mapsforge
mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/ClusterMapActivity.java
ClusterMapActivity.onOptionsItemSelected
@Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case 1234: if (clusterer != null) { break; } // create clusterer instance clusterer = new ClusterManager( mapView, getMarkerBitmap(), getZoomLevelMax(), false); // Create a Toast, see e.g. http://www.mkyong.com/android/android-toast-example/ Toast toast = Toast.makeText(this, "", Toast.LENGTH_LONG); ClusterManager.setToast(toast); // this uses the framebuffer position, the mapview position can be out of sync with // what the user sees on the screen if an animation is in progress this.mapView.getModel().frameBufferModel.addObserver(clusterer); // add geoitems for clustering for (int i = 0; i < geoItems.length; i++) { clusterer.addItem(geoItems[i]); } // now redraw the cluster. it will create markers. clusterer.redraw(); displayItems.setEnabled(false); displayMoreItems.setEnabled(true); hideItems.setEnabled(true); // now you can see items clustered on the map. // zoom in/out to see how icons change. break; case 5678: setProgressBarIndeterminateVisibility(true); Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: // calling to this function from other places // The notice call method of doing things addMarker(); break; default: break; } } }; new ManyDummyContent(myHandler); item.setEnabled(false); break; case 9012: if (clusterer != null) { clusterer.destroyGeoClusterer(); this.mapView.getModel().frameBufferModel.removeObserver(clusterer); clusterer = null; } displayItems.setEnabled(true); displayMoreItems.setEnabled(false); hideItems.setEnabled(false); break; } return true; }
java
@Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case 1234: if (clusterer != null) { break; } // create clusterer instance clusterer = new ClusterManager( mapView, getMarkerBitmap(), getZoomLevelMax(), false); // Create a Toast, see e.g. http://www.mkyong.com/android/android-toast-example/ Toast toast = Toast.makeText(this, "", Toast.LENGTH_LONG); ClusterManager.setToast(toast); // this uses the framebuffer position, the mapview position can be out of sync with // what the user sees on the screen if an animation is in progress this.mapView.getModel().frameBufferModel.addObserver(clusterer); // add geoitems for clustering for (int i = 0; i < geoItems.length; i++) { clusterer.addItem(geoItems[i]); } // now redraw the cluster. it will create markers. clusterer.redraw(); displayItems.setEnabled(false); displayMoreItems.setEnabled(true); hideItems.setEnabled(true); // now you can see items clustered on the map. // zoom in/out to see how icons change. break; case 5678: setProgressBarIndeterminateVisibility(true); Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: // calling to this function from other places // The notice call method of doing things addMarker(); break; default: break; } } }; new ManyDummyContent(myHandler); item.setEnabled(false); break; case 9012: if (clusterer != null) { clusterer.destroyGeoClusterer(); this.mapView.getModel().frameBufferModel.removeObserver(clusterer); clusterer = null; } displayItems.setEnabled(true); displayMoreItems.setEnabled(false); hideItems.setEnabled(false); break; } return true; }
[ "@", "Override", "public", "boolean", "onOptionsItemSelected", "(", "MenuItem", "item", ")", "{", "super", ".", "onOptionsItemSelected", "(", "item", ")", ";", "switch", "(", "item", ".", "getItemId", "(", ")", ")", "{", "case", "1234", ":", "if", "(", "clusterer", "!=", "null", ")", "{", "break", ";", "}", "// create clusterer instance", "clusterer", "=", "new", "ClusterManager", "(", "mapView", ",", "getMarkerBitmap", "(", ")", ",", "getZoomLevelMax", "(", ")", ",", "false", ")", ";", "// Create a Toast, see e.g. http://www.mkyong.com/android/android-toast-example/", "Toast", "toast", "=", "Toast", ".", "makeText", "(", "this", ",", "\"\"", ",", "Toast", ".", "LENGTH_LONG", ")", ";", "ClusterManager", ".", "setToast", "(", "toast", ")", ";", "// this uses the framebuffer position, the mapview position can be out of sync with", "// what the user sees on the screen if an animation is in progress", "this", ".", "mapView", ".", "getModel", "(", ")", ".", "frameBufferModel", ".", "addObserver", "(", "clusterer", ")", ";", "// add geoitems for clustering", "for", "(", "int", "i", "=", "0", ";", "i", "<", "geoItems", ".", "length", ";", "i", "++", ")", "{", "clusterer", ".", "addItem", "(", "geoItems", "[", "i", "]", ")", ";", "}", "// now redraw the cluster. it will create markers.", "clusterer", ".", "redraw", "(", ")", ";", "displayItems", ".", "setEnabled", "(", "false", ")", ";", "displayMoreItems", ".", "setEnabled", "(", "true", ")", ";", "hideItems", ".", "setEnabled", "(", "true", ")", ";", "// now you can see items clustered on the map.", "// zoom in/out to see how icons change.", "break", ";", "case", "5678", ":", "setProgressBarIndeterminateVisibility", "(", "true", ")", ";", "Handler", "myHandler", "=", "new", "Handler", "(", ")", "{", "@", "Override", "public", "void", "handleMessage", "(", "Message", "msg", ")", "{", "switch", "(", "msg", ".", "what", ")", "{", "case", "0", ":", "// calling to this function from other places", "// The notice call method of doing things", "addMarker", "(", ")", ";", "break", ";", "default", ":", "break", ";", "}", "}", "}", ";", "new", "ManyDummyContent", "(", "myHandler", ")", ";", "item", ".", "setEnabled", "(", "false", ")", ";", "break", ";", "case", "9012", ":", "if", "(", "clusterer", "!=", "null", ")", "{", "clusterer", ".", "destroyGeoClusterer", "(", ")", ";", "this", ".", "mapView", ".", "getModel", "(", ")", ".", "frameBufferModel", ".", "removeObserver", "(", "clusterer", ")", ";", "clusterer", "=", "null", ";", "}", "displayItems", ".", "setEnabled", "(", "true", ")", ";", "displayMoreItems", ".", "setEnabled", "(", "false", ")", ";", "hideItems", ".", "setEnabled", "(", "false", ")", ";", "break", ";", "}", "return", "true", ";", "}" ]
onOptionsItemSelected handler since clustering need MapView to be created and visible, this sample do clustering here.
[ "onOptionsItemSelected", "handler", "since", "clustering", "need", "MapView", "to", "be", "created", "and", "visible", "this", "sample", "do", "clustering", "here", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/ClusterMapActivity.java#L205-L269
28,264
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/GeoTagger.java
GeoTagger.updateTagData
private void updateTagData(Map<Poi, Map<String, String>> pois, String key, String value) { for (Map.Entry<Poi, Map<String, String>> entry : pois.entrySet()) { Poi poi = entry.getKey(); String tmpValue = value; Map<String, String> tagmap = entry.getValue(); if (!tagmap.keySet().contains("name")) { continue; } if (tagmap.keySet().contains(key)) { // Process is_in tags if (!key.equals("is_in")) { continue; } String prev = tagmap.get(key); // Continue if tag already set correctly if (prev.contains(",") || prev.contains(";")) { continue; } // If string is a correct value, append it to existent value; if (tmpValue.contains(",") || tmpValue.contains(";")) { tmpValue = (prev + "," + tmpValue); } } //Write surrounding area as parent in "is_in" tag. tagmap.put(key, tmpValue); try { this.pStmtUpdateData.setLong(2, poi.id); this.pStmtUpdateData.setString(1, writer.tagsToString(tagmap)); this.pStmtUpdateData.addBatch(); batchCountRelation++; if (batchCountRelation % PoiWriter.BATCH_LIMIT == 0) { pStmtUpdateData.executeBatch(); pStmtUpdateData.clearBatch(); writer.conn.commit(); } } catch (SQLException e) { e.printStackTrace(); } } }
java
private void updateTagData(Map<Poi, Map<String, String>> pois, String key, String value) { for (Map.Entry<Poi, Map<String, String>> entry : pois.entrySet()) { Poi poi = entry.getKey(); String tmpValue = value; Map<String, String> tagmap = entry.getValue(); if (!tagmap.keySet().contains("name")) { continue; } if (tagmap.keySet().contains(key)) { // Process is_in tags if (!key.equals("is_in")) { continue; } String prev = tagmap.get(key); // Continue if tag already set correctly if (prev.contains(",") || prev.contains(";")) { continue; } // If string is a correct value, append it to existent value; if (tmpValue.contains(",") || tmpValue.contains(";")) { tmpValue = (prev + "," + tmpValue); } } //Write surrounding area as parent in "is_in" tag. tagmap.put(key, tmpValue); try { this.pStmtUpdateData.setLong(2, poi.id); this.pStmtUpdateData.setString(1, writer.tagsToString(tagmap)); this.pStmtUpdateData.addBatch(); batchCountRelation++; if (batchCountRelation % PoiWriter.BATCH_LIMIT == 0) { pStmtUpdateData.executeBatch(); pStmtUpdateData.clearBatch(); writer.conn.commit(); } } catch (SQLException e) { e.printStackTrace(); } } }
[ "private", "void", "updateTagData", "(", "Map", "<", "Poi", ",", "Map", "<", "String", ",", "String", ">", ">", "pois", ",", "String", "key", ",", "String", "value", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Poi", ",", "Map", "<", "String", ",", "String", ">", ">", "entry", ":", "pois", ".", "entrySet", "(", ")", ")", "{", "Poi", "poi", "=", "entry", ".", "getKey", "(", ")", ";", "String", "tmpValue", "=", "value", ";", "Map", "<", "String", ",", "String", ">", "tagmap", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "!", "tagmap", ".", "keySet", "(", ")", ".", "contains", "(", "\"name\"", ")", ")", "{", "continue", ";", "}", "if", "(", "tagmap", ".", "keySet", "(", ")", ".", "contains", "(", "key", ")", ")", "{", "// Process is_in tags", "if", "(", "!", "key", ".", "equals", "(", "\"is_in\"", ")", ")", "{", "continue", ";", "}", "String", "prev", "=", "tagmap", ".", "get", "(", "key", ")", ";", "// Continue if tag already set correctly", "if", "(", "prev", ".", "contains", "(", "\",\"", ")", "||", "prev", ".", "contains", "(", "\";\"", ")", ")", "{", "continue", ";", "}", "// If string is a correct value, append it to existent value;", "if", "(", "tmpValue", ".", "contains", "(", "\",\"", ")", "||", "tmpValue", ".", "contains", "(", "\";\"", ")", ")", "{", "tmpValue", "=", "(", "prev", "+", "\",\"", "+", "tmpValue", ")", ";", "}", "}", "//Write surrounding area as parent in \"is_in\" tag.", "tagmap", ".", "put", "(", "key", ",", "tmpValue", ")", ";", "try", "{", "this", ".", "pStmtUpdateData", ".", "setLong", "(", "2", ",", "poi", ".", "id", ")", ";", "this", ".", "pStmtUpdateData", ".", "setString", "(", "1", ",", "writer", ".", "tagsToString", "(", "tagmap", ")", ")", ";", "this", ".", "pStmtUpdateData", ".", "addBatch", "(", ")", ";", "batchCountRelation", "++", ";", "if", "(", "batchCountRelation", "%", "PoiWriter", ".", "BATCH_LIMIT", "==", "0", ")", "{", "pStmtUpdateData", ".", "executeBatch", "(", ")", ";", "pStmtUpdateData", ".", "clearBatch", "(", ")", ";", "writer", ".", "conn", ".", "commit", "(", ")", ";", "}", "}", "catch", "(", "SQLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}" ]
Updates the tags of a POI-List with key and value. @param pois Pois, which should be tagged @param key The tag key @param value The tag value
[ "Updates", "the", "tags", "of", "a", "POI", "-", "List", "with", "key", "and", "value", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/GeoTagger.java#L334-L378
28,265
mapsforge/mapsforge
mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/model/TDRelation.java
TDRelation.fromRelation
public static TDRelation fromRelation(Relation relation, WayResolver resolver, List<String> preferredLanguages) { if (relation == null) { return null; } if (relation.getMembers().isEmpty()) { return null; } SpecialTagExtractionResult ster = OSMUtils.extractSpecialFields(relation, preferredLanguages); Map<Short, Object> knownWayTags = OSMUtils.extractKnownWayTags(relation); // special tags // TODO what about the layer of relations? // TODO exclude boundaries if (!knownRelationType(ster.getType())) { return null; } List<RelationMember> members = relation.getMembers(); List<TDWay> wayMembers = new ArrayList<>(); for (RelationMember relationMember : members) { if (relationMember.getMemberType() != EntityType.Way) { continue; } TDWay member = resolver.getWay(relationMember.getMemberId()); if (member == null) { LOGGER.finest("relation is missing a member, rel-id: " + relation.getId() + " member id: " + relationMember.getMemberId()); continue; } wayMembers.add(member); } if (wayMembers.isEmpty()) { LOGGER.finest("relation has no valid members: " + relation.getId()); return null; } return new TDRelation(relation.getId(), ster.getLayer(), ster.getName(), ster.getHousenumber(), ster.getRef(), knownWayTags, wayMembers.toArray(new TDWay[wayMembers.size()])); }
java
public static TDRelation fromRelation(Relation relation, WayResolver resolver, List<String> preferredLanguages) { if (relation == null) { return null; } if (relation.getMembers().isEmpty()) { return null; } SpecialTagExtractionResult ster = OSMUtils.extractSpecialFields(relation, preferredLanguages); Map<Short, Object> knownWayTags = OSMUtils.extractKnownWayTags(relation); // special tags // TODO what about the layer of relations? // TODO exclude boundaries if (!knownRelationType(ster.getType())) { return null; } List<RelationMember> members = relation.getMembers(); List<TDWay> wayMembers = new ArrayList<>(); for (RelationMember relationMember : members) { if (relationMember.getMemberType() != EntityType.Way) { continue; } TDWay member = resolver.getWay(relationMember.getMemberId()); if (member == null) { LOGGER.finest("relation is missing a member, rel-id: " + relation.getId() + " member id: " + relationMember.getMemberId()); continue; } wayMembers.add(member); } if (wayMembers.isEmpty()) { LOGGER.finest("relation has no valid members: " + relation.getId()); return null; } return new TDRelation(relation.getId(), ster.getLayer(), ster.getName(), ster.getHousenumber(), ster.getRef(), knownWayTags, wayMembers.toArray(new TDWay[wayMembers.size()])); }
[ "public", "static", "TDRelation", "fromRelation", "(", "Relation", "relation", ",", "WayResolver", "resolver", ",", "List", "<", "String", ">", "preferredLanguages", ")", "{", "if", "(", "relation", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "relation", ".", "getMembers", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "SpecialTagExtractionResult", "ster", "=", "OSMUtils", ".", "extractSpecialFields", "(", "relation", ",", "preferredLanguages", ")", ";", "Map", "<", "Short", ",", "Object", ">", "knownWayTags", "=", "OSMUtils", ".", "extractKnownWayTags", "(", "relation", ")", ";", "// special tags", "// TODO what about the layer of relations?", "// TODO exclude boundaries", "if", "(", "!", "knownRelationType", "(", "ster", ".", "getType", "(", ")", ")", ")", "{", "return", "null", ";", "}", "List", "<", "RelationMember", ">", "members", "=", "relation", ".", "getMembers", "(", ")", ";", "List", "<", "TDWay", ">", "wayMembers", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "RelationMember", "relationMember", ":", "members", ")", "{", "if", "(", "relationMember", ".", "getMemberType", "(", ")", "!=", "EntityType", ".", "Way", ")", "{", "continue", ";", "}", "TDWay", "member", "=", "resolver", ".", "getWay", "(", "relationMember", ".", "getMemberId", "(", ")", ")", ";", "if", "(", "member", "==", "null", ")", "{", "LOGGER", ".", "finest", "(", "\"relation is missing a member, rel-id: \"", "+", "relation", ".", "getId", "(", ")", "+", "\" member id: \"", "+", "relationMember", ".", "getMemberId", "(", ")", ")", ";", "continue", ";", "}", "wayMembers", ".", "add", "(", "member", ")", ";", "}", "if", "(", "wayMembers", ".", "isEmpty", "(", ")", ")", "{", "LOGGER", ".", "finest", "(", "\"relation has no valid members: \"", "+", "relation", ".", "getId", "(", ")", ")", ";", "return", "null", ";", "}", "return", "new", "TDRelation", "(", "relation", ".", "getId", "(", ")", ",", "ster", ".", "getLayer", "(", ")", ",", "ster", ".", "getName", "(", ")", ",", "ster", ".", "getHousenumber", "(", ")", ",", "ster", ".", "getRef", "(", ")", ",", "knownWayTags", ",", "wayMembers", ".", "toArray", "(", "new", "TDWay", "[", "wayMembers", ".", "size", "(", ")", "]", ")", ")", ";", "}" ]
Creates a new TDRelation from an osmosis entity using the given WayResolver. @param relation the relation @param resolver the resolver @param preferredLanguages the preferred(s) language or null if no preference @return a new TDRelation if all members are valid and the relation is of a known type, null otherwise
[ "Creates", "a", "new", "TDRelation", "from", "an", "osmosis", "entity", "using", "the", "given", "WayResolver", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/model/TDRelation.java#L45-L88
28,266
mapsforge/mapsforge
mapsforge-map/src/main/java/org/mapsforge/map/layer/GroupLayer.java
GroupLayer.onTap
@Override public boolean onTap(LatLong tapLatLong, Point layerXY, Point tapXY) { for (int i = layers.size() - 1; i >= 0; i--) { Layer layer = layers.get(i); if (layer.onTap(tapLatLong, layerXY, tapXY)) { return true; } } return false; }
java
@Override public boolean onTap(LatLong tapLatLong, Point layerXY, Point tapXY) { for (int i = layers.size() - 1; i >= 0; i--) { Layer layer = layers.get(i); if (layer.onTap(tapLatLong, layerXY, tapXY)) { return true; } } return false; }
[ "@", "Override", "public", "boolean", "onTap", "(", "LatLong", "tapLatLong", ",", "Point", "layerXY", ",", "Point", "tapXY", ")", "{", "for", "(", "int", "i", "=", "layers", ".", "size", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "Layer", "layer", "=", "layers", ".", "get", "(", "i", ")", ";", "if", "(", "layer", ".", "onTap", "(", "tapLatLong", ",", "layerXY", ",", "tapXY", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
GroupLayer does not have a position, layerXY is null.
[ "GroupLayer", "does", "not", "have", "a", "position", "layerXY", "is", "null", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/layer/GroupLayer.java#L71-L80
28,267
mapsforge/mapsforge
mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/ClusterManager.java
ClusterManager.isItemInViewport
protected boolean isItemInViewport(final GeoItem item) { BoundingBox curBounds = getCurBounds(); return curBounds != null && curBounds.contains(item.getLatLong()); }
java
protected boolean isItemInViewport(final GeoItem item) { BoundingBox curBounds = getCurBounds(); return curBounds != null && curBounds.contains(item.getLatLong()); }
[ "protected", "boolean", "isItemInViewport", "(", "final", "GeoItem", "item", ")", "{", "BoundingBox", "curBounds", "=", "getCurBounds", "(", ")", ";", "return", "curBounds", "!=", "null", "&&", "curBounds", ".", "contains", "(", "item", ".", "getLatLong", "(", ")", ")", ";", "}" ]
check if the item is within current viewport. @return true if item is within viewport.
[ "check", "if", "the", "item", "is", "within", "current", "viewport", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/ClusterManager.java#L267-L270
28,268
mapsforge/mapsforge
mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/ClusterManager.java
ClusterManager.getCurBounds
protected synchronized BoundingBox getCurBounds() { if (currBoundingBox == null) { if (mapView == null) { throw new NullPointerException("mapView == null"); } if (mapView.getWidth() <= 0 || mapView.getHeight() <= 0) { throw new IllegalArgumentException(" mapView.getWidth() <= 0 " + "|| mapView.getHeight() <= 0 " + mapView.getWidth() + " || " + mapView.getHeight()); } /** North-West geo point of the bound */ LatLong nw_ = mapView.getMapViewProjection().fromPixels(0, 0); // Log.e(TAG, " nw_.latitude => " + nw_.latitude + " nw_.longitude => " + nw_.longitude ); /** South-East geo point of the bound */ LatLong se_ = mapView.getMapViewProjection().fromPixels(mapView.getWidth(), mapView.getHeight()); // Log.e(TAG, " se_.latitude => " + se_.latitude + " se_.longitude => " + se_.longitude ); if (nw_ != null && se_ != null) { if (se_.latitude > nw_.latitude) { currBoundingBox = new BoundingBox(nw_.latitude, se_.longitude, se_.latitude, nw_.longitude); } else { currBoundingBox = new BoundingBox(se_.latitude, nw_.longitude, nw_.latitude, se_.longitude); } } } return currBoundingBox; }
java
protected synchronized BoundingBox getCurBounds() { if (currBoundingBox == null) { if (mapView == null) { throw new NullPointerException("mapView == null"); } if (mapView.getWidth() <= 0 || mapView.getHeight() <= 0) { throw new IllegalArgumentException(" mapView.getWidth() <= 0 " + "|| mapView.getHeight() <= 0 " + mapView.getWidth() + " || " + mapView.getHeight()); } /** North-West geo point of the bound */ LatLong nw_ = mapView.getMapViewProjection().fromPixels(0, 0); // Log.e(TAG, " nw_.latitude => " + nw_.latitude + " nw_.longitude => " + nw_.longitude ); /** South-East geo point of the bound */ LatLong se_ = mapView.getMapViewProjection().fromPixels(mapView.getWidth(), mapView.getHeight()); // Log.e(TAG, " se_.latitude => " + se_.latitude + " se_.longitude => " + se_.longitude ); if (nw_ != null && se_ != null) { if (se_.latitude > nw_.latitude) { currBoundingBox = new BoundingBox(nw_.latitude, se_.longitude, se_.latitude, nw_.longitude); } else { currBoundingBox = new BoundingBox(se_.latitude, nw_.longitude, nw_.latitude, se_.longitude); } } } return currBoundingBox; }
[ "protected", "synchronized", "BoundingBox", "getCurBounds", "(", ")", "{", "if", "(", "currBoundingBox", "==", "null", ")", "{", "if", "(", "mapView", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"mapView == null\"", ")", ";", "}", "if", "(", "mapView", ".", "getWidth", "(", ")", "<=", "0", "||", "mapView", ".", "getHeight", "(", ")", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\" mapView.getWidth() <= 0 \"", "+", "\"|| mapView.getHeight() <= 0 \"", "+", "mapView", ".", "getWidth", "(", ")", "+", "\" || \"", "+", "mapView", ".", "getHeight", "(", ")", ")", ";", "}", "/** North-West geo point of the bound */", "LatLong", "nw_", "=", "mapView", ".", "getMapViewProjection", "(", ")", ".", "fromPixels", "(", "0", ",", "0", ")", ";", "// Log.e(TAG, \" nw_.latitude => \" + nw_.latitude + \" nw_.longitude => \" + nw_.longitude );", "/** South-East geo point of the bound */", "LatLong", "se_", "=", "mapView", ".", "getMapViewProjection", "(", ")", ".", "fromPixels", "(", "mapView", ".", "getWidth", "(", ")", ",", "mapView", ".", "getHeight", "(", ")", ")", ";", "// Log.e(TAG, \" se_.latitude => \" + se_.latitude + \" se_.longitude => \" + se_.longitude );", "if", "(", "nw_", "!=", "null", "&&", "se_", "!=", "null", ")", "{", "if", "(", "se_", ".", "latitude", ">", "nw_", ".", "latitude", ")", "{", "currBoundingBox", "=", "new", "BoundingBox", "(", "nw_", ".", "latitude", ",", "se_", ".", "longitude", ",", "se_", ".", "latitude", ",", "nw_", ".", "longitude", ")", ";", "}", "else", "{", "currBoundingBox", "=", "new", "BoundingBox", "(", "se_", ".", "latitude", ",", "nw_", ".", "longitude", ",", "nw_", ".", "latitude", ",", "se_", ".", "longitude", ")", ";", "}", "}", "}", "return", "currBoundingBox", ";", "}" ]
get the current BoundingBox of the viewport @return current BoundingBox of the viewport
[ "get", "the", "current", "BoundingBox", "of", "the", "viewport" ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/ClusterManager.java#L277-L305
28,269
mapsforge/mapsforge
mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/ClusterManager.java
ClusterManager.addLeftItems
private void addLeftItems() { // Log.w(TAG,"addLeftItems() {.... (0)"); if (leftItems.size() == 0) { return; } // Log.w(TAG,"addLeftItems() {.... (1)"); ArrayList<T> currentLeftItems = new ArrayList<T>(); currentLeftItems.addAll(leftItems); // Log.w(TAG,"addLeftItems() {.... (2)"); synchronized (leftItems) { // Log.w(TAG,"addLeftItems() {.... (3.1)"); leftItems.clear(); // Log.w(TAG,"addLeftItems() {.... (3.1)"); } // Log.w(TAG,"addLeftItems() {.... (4)"); for (T currentLeftItem : currentLeftItems) { // Log.w(TAG,"addLeftItems() {.... (5.1)"); addItem(currentLeftItem); // Log.w(TAG,"addLeftItems() {.... (5.2)"); } }
java
private void addLeftItems() { // Log.w(TAG,"addLeftItems() {.... (0)"); if (leftItems.size() == 0) { return; } // Log.w(TAG,"addLeftItems() {.... (1)"); ArrayList<T> currentLeftItems = new ArrayList<T>(); currentLeftItems.addAll(leftItems); // Log.w(TAG,"addLeftItems() {.... (2)"); synchronized (leftItems) { // Log.w(TAG,"addLeftItems() {.... (3.1)"); leftItems.clear(); // Log.w(TAG,"addLeftItems() {.... (3.1)"); } // Log.w(TAG,"addLeftItems() {.... (4)"); for (T currentLeftItem : currentLeftItems) { // Log.w(TAG,"addLeftItems() {.... (5.1)"); addItem(currentLeftItem); // Log.w(TAG,"addLeftItems() {.... (5.2)"); } }
[ "private", "void", "addLeftItems", "(", ")", "{", "// Log.w(TAG,\"addLeftItems() {.... (0)\");", "if", "(", "leftItems", ".", "size", "(", ")", "==", "0", ")", "{", "return", ";", "}", "// Log.w(TAG,\"addLeftItems() {.... (1)\");", "ArrayList", "<", "T", ">", "currentLeftItems", "=", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "currentLeftItems", ".", "addAll", "(", "leftItems", ")", ";", "// Log.w(TAG,\"addLeftItems() {.... (2)\");", "synchronized", "(", "leftItems", ")", "{", "// Log.w(TAG,\"addLeftItems() {.... (3.1)\");", "leftItems", ".", "clear", "(", ")", ";", "// Log.w(TAG,\"addLeftItems() {.... (3.1)\");", "}", "// Log.w(TAG,\"addLeftItems() {.... (4)\");", "for", "(", "T", "currentLeftItem", ":", "currentLeftItems", ")", "{", "// Log.w(TAG,\"addLeftItems() {.... (5.1)\");", "addItem", "(", "currentLeftItem", ")", ";", "// Log.w(TAG,\"addLeftItems() {.... (5.2)\");", "}", "}" ]
add items that were not clustered in last isClustering.
[ "add", "items", "that", "were", "not", "clustered", "in", "last", "isClustering", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/ClusterManager.java#L310-L332
28,270
mapsforge/mapsforge
mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/ClusterManager.java
ClusterManager.resetViewport
private synchronized void resetViewport(boolean isMoving) { isClustering = true; clusterTask = new ClusterTask(); clusterTask.execute(new Boolean[]{isMoving}); }
java
private synchronized void resetViewport(boolean isMoving) { isClustering = true; clusterTask = new ClusterTask(); clusterTask.execute(new Boolean[]{isMoving}); }
[ "private", "synchronized", "void", "resetViewport", "(", "boolean", "isMoving", ")", "{", "isClustering", "=", "true", ";", "clusterTask", "=", "new", "ClusterTask", "(", ")", ";", "clusterTask", ".", "execute", "(", "new", "Boolean", "[", "]", "{", "isMoving", "}", ")", ";", "}" ]
reset current viewport, re-cluster the items when zoom has changed, else add not clustered items .
[ "reset", "current", "viewport", "re", "-", "cluster", "the", "items", "when", "zoom", "has", "changed", "else", "add", "not", "clustered", "items", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/ClusterManager.java#L370-L374
28,271
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.commit
private void commit() throws SQLException { LOGGER.info("Committing..."); this.progressManager.setMessage("Committing..."); this.pStmtIndex.executeBatch(); this.pStmtData.executeBatch(); this.pStmtCatMap.executeBatch(); if (this.configuration.isGeoTags()) { this.geoTagger.commit(); } this.conn.commit(); }
java
private void commit() throws SQLException { LOGGER.info("Committing..."); this.progressManager.setMessage("Committing..."); this.pStmtIndex.executeBatch(); this.pStmtData.executeBatch(); this.pStmtCatMap.executeBatch(); if (this.configuration.isGeoTags()) { this.geoTagger.commit(); } this.conn.commit(); }
[ "private", "void", "commit", "(", ")", "throws", "SQLException", "{", "LOGGER", ".", "info", "(", "\"Committing...\"", ")", ";", "this", ".", "progressManager", ".", "setMessage", "(", "\"Committing...\"", ")", ";", "this", ".", "pStmtIndex", ".", "executeBatch", "(", ")", ";", "this", ".", "pStmtData", ".", "executeBatch", "(", ")", ";", "this", ".", "pStmtCatMap", ".", "executeBatch", "(", ")", ";", "if", "(", "this", ".", "configuration", ".", "isGeoTags", "(", ")", ")", "{", "this", ".", "geoTagger", ".", "commit", "(", ")", ";", "}", "this", ".", "conn", ".", "commit", "(", ")", ";", "}" ]
Commit changes.
[ "Commit", "changes", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L168-L178
28,272
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.complete
public void complete() { if (this.configuration.isGeoTags()) { this.geoTagger.processBoundaries(); } NumberFormat nfMegabyte = NumberFormat.getInstance(); nfMegabyte.setMaximumFractionDigits(2); try { commit(); if (this.configuration.isFilterCategories()) { filterCategories(); } writeMetadata(); this.conn.close(); postProcess(); } catch (SQLException e) { e.printStackTrace(); } LOGGER.info("Added " + nfCounts.format(this.poiAdded) + " POIs."); this.progressManager.setMessage("Done."); LOGGER.info("Estimated memory consumption: " + nfMegabyte.format(+((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / Math .pow(1024, 2))) + "MB"); }
java
public void complete() { if (this.configuration.isGeoTags()) { this.geoTagger.processBoundaries(); } NumberFormat nfMegabyte = NumberFormat.getInstance(); nfMegabyte.setMaximumFractionDigits(2); try { commit(); if (this.configuration.isFilterCategories()) { filterCategories(); } writeMetadata(); this.conn.close(); postProcess(); } catch (SQLException e) { e.printStackTrace(); } LOGGER.info("Added " + nfCounts.format(this.poiAdded) + " POIs."); this.progressManager.setMessage("Done."); LOGGER.info("Estimated memory consumption: " + nfMegabyte.format(+((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / Math .pow(1024, 2))) + "MB"); }
[ "public", "void", "complete", "(", ")", "{", "if", "(", "this", ".", "configuration", ".", "isGeoTags", "(", ")", ")", "{", "this", ".", "geoTagger", ".", "processBoundaries", "(", ")", ";", "}", "NumberFormat", "nfMegabyte", "=", "NumberFormat", ".", "getInstance", "(", ")", ";", "nfMegabyte", ".", "setMaximumFractionDigits", "(", "2", ")", ";", "try", "{", "commit", "(", ")", ";", "if", "(", "this", ".", "configuration", ".", "isFilterCategories", "(", ")", ")", "{", "filterCategories", "(", ")", ";", "}", "writeMetadata", "(", ")", ";", "this", ".", "conn", ".", "close", "(", ")", ";", "postProcess", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "LOGGER", ".", "info", "(", "\"Added \"", "+", "nfCounts", ".", "format", "(", "this", ".", "poiAdded", ")", "+", "\" POIs.\"", ")", ";", "this", ".", "progressManager", ".", "setMessage", "(", "\"Done.\"", ")", ";", "LOGGER", ".", "info", "(", "\"Estimated memory consumption: \"", "+", "nfMegabyte", ".", "format", "(", "+", "(", "(", "Runtime", ".", "getRuntime", "(", ")", ".", "totalMemory", "(", ")", "-", "Runtime", ".", "getRuntime", "(", ")", ".", "freeMemory", "(", ")", ")", "/", "Math", ".", "pow", "(", "1024", ",", "2", ")", ")", ")", "+", "\"MB\"", ")", ";", "}" ]
Complete task.
[ "Complete", "task", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L183-L209
28,273
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.filterCategories
private void filterCategories() throws SQLException { LOGGER.info("Filtering categories..."); PreparedStatement pStmtChildren = this.conn.prepareStatement("SELECT COUNT(*) FROM poi_categories WHERE parent = ?;"); PreparedStatement pStmtPoi = this.conn.prepareStatement("SELECT COUNT(*) FROM poi_category_map WHERE category = ?;"); PreparedStatement pStmtDel = this.conn.prepareStatement("DELETE FROM poi_categories WHERE id = ?;"); Statement stmt = this.conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id FROM poi_categories ORDER BY id;"); while (rs.next()) { int id = rs.getInt(1); pStmtChildren.setInt(1, id); ResultSet rsChildren = pStmtChildren.executeQuery(); if (rsChildren.next()) { long nChildren = rsChildren.getLong(1); if (nChildren == 0) { pStmtPoi.setInt(1, id); ResultSet rsPoi = pStmtPoi.executeQuery(); if (rsPoi.next()) { long nPoi = rsPoi.getLong(1); // If category not have POI, delete it from DB if (nPoi == 0) { pStmtDel.setInt(1, id); pStmtDel.executeUpdate(); } } } } } }
java
private void filterCategories() throws SQLException { LOGGER.info("Filtering categories..."); PreparedStatement pStmtChildren = this.conn.prepareStatement("SELECT COUNT(*) FROM poi_categories WHERE parent = ?;"); PreparedStatement pStmtPoi = this.conn.prepareStatement("SELECT COUNT(*) FROM poi_category_map WHERE category = ?;"); PreparedStatement pStmtDel = this.conn.prepareStatement("DELETE FROM poi_categories WHERE id = ?;"); Statement stmt = this.conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id FROM poi_categories ORDER BY id;"); while (rs.next()) { int id = rs.getInt(1); pStmtChildren.setInt(1, id); ResultSet rsChildren = pStmtChildren.executeQuery(); if (rsChildren.next()) { long nChildren = rsChildren.getLong(1); if (nChildren == 0) { pStmtPoi.setInt(1, id); ResultSet rsPoi = pStmtPoi.executeQuery(); if (rsPoi.next()) { long nPoi = rsPoi.getLong(1); // If category not have POI, delete it from DB if (nPoi == 0) { pStmtDel.setInt(1, id); pStmtDel.executeUpdate(); } } } } } }
[ "private", "void", "filterCategories", "(", ")", "throws", "SQLException", "{", "LOGGER", ".", "info", "(", "\"Filtering categories...\"", ")", ";", "PreparedStatement", "pStmtChildren", "=", "this", ".", "conn", ".", "prepareStatement", "(", "\"SELECT COUNT(*) FROM poi_categories WHERE parent = ?;\"", ")", ";", "PreparedStatement", "pStmtPoi", "=", "this", ".", "conn", ".", "prepareStatement", "(", "\"SELECT COUNT(*) FROM poi_category_map WHERE category = ?;\"", ")", ";", "PreparedStatement", "pStmtDel", "=", "this", ".", "conn", ".", "prepareStatement", "(", "\"DELETE FROM poi_categories WHERE id = ?;\"", ")", ";", "Statement", "stmt", "=", "this", ".", "conn", ".", "createStatement", "(", ")", ";", "ResultSet", "rs", "=", "stmt", ".", "executeQuery", "(", "\"SELECT id FROM poi_categories ORDER BY id;\"", ")", ";", "while", "(", "rs", ".", "next", "(", ")", ")", "{", "int", "id", "=", "rs", ".", "getInt", "(", "1", ")", ";", "pStmtChildren", ".", "setInt", "(", "1", ",", "id", ")", ";", "ResultSet", "rsChildren", "=", "pStmtChildren", ".", "executeQuery", "(", ")", ";", "if", "(", "rsChildren", ".", "next", "(", ")", ")", "{", "long", "nChildren", "=", "rsChildren", ".", "getLong", "(", "1", ")", ";", "if", "(", "nChildren", "==", "0", ")", "{", "pStmtPoi", ".", "setInt", "(", "1", ",", "id", ")", ";", "ResultSet", "rsPoi", "=", "pStmtPoi", ".", "executeQuery", "(", ")", ";", "if", "(", "rsPoi", ".", "next", "(", ")", ")", "{", "long", "nPoi", "=", "rsPoi", ".", "getLong", "(", "1", ")", ";", "// If category not have POI, delete it from DB", "if", "(", "nPoi", "==", "0", ")", "{", "pStmtDel", ".", "setInt", "(", "1", ",", "id", ")", ";", "pStmtDel", ".", "executeUpdate", "(", ")", ";", "}", "}", "}", "}", "}", "}" ]
Filter categories, i.e. without POIs and children.
[ "Filter", "categories", "i", ".", "e", ".", "without", "POIs", "and", "children", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L214-L241
28,274
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.findWayNodesByWayID
List<Long> findWayNodesByWayID(long id) { try { this.pStmtWayNodesR.setLong(1, id); ResultSet rs = this.pStmtWayNodesR.executeQuery(); Map<Integer, Long> nodeList = new TreeMap<>(); while (rs.next()) { // way, node, position Long nodeID = rs.getLong(1); Integer pos = rs.getInt(2); nodeList.put(pos, nodeID); } rs.close(); return new ArrayList<>(nodeList.values()); } catch (SQLException e) { e.printStackTrace(); } return null; }
java
List<Long> findWayNodesByWayID(long id) { try { this.pStmtWayNodesR.setLong(1, id); ResultSet rs = this.pStmtWayNodesR.executeQuery(); Map<Integer, Long> nodeList = new TreeMap<>(); while (rs.next()) { // way, node, position Long nodeID = rs.getLong(1); Integer pos = rs.getInt(2); nodeList.put(pos, nodeID); } rs.close(); return new ArrayList<>(nodeList.values()); } catch (SQLException e) { e.printStackTrace(); } return null; }
[ "List", "<", "Long", ">", "findWayNodesByWayID", "(", "long", "id", ")", "{", "try", "{", "this", ".", "pStmtWayNodesR", ".", "setLong", "(", "1", ",", "id", ")", ";", "ResultSet", "rs", "=", "this", ".", "pStmtWayNodesR", ".", "executeQuery", "(", ")", ";", "Map", "<", "Integer", ",", "Long", ">", "nodeList", "=", "new", "TreeMap", "<>", "(", ")", ";", "while", "(", "rs", ".", "next", "(", ")", ")", "{", "// way, node, position", "Long", "nodeID", "=", "rs", ".", "getLong", "(", "1", ")", ";", "Integer", "pos", "=", "rs", ".", "getInt", "(", "2", ")", ";", "nodeList", ".", "put", "(", "pos", ",", "nodeID", ")", ";", "}", "rs", ".", "close", "(", ")", ";", "return", "new", "ArrayList", "<>", "(", "nodeList", ".", "values", "(", ")", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "null", ";", "}" ]
Find way nodes by its ID.
[ "Find", "way", "nodes", "by", "its", "ID", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L268-L286
28,275
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.getTagValue
String getTagValue(Collection<Tag> tags, String key) { for (Tag tag : tags) { if (tag.getKey().toLowerCase(Locale.ENGLISH).equals(key.toLowerCase(Locale.ENGLISH))) { return tag.getValue(); } } return null; }
java
String getTagValue(Collection<Tag> tags, String key) { for (Tag tag : tags) { if (tag.getKey().toLowerCase(Locale.ENGLISH).equals(key.toLowerCase(Locale.ENGLISH))) { return tag.getValue(); } } return null; }
[ "String", "getTagValue", "(", "Collection", "<", "Tag", ">", "tags", ",", "String", "key", ")", "{", "for", "(", "Tag", "tag", ":", "tags", ")", "{", "if", "(", "tag", ".", "getKey", "(", ")", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", ".", "equals", "(", "key", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", ")", ")", "{", "return", "tag", ".", "getValue", "(", ")", ";", "}", "}", "return", "null", ";", "}" ]
Returns value of given tag in a set of tags. @param tags collection of tags @param key tag key @return Tag value or null if not exists
[ "Returns", "value", "of", "given", "tag", "in", "a", "set", "of", "tags", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L295-L302
28,276
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.postProcess
private void postProcess() throws SQLException { LOGGER.info("Post-processing..."); this.conn = DriverManager.getConnection("jdbc:sqlite:" + this.configuration.getOutputFile().getAbsolutePath()); this.conn.createStatement().execute(DbConstants.DROP_NODES_STATEMENT); this.conn.createStatement().execute(DbConstants.DROP_WAYNODES_STATEMENT); this.conn.close(); this.conn = DriverManager.getConnection("jdbc:sqlite:" + this.configuration.getOutputFile().getAbsolutePath()); this.conn.createStatement().execute("VACUUM;"); this.conn.close(); }
java
private void postProcess() throws SQLException { LOGGER.info("Post-processing..."); this.conn = DriverManager.getConnection("jdbc:sqlite:" + this.configuration.getOutputFile().getAbsolutePath()); this.conn.createStatement().execute(DbConstants.DROP_NODES_STATEMENT); this.conn.createStatement().execute(DbConstants.DROP_WAYNODES_STATEMENT); this.conn.close(); this.conn = DriverManager.getConnection("jdbc:sqlite:" + this.configuration.getOutputFile().getAbsolutePath()); this.conn.createStatement().execute("VACUUM;"); this.conn.close(); }
[ "private", "void", "postProcess", "(", ")", "throws", "SQLException", "{", "LOGGER", ".", "info", "(", "\"Post-processing...\"", ")", ";", "this", ".", "conn", "=", "DriverManager", ".", "getConnection", "(", "\"jdbc:sqlite:\"", "+", "this", ".", "configuration", ".", "getOutputFile", "(", ")", ".", "getAbsolutePath", "(", ")", ")", ";", "this", ".", "conn", ".", "createStatement", "(", ")", ".", "execute", "(", "DbConstants", ".", "DROP_NODES_STATEMENT", ")", ";", "this", ".", "conn", ".", "createStatement", "(", ")", ".", "execute", "(", "DbConstants", ".", "DROP_WAYNODES_STATEMENT", ")", ";", "this", ".", "conn", ".", "close", "(", ")", ";", "this", ".", "conn", "=", "DriverManager", ".", "getConnection", "(", "\"jdbc:sqlite:\"", "+", "this", ".", "configuration", ".", "getOutputFile", "(", ")", ".", "getAbsolutePath", "(", ")", ")", ";", "this", ".", "conn", ".", "createStatement", "(", ")", ".", "execute", "(", "\"VACUUM;\"", ")", ";", "this", ".", "conn", ".", "close", "(", ")", ";", "}" ]
Post-process.
[ "Post", "-", "process", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L307-L318
28,277
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.prepareDatabase
private void prepareDatabase() throws ClassNotFoundException, SQLException, UnknownPoiCategoryException { Class.forName("org.sqlite.JDBC"); this.conn = DriverManager.getConnection("jdbc:sqlite:" + this.configuration.getOutputFile().getAbsolutePath()); this.conn.setAutoCommit(false); Statement stmt = this.conn.createStatement(); // Create tables stmt.execute(DbConstants.DROP_WAYNODES_STATEMENT); stmt.execute(DbConstants.DROP_NODES_STATEMENT); stmt.execute(DbConstants.DROP_METADATA_STATEMENT); stmt.execute(DbConstants.DROP_INDEX_STATEMENT); stmt.execute(DbConstants.DROP_CATEGORY_MAP_STATEMENT); stmt.execute(DbConstants.DROP_DATA_STATEMENT); stmt.execute(DbConstants.DROP_CATEGORIES_STATEMENT); stmt.execute(DbConstants.CREATE_CATEGORIES_STATEMENT); stmt.execute(DbConstants.CREATE_DATA_STATEMENT); stmt.execute(DbConstants.CREATE_CATEGORY_MAP_STATEMENT); stmt.execute(DbConstants.CREATE_INDEX_STATEMENT); stmt.execute(DbConstants.CREATE_METADATA_STATEMENT); stmt.execute(DbConstants.CREATE_NODES_STATEMENT); stmt.execute(DbConstants.CREATE_WAYNODES_STATEMENT); this.pStmtCatMap = this.conn.prepareStatement(DbConstants.INSERT_CATEGORY_MAP_STATEMENT); this.pStmtData = this.conn.prepareStatement(DbConstants.INSERT_DATA_STATEMENT); this.pStmtIndex = this.conn.prepareStatement(DbConstants.INSERT_INDEX_STATEMENT); this.pStmtNodesC = this.conn.prepareStatement(DbConstants.INSERT_NODES_STATEMENT); this.pStmtNodesR = this.conn.prepareStatement(DbConstants.FIND_NODES_STATEMENT); this.pStmtWayNodesR = this.conn.prepareStatement(DbConstants.FIND_WAYNODES_BY_ID_STATEMENT); // Insert categories PreparedStatement pStmt = this.conn.prepareStatement(DbConstants.INSERT_CATEGORIES_STATEMENT); PoiCategory root = this.categoryManager.getRootCategory(); pStmt.setLong(1, root.getID()); pStmt.setString(2, root.getTitle()); pStmt.setNull(3, 0); pStmt.addBatch(); Stack<PoiCategory> children = new Stack<>(); children.push(root); while (!children.isEmpty()) { for (PoiCategory c : children.pop().getChildren()) { pStmt.setLong(1, c.getID()); pStmt.setString(2, c.getTitle()); pStmt.setInt(3, c.getParent().getID()); pStmt.addBatch(); children.push(c); } } pStmt.executeBatch(); this.conn.commit(); }
java
private void prepareDatabase() throws ClassNotFoundException, SQLException, UnknownPoiCategoryException { Class.forName("org.sqlite.JDBC"); this.conn = DriverManager.getConnection("jdbc:sqlite:" + this.configuration.getOutputFile().getAbsolutePath()); this.conn.setAutoCommit(false); Statement stmt = this.conn.createStatement(); // Create tables stmt.execute(DbConstants.DROP_WAYNODES_STATEMENT); stmt.execute(DbConstants.DROP_NODES_STATEMENT); stmt.execute(DbConstants.DROP_METADATA_STATEMENT); stmt.execute(DbConstants.DROP_INDEX_STATEMENT); stmt.execute(DbConstants.DROP_CATEGORY_MAP_STATEMENT); stmt.execute(DbConstants.DROP_DATA_STATEMENT); stmt.execute(DbConstants.DROP_CATEGORIES_STATEMENT); stmt.execute(DbConstants.CREATE_CATEGORIES_STATEMENT); stmt.execute(DbConstants.CREATE_DATA_STATEMENT); stmt.execute(DbConstants.CREATE_CATEGORY_MAP_STATEMENT); stmt.execute(DbConstants.CREATE_INDEX_STATEMENT); stmt.execute(DbConstants.CREATE_METADATA_STATEMENT); stmt.execute(DbConstants.CREATE_NODES_STATEMENT); stmt.execute(DbConstants.CREATE_WAYNODES_STATEMENT); this.pStmtCatMap = this.conn.prepareStatement(DbConstants.INSERT_CATEGORY_MAP_STATEMENT); this.pStmtData = this.conn.prepareStatement(DbConstants.INSERT_DATA_STATEMENT); this.pStmtIndex = this.conn.prepareStatement(DbConstants.INSERT_INDEX_STATEMENT); this.pStmtNodesC = this.conn.prepareStatement(DbConstants.INSERT_NODES_STATEMENT); this.pStmtNodesR = this.conn.prepareStatement(DbConstants.FIND_NODES_STATEMENT); this.pStmtWayNodesR = this.conn.prepareStatement(DbConstants.FIND_WAYNODES_BY_ID_STATEMENT); // Insert categories PreparedStatement pStmt = this.conn.prepareStatement(DbConstants.INSERT_CATEGORIES_STATEMENT); PoiCategory root = this.categoryManager.getRootCategory(); pStmt.setLong(1, root.getID()); pStmt.setString(2, root.getTitle()); pStmt.setNull(3, 0); pStmt.addBatch(); Stack<PoiCategory> children = new Stack<>(); children.push(root); while (!children.isEmpty()) { for (PoiCategory c : children.pop().getChildren()) { pStmt.setLong(1, c.getID()); pStmt.setString(2, c.getTitle()); pStmt.setInt(3, c.getParent().getID()); pStmt.addBatch(); children.push(c); } } pStmt.executeBatch(); this.conn.commit(); }
[ "private", "void", "prepareDatabase", "(", ")", "throws", "ClassNotFoundException", ",", "SQLException", ",", "UnknownPoiCategoryException", "{", "Class", ".", "forName", "(", "\"org.sqlite.JDBC\"", ")", ";", "this", ".", "conn", "=", "DriverManager", ".", "getConnection", "(", "\"jdbc:sqlite:\"", "+", "this", ".", "configuration", ".", "getOutputFile", "(", ")", ".", "getAbsolutePath", "(", ")", ")", ";", "this", ".", "conn", ".", "setAutoCommit", "(", "false", ")", ";", "Statement", "stmt", "=", "this", ".", "conn", ".", "createStatement", "(", ")", ";", "// Create tables", "stmt", ".", "execute", "(", "DbConstants", ".", "DROP_WAYNODES_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "DROP_NODES_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "DROP_METADATA_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "DROP_INDEX_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "DROP_CATEGORY_MAP_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "DROP_DATA_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "DROP_CATEGORIES_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "CREATE_CATEGORIES_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "CREATE_DATA_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "CREATE_CATEGORY_MAP_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "CREATE_INDEX_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "CREATE_METADATA_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "CREATE_NODES_STATEMENT", ")", ";", "stmt", ".", "execute", "(", "DbConstants", ".", "CREATE_WAYNODES_STATEMENT", ")", ";", "this", ".", "pStmtCatMap", "=", "this", ".", "conn", ".", "prepareStatement", "(", "DbConstants", ".", "INSERT_CATEGORY_MAP_STATEMENT", ")", ";", "this", ".", "pStmtData", "=", "this", ".", "conn", ".", "prepareStatement", "(", "DbConstants", ".", "INSERT_DATA_STATEMENT", ")", ";", "this", ".", "pStmtIndex", "=", "this", ".", "conn", ".", "prepareStatement", "(", "DbConstants", ".", "INSERT_INDEX_STATEMENT", ")", ";", "this", ".", "pStmtNodesC", "=", "this", ".", "conn", ".", "prepareStatement", "(", "DbConstants", ".", "INSERT_NODES_STATEMENT", ")", ";", "this", ".", "pStmtNodesR", "=", "this", ".", "conn", ".", "prepareStatement", "(", "DbConstants", ".", "FIND_NODES_STATEMENT", ")", ";", "this", ".", "pStmtWayNodesR", "=", "this", ".", "conn", ".", "prepareStatement", "(", "DbConstants", ".", "FIND_WAYNODES_BY_ID_STATEMENT", ")", ";", "// Insert categories", "PreparedStatement", "pStmt", "=", "this", ".", "conn", ".", "prepareStatement", "(", "DbConstants", ".", "INSERT_CATEGORIES_STATEMENT", ")", ";", "PoiCategory", "root", "=", "this", ".", "categoryManager", ".", "getRootCategory", "(", ")", ";", "pStmt", ".", "setLong", "(", "1", ",", "root", ".", "getID", "(", ")", ")", ";", "pStmt", ".", "setString", "(", "2", ",", "root", ".", "getTitle", "(", ")", ")", ";", "pStmt", ".", "setNull", "(", "3", ",", "0", ")", ";", "pStmt", ".", "addBatch", "(", ")", ";", "Stack", "<", "PoiCategory", ">", "children", "=", "new", "Stack", "<>", "(", ")", ";", "children", ".", "push", "(", "root", ")", ";", "while", "(", "!", "children", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "PoiCategory", "c", ":", "children", ".", "pop", "(", ")", ".", "getChildren", "(", ")", ")", "{", "pStmt", ".", "setLong", "(", "1", ",", "c", ".", "getID", "(", ")", ")", ";", "pStmt", ".", "setString", "(", "2", ",", "c", ".", "getTitle", "(", ")", ")", ";", "pStmt", ".", "setInt", "(", "3", ",", "c", ".", "getParent", "(", ")", ".", "getID", "(", ")", ")", ";", "pStmt", ".", "addBatch", "(", ")", ";", "children", ".", "push", "(", "c", ")", ";", "}", "}", "pStmt", ".", "executeBatch", "(", ")", ";", "this", ".", "conn", ".", "commit", "(", ")", ";", "}" ]
Prepare database.
[ "Prepare", "database", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L323-L375
28,278
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.process
public void process(EntityContainer entityContainer) { Entity entity = entityContainer.getEntity(); LOGGER.finest("Processing entity: " + entity.toString()); switch (entity.getType()) { case Node: Node node = (Node) entity; if (this.nNodes == 0) { LOGGER.info("Processing nodes..."); } if (this.configuration.isProgressLogs()) { if (nNodes % 100000 == 0) { System.out.print("Progress: Nodes " + nfCounts.format(nNodes) + " \r"); } } ++this.nNodes; if (this.configuration.isWays()) { writeNode(node); } processEntity(node, node.getLatitude(), node.getLongitude()); break; case Way: if (this.configuration.isWays()) { Way way = (Way) entity; if (this.nWays == 0) { LOGGER.info("Processing ways..."); try { // Write rest nodes this.pStmtNodesC.executeBatch(); this.pStmtNodesC.clearBatch(); } catch (SQLException e) { e.printStackTrace(); } } if (this.configuration.isProgressLogs()) { if (nWays % 10000 == 0) { System.out.print("Progress: Ways " + nfCounts.format(nWays) + " \r"); } } ++this.nWays; processWay(way); } break; case Relation: if (this.configuration.isGeoTags() && this.configuration.isWays()) { Relation relation = (Relation) entity; if (this.nRelations == 0) { LOGGER.info("Processing relations..."); this.geoTagger.commit(); } this.geoTagger.filterBoundaries(relation); if (this.configuration.isProgressLogs()) { if (nRelations % 10000 == 0) { System.out.print("Progress: Relations " + nfCounts.format(nRelations) + " \r"); } } ++this.nRelations; } break; default: break; } // Hint to GC entity = null; }
java
public void process(EntityContainer entityContainer) { Entity entity = entityContainer.getEntity(); LOGGER.finest("Processing entity: " + entity.toString()); switch (entity.getType()) { case Node: Node node = (Node) entity; if (this.nNodes == 0) { LOGGER.info("Processing nodes..."); } if (this.configuration.isProgressLogs()) { if (nNodes % 100000 == 0) { System.out.print("Progress: Nodes " + nfCounts.format(nNodes) + " \r"); } } ++this.nNodes; if (this.configuration.isWays()) { writeNode(node); } processEntity(node, node.getLatitude(), node.getLongitude()); break; case Way: if (this.configuration.isWays()) { Way way = (Way) entity; if (this.nWays == 0) { LOGGER.info("Processing ways..."); try { // Write rest nodes this.pStmtNodesC.executeBatch(); this.pStmtNodesC.clearBatch(); } catch (SQLException e) { e.printStackTrace(); } } if (this.configuration.isProgressLogs()) { if (nWays % 10000 == 0) { System.out.print("Progress: Ways " + nfCounts.format(nWays) + " \r"); } } ++this.nWays; processWay(way); } break; case Relation: if (this.configuration.isGeoTags() && this.configuration.isWays()) { Relation relation = (Relation) entity; if (this.nRelations == 0) { LOGGER.info("Processing relations..."); this.geoTagger.commit(); } this.geoTagger.filterBoundaries(relation); if (this.configuration.isProgressLogs()) { if (nRelations % 10000 == 0) { System.out.print("Progress: Relations " + nfCounts.format(nRelations) + " \r"); } } ++this.nRelations; } break; default: break; } // Hint to GC entity = null; }
[ "public", "void", "process", "(", "EntityContainer", "entityContainer", ")", "{", "Entity", "entity", "=", "entityContainer", ".", "getEntity", "(", ")", ";", "LOGGER", ".", "finest", "(", "\"Processing entity: \"", "+", "entity", ".", "toString", "(", ")", ")", ";", "switch", "(", "entity", ".", "getType", "(", ")", ")", "{", "case", "Node", ":", "Node", "node", "=", "(", "Node", ")", "entity", ";", "if", "(", "this", ".", "nNodes", "==", "0", ")", "{", "LOGGER", ".", "info", "(", "\"Processing nodes...\"", ")", ";", "}", "if", "(", "this", ".", "configuration", ".", "isProgressLogs", "(", ")", ")", "{", "if", "(", "nNodes", "%", "100000", "==", "0", ")", "{", "System", ".", "out", ".", "print", "(", "\"Progress: Nodes \"", "+", "nfCounts", ".", "format", "(", "nNodes", ")", "+", "\" \\r\"", ")", ";", "}", "}", "++", "this", ".", "nNodes", ";", "if", "(", "this", ".", "configuration", ".", "isWays", "(", ")", ")", "{", "writeNode", "(", "node", ")", ";", "}", "processEntity", "(", "node", ",", "node", ".", "getLatitude", "(", ")", ",", "node", ".", "getLongitude", "(", ")", ")", ";", "break", ";", "case", "Way", ":", "if", "(", "this", ".", "configuration", ".", "isWays", "(", ")", ")", "{", "Way", "way", "=", "(", "Way", ")", "entity", ";", "if", "(", "this", ".", "nWays", "==", "0", ")", "{", "LOGGER", ".", "info", "(", "\"Processing ways...\"", ")", ";", "try", "{", "// Write rest nodes", "this", ".", "pStmtNodesC", ".", "executeBatch", "(", ")", ";", "this", ".", "pStmtNodesC", ".", "clearBatch", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "if", "(", "this", ".", "configuration", ".", "isProgressLogs", "(", ")", ")", "{", "if", "(", "nWays", "%", "10000", "==", "0", ")", "{", "System", ".", "out", ".", "print", "(", "\"Progress: Ways \"", "+", "nfCounts", ".", "format", "(", "nWays", ")", "+", "\" \\r\"", ")", ";", "}", "}", "++", "this", ".", "nWays", ";", "processWay", "(", "way", ")", ";", "}", "break", ";", "case", "Relation", ":", "if", "(", "this", ".", "configuration", ".", "isGeoTags", "(", ")", "&&", "this", ".", "configuration", ".", "isWays", "(", ")", ")", "{", "Relation", "relation", "=", "(", "Relation", ")", "entity", ";", "if", "(", "this", ".", "nRelations", "==", "0", ")", "{", "LOGGER", ".", "info", "(", "\"Processing relations...\"", ")", ";", "this", ".", "geoTagger", ".", "commit", "(", ")", ";", "}", "this", ".", "geoTagger", ".", "filterBoundaries", "(", "relation", ")", ";", "if", "(", "this", ".", "configuration", ".", "isProgressLogs", "(", ")", ")", "{", "if", "(", "nRelations", "%", "10000", "==", "0", ")", "{", "System", ".", "out", ".", "print", "(", "\"Progress: Relations \"", "+", "nfCounts", ".", "format", "(", "nRelations", ")", "+", "\" \\r\"", ")", ";", "}", "}", "++", "this", ".", "nRelations", ";", "}", "break", ";", "default", ":", "break", ";", "}", "// Hint to GC", "entity", "=", "null", ";", "}" ]
Process task.
[ "Process", "task", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L380-L445
28,279
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.stringToTags
Map<String, String> stringToTags(String tagsmapstring) { String[] sb = tagsmapstring.split("\\r"); Map<String, String> map = new HashMap<>(); for (String key : sb) { if (key.contains("=")) { String[] set = key.split("="); if (set.length == 2) map.put(set[0], set[1]); } } return map; }
java
Map<String, String> stringToTags(String tagsmapstring) { String[] sb = tagsmapstring.split("\\r"); Map<String, String> map = new HashMap<>(); for (String key : sb) { if (key.contains("=")) { String[] set = key.split("="); if (set.length == 2) map.put(set[0], set[1]); } } return map; }
[ "Map", "<", "String", ",", "String", ">", "stringToTags", "(", "String", "tagsmapstring", ")", "{", "String", "[", "]", "sb", "=", "tagsmapstring", ".", "split", "(", "\"\\\\r\"", ")", ";", "Map", "<", "String", ",", "String", ">", "map", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "String", "key", ":", "sb", ")", "{", "if", "(", "key", ".", "contains", "(", "\"=\"", ")", ")", "{", "String", "[", "]", "set", "=", "key", ".", "split", "(", "\"=\"", ")", ";", "if", "(", "set", ".", "length", "==", "2", ")", "map", ".", "put", "(", "set", "[", "0", "]", ",", "set", "[", "1", "]", ")", ";", "}", "}", "return", "map", ";", "}" ]
Convert string representation back to tags map.
[ "Convert", "string", "representation", "back", "to", "tags", "map", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L581-L592
28,280
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.tagsToString
String tagsToString(Map<String, String> tagMap) { StringBuilder sb = new StringBuilder(); for (String key : tagMap.keySet()) { // Skip some tags if (key.equalsIgnoreCase("created_by")) { continue; } if (sb.length() > 0) { sb.append('\r'); } sb.append(key).append('=').append(tagMap.get(key)); } return sb.toString(); }
java
String tagsToString(Map<String, String> tagMap) { StringBuilder sb = new StringBuilder(); for (String key : tagMap.keySet()) { // Skip some tags if (key.equalsIgnoreCase("created_by")) { continue; } if (sb.length() > 0) { sb.append('\r'); } sb.append(key).append('=').append(tagMap.get(key)); } return sb.toString(); }
[ "String", "tagsToString", "(", "Map", "<", "String", ",", "String", ">", "tagMap", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "key", ":", "tagMap", ".", "keySet", "(", ")", ")", "{", "// Skip some tags", "if", "(", "key", ".", "equalsIgnoreCase", "(", "\"created_by\"", ")", ")", "{", "continue", ";", "}", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "sb", ".", "append", "(", "key", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "tagMap", ".", "get", "(", "key", ")", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Convert tags to a string representation using '\r' delimiter.
[ "Convert", "tags", "to", "a", "string", "representation", "using", "\\", "r", "delimiter", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L597-L610
28,281
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.writeMetadata
private void writeMetadata() throws SQLException { LOGGER.info("Writing metadata..."); PreparedStatement pStmtMetadata = this.conn.prepareStatement(DbConstants.INSERT_METADATA_STATEMENT); // Bounds pStmtMetadata.setString(1, DbConstants.METADATA_BOUNDS); BoundingBox bb = this.configuration.getBboxConfiguration(); if (bb == null) { // Calculate bounding box from poi coordinates Statement stmt = this.conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT MIN(minLat), MIN(minLon), MAX(maxLat), MAX(maxLon) FROM poi_index;"); rs.next(); bb = new BoundingBox(rs.getDouble(1), rs.getDouble(2), rs.getDouble(3), rs.getDouble(4)); } pStmtMetadata.setString(2, bb.minLatitude + "," + bb.minLongitude + "," + bb.maxLatitude + "," + bb.maxLongitude); pStmtMetadata.addBatch(); // Comment pStmtMetadata.setString(1, DbConstants.METADATA_COMMENT); if (this.configuration.getComment() != null) { pStmtMetadata.setString(2, this.configuration.getComment()); } else { pStmtMetadata.setNull(2, Types.NULL); } pStmtMetadata.addBatch(); // Date pStmtMetadata.setString(1, DbConstants.METADATA_DATE); pStmtMetadata.setLong(2, System.currentTimeMillis()); pStmtMetadata.addBatch(); // Language pStmtMetadata.setString(1, DbConstants.METADATA_LANGUAGE); if (!this.configuration.isAllTags() && this.configuration.getPreferredLanguage() != null) { pStmtMetadata.setString(2, this.configuration.getPreferredLanguage()); } else { pStmtMetadata.setNull(2, Types.NULL); } pStmtMetadata.addBatch(); // Version pStmtMetadata.setString(1, DbConstants.METADATA_VERSION); pStmtMetadata.setInt(2, this.configuration.getFileSpecificationVersion()); pStmtMetadata.addBatch(); // Ways pStmtMetadata.setString(1, DbConstants.METADATA_WAYS); pStmtMetadata.setString(2, Boolean.toString(this.configuration.isWays())); pStmtMetadata.addBatch(); // Writer pStmtMetadata.setString(1, DbConstants.METADATA_WRITER); pStmtMetadata.setString(2, this.configuration.getWriterVersion()); pStmtMetadata.addBatch(); pStmtMetadata.executeBatch(); this.conn.commit(); }
java
private void writeMetadata() throws SQLException { LOGGER.info("Writing metadata..."); PreparedStatement pStmtMetadata = this.conn.prepareStatement(DbConstants.INSERT_METADATA_STATEMENT); // Bounds pStmtMetadata.setString(1, DbConstants.METADATA_BOUNDS); BoundingBox bb = this.configuration.getBboxConfiguration(); if (bb == null) { // Calculate bounding box from poi coordinates Statement stmt = this.conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT MIN(minLat), MIN(minLon), MAX(maxLat), MAX(maxLon) FROM poi_index;"); rs.next(); bb = new BoundingBox(rs.getDouble(1), rs.getDouble(2), rs.getDouble(3), rs.getDouble(4)); } pStmtMetadata.setString(2, bb.minLatitude + "," + bb.minLongitude + "," + bb.maxLatitude + "," + bb.maxLongitude); pStmtMetadata.addBatch(); // Comment pStmtMetadata.setString(1, DbConstants.METADATA_COMMENT); if (this.configuration.getComment() != null) { pStmtMetadata.setString(2, this.configuration.getComment()); } else { pStmtMetadata.setNull(2, Types.NULL); } pStmtMetadata.addBatch(); // Date pStmtMetadata.setString(1, DbConstants.METADATA_DATE); pStmtMetadata.setLong(2, System.currentTimeMillis()); pStmtMetadata.addBatch(); // Language pStmtMetadata.setString(1, DbConstants.METADATA_LANGUAGE); if (!this.configuration.isAllTags() && this.configuration.getPreferredLanguage() != null) { pStmtMetadata.setString(2, this.configuration.getPreferredLanguage()); } else { pStmtMetadata.setNull(2, Types.NULL); } pStmtMetadata.addBatch(); // Version pStmtMetadata.setString(1, DbConstants.METADATA_VERSION); pStmtMetadata.setInt(2, this.configuration.getFileSpecificationVersion()); pStmtMetadata.addBatch(); // Ways pStmtMetadata.setString(1, DbConstants.METADATA_WAYS); pStmtMetadata.setString(2, Boolean.toString(this.configuration.isWays())); pStmtMetadata.addBatch(); // Writer pStmtMetadata.setString(1, DbConstants.METADATA_WRITER); pStmtMetadata.setString(2, this.configuration.getWriterVersion()); pStmtMetadata.addBatch(); pStmtMetadata.executeBatch(); this.conn.commit(); }
[ "private", "void", "writeMetadata", "(", ")", "throws", "SQLException", "{", "LOGGER", ".", "info", "(", "\"Writing metadata...\"", ")", ";", "PreparedStatement", "pStmtMetadata", "=", "this", ".", "conn", ".", "prepareStatement", "(", "DbConstants", ".", "INSERT_METADATA_STATEMENT", ")", ";", "// Bounds", "pStmtMetadata", ".", "setString", "(", "1", ",", "DbConstants", ".", "METADATA_BOUNDS", ")", ";", "BoundingBox", "bb", "=", "this", ".", "configuration", ".", "getBboxConfiguration", "(", ")", ";", "if", "(", "bb", "==", "null", ")", "{", "// Calculate bounding box from poi coordinates", "Statement", "stmt", "=", "this", ".", "conn", ".", "createStatement", "(", ")", ";", "ResultSet", "rs", "=", "stmt", ".", "executeQuery", "(", "\"SELECT MIN(minLat), MIN(minLon), MAX(maxLat), MAX(maxLon) FROM poi_index;\"", ")", ";", "rs", ".", "next", "(", ")", ";", "bb", "=", "new", "BoundingBox", "(", "rs", ".", "getDouble", "(", "1", ")", ",", "rs", ".", "getDouble", "(", "2", ")", ",", "rs", ".", "getDouble", "(", "3", ")", ",", "rs", ".", "getDouble", "(", "4", ")", ")", ";", "}", "pStmtMetadata", ".", "setString", "(", "2", ",", "bb", ".", "minLatitude", "+", "\",\"", "+", "bb", ".", "minLongitude", "+", "\",\"", "+", "bb", ".", "maxLatitude", "+", "\",\"", "+", "bb", ".", "maxLongitude", ")", ";", "pStmtMetadata", ".", "addBatch", "(", ")", ";", "// Comment", "pStmtMetadata", ".", "setString", "(", "1", ",", "DbConstants", ".", "METADATA_COMMENT", ")", ";", "if", "(", "this", ".", "configuration", ".", "getComment", "(", ")", "!=", "null", ")", "{", "pStmtMetadata", ".", "setString", "(", "2", ",", "this", ".", "configuration", ".", "getComment", "(", ")", ")", ";", "}", "else", "{", "pStmtMetadata", ".", "setNull", "(", "2", ",", "Types", ".", "NULL", ")", ";", "}", "pStmtMetadata", ".", "addBatch", "(", ")", ";", "// Date", "pStmtMetadata", ".", "setString", "(", "1", ",", "DbConstants", ".", "METADATA_DATE", ")", ";", "pStmtMetadata", ".", "setLong", "(", "2", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "pStmtMetadata", ".", "addBatch", "(", ")", ";", "// Language", "pStmtMetadata", ".", "setString", "(", "1", ",", "DbConstants", ".", "METADATA_LANGUAGE", ")", ";", "if", "(", "!", "this", ".", "configuration", ".", "isAllTags", "(", ")", "&&", "this", ".", "configuration", ".", "getPreferredLanguage", "(", ")", "!=", "null", ")", "{", "pStmtMetadata", ".", "setString", "(", "2", ",", "this", ".", "configuration", ".", "getPreferredLanguage", "(", ")", ")", ";", "}", "else", "{", "pStmtMetadata", ".", "setNull", "(", "2", ",", "Types", ".", "NULL", ")", ";", "}", "pStmtMetadata", ".", "addBatch", "(", ")", ";", "// Version", "pStmtMetadata", ".", "setString", "(", "1", ",", "DbConstants", ".", "METADATA_VERSION", ")", ";", "pStmtMetadata", ".", "setInt", "(", "2", ",", "this", ".", "configuration", ".", "getFileSpecificationVersion", "(", ")", ")", ";", "pStmtMetadata", ".", "addBatch", "(", ")", ";", "// Ways", "pStmtMetadata", ".", "setString", "(", "1", ",", "DbConstants", ".", "METADATA_WAYS", ")", ";", "pStmtMetadata", ".", "setString", "(", "2", ",", "Boolean", ".", "toString", "(", "this", ".", "configuration", ".", "isWays", "(", ")", ")", ")", ";", "pStmtMetadata", ".", "addBatch", "(", ")", ";", "// Writer", "pStmtMetadata", ".", "setString", "(", "1", ",", "DbConstants", ".", "METADATA_WRITER", ")", ";", "pStmtMetadata", ".", "setString", "(", "2", ",", "this", ".", "configuration", ".", "getWriterVersion", "(", ")", ")", ";", "pStmtMetadata", ".", "addBatch", "(", ")", ";", "pStmtMetadata", ".", "executeBatch", "(", ")", ";", "this", ".", "conn", ".", "commit", "(", ")", ";", "}" ]
Write the metadata to the database.
[ "Write", "the", "metadata", "to", "the", "database", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L615-L672
28,282
mapsforge/mapsforge
mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java
PoiWriter.writePOI
private void writePOI(long id, double latitude, double longitude, Map<String, String> poiData, Set<PoiCategory> categories) { try { // Index data this.pStmtIndex.setLong(1, id); this.pStmtIndex.setDouble(2, latitude); this.pStmtIndex.setDouble(3, latitude); this.pStmtIndex.setDouble(4, longitude); this.pStmtIndex.setDouble(5, longitude); this.pStmtIndex.addBatch(); // POI data this.pStmtData.setLong(1, id); if (this.configuration.isAllTags()) { // All tags should be written to DB this.pStmtData.setString(2, tagsToString(poiData)); } else { // Use preferred language boolean foundPreferredLanguageName = false; String name = null; for (String key : poiData.keySet()) { if ("name".equals(key) && !foundPreferredLanguageName) { name = poiData.get(key); } else if (this.configuration.getPreferredLanguage() != null && !foundPreferredLanguageName) { Matcher matcher = NAME_LANGUAGE_PATTERN.matcher(key); if (matcher.matches()) { String language = matcher.group(3); if (language.equalsIgnoreCase(this.configuration.getPreferredLanguage())) { name = poiData.get(key); foundPreferredLanguageName = true; } } } } // If name tag is set if (name != null) { this.pStmtData.setString(2, name); } else { this.pStmtData.setNull(2, Types.NULL); } } this.pStmtData.addBatch(); // Categories data this.pStmtCatMap.setLong(1, id); for (PoiCategory category : categories) { this.pStmtCatMap.setInt(2, category.getID()); this.pStmtCatMap.addBatch(); } if (this.poiAdded % BATCH_LIMIT == 0) { this.pStmtIndex.executeBatch(); this.pStmtData.executeBatch(); this.pStmtCatMap.executeBatch(); this.pStmtIndex.clearBatch(); this.pStmtData.clearBatch(); this.pStmtCatMap.clearBatch(); } } catch (SQLException e) { e.printStackTrace(); } }
java
private void writePOI(long id, double latitude, double longitude, Map<String, String> poiData, Set<PoiCategory> categories) { try { // Index data this.pStmtIndex.setLong(1, id); this.pStmtIndex.setDouble(2, latitude); this.pStmtIndex.setDouble(3, latitude); this.pStmtIndex.setDouble(4, longitude); this.pStmtIndex.setDouble(5, longitude); this.pStmtIndex.addBatch(); // POI data this.pStmtData.setLong(1, id); if (this.configuration.isAllTags()) { // All tags should be written to DB this.pStmtData.setString(2, tagsToString(poiData)); } else { // Use preferred language boolean foundPreferredLanguageName = false; String name = null; for (String key : poiData.keySet()) { if ("name".equals(key) && !foundPreferredLanguageName) { name = poiData.get(key); } else if (this.configuration.getPreferredLanguage() != null && !foundPreferredLanguageName) { Matcher matcher = NAME_LANGUAGE_PATTERN.matcher(key); if (matcher.matches()) { String language = matcher.group(3); if (language.equalsIgnoreCase(this.configuration.getPreferredLanguage())) { name = poiData.get(key); foundPreferredLanguageName = true; } } } } // If name tag is set if (name != null) { this.pStmtData.setString(2, name); } else { this.pStmtData.setNull(2, Types.NULL); } } this.pStmtData.addBatch(); // Categories data this.pStmtCatMap.setLong(1, id); for (PoiCategory category : categories) { this.pStmtCatMap.setInt(2, category.getID()); this.pStmtCatMap.addBatch(); } if (this.poiAdded % BATCH_LIMIT == 0) { this.pStmtIndex.executeBatch(); this.pStmtData.executeBatch(); this.pStmtCatMap.executeBatch(); this.pStmtIndex.clearBatch(); this.pStmtData.clearBatch(); this.pStmtCatMap.clearBatch(); } } catch (SQLException e) { e.printStackTrace(); } }
[ "private", "void", "writePOI", "(", "long", "id", ",", "double", "latitude", ",", "double", "longitude", ",", "Map", "<", "String", ",", "String", ">", "poiData", ",", "Set", "<", "PoiCategory", ">", "categories", ")", "{", "try", "{", "// Index data", "this", ".", "pStmtIndex", ".", "setLong", "(", "1", ",", "id", ")", ";", "this", ".", "pStmtIndex", ".", "setDouble", "(", "2", ",", "latitude", ")", ";", "this", ".", "pStmtIndex", ".", "setDouble", "(", "3", ",", "latitude", ")", ";", "this", ".", "pStmtIndex", ".", "setDouble", "(", "4", ",", "longitude", ")", ";", "this", ".", "pStmtIndex", ".", "setDouble", "(", "5", ",", "longitude", ")", ";", "this", ".", "pStmtIndex", ".", "addBatch", "(", ")", ";", "// POI data", "this", ".", "pStmtData", ".", "setLong", "(", "1", ",", "id", ")", ";", "if", "(", "this", ".", "configuration", ".", "isAllTags", "(", ")", ")", "{", "// All tags should be written to DB", "this", ".", "pStmtData", ".", "setString", "(", "2", ",", "tagsToString", "(", "poiData", ")", ")", ";", "}", "else", "{", "// Use preferred language", "boolean", "foundPreferredLanguageName", "=", "false", ";", "String", "name", "=", "null", ";", "for", "(", "String", "key", ":", "poiData", ".", "keySet", "(", ")", ")", "{", "if", "(", "\"name\"", ".", "equals", "(", "key", ")", "&&", "!", "foundPreferredLanguageName", ")", "{", "name", "=", "poiData", ".", "get", "(", "key", ")", ";", "}", "else", "if", "(", "this", ".", "configuration", ".", "getPreferredLanguage", "(", ")", "!=", "null", "&&", "!", "foundPreferredLanguageName", ")", "{", "Matcher", "matcher", "=", "NAME_LANGUAGE_PATTERN", ".", "matcher", "(", "key", ")", ";", "if", "(", "matcher", ".", "matches", "(", ")", ")", "{", "String", "language", "=", "matcher", ".", "group", "(", "3", ")", ";", "if", "(", "language", ".", "equalsIgnoreCase", "(", "this", ".", "configuration", ".", "getPreferredLanguage", "(", ")", ")", ")", "{", "name", "=", "poiData", ".", "get", "(", "key", ")", ";", "foundPreferredLanguageName", "=", "true", ";", "}", "}", "}", "}", "// If name tag is set", "if", "(", "name", "!=", "null", ")", "{", "this", ".", "pStmtData", ".", "setString", "(", "2", ",", "name", ")", ";", "}", "else", "{", "this", ".", "pStmtData", ".", "setNull", "(", "2", ",", "Types", ".", "NULL", ")", ";", "}", "}", "this", ".", "pStmtData", ".", "addBatch", "(", ")", ";", "// Categories data", "this", ".", "pStmtCatMap", ".", "setLong", "(", "1", ",", "id", ")", ";", "for", "(", "PoiCategory", "category", ":", "categories", ")", "{", "this", ".", "pStmtCatMap", ".", "setInt", "(", "2", ",", "category", ".", "getID", "(", ")", ")", ";", "this", ".", "pStmtCatMap", ".", "addBatch", "(", ")", ";", "}", "if", "(", "this", ".", "poiAdded", "%", "BATCH_LIMIT", "==", "0", ")", "{", "this", ".", "pStmtIndex", ".", "executeBatch", "(", ")", ";", "this", ".", "pStmtData", ".", "executeBatch", "(", ")", ";", "this", ".", "pStmtCatMap", ".", "executeBatch", "(", ")", ";", "this", ".", "pStmtIndex", ".", "clearBatch", "(", ")", ";", "this", ".", "pStmtData", ".", "clearBatch", "(", ")", ";", "this", ".", "pStmtCatMap", ".", "clearBatch", "(", ")", ";", "}", "}", "catch", "(", "SQLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Write a POI to the database.
[ "Write", "a", "POI", "to", "the", "database", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L698-L760
28,283
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/model/Tag.java
Tag.compareTo
@Override public int compareTo(Tag tag) { int keyResult = this.key.compareTo(tag.key); if (keyResult != 0) { return keyResult; } return this.value.compareTo(tag.value); }
java
@Override public int compareTo(Tag tag) { int keyResult = this.key.compareTo(tag.key); if (keyResult != 0) { return keyResult; } return this.value.compareTo(tag.value); }
[ "@", "Override", "public", "int", "compareTo", "(", "Tag", "tag", ")", "{", "int", "keyResult", "=", "this", ".", "key", ".", "compareTo", "(", "tag", ".", "key", ")", ";", "if", "(", "keyResult", "!=", "0", ")", "{", "return", "keyResult", ";", "}", "return", "this", ".", "value", ".", "compareTo", "(", "tag", ".", "value", ")", ";", "}" ]
Compares this tag to the specified tag. The tag comparison is based on a comparison of key and value in that order. @param tag The tag to compare to. @return 0 if equal, &lt; 0 if considered "smaller", and &gt; 0 if considered "bigger".
[ "Compares", "this", "tag", "to", "the", "specified", "tag", ".", "The", "tag", "comparison", "is", "based", "on", "a", "comparison", "of", "key", "and", "value", "in", "that", "order", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/model/Tag.java#L65-L74
28,284
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/model/Rectangle.java
Rectangle.enlarge
public Rectangle enlarge(double left, double top, double right, double bottom) { return new Rectangle(this.left - left, this.top - top, this.right + right, this.bottom + bottom); }
java
public Rectangle enlarge(double left, double top, double right, double bottom) { return new Rectangle(this.left - left, this.top - top, this.right + right, this.bottom + bottom); }
[ "public", "Rectangle", "enlarge", "(", "double", "left", ",", "double", "top", ",", "double", "right", ",", "double", "bottom", ")", "{", "return", "new", "Rectangle", "(", "this", ".", "left", "-", "left", ",", "this", ".", "top", "-", "top", ",", "this", ".", "right", "+", "right", ",", "this", ".", "bottom", "+", "bottom", ")", ";", "}" ]
Enlarges the Rectangle sides individually @param left left enlargement @param top top enlargement @param right right enlargement @param bottom bottom enlargement @return
[ "Enlarges", "the", "Rectangle", "sides", "individually" ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/model/Rectangle.java#L58-L60
28,285
mapsforge/mapsforge
mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/DualMapViewer.java
DualMapViewer.createLayers2
protected void createLayers2() { this.mapView2.getLayerManager() .getLayers().add(AndroidUtil.createTileRendererLayer(this.tileCaches.get(1), this.mapView2.getModel().mapViewPosition, getMapFile2(), getRenderTheme2(), false, true, false)); }
java
protected void createLayers2() { this.mapView2.getLayerManager() .getLayers().add(AndroidUtil.createTileRendererLayer(this.tileCaches.get(1), this.mapView2.getModel().mapViewPosition, getMapFile2(), getRenderTheme2(), false, true, false)); }
[ "protected", "void", "createLayers2", "(", ")", "{", "this", ".", "mapView2", ".", "getLayerManager", "(", ")", ".", "getLayers", "(", ")", ".", "add", "(", "AndroidUtil", ".", "createTileRendererLayer", "(", "this", ".", "tileCaches", ".", "get", "(", "1", ")", ",", "this", ".", "mapView2", ".", "getModel", "(", ")", ".", "mapViewPosition", ",", "getMapFile2", "(", ")", ",", "getRenderTheme2", "(", ")", ",", "false", ",", "true", ",", "false", ")", ")", ";", "}" ]
creates the layers for the second map view.
[ "creates", "the", "layers", "for", "the", "second", "map", "view", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/DualMapViewer.java#L52-L57
28,286
mapsforge/mapsforge
mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/Samples.java
Samples.startupDialog
private void startupDialog(String prefs, int message, final Class clazz) { final SharedPreferences preferences = getSharedPreferences(prefs, Activity.MODE_PRIVATE); final String accepted = "accepted"; if (!preferences.getBoolean(accepted, false)) { AlertDialog.Builder builder = new AlertDialog.Builder(Samples.this); builder.setTitle("Warning"); builder.setMessage(message); builder.setPositiveButton(R.string.startup_dontshowagain, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { preferences.edit().putBoolean(accepted, true).apply(); startActivity(new Intent(Samples.this, clazz)); } }); builder.show(); } else { startActivity(new Intent(Samples.this, clazz)); } }
java
private void startupDialog(String prefs, int message, final Class clazz) { final SharedPreferences preferences = getSharedPreferences(prefs, Activity.MODE_PRIVATE); final String accepted = "accepted"; if (!preferences.getBoolean(accepted, false)) { AlertDialog.Builder builder = new AlertDialog.Builder(Samples.this); builder.setTitle("Warning"); builder.setMessage(message); builder.setPositiveButton(R.string.startup_dontshowagain, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { preferences.edit().putBoolean(accepted, true).apply(); startActivity(new Intent(Samples.this, clazz)); } }); builder.show(); } else { startActivity(new Intent(Samples.this, clazz)); } }
[ "private", "void", "startupDialog", "(", "String", "prefs", ",", "int", "message", ",", "final", "Class", "clazz", ")", "{", "final", "SharedPreferences", "preferences", "=", "getSharedPreferences", "(", "prefs", ",", "Activity", ".", "MODE_PRIVATE", ")", ";", "final", "String", "accepted", "=", "\"accepted\"", ";", "if", "(", "!", "preferences", ".", "getBoolean", "(", "accepted", ",", "false", ")", ")", "{", "AlertDialog", ".", "Builder", "builder", "=", "new", "AlertDialog", ".", "Builder", "(", "Samples", ".", "this", ")", ";", "builder", ".", "setTitle", "(", "\"Warning\"", ")", ";", "builder", ".", "setMessage", "(", "message", ")", ";", "builder", ".", "setPositiveButton", "(", "R", ".", "string", ".", "startup_dontshowagain", ",", "new", "DialogInterface", ".", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "DialogInterface", "dialog", ",", "int", "which", ")", "{", "preferences", ".", "edit", "(", ")", ".", "putBoolean", "(", "accepted", ",", "true", ")", ".", "apply", "(", ")", ";", "startActivity", "(", "new", "Intent", "(", "Samples", ".", "this", ",", "clazz", ")", ")", ";", "}", "}", ")", ";", "builder", ".", "show", "(", ")", ";", "}", "else", "{", "startActivity", "(", "new", "Intent", "(", "Samples", ".", "this", ",", "clazz", ")", ")", ";", "}", "}" ]
Warning startup dialog.
[ "Warning", "startup", "dialog", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/Samples.java#L267-L285
28,287
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/mapelements/MapElementContainer.java
MapElementContainer.compareTo
@Override public int compareTo(MapElementContainer other) { if (this.priority < other.priority) { return -1; } if (this.priority > other.priority) { return 1; } return 0; }
java
@Override public int compareTo(MapElementContainer other) { if (this.priority < other.priority) { return -1; } if (this.priority > other.priority) { return 1; } return 0; }
[ "@", "Override", "public", "int", "compareTo", "(", "MapElementContainer", "other", ")", "{", "if", "(", "this", ".", "priority", "<", "other", ".", "priority", ")", "{", "return", "-", "1", ";", "}", "if", "(", "this", ".", "priority", ">", "other", ".", "priority", ")", "{", "return", "1", ";", "}", "return", "0", ";", "}" ]
Compares elements according to their priority. @param other @return priority order
[ "Compares", "elements", "according", "to", "their", "priority", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/mapelements/MapElementContainer.java#L58-L67
28,288
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/mapelements/MapElementContainer.java
MapElementContainer.clashesWith
public boolean clashesWith(MapElementContainer other) { // if either of the elements is always drawn, the elements do not clash if (Display.ALWAYS == this.display || Display.ALWAYS == other.display) { return false; } return this.getBoundaryAbsolute().intersects(other.getBoundaryAbsolute()); }
java
public boolean clashesWith(MapElementContainer other) { // if either of the elements is always drawn, the elements do not clash if (Display.ALWAYS == this.display || Display.ALWAYS == other.display) { return false; } return this.getBoundaryAbsolute().intersects(other.getBoundaryAbsolute()); }
[ "public", "boolean", "clashesWith", "(", "MapElementContainer", "other", ")", "{", "// if either of the elements is always drawn, the elements do not clash", "if", "(", "Display", ".", "ALWAYS", "==", "this", ".", "display", "||", "Display", ".", "ALWAYS", "==", "other", ".", "display", ")", "{", "return", "false", ";", "}", "return", "this", ".", "getBoundaryAbsolute", "(", ")", ".", "intersects", "(", "other", ".", "getBoundaryAbsolute", "(", ")", ")", ";", "}" ]
Returns if MapElementContainers clash with each other @param other element to test against @return true if they overlap
[ "Returns", "if", "MapElementContainers", "clash", "with", "each", "other" ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/mapelements/MapElementContainer.java#L113-L119
28,289
mapsforge/mapsforge
mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/util/OSMUtils.java
OSMUtils.extractKnownPOITags
public static Map<Short, Object> extractKnownPOITags(Entity entity) { Map<Short, Object> tagMap = new HashMap<>(); OSMTagMapping mapping = OSMTagMapping.getInstance(); if (entity.getTags() != null) { for (Tag tag : entity.getTags()) { OSMTag poiTag = mapping.getPoiTag(tag.getKey(), tag.getValue()); if (poiTag != null) { String wildcard = poiTag.getValue(); tagMap.put(poiTag.getId(), getObjectFromWildcardAndValue(wildcard, tag.getValue())); } } } return tagMap; }
java
public static Map<Short, Object> extractKnownPOITags(Entity entity) { Map<Short, Object> tagMap = new HashMap<>(); OSMTagMapping mapping = OSMTagMapping.getInstance(); if (entity.getTags() != null) { for (Tag tag : entity.getTags()) { OSMTag poiTag = mapping.getPoiTag(tag.getKey(), tag.getValue()); if (poiTag != null) { String wildcard = poiTag.getValue(); tagMap.put(poiTag.getId(), getObjectFromWildcardAndValue(wildcard, tag.getValue())); } } } return tagMap; }
[ "public", "static", "Map", "<", "Short", ",", "Object", ">", "extractKnownPOITags", "(", "Entity", "entity", ")", "{", "Map", "<", "Short", ",", "Object", ">", "tagMap", "=", "new", "HashMap", "<>", "(", ")", ";", "OSMTagMapping", "mapping", "=", "OSMTagMapping", ".", "getInstance", "(", ")", ";", "if", "(", "entity", ".", "getTags", "(", ")", "!=", "null", ")", "{", "for", "(", "Tag", "tag", ":", "entity", ".", "getTags", "(", ")", ")", "{", "OSMTag", "poiTag", "=", "mapping", ".", "getPoiTag", "(", "tag", ".", "getKey", "(", ")", ",", "tag", ".", "getValue", "(", ")", ")", ";", "if", "(", "poiTag", "!=", "null", ")", "{", "String", "wildcard", "=", "poiTag", ".", "getValue", "(", ")", ";", "tagMap", ".", "put", "(", "poiTag", ".", "getId", "(", ")", ",", "getObjectFromWildcardAndValue", "(", "wildcard", ",", "tag", ".", "getValue", "(", ")", ")", ")", ";", "}", "}", "}", "return", "tagMap", ";", "}" ]
Extracts known POI tags and returns their ids. @param entity the node @return the ids of the identified tags
[ "Extracts", "known", "POI", "tags", "and", "returns", "their", "ids", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/util/OSMUtils.java#L59-L72
28,290
mapsforge/mapsforge
mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/util/OSMUtils.java
OSMUtils.extractKnownWayTags
public static Map<Short, Object> extractKnownWayTags(Entity entity) { Map<Short, Object> tagMap = new HashMap<>(); OSMTagMapping mapping = OSMTagMapping.getInstance(); if (entity.getTags() != null) { for (Tag tag : entity.getTags()) { OSMTag wayTag = mapping.getWayTag(tag.getKey(), tag.getValue()); if (wayTag != null) { String wildcard = wayTag.getValue(); tagMap.put(wayTag.getId(), getObjectFromWildcardAndValue(wildcard, tag.getValue())); } } } return tagMap; }
java
public static Map<Short, Object> extractKnownWayTags(Entity entity) { Map<Short, Object> tagMap = new HashMap<>(); OSMTagMapping mapping = OSMTagMapping.getInstance(); if (entity.getTags() != null) { for (Tag tag : entity.getTags()) { OSMTag wayTag = mapping.getWayTag(tag.getKey(), tag.getValue()); if (wayTag != null) { String wildcard = wayTag.getValue(); tagMap.put(wayTag.getId(), getObjectFromWildcardAndValue(wildcard, tag.getValue())); } } } return tagMap; }
[ "public", "static", "Map", "<", "Short", ",", "Object", ">", "extractKnownWayTags", "(", "Entity", "entity", ")", "{", "Map", "<", "Short", ",", "Object", ">", "tagMap", "=", "new", "HashMap", "<>", "(", ")", ";", "OSMTagMapping", "mapping", "=", "OSMTagMapping", ".", "getInstance", "(", ")", ";", "if", "(", "entity", ".", "getTags", "(", ")", "!=", "null", ")", "{", "for", "(", "Tag", "tag", ":", "entity", ".", "getTags", "(", ")", ")", "{", "OSMTag", "wayTag", "=", "mapping", ".", "getWayTag", "(", "tag", ".", "getKey", "(", ")", ",", "tag", ".", "getValue", "(", ")", ")", ";", "if", "(", "wayTag", "!=", "null", ")", "{", "String", "wildcard", "=", "wayTag", ".", "getValue", "(", ")", ";", "tagMap", ".", "put", "(", "wayTag", ".", "getId", "(", ")", ",", "getObjectFromWildcardAndValue", "(", "wildcard", ",", "tag", ".", "getValue", "(", ")", ")", ")", ";", "}", "}", "}", "return", "tagMap", ";", "}" ]
Extracts known way tags and returns their ids. @param entity the way @return the ids of the identified tags
[ "Extracts", "known", "way", "tags", "and", "returns", "their", "ids", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/util/OSMUtils.java#L80-L93
28,291
mapsforge/mapsforge
mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/DatabaseRenderer.java
DatabaseRenderer.createBackgroundBitmap
private TileBitmap createBackgroundBitmap(RenderContext renderContext) { TileBitmap bitmap = this.graphicFactory.createTileBitmap(renderContext.rendererJob.tile.tileSize, renderContext.rendererJob.hasAlpha); renderContext.canvasRasterer.setCanvasBitmap(bitmap); if (!renderContext.rendererJob.hasAlpha) { renderContext.canvasRasterer.fill(renderContext.renderTheme.getMapBackgroundOutside()); } return bitmap; }
java
private TileBitmap createBackgroundBitmap(RenderContext renderContext) { TileBitmap bitmap = this.graphicFactory.createTileBitmap(renderContext.rendererJob.tile.tileSize, renderContext.rendererJob.hasAlpha); renderContext.canvasRasterer.setCanvasBitmap(bitmap); if (!renderContext.rendererJob.hasAlpha) { renderContext.canvasRasterer.fill(renderContext.renderTheme.getMapBackgroundOutside()); } return bitmap; }
[ "private", "TileBitmap", "createBackgroundBitmap", "(", "RenderContext", "renderContext", ")", "{", "TileBitmap", "bitmap", "=", "this", ".", "graphicFactory", ".", "createTileBitmap", "(", "renderContext", ".", "rendererJob", ".", "tile", ".", "tileSize", ",", "renderContext", ".", "rendererJob", ".", "hasAlpha", ")", ";", "renderContext", ".", "canvasRasterer", ".", "setCanvasBitmap", "(", "bitmap", ")", ";", "if", "(", "!", "renderContext", ".", "rendererJob", ".", "hasAlpha", ")", "{", "renderContext", ".", "canvasRasterer", ".", "fill", "(", "renderContext", ".", "renderTheme", ".", "getMapBackgroundOutside", "(", ")", ")", ";", "}", "return", "bitmap", ";", "}" ]
Draws a bitmap just with outside colour, used for bitmaps outside of map area. @param renderContext the RenderContext @return bitmap drawn in single colour.
[ "Draws", "a", "bitmap", "just", "with", "outside", "colour", "used", "for", "bitmaps", "outside", "of", "map", "area", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/DatabaseRenderer.java#L159-L167
28,292
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.createExternalStorageTileCache
public static TileCache createExternalStorageTileCache(Context c, String id, int firstLevelSize, int tileSize) { return createExternalStorageTileCache(c, id, firstLevelSize, tileSize, false); }
java
public static TileCache createExternalStorageTileCache(Context c, String id, int firstLevelSize, int tileSize) { return createExternalStorageTileCache(c, id, firstLevelSize, tileSize, false); }
[ "public", "static", "TileCache", "createExternalStorageTileCache", "(", "Context", "c", ",", "String", "id", ",", "int", "firstLevelSize", ",", "int", "tileSize", ")", "{", "return", "createExternalStorageTileCache", "(", "c", ",", "id", ",", "firstLevelSize", ",", "tileSize", ",", "false", ")", ";", "}" ]
Utility function to create a two-level tile cache along with its backends. This is the compatibility version that by default creates a non-persistent cache. @param c the Android context @param id name for the directory, which will be created as a subdirectory of the default cache directory (as returned by {@link android.content.Context#getExternalCacheDir()}). @param firstLevelSize size of the first level cache (tiles number) @param tileSize tile size @return a new cache created on the external storage
[ "Utility", "function", "to", "create", "a", "two", "-", "level", "tile", "cache", "along", "with", "its", "backends", ".", "This", "is", "the", "compatibility", "version", "that", "by", "default", "creates", "a", "non", "-", "persistent", "cache", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L66-L68
28,293
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.createTileCache
public static TileCache createTileCache(Context c, String id, int tileSize, float screenRatio, double overdraw) { return createTileCache(c, id, tileSize, screenRatio, overdraw, false); }
java
public static TileCache createTileCache(Context c, String id, int tileSize, float screenRatio, double overdraw) { return createTileCache(c, id, tileSize, screenRatio, overdraw, false); }
[ "public", "static", "TileCache", "createTileCache", "(", "Context", "c", ",", "String", "id", ",", "int", "tileSize", ",", "float", "screenRatio", ",", "double", "overdraw", ")", "{", "return", "createTileCache", "(", "c", ",", "id", ",", "tileSize", ",", "screenRatio", ",", "overdraw", ",", "false", ")", ";", "}" ]
Utility function to create a two-level tile cache with the right size. When the cache is created we do not actually know the size of the mapview, so the screenRatio is an approximation of the required size. This is the compatibility version that by default creates a non-persistent cache. @param c the Android context @param id name for the storage directory @param tileSize tile size @param screenRatio part of the screen the view takes up @param overdraw overdraw allowance @return a new cache created on the external storage
[ "Utility", "function", "to", "create", "a", "two", "-", "level", "tile", "cache", "with", "the", "right", "size", ".", "When", "the", "cache", "is", "created", "we", "do", "not", "actually", "know", "the", "size", "of", "the", "mapview", "so", "the", "screenRatio", "is", "an", "approximation", "of", "the", "required", "size", ".", "This", "is", "the", "compatibility", "version", "that", "by", "default", "creates", "a", "non", "-", "persistent", "cache", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L170-L172
28,294
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.createTileCache
public static TileCache createTileCache(Context c, String id, int tileSize, int width, int height, double overdraw) { return createTileCache(c, id, tileSize, width, height, overdraw, false); }
java
public static TileCache createTileCache(Context c, String id, int tileSize, int width, int height, double overdraw) { return createTileCache(c, id, tileSize, width, height, overdraw, false); }
[ "public", "static", "TileCache", "createTileCache", "(", "Context", "c", ",", "String", "id", ",", "int", "tileSize", ",", "int", "width", ",", "int", "height", ",", "double", "overdraw", ")", "{", "return", "createTileCache", "(", "c", ",", "id", ",", "tileSize", ",", "width", ",", "height", ",", "overdraw", ",", "false", ")", ";", "}" ]
Utility function to create a two-level tile cache with the right size, using the size of the map view. This is the compatibility version that by default creates a non-persistent cache. @param c the Android context @param id name for the storage directory @param tileSize tile size @param width the width of the map view @param height the height of the map view @param overdraw overdraw allowance @return a new cache created on the external storage
[ "Utility", "function", "to", "create", "a", "two", "-", "level", "tile", "cache", "with", "the", "right", "size", "using", "the", "size", "of", "the", "map", "view", ".", "This", "is", "the", "compatibility", "version", "that", "by", "default", "creates", "a", "non", "-", "persistent", "cache", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L222-L224
28,295
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.getAvailableCacheSlots
@SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static long getAvailableCacheSlots(String directory, int fileSize) { StatFs statfs = new StatFs(directory); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return statfs.getAvailableBytes() / fileSize; } // problem is overflow with devices with large storage, so order is important here // additionally avoid division by zero in devices with a large block size int blocksPerFile = Math.max(fileSize / statfs.getBlockSize(), 1); return statfs.getAvailableBlocks() / blocksPerFile; }
java
@SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static long getAvailableCacheSlots(String directory, int fileSize) { StatFs statfs = new StatFs(directory); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return statfs.getAvailableBytes() / fileSize; } // problem is overflow with devices with large storage, so order is important here // additionally avoid division by zero in devices with a large block size int blocksPerFile = Math.max(fileSize / statfs.getBlockSize(), 1); return statfs.getAvailableBlocks() / blocksPerFile; }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN_MR2", ")", "public", "static", "long", "getAvailableCacheSlots", "(", "String", "directory", ",", "int", "fileSize", ")", "{", "StatFs", "statfs", "=", "new", "StatFs", "(", "directory", ")", ";", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN_MR2", ")", "{", "return", "statfs", ".", "getAvailableBytes", "(", ")", "/", "fileSize", ";", "}", "// problem is overflow with devices with large storage, so order is important here", "// additionally avoid division by zero in devices with a large block size", "int", "blocksPerFile", "=", "Math", ".", "max", "(", "fileSize", "/", "statfs", ".", "getBlockSize", "(", ")", ",", "1", ")", ";", "return", "statfs", ".", "getAvailableBlocks", "(", ")", "/", "blocksPerFile", ";", "}" ]
Get the number of tiles that can be stored on the file system. @param directory where the cache will reside @param fileSize average size of tile to be cached @return number of tiles that can be stored without running out of space
[ "Get", "the", "number", "of", "tiles", "that", "can", "be", "stored", "on", "the", "file", "system", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L326-L337
28,296
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.getMinimumCacheSize
@SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static int getMinimumCacheSize(Context c, int tileSize, double overdrawFactor, float screenRatio) { WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); int height; int width; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { Point p = new Point(); display.getSize(p); height = p.y; width = p.x; } else { // deprecated since Android 13 height = display.getHeight(); width = display.getWidth(); } // height * overdrawFactor / tileSize calculates the number of tiles that would cover // the view port, adding 1 is required since we can have part tiles on either side, // adding 2 adds another row/column as spare and ensures that we will generally have // a larger number of tiles in the cache than a TileLayer will render for a view. // Multiplying by screenRatio adjusts this somewhat inaccurately for MapViews on only part // of a screen (the result can be too low if a MapView is very narrow). // For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the // middle of a view. Dimension dimension = FrameBufferController.calculateFrameBufferDimension(new Dimension(width, height), overdrawFactor); return (int) Math.max(4, screenRatio * (2 + (dimension.height / tileSize)) * (2 + (dimension.width / tileSize))); }
java
@SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static int getMinimumCacheSize(Context c, int tileSize, double overdrawFactor, float screenRatio) { WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); int height; int width; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { Point p = new Point(); display.getSize(p); height = p.y; width = p.x; } else { // deprecated since Android 13 height = display.getHeight(); width = display.getWidth(); } // height * overdrawFactor / tileSize calculates the number of tiles that would cover // the view port, adding 1 is required since we can have part tiles on either side, // adding 2 adds another row/column as spare and ensures that we will generally have // a larger number of tiles in the cache than a TileLayer will render for a view. // Multiplying by screenRatio adjusts this somewhat inaccurately for MapViews on only part // of a screen (the result can be too low if a MapView is very narrow). // For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the // middle of a view. Dimension dimension = FrameBufferController.calculateFrameBufferDimension(new Dimension(width, height), overdrawFactor); return (int) Math.max(4, screenRatio * (2 + (dimension.height / tileSize)) * (2 + (dimension.width / tileSize))); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "HONEYCOMB_MR2", ")", "public", "static", "int", "getMinimumCacheSize", "(", "Context", "c", ",", "int", "tileSize", ",", "double", "overdrawFactor", ",", "float", "screenRatio", ")", "{", "WindowManager", "wm", "=", "(", "WindowManager", ")", "c", ".", "getSystemService", "(", "Context", ".", "WINDOW_SERVICE", ")", ";", "Display", "display", "=", "wm", ".", "getDefaultDisplay", "(", ")", ";", "int", "height", ";", "int", "width", ";", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_CODES", ".", "HONEYCOMB_MR2", ")", "{", "Point", "p", "=", "new", "Point", "(", ")", ";", "display", ".", "getSize", "(", "p", ")", ";", "height", "=", "p", ".", "y", ";", "width", "=", "p", ".", "x", ";", "}", "else", "{", "// deprecated since Android 13", "height", "=", "display", ".", "getHeight", "(", ")", ";", "width", "=", "display", ".", "getWidth", "(", ")", ";", "}", "// height * overdrawFactor / tileSize calculates the number of tiles that would cover", "// the view port, adding 1 is required since we can have part tiles on either side,", "// adding 2 adds another row/column as spare and ensures that we will generally have", "// a larger number of tiles in the cache than a TileLayer will render for a view.", "// Multiplying by screenRatio adjusts this somewhat inaccurately for MapViews on only part", "// of a screen (the result can be too low if a MapView is very narrow).", "// For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the", "// middle of a view.", "Dimension", "dimension", "=", "FrameBufferController", ".", "calculateFrameBufferDimension", "(", "new", "Dimension", "(", "width", ",", "height", ")", ",", "overdrawFactor", ")", ";", "return", "(", "int", ")", "Math", ".", "max", "(", "4", ",", "screenRatio", "*", "(", "2", "+", "(", "dimension", ".", "height", "/", "tileSize", ")", ")", "*", "(", "2", "+", "(", "dimension", ".", "width", "/", "tileSize", ")", ")", ")", ";", "}" ]
Compute the minimum cache size for a view. When the cache is created we do not actually know the size of the mapview, so the screenRatio is an approximation of the required size. For the view size we use the frame buffer calculated dimension. @param c the context @param tileSize the tile size @param overdrawFactor the overdraw factor applied to the mapview @param screenRatio the part of the screen the view covers @return the minimum cache size for the view
[ "Compute", "the", "minimum", "cache", "size", "for", "a", "view", ".", "When", "the", "cache", "is", "created", "we", "do", "not", "actually", "know", "the", "size", "of", "the", "mapview", "so", "the", "screenRatio", "is", "an", "approximation", "of", "the", "required", "size", ".", "For", "the", "view", "size", "we", "use", "the", "frame", "buffer", "calculated", "dimension", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L350-L379
28,297
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.getMinimumCacheSize
public static int getMinimumCacheSize(int tileSize, double overdrawFactor, int width, int height) { // height * overdrawFactor / tileSize calculates the number of tiles that would cover // the view port, adding 1 is required since we can have part tiles on either side, // adding 2 adds another row/column as spare and ensures that we will generally have // a larger number of tiles in the cache than a TileLayer will render for a view. // For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the // middle of a view. Dimension dimension = FrameBufferController.calculateFrameBufferDimension(new Dimension(width, height), overdrawFactor); return Math.max(4, (2 + (dimension.height / tileSize)) * (2 + (dimension.width / tileSize))); }
java
public static int getMinimumCacheSize(int tileSize, double overdrawFactor, int width, int height) { // height * overdrawFactor / tileSize calculates the number of tiles that would cover // the view port, adding 1 is required since we can have part tiles on either side, // adding 2 adds another row/column as spare and ensures that we will generally have // a larger number of tiles in the cache than a TileLayer will render for a view. // For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the // middle of a view. Dimension dimension = FrameBufferController.calculateFrameBufferDimension(new Dimension(width, height), overdrawFactor); return Math.max(4, (2 + (dimension.height / tileSize)) * (2 + (dimension.width / tileSize))); }
[ "public", "static", "int", "getMinimumCacheSize", "(", "int", "tileSize", ",", "double", "overdrawFactor", ",", "int", "width", ",", "int", "height", ")", "{", "// height * overdrawFactor / tileSize calculates the number of tiles that would cover", "// the view port, adding 1 is required since we can have part tiles on either side,", "// adding 2 adds another row/column as spare and ensures that we will generally have", "// a larger number of tiles in the cache than a TileLayer will render for a view.", "// For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the", "// middle of a view.", "Dimension", "dimension", "=", "FrameBufferController", ".", "calculateFrameBufferDimension", "(", "new", "Dimension", "(", "width", ",", "height", ")", ",", "overdrawFactor", ")", ";", "return", "Math", ".", "max", "(", "4", ",", "(", "2", "+", "(", "dimension", ".", "height", "/", "tileSize", ")", ")", "*", "(", "2", "+", "(", "dimension", ".", "width", "/", "tileSize", ")", ")", ")", ";", "}" ]
Compute the minimum cache size for a view, using the size of the map view. For the view size we use the frame buffer calculated dimension. @param tileSize the tile size @param overdrawFactor the overdraw factor applied to the mapview @param width the width of the map view @param height the height of the map view @return the minimum cache size for the view
[ "Compute", "the", "minimum", "cache", "size", "for", "a", "view", "using", "the", "size", "of", "the", "map", "view", ".", "For", "the", "view", "size", "we", "use", "the", "frame", "buffer", "calculated", "dimension", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L391-L401
28,298
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.setMapScaleBar
public static void setMapScaleBar(MapView mapView, DistanceUnitAdapter primaryDistanceUnitAdapter, DistanceUnitAdapter secondaryDistanceUnitAdapter) { if (null == primaryDistanceUnitAdapter && null == secondaryDistanceUnitAdapter) { mapView.setMapScaleBar(null); } else { MapScaleBar scaleBar = mapView.getMapScaleBar(); if (scaleBar == null) { scaleBar = new DefaultMapScaleBar(mapView.getModel().mapViewPosition, mapView.getModel().mapViewDimension, AndroidGraphicFactory.INSTANCE, mapView.getModel().displayModel); mapView.setMapScaleBar(scaleBar); } if (scaleBar instanceof DefaultMapScaleBar) { if (null != secondaryDistanceUnitAdapter) { ((DefaultMapScaleBar) scaleBar).setScaleBarMode(DefaultMapScaleBar.ScaleBarMode.BOTH); ((DefaultMapScaleBar) scaleBar).setSecondaryDistanceUnitAdapter(secondaryDistanceUnitAdapter); } else { ((DefaultMapScaleBar) scaleBar).setScaleBarMode(DefaultMapScaleBar.ScaleBarMode.SINGLE); } } scaleBar.setDistanceUnitAdapter(primaryDistanceUnitAdapter); } }
java
public static void setMapScaleBar(MapView mapView, DistanceUnitAdapter primaryDistanceUnitAdapter, DistanceUnitAdapter secondaryDistanceUnitAdapter) { if (null == primaryDistanceUnitAdapter && null == secondaryDistanceUnitAdapter) { mapView.setMapScaleBar(null); } else { MapScaleBar scaleBar = mapView.getMapScaleBar(); if (scaleBar == null) { scaleBar = new DefaultMapScaleBar(mapView.getModel().mapViewPosition, mapView.getModel().mapViewDimension, AndroidGraphicFactory.INSTANCE, mapView.getModel().displayModel); mapView.setMapScaleBar(scaleBar); } if (scaleBar instanceof DefaultMapScaleBar) { if (null != secondaryDistanceUnitAdapter) { ((DefaultMapScaleBar) scaleBar).setScaleBarMode(DefaultMapScaleBar.ScaleBarMode.BOTH); ((DefaultMapScaleBar) scaleBar).setSecondaryDistanceUnitAdapter(secondaryDistanceUnitAdapter); } else { ((DefaultMapScaleBar) scaleBar).setScaleBarMode(DefaultMapScaleBar.ScaleBarMode.SINGLE); } } scaleBar.setDistanceUnitAdapter(primaryDistanceUnitAdapter); } }
[ "public", "static", "void", "setMapScaleBar", "(", "MapView", "mapView", ",", "DistanceUnitAdapter", "primaryDistanceUnitAdapter", ",", "DistanceUnitAdapter", "secondaryDistanceUnitAdapter", ")", "{", "if", "(", "null", "==", "primaryDistanceUnitAdapter", "&&", "null", "==", "secondaryDistanceUnitAdapter", ")", "{", "mapView", ".", "setMapScaleBar", "(", "null", ")", ";", "}", "else", "{", "MapScaleBar", "scaleBar", "=", "mapView", ".", "getMapScaleBar", "(", ")", ";", "if", "(", "scaleBar", "==", "null", ")", "{", "scaleBar", "=", "new", "DefaultMapScaleBar", "(", "mapView", ".", "getModel", "(", ")", ".", "mapViewPosition", ",", "mapView", ".", "getModel", "(", ")", ".", "mapViewDimension", ",", "AndroidGraphicFactory", ".", "INSTANCE", ",", "mapView", ".", "getModel", "(", ")", ".", "displayModel", ")", ";", "mapView", ".", "setMapScaleBar", "(", "scaleBar", ")", ";", "}", "if", "(", "scaleBar", "instanceof", "DefaultMapScaleBar", ")", "{", "if", "(", "null", "!=", "secondaryDistanceUnitAdapter", ")", "{", "(", "(", "DefaultMapScaleBar", ")", "scaleBar", ")", ".", "setScaleBarMode", "(", "DefaultMapScaleBar", ".", "ScaleBarMode", ".", "BOTH", ")", ";", "(", "(", "DefaultMapScaleBar", ")", "scaleBar", ")", ".", "setSecondaryDistanceUnitAdapter", "(", "secondaryDistanceUnitAdapter", ")", ";", "}", "else", "{", "(", "(", "DefaultMapScaleBar", ")", "scaleBar", ")", ".", "setScaleBarMode", "(", "DefaultMapScaleBar", ".", "ScaleBarMode", ".", "SINGLE", ")", ";", "}", "}", "scaleBar", ".", "setDistanceUnitAdapter", "(", "primaryDistanceUnitAdapter", ")", ";", "}", "}" ]
Sets the scale bar on a map view with implicit arguments. If no distance unit adapters are supplied, there will be no scalebar, with only a primary adapter supplied, the mode will be single, with two adapters supplied, the mode will be dual. @param mapView the map view to change @param primaryDistanceUnitAdapter primary scale @param secondaryDistanceUnitAdapter secondary scale
[ "Sets", "the", "scale", "bar", "on", "a", "map", "view", "with", "implicit", "arguments", ".", "If", "no", "distance", "unit", "adapters", "are", "supplied", "there", "will", "be", "no", "scalebar", "with", "only", "a", "primary", "adapter", "supplied", "the", "mode", "will", "be", "single", "with", "two", "adapters", "supplied", "the", "mode", "will", "be", "dual", "." ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L433-L455
28,299
mapsforge/mapsforge
mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/dummy/ManyDummyContent.java
ManyDummyContent.loadXmlFromNetwork
private List<DummyItem> loadXmlFromNetwork(String urlString) throws IOException { String jString; // Instantiate the parser List<Entry> entries = null; List<DummyItem> rtnArray = new ArrayList<DummyItem>(); BufferedReader streamReader = null; try { streamReader = new BufferedReader(downloadUrl(urlString)); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); jString = responseStrBuilder.toString(); if (jString == null) { Log.e(SamplesApplication.TAG, "Nominatim Webpage: request failed for " + urlString); return new ArrayList<DummyItem>(0); } JSONArray jPlaceIds = new JSONArray(jString); int n = jPlaceIds.length(); entries = new ArrayList<Entry>(n); for (int i = 0; i < n; i++) { JSONObject jPlace = jPlaceIds.getJSONObject(i); Entry poi = new Entry( jPlace.optLong("place_id"), jPlace.getString("osm_type"), jPlace.getString("osm_id"), // jPlace.getString("place_rank"), jPlace.getString("boundingbox"), jPlace.getString("lat"), jPlace.getString("lon"), jPlace.getString("display_name"), jPlace.getString("class"), jPlace.getString("type"), jPlace.getString("importance")); entries.add(poi); } } catch (JSONException e) { e.printStackTrace(); return null; } finally { if (streamReader != null) { streamReader.close(); } } // StackOverflowXmlParser returns a List (called "entries") of Entry objects. // Each Entry object represents a single place in the XML searchresult. // This section processes the entries list to create a 'DummyItem' from each entry. for (Entry entry : entries) { rtnArray.add( new DummyItem(entry.mOsm_id, entry.mDisplay_name.split(",")[0], new LatLong(Double.parseDouble(entry.mLat), Double.parseDouble(entry.mLon)), entry.mDisplay_name)); } return rtnArray; }
java
private List<DummyItem> loadXmlFromNetwork(String urlString) throws IOException { String jString; // Instantiate the parser List<Entry> entries = null; List<DummyItem> rtnArray = new ArrayList<DummyItem>(); BufferedReader streamReader = null; try { streamReader = new BufferedReader(downloadUrl(urlString)); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); jString = responseStrBuilder.toString(); if (jString == null) { Log.e(SamplesApplication.TAG, "Nominatim Webpage: request failed for " + urlString); return new ArrayList<DummyItem>(0); } JSONArray jPlaceIds = new JSONArray(jString); int n = jPlaceIds.length(); entries = new ArrayList<Entry>(n); for (int i = 0; i < n; i++) { JSONObject jPlace = jPlaceIds.getJSONObject(i); Entry poi = new Entry( jPlace.optLong("place_id"), jPlace.getString("osm_type"), jPlace.getString("osm_id"), // jPlace.getString("place_rank"), jPlace.getString("boundingbox"), jPlace.getString("lat"), jPlace.getString("lon"), jPlace.getString("display_name"), jPlace.getString("class"), jPlace.getString("type"), jPlace.getString("importance")); entries.add(poi); } } catch (JSONException e) { e.printStackTrace(); return null; } finally { if (streamReader != null) { streamReader.close(); } } // StackOverflowXmlParser returns a List (called "entries") of Entry objects. // Each Entry object represents a single place in the XML searchresult. // This section processes the entries list to create a 'DummyItem' from each entry. for (Entry entry : entries) { rtnArray.add( new DummyItem(entry.mOsm_id, entry.mDisplay_name.split(",")[0], new LatLong(Double.parseDouble(entry.mLat), Double.parseDouble(entry.mLon)), entry.mDisplay_name)); } return rtnArray; }
[ "private", "List", "<", "DummyItem", ">", "loadXmlFromNetwork", "(", "String", "urlString", ")", "throws", "IOException", "{", "String", "jString", ";", "// Instantiate the parser", "List", "<", "Entry", ">", "entries", "=", "null", ";", "List", "<", "DummyItem", ">", "rtnArray", "=", "new", "ArrayList", "<", "DummyItem", ">", "(", ")", ";", "BufferedReader", "streamReader", "=", "null", ";", "try", "{", "streamReader", "=", "new", "BufferedReader", "(", "downloadUrl", "(", "urlString", ")", ")", ";", "StringBuilder", "responseStrBuilder", "=", "new", "StringBuilder", "(", ")", ";", "String", "inputStr", ";", "while", "(", "(", "inputStr", "=", "streamReader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "responseStrBuilder", ".", "append", "(", "inputStr", ")", ";", "jString", "=", "responseStrBuilder", ".", "toString", "(", ")", ";", "if", "(", "jString", "==", "null", ")", "{", "Log", ".", "e", "(", "SamplesApplication", ".", "TAG", ",", "\"Nominatim Webpage: request failed for \"", "+", "urlString", ")", ";", "return", "new", "ArrayList", "<", "DummyItem", ">", "(", "0", ")", ";", "}", "JSONArray", "jPlaceIds", "=", "new", "JSONArray", "(", "jString", ")", ";", "int", "n", "=", "jPlaceIds", ".", "length", "(", ")", ";", "entries", "=", "new", "ArrayList", "<", "Entry", ">", "(", "n", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "JSONObject", "jPlace", "=", "jPlaceIds", ".", "getJSONObject", "(", "i", ")", ";", "Entry", "poi", "=", "new", "Entry", "(", "jPlace", ".", "optLong", "(", "\"place_id\"", ")", ",", "jPlace", ".", "getString", "(", "\"osm_type\"", ")", ",", "jPlace", ".", "getString", "(", "\"osm_id\"", ")", ",", "// jPlace.getString(\"place_rank\"),", "jPlace", ".", "getString", "(", "\"boundingbox\"", ")", ",", "jPlace", ".", "getString", "(", "\"lat\"", ")", ",", "jPlace", ".", "getString", "(", "\"lon\"", ")", ",", "jPlace", ".", "getString", "(", "\"display_name\"", ")", ",", "jPlace", ".", "getString", "(", "\"class\"", ")", ",", "jPlace", ".", "getString", "(", "\"type\"", ")", ",", "jPlace", ".", "getString", "(", "\"importance\"", ")", ")", ";", "entries", ".", "add", "(", "poi", ")", ";", "}", "}", "catch", "(", "JSONException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "finally", "{", "if", "(", "streamReader", "!=", "null", ")", "{", "streamReader", ".", "close", "(", ")", ";", "}", "}", "// StackOverflowXmlParser returns a List (called \"entries\") of Entry objects.", "// Each Entry object represents a single place in the XML searchresult.", "// This section processes the entries list to create a 'DummyItem' from each entry.", "for", "(", "Entry", "entry", ":", "entries", ")", "{", "rtnArray", ".", "add", "(", "new", "DummyItem", "(", "entry", ".", "mOsm_id", ",", "entry", ".", "mDisplay_name", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "new", "LatLong", "(", "Double", ".", "parseDouble", "(", "entry", ".", "mLat", ")", ",", "Double", ".", "parseDouble", "(", "entry", ".", "mLon", ")", ")", ",", "entry", ".", "mDisplay_name", ")", ")", ";", "}", "return", "rtnArray", ";", "}" ]
Uploads XML from nominatim.openstreetmap.org, parses it, and create DummyItems from it
[ "Uploads", "XML", "from", "nominatim", ".", "openstreetmap", ".", "org", "parses", "it", "and", "create", "DummyItems", "from", "it" ]
c49c83f7f727552f793dff15cefa532ade030842
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/dummy/ManyDummyContent.java#L83-L141