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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
21,000
|
qos-ch/slf4j
|
slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java
|
LocLogger.warn
|
public void warn(Enum<?> key, Object... args) {
if (!logger.isWarnEnabled()) {
return;
}
String translatedMsg = imc.getMessage(key, args);
MessageParameterObj mpo = new MessageParameterObj(key, args);
if (instanceofLAL) {
((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.WARN_INT, translatedMsg, args, null);
} else {
logger.warn(LOCALIZED, translatedMsg, mpo);
}
}
|
java
|
public void warn(Enum<?> key, Object... args) {
if (!logger.isWarnEnabled()) {
return;
}
String translatedMsg = imc.getMessage(key, args);
MessageParameterObj mpo = new MessageParameterObj(key, args);
if (instanceofLAL) {
((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.WARN_INT, translatedMsg, args, null);
} else {
logger.warn(LOCALIZED, translatedMsg, mpo);
}
}
|
[
"public",
"void",
"warn",
"(",
"Enum",
"<",
"?",
">",
"key",
",",
"Object",
"...",
"args",
")",
"{",
"if",
"(",
"!",
"logger",
".",
"isWarnEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"String",
"translatedMsg",
"=",
"imc",
".",
"getMessage",
"(",
"key",
",",
"args",
")",
";",
"MessageParameterObj",
"mpo",
"=",
"new",
"MessageParameterObj",
"(",
"key",
",",
"args",
")",
";",
"if",
"(",
"instanceofLAL",
")",
"{",
"(",
"(",
"LocationAwareLogger",
")",
"logger",
")",
".",
"log",
"(",
"LOCALIZED",
",",
"FQCN",
",",
"LocationAwareLogger",
".",
"WARN_INT",
",",
"translatedMsg",
",",
"args",
",",
"null",
")",
";",
"}",
"else",
"{",
"logger",
".",
"warn",
"(",
"LOCALIZED",
",",
"translatedMsg",
",",
"mpo",
")",
";",
"}",
"}"
] |
Log a localized message at the WARN level.
@param key
the key used for localization
@param args
optional arguments
|
[
"Log",
"a",
"localized",
"message",
"at",
"the",
"WARN",
"level",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java#L137-L149
|
21,001
|
qos-ch/slf4j
|
slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java
|
LocLogger.error
|
public void error(Enum<?> key, Object... args) {
if (!logger.isErrorEnabled()) {
return;
}
String translatedMsg = imc.getMessage(key, args);
MessageParameterObj mpo = new MessageParameterObj(key, args);
if (instanceofLAL) {
((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.ERROR_INT, translatedMsg, args, null);
} else {
logger.error(LOCALIZED, translatedMsg, mpo);
}
}
|
java
|
public void error(Enum<?> key, Object... args) {
if (!logger.isErrorEnabled()) {
return;
}
String translatedMsg = imc.getMessage(key, args);
MessageParameterObj mpo = new MessageParameterObj(key, args);
if (instanceofLAL) {
((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.ERROR_INT, translatedMsg, args, null);
} else {
logger.error(LOCALIZED, translatedMsg, mpo);
}
}
|
[
"public",
"void",
"error",
"(",
"Enum",
"<",
"?",
">",
"key",
",",
"Object",
"...",
"args",
")",
"{",
"if",
"(",
"!",
"logger",
".",
"isErrorEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"String",
"translatedMsg",
"=",
"imc",
".",
"getMessage",
"(",
"key",
",",
"args",
")",
";",
"MessageParameterObj",
"mpo",
"=",
"new",
"MessageParameterObj",
"(",
"key",
",",
"args",
")",
";",
"if",
"(",
"instanceofLAL",
")",
"{",
"(",
"(",
"LocationAwareLogger",
")",
"logger",
")",
".",
"log",
"(",
"LOCALIZED",
",",
"FQCN",
",",
"LocationAwareLogger",
".",
"ERROR_INT",
",",
"translatedMsg",
",",
"args",
",",
"null",
")",
";",
"}",
"else",
"{",
"logger",
".",
"error",
"(",
"LOCALIZED",
",",
"translatedMsg",
",",
"mpo",
")",
";",
"}",
"}"
] |
Log a localized message at the ERROR level.
@param key
the key used for localization
@param args
optional arguments
|
[
"Log",
"a",
"localized",
"message",
"at",
"the",
"ERROR",
"level",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java#L159-L171
|
21,002
|
qos-ch/slf4j
|
slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java
|
XLogger.entry
|
public void entry(Object... argArray) {
if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
String messagePattern = null;
if (argArray.length < ENTRY_MESSAGE_ARRAY_LEN) {
messagePattern = ENTRY_MESSAGE_ARRAY[argArray.length];
} else {
messagePattern = buildMessagePattern(argArray.length);
}
FormattingTuple tp = MessageFormatter.arrayFormat(messagePattern, argArray);
((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), argArray, tp.getThrowable());
}
}
|
java
|
public void entry(Object... argArray) {
if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
String messagePattern = null;
if (argArray.length < ENTRY_MESSAGE_ARRAY_LEN) {
messagePattern = ENTRY_MESSAGE_ARRAY[argArray.length];
} else {
messagePattern = buildMessagePattern(argArray.length);
}
FormattingTuple tp = MessageFormatter.arrayFormat(messagePattern, argArray);
((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), argArray, tp.getThrowable());
}
}
|
[
"public",
"void",
"entry",
"(",
"Object",
"...",
"argArray",
")",
"{",
"if",
"(",
"instanceofLAL",
"&&",
"logger",
".",
"isTraceEnabled",
"(",
"ENTRY_MARKER",
")",
")",
"{",
"String",
"messagePattern",
"=",
"null",
";",
"if",
"(",
"argArray",
".",
"length",
"<",
"ENTRY_MESSAGE_ARRAY_LEN",
")",
"{",
"messagePattern",
"=",
"ENTRY_MESSAGE_ARRAY",
"[",
"argArray",
".",
"length",
"]",
";",
"}",
"else",
"{",
"messagePattern",
"=",
"buildMessagePattern",
"(",
"argArray",
".",
"length",
")",
";",
"}",
"FormattingTuple",
"tp",
"=",
"MessageFormatter",
".",
"arrayFormat",
"(",
"messagePattern",
",",
"argArray",
")",
";",
"(",
"(",
"LocationAwareLogger",
")",
"logger",
")",
".",
"log",
"(",
"ENTRY_MARKER",
",",
"FQCN",
",",
"LocationAwareLogger",
".",
"TRACE_INT",
",",
"tp",
".",
"getMessage",
"(",
")",
",",
"argArray",
",",
"tp",
".",
"getThrowable",
"(",
")",
")",
";",
"}",
"}"
] |
Log method entry.
@param argArray
supplied parameters
|
[
"Log",
"method",
"entry",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java#L115-L126
|
21,003
|
qos-ch/slf4j
|
slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java
|
XLogger.throwing
|
public <T extends Throwable> T throwing(T throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", null, throwable);
}
return throwable;
}
|
java
|
public <T extends Throwable> T throwing(T throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", null, throwable);
}
return throwable;
}
|
[
"public",
"<",
"T",
"extends",
"Throwable",
">",
"T",
"throwing",
"(",
"T",
"throwable",
")",
"{",
"if",
"(",
"instanceofLAL",
")",
"{",
"(",
"(",
"LocationAwareLogger",
")",
"logger",
")",
".",
"log",
"(",
"THROWING_MARKER",
",",
"FQCN",
",",
"LocationAwareLogger",
".",
"ERROR_INT",
",",
"\"throwing\"",
",",
"null",
",",
"throwable",
")",
";",
"}",
"return",
"throwable",
";",
"}"
] |
Log an exception being thrown. The generated log event uses Level ERROR.
@param throwable
the exception being caught.
|
[
"Log",
"an",
"exception",
"being",
"thrown",
".",
"The",
"generated",
"log",
"event",
"uses",
"Level",
"ERROR",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java#L157-L162
|
21,004
|
qos-ch/slf4j
|
slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java
|
XLogger.throwing
|
public <T extends Throwable> T throwing(Level level, T throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, level.level, "throwing", null, throwable);
}
return throwable;
}
|
java
|
public <T extends Throwable> T throwing(Level level, T throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, level.level, "throwing", null, throwable);
}
return throwable;
}
|
[
"public",
"<",
"T",
"extends",
"Throwable",
">",
"T",
"throwing",
"(",
"Level",
"level",
",",
"T",
"throwable",
")",
"{",
"if",
"(",
"instanceofLAL",
")",
"{",
"(",
"(",
"LocationAwareLogger",
")",
"logger",
")",
".",
"log",
"(",
"THROWING_MARKER",
",",
"FQCN",
",",
"level",
".",
"level",
",",
"\"throwing\"",
",",
"null",
",",
"throwable",
")",
";",
"}",
"return",
"throwable",
";",
"}"
] |
Log an exception being thrown allowing the log level to be specified.
@param level
the logging level to use.
@param throwable
the exception being caught.
|
[
"Log",
"an",
"exception",
"being",
"thrown",
"allowing",
"the",
"log",
"level",
"to",
"be",
"specified",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java#L172-L177
|
21,005
|
qos-ch/slf4j
|
slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java
|
XLogger.catching
|
public void catching(Throwable throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "catching", null, throwable);
}
}
|
java
|
public void catching(Throwable throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "catching", null, throwable);
}
}
|
[
"public",
"void",
"catching",
"(",
"Throwable",
"throwable",
")",
"{",
"if",
"(",
"instanceofLAL",
")",
"{",
"(",
"(",
"LocationAwareLogger",
")",
"logger",
")",
".",
"log",
"(",
"CATCHING_MARKER",
",",
"FQCN",
",",
"LocationAwareLogger",
".",
"ERROR_INT",
",",
"\"catching\"",
",",
"null",
",",
"throwable",
")",
";",
"}",
"}"
] |
Log an exception being caught. The generated log event uses Level ERROR.
@param throwable
the exception being caught.
|
[
"Log",
"an",
"exception",
"being",
"caught",
".",
"The",
"generated",
"log",
"event",
"uses",
"Level",
"ERROR",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java#L185-L189
|
21,006
|
qos-ch/slf4j
|
slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java
|
XLogger.catching
|
public void catching(Level level, Throwable throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, level.level, "catching", null, throwable);
}
}
|
java
|
public void catching(Level level, Throwable throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, level.level, "catching", null, throwable);
}
}
|
[
"public",
"void",
"catching",
"(",
"Level",
"level",
",",
"Throwable",
"throwable",
")",
"{",
"if",
"(",
"instanceofLAL",
")",
"{",
"(",
"(",
"LocationAwareLogger",
")",
"logger",
")",
".",
"log",
"(",
"CATCHING_MARKER",
",",
"FQCN",
",",
"level",
".",
"level",
",",
"\"catching\"",
",",
"null",
",",
"throwable",
")",
";",
"}",
"}"
] |
Log an exception being caught allowing the log level to be specified.
@param level
the logging level to use.
@param throwable
the exception being caught.
|
[
"Log",
"an",
"exception",
"being",
"caught",
"allowing",
"the",
"log",
"level",
"to",
"be",
"specified",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java#L199-L203
|
21,007
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.formatAndLog
|
private void formatAndLog(int level, String format, Object arg1, Object arg2) {
if (!isLevelEnabled(level)) {
return;
}
FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
log(level, tp.getMessage(), tp.getThrowable());
}
|
java
|
private void formatAndLog(int level, String format, Object arg1, Object arg2) {
if (!isLevelEnabled(level)) {
return;
}
FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
log(level, tp.getMessage(), tp.getThrowable());
}
|
[
"private",
"void",
"formatAndLog",
"(",
"int",
"level",
",",
"String",
"format",
",",
"Object",
"arg1",
",",
"Object",
"arg2",
")",
"{",
"if",
"(",
"!",
"isLevelEnabled",
"(",
"level",
")",
")",
"{",
"return",
";",
"}",
"FormattingTuple",
"tp",
"=",
"MessageFormatter",
".",
"format",
"(",
"format",
",",
"arg1",
",",
"arg2",
")",
";",
"log",
"(",
"level",
",",
"tp",
".",
"getMessage",
"(",
")",
",",
"tp",
".",
"getThrowable",
"(",
")",
")",
";",
"}"
] |
For formatted messages, first substitute arguments and then log.
@param level
@param format
@param arg1
@param arg2
|
[
"For",
"formatted",
"messages",
"first",
"substitute",
"arguments",
"and",
"then",
"log",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L350-L356
|
21,008
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.trace
|
public void trace(String format, Object param1) {
formatAndLog(LOG_LEVEL_TRACE, format, param1, null);
}
|
java
|
public void trace(String format, Object param1) {
formatAndLog(LOG_LEVEL_TRACE, format, param1, null);
}
|
[
"public",
"void",
"trace",
"(",
"String",
"format",
",",
"Object",
"param1",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_TRACE",
",",
"format",
",",
"param1",
",",
"null",
")",
";",
"}"
] |
Perform single parameter substitution before logging the message of level
TRACE according to the format outlined above.
|
[
"Perform",
"single",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"TRACE",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L403-L405
|
21,009
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.trace
|
public void trace(String format, Object param1, Object param2) {
formatAndLog(LOG_LEVEL_TRACE, format, param1, param2);
}
|
java
|
public void trace(String format, Object param1, Object param2) {
formatAndLog(LOG_LEVEL_TRACE, format, param1, param2);
}
|
[
"public",
"void",
"trace",
"(",
"String",
"format",
",",
"Object",
"param1",
",",
"Object",
"param2",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_TRACE",
",",
"format",
",",
"param1",
",",
"param2",
")",
";",
"}"
] |
Perform double parameter substitution before logging the message of level
TRACE according to the format outlined above.
|
[
"Perform",
"double",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"TRACE",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L411-L413
|
21,010
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.debug
|
public void debug(String format, Object param1) {
formatAndLog(LOG_LEVEL_DEBUG, format, param1, null);
}
|
java
|
public void debug(String format, Object param1) {
formatAndLog(LOG_LEVEL_DEBUG, format, param1, null);
}
|
[
"public",
"void",
"debug",
"(",
"String",
"format",
",",
"Object",
"param1",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_DEBUG",
",",
"format",
",",
"param1",
",",
"null",
")",
";",
"}"
] |
Perform single parameter substitution before logging the message of level
DEBUG according to the format outlined above.
|
[
"Perform",
"single",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"DEBUG",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L445-L447
|
21,011
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.debug
|
public void debug(String format, Object param1, Object param2) {
formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2);
}
|
java
|
public void debug(String format, Object param1, Object param2) {
formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2);
}
|
[
"public",
"void",
"debug",
"(",
"String",
"format",
",",
"Object",
"param1",
",",
"Object",
"param2",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_DEBUG",
",",
"format",
",",
"param1",
",",
"param2",
")",
";",
"}"
] |
Perform double parameter substitution before logging the message of level
DEBUG according to the format outlined above.
|
[
"Perform",
"double",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"DEBUG",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L453-L455
|
21,012
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.info
|
public void info(String format, Object arg) {
formatAndLog(LOG_LEVEL_INFO, format, arg, null);
}
|
java
|
public void info(String format, Object arg) {
formatAndLog(LOG_LEVEL_INFO, format, arg, null);
}
|
[
"public",
"void",
"info",
"(",
"String",
"format",
",",
"Object",
"arg",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_INFO",
",",
"format",
",",
"arg",
",",
"null",
")",
";",
"}"
] |
Perform single parameter substitution before logging the message of level
INFO according to the format outlined above.
|
[
"Perform",
"single",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"INFO",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L487-L489
|
21,013
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.info
|
public void info(String format, Object arg1, Object arg2) {
formatAndLog(LOG_LEVEL_INFO, format, arg1, arg2);
}
|
java
|
public void info(String format, Object arg1, Object arg2) {
formatAndLog(LOG_LEVEL_INFO, format, arg1, arg2);
}
|
[
"public",
"void",
"info",
"(",
"String",
"format",
",",
"Object",
"arg1",
",",
"Object",
"arg2",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_INFO",
",",
"format",
",",
"arg1",
",",
"arg2",
")",
";",
"}"
] |
Perform double parameter substitution before logging the message of level
INFO according to the format outlined above.
|
[
"Perform",
"double",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"INFO",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L495-L497
|
21,014
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.warn
|
public void warn(String format, Object arg) {
formatAndLog(LOG_LEVEL_WARN, format, arg, null);
}
|
java
|
public void warn(String format, Object arg) {
formatAndLog(LOG_LEVEL_WARN, format, arg, null);
}
|
[
"public",
"void",
"warn",
"(",
"String",
"format",
",",
"Object",
"arg",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_WARN",
",",
"format",
",",
"arg",
",",
"null",
")",
";",
"}"
] |
Perform single parameter substitution before logging the message of level
WARN according to the format outlined above.
|
[
"Perform",
"single",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"WARN",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L529-L531
|
21,015
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.warn
|
public void warn(String format, Object arg1, Object arg2) {
formatAndLog(LOG_LEVEL_WARN, format, arg1, arg2);
}
|
java
|
public void warn(String format, Object arg1, Object arg2) {
formatAndLog(LOG_LEVEL_WARN, format, arg1, arg2);
}
|
[
"public",
"void",
"warn",
"(",
"String",
"format",
",",
"Object",
"arg1",
",",
"Object",
"arg2",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_WARN",
",",
"format",
",",
"arg1",
",",
"arg2",
")",
";",
"}"
] |
Perform double parameter substitution before logging the message of level
WARN according to the format outlined above.
|
[
"Perform",
"double",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"WARN",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L537-L539
|
21,016
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.error
|
public void error(String format, Object arg) {
formatAndLog(LOG_LEVEL_ERROR, format, arg, null);
}
|
java
|
public void error(String format, Object arg) {
formatAndLog(LOG_LEVEL_ERROR, format, arg, null);
}
|
[
"public",
"void",
"error",
"(",
"String",
"format",
",",
"Object",
"arg",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_ERROR",
",",
"format",
",",
"arg",
",",
"null",
")",
";",
"}"
] |
Perform single parameter substitution before logging the message of level
ERROR according to the format outlined above.
|
[
"Perform",
"single",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"ERROR",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L571-L573
|
21,017
|
qos-ch/slf4j
|
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
|
SimpleLogger.error
|
public void error(String format, Object arg1, Object arg2) {
formatAndLog(LOG_LEVEL_ERROR, format, arg1, arg2);
}
|
java
|
public void error(String format, Object arg1, Object arg2) {
formatAndLog(LOG_LEVEL_ERROR, format, arg1, arg2);
}
|
[
"public",
"void",
"error",
"(",
"String",
"format",
",",
"Object",
"arg1",
",",
"Object",
"arg2",
")",
"{",
"formatAndLog",
"(",
"LOG_LEVEL_ERROR",
",",
"format",
",",
"arg1",
",",
"arg2",
")",
";",
"}"
] |
Perform double parameter substitution before logging the message of level
ERROR according to the format outlined above.
|
[
"Perform",
"double",
"parameter",
"substitution",
"before",
"logging",
"the",
"message",
"of",
"level",
"ERROR",
"according",
"to",
"the",
"format",
"outlined",
"above",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java#L579-L581
|
21,018
|
qos-ch/slf4j
|
jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java
|
SLF4JBridgeHandler.isInstalled
|
public static boolean isInstalled() throws SecurityException {
java.util.logging.Logger rootLogger = getRootLogger();
Handler[] handlers = rootLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
if (handlers[i] instanceof SLF4JBridgeHandler) {
return true;
}
}
return false;
}
|
java
|
public static boolean isInstalled() throws SecurityException {
java.util.logging.Logger rootLogger = getRootLogger();
Handler[] handlers = rootLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
if (handlers[i] instanceof SLF4JBridgeHandler) {
return true;
}
}
return false;
}
|
[
"public",
"static",
"boolean",
"isInstalled",
"(",
")",
"throws",
"SecurityException",
"{",
"java",
".",
"util",
".",
"logging",
".",
"Logger",
"rootLogger",
"=",
"getRootLogger",
"(",
")",
";",
"Handler",
"[",
"]",
"handlers",
"=",
"rootLogger",
".",
"getHandlers",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"handlers",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"handlers",
"[",
"i",
"]",
"instanceof",
"SLF4JBridgeHandler",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Returns true if SLF4JBridgeHandler has been previously installed, returns false otherwise.
@return true if SLF4JBridgeHandler is already installed, false other wise
@throws SecurityException
|
[
"Returns",
"true",
"if",
"SLF4JBridgeHandler",
"has",
"been",
"previously",
"installed",
"returns",
"false",
"otherwise",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java#L160-L169
|
21,019
|
qos-ch/slf4j
|
jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java
|
SLF4JBridgeHandler.getSLF4JLogger
|
protected Logger getSLF4JLogger(LogRecord record) {
String name = record.getLoggerName();
if (name == null) {
name = UNKNOWN_LOGGER_NAME;
}
return LoggerFactory.getLogger(name);
}
|
java
|
protected Logger getSLF4JLogger(LogRecord record) {
String name = record.getLoggerName();
if (name == null) {
name = UNKNOWN_LOGGER_NAME;
}
return LoggerFactory.getLogger(name);
}
|
[
"protected",
"Logger",
"getSLF4JLogger",
"(",
"LogRecord",
"record",
")",
"{",
"String",
"name",
"=",
"record",
".",
"getLoggerName",
"(",
")",
";",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"name",
"=",
"UNKNOWN_LOGGER_NAME",
";",
"}",
"return",
"LoggerFactory",
".",
"getLogger",
"(",
"name",
")",
";",
"}"
] |
Return the Logger instance that will be used for logging.
|
[
"Return",
"the",
"Logger",
"instance",
"that",
"will",
"be",
"used",
"for",
"logging",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java#L206-L212
|
21,020
|
qos-ch/slf4j
|
jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java
|
SLF4JBridgeHandler.getMessageI18N
|
private String getMessageI18N(LogRecord record) {
String message = record.getMessage();
if (message == null) {
return null;
}
ResourceBundle bundle = record.getResourceBundle();
if (bundle != null) {
try {
message = bundle.getString(message);
} catch (MissingResourceException e) {
}
}
Object[] params = record.getParameters();
// avoid formatting when there are no or 0 parameters. see also
// http://jira.qos.ch/browse/SLF4J-203
if (params != null && params.length > 0) {
try {
message = MessageFormat.format(message, params);
} catch (IllegalArgumentException e) {
// default to the same behavior as in java.util.logging.Formatter.formatMessage(LogRecord)
// see also http://jira.qos.ch/browse/SLF4J-337
return message;
}
}
return message;
}
|
java
|
private String getMessageI18N(LogRecord record) {
String message = record.getMessage();
if (message == null) {
return null;
}
ResourceBundle bundle = record.getResourceBundle();
if (bundle != null) {
try {
message = bundle.getString(message);
} catch (MissingResourceException e) {
}
}
Object[] params = record.getParameters();
// avoid formatting when there are no or 0 parameters. see also
// http://jira.qos.ch/browse/SLF4J-203
if (params != null && params.length > 0) {
try {
message = MessageFormat.format(message, params);
} catch (IllegalArgumentException e) {
// default to the same behavior as in java.util.logging.Formatter.formatMessage(LogRecord)
// see also http://jira.qos.ch/browse/SLF4J-337
return message;
}
}
return message;
}
|
[
"private",
"String",
"getMessageI18N",
"(",
"LogRecord",
"record",
")",
"{",
"String",
"message",
"=",
"record",
".",
"getMessage",
"(",
")",
";",
"if",
"(",
"message",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"ResourceBundle",
"bundle",
"=",
"record",
".",
"getResourceBundle",
"(",
")",
";",
"if",
"(",
"bundle",
"!=",
"null",
")",
"{",
"try",
"{",
"message",
"=",
"bundle",
".",
"getString",
"(",
"message",
")",
";",
"}",
"catch",
"(",
"MissingResourceException",
"e",
")",
"{",
"}",
"}",
"Object",
"[",
"]",
"params",
"=",
"record",
".",
"getParameters",
"(",
")",
";",
"// avoid formatting when there are no or 0 parameters. see also",
"// http://jira.qos.ch/browse/SLF4J-203",
"if",
"(",
"params",
"!=",
"null",
"&&",
"params",
".",
"length",
">",
"0",
")",
"{",
"try",
"{",
"message",
"=",
"MessageFormat",
".",
"format",
"(",
"message",
",",
"params",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"// default to the same behavior as in java.util.logging.Formatter.formatMessage(LogRecord)",
"// see also http://jira.qos.ch/browse/SLF4J-337",
"return",
"message",
";",
"}",
"}",
"return",
"message",
";",
"}"
] |
Get the record's message, possibly via a resource bundle.
@param record
@return
|
[
"Get",
"the",
"record",
"s",
"message",
"possibly",
"via",
"a",
"resource",
"bundle",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java#L255-L282
|
21,021
|
qos-ch/slf4j
|
slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java
|
AgentPremain.printStartStopTimes
|
private static void printStartStopTimes() {
final long start = System.currentTimeMillis();
System.err.println("Start at " + new Date());
Thread hook = new Thread() {
@Override
public void run() {
long timePassed = System.currentTimeMillis() - start;
System.err.println("Stop at " + new Date() + ", execution time = " + timePassed + " ms");
}
};
Runtime.getRuntime().addShutdownHook(hook);
}
|
java
|
private static void printStartStopTimes() {
final long start = System.currentTimeMillis();
System.err.println("Start at " + new Date());
Thread hook = new Thread() {
@Override
public void run() {
long timePassed = System.currentTimeMillis() - start;
System.err.println("Stop at " + new Date() + ", execution time = " + timePassed + " ms");
}
};
Runtime.getRuntime().addShutdownHook(hook);
}
|
[
"private",
"static",
"void",
"printStartStopTimes",
"(",
")",
"{",
"final",
"long",
"start",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
"\"Start at \"",
"+",
"new",
"Date",
"(",
")",
")",
";",
"Thread",
"hook",
"=",
"new",
"Thread",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"long",
"timePassed",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"start",
";",
"System",
".",
"err",
".",
"println",
"(",
"\"Stop at \"",
"+",
"new",
"Date",
"(",
")",
"+",
"\", execution time = \"",
"+",
"timePassed",
"+",
"\" ms\"",
")",
";",
"}",
"}",
";",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"addShutdownHook",
"(",
"hook",
")",
";",
"}"
] |
Print the start message to System.err with the time NOW, and register a
shutdown hook which will print the stop message to System.err with the
time then and the number of milliseconds passed since.
|
[
"Print",
"the",
"start",
"message",
"to",
"System",
".",
"err",
"with",
"the",
"time",
"NOW",
"and",
"register",
"a",
"shutdown",
"hook",
"which",
"will",
"print",
"the",
"stop",
"message",
"to",
"System",
".",
"err",
"with",
"the",
"time",
"then",
"and",
"the",
"number",
"of",
"milliseconds",
"passed",
"since",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java#L112-L125
|
21,022
|
qos-ch/slf4j
|
log4j-over-slf4j/src/main/java/org/apache/log4j/Category.java
|
Category.isEnabledFor
|
public boolean isEnabledFor(Priority p) {
switch (p.level) {
case Level.TRACE_INT:
return slf4jLogger.isTraceEnabled();
case Level.DEBUG_INT:
return slf4jLogger.isDebugEnabled();
case Level.INFO_INT:
return slf4jLogger.isInfoEnabled();
case Level.WARN_INT:
return slf4jLogger.isWarnEnabled();
case Level.ERROR_INT:
return slf4jLogger.isErrorEnabled();
case Priority.FATAL_INT:
return slf4jLogger.isErrorEnabled();
}
return false;
}
|
java
|
public boolean isEnabledFor(Priority p) {
switch (p.level) {
case Level.TRACE_INT:
return slf4jLogger.isTraceEnabled();
case Level.DEBUG_INT:
return slf4jLogger.isDebugEnabled();
case Level.INFO_INT:
return slf4jLogger.isInfoEnabled();
case Level.WARN_INT:
return slf4jLogger.isWarnEnabled();
case Level.ERROR_INT:
return slf4jLogger.isErrorEnabled();
case Priority.FATAL_INT:
return slf4jLogger.isErrorEnabled();
}
return false;
}
|
[
"public",
"boolean",
"isEnabledFor",
"(",
"Priority",
"p",
")",
"{",
"switch",
"(",
"p",
".",
"level",
")",
"{",
"case",
"Level",
".",
"TRACE_INT",
":",
"return",
"slf4jLogger",
".",
"isTraceEnabled",
"(",
")",
";",
"case",
"Level",
".",
"DEBUG_INT",
":",
"return",
"slf4jLogger",
".",
"isDebugEnabled",
"(",
")",
";",
"case",
"Level",
".",
"INFO_INT",
":",
"return",
"slf4jLogger",
".",
"isInfoEnabled",
"(",
")",
";",
"case",
"Level",
".",
"WARN_INT",
":",
"return",
"slf4jLogger",
".",
"isWarnEnabled",
"(",
")",
";",
"case",
"Level",
".",
"ERROR_INT",
":",
"return",
"slf4jLogger",
".",
"isErrorEnabled",
"(",
")",
";",
"case",
"Priority",
".",
"FATAL_INT",
":",
"return",
"slf4jLogger",
".",
"isErrorEnabled",
"(",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Determines whether the priority passed as parameter is enabled in the
underlying SLF4J logger. Each log4j priority is mapped directly to its
SLF4J equivalent, except for FATAL which is mapped as ERROR.
@param p
the priority to check against
@return true if this logger is enabled for the given level, false
otherwise.
|
[
"Determines",
"whether",
"the",
"priority",
"passed",
"as",
"parameter",
"is",
"enabled",
"in",
"the",
"underlying",
"SLF4J",
"logger",
".",
"Each",
"log4j",
"priority",
"is",
"mapped",
"directly",
"to",
"its",
"SLF4J",
"equivalent",
"except",
"for",
"FATAL",
"which",
"is",
"mapped",
"as",
"ERROR",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/log4j-over-slf4j/src/main/java/org/apache/log4j/Category.java#L171-L187
|
21,023
|
qos-ch/slf4j
|
slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java
|
ProjectConverter.scanFileList
|
private void scanFileList(List<File> lstFiles) {
progressListener.onFileScanBegin();
Iterator<File> itFile = lstFiles.iterator();
while (itFile.hasNext()) {
File currentFile = itFile.next();
progressListener.onFileScan(currentFile);
scanFile(currentFile);
}
}
|
java
|
private void scanFileList(List<File> lstFiles) {
progressListener.onFileScanBegin();
Iterator<File> itFile = lstFiles.iterator();
while (itFile.hasNext()) {
File currentFile = itFile.next();
progressListener.onFileScan(currentFile);
scanFile(currentFile);
}
}
|
[
"private",
"void",
"scanFileList",
"(",
"List",
"<",
"File",
">",
"lstFiles",
")",
"{",
"progressListener",
".",
"onFileScanBegin",
"(",
")",
";",
"Iterator",
"<",
"File",
">",
"itFile",
"=",
"lstFiles",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"itFile",
".",
"hasNext",
"(",
")",
")",
"{",
"File",
"currentFile",
"=",
"itFile",
".",
"next",
"(",
")",
";",
"progressListener",
".",
"onFileScan",
"(",
"currentFile",
")",
";",
"scanFile",
"(",
"currentFile",
")",
";",
"}",
"}"
] |
Convert a list of files
@param lstFiles
|
[
"Convert",
"a",
"list",
"of",
"files"
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java#L84-L92
|
21,024
|
qos-ch/slf4j
|
slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java
|
ProjectConverter.scanFile
|
private void scanFile(File file) {
try {
InplaceFileConverter fc = new InplaceFileConverter(ruleSet, progressListener);
fc.convert(file);
} catch (IOException exc) {
addException(new ConversionException(exc.toString()));
}
}
|
java
|
private void scanFile(File file) {
try {
InplaceFileConverter fc = new InplaceFileConverter(ruleSet, progressListener);
fc.convert(file);
} catch (IOException exc) {
addException(new ConversionException(exc.toString()));
}
}
|
[
"private",
"void",
"scanFile",
"(",
"File",
"file",
")",
"{",
"try",
"{",
"InplaceFileConverter",
"fc",
"=",
"new",
"InplaceFileConverter",
"(",
"ruleSet",
",",
"progressListener",
")",
";",
"fc",
".",
"convert",
"(",
"file",
")",
";",
"}",
"catch",
"(",
"IOException",
"exc",
")",
"{",
"addException",
"(",
"new",
"ConversionException",
"(",
"exc",
".",
"toString",
"(",
")",
")",
")",
";",
"}",
"}"
] |
Convert the specified file Read each line and ask matcher implementation
for conversion Rewrite the line returned by matcher
@param file
|
[
"Convert",
"the",
"specified",
"file",
"Read",
"each",
"line",
"and",
"ask",
"matcher",
"implementation",
"for",
"conversion",
"Rewrite",
"the",
"line",
"returned",
"by",
"matcher"
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java#L100-L107
|
21,025
|
qos-ch/slf4j
|
slf4j-jdk14/src/main/java/org/slf4j/jul/JDK14LoggerAdapter.java
|
JDK14LoggerAdapter.trace
|
public void trace(String msg) {
if (logger.isLoggable(Level.FINEST)) {
log(SELF, Level.FINEST, msg, null);
}
}
|
java
|
public void trace(String msg) {
if (logger.isLoggable(Level.FINEST)) {
log(SELF, Level.FINEST, msg, null);
}
}
|
[
"public",
"void",
"trace",
"(",
"String",
"msg",
")",
"{",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"FINEST",
")",
")",
"{",
"log",
"(",
"SELF",
",",
"Level",
".",
"FINEST",
",",
"msg",
",",
"null",
")",
";",
"}",
"}"
] |
Log a message object at level FINEST.
@param msg
- the message object to be logged
|
[
"Log",
"a",
"message",
"object",
"at",
"level",
"FINEST",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-jdk14/src/main/java/org/slf4j/jul/JDK14LoggerAdapter.java#L77-L81
|
21,026
|
qos-ch/slf4j
|
slf4j-jdk14/src/main/java/org/slf4j/jul/JDK14LoggerAdapter.java
|
JDK14LoggerAdapter.info
|
public void info(String msg) {
if (logger.isLoggable(Level.INFO)) {
log(SELF, Level.INFO, msg, null);
}
}
|
java
|
public void info(String msg) {
if (logger.isLoggable(Level.INFO)) {
log(SELF, Level.INFO, msg, null);
}
}
|
[
"public",
"void",
"info",
"(",
"String",
"msg",
")",
"{",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"INFO",
")",
")",
"{",
"log",
"(",
"SELF",
",",
"Level",
".",
"INFO",
",",
"msg",
",",
"null",
")",
";",
"}",
"}"
] |
Log a message object at the INFO level.
@param msg
- the message object to be logged
|
[
"Log",
"a",
"message",
"object",
"at",
"the",
"INFO",
"level",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-jdk14/src/main/java/org/slf4j/jul/JDK14LoggerAdapter.java#L276-L280
|
21,027
|
qos-ch/slf4j
|
slf4j-jdk14/src/main/java/org/slf4j/jul/JDK14LoggerAdapter.java
|
JDK14LoggerAdapter.warn
|
public void warn(String msg) {
if (logger.isLoggable(Level.WARNING)) {
log(SELF, Level.WARNING, msg, null);
}
}
|
java
|
public void warn(String msg) {
if (logger.isLoggable(Level.WARNING)) {
log(SELF, Level.WARNING, msg, null);
}
}
|
[
"public",
"void",
"warn",
"(",
"String",
"msg",
")",
"{",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"WARNING",
")",
")",
"{",
"log",
"(",
"SELF",
",",
"Level",
".",
"WARNING",
",",
"msg",
",",
"null",
")",
";",
"}",
"}"
] |
Log a message object at the WARNING level.
@param msg
- the message object to be logged
|
[
"Log",
"a",
"message",
"object",
"at",
"the",
"WARNING",
"level",
"."
] |
905443f39fadd88a8dd2c467e44affd8cb072a4d
|
https://github.com/qos-ch/slf4j/blob/905443f39fadd88a8dd2c467e44affd8cb072a4d/slf4j-jdk14/src/main/java/org/slf4j/jul/JDK14LoggerAdapter.java#L377-L381
|
21,028
|
jamesdbloom/mockserver
|
mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java
|
MockServerClient.isRunning
|
public boolean isRunning(int attempts, long timeout, TimeUnit timeUnit) {
try {
HttpResponse httpResponse = sendRequest(request().withMethod("PUT").withPath(calculatePath("status")));
if (httpResponse.getStatusCode() == HttpStatusCode.OK_200.code()) {
return true;
} else if (attempts == 0) {
return false;
} else {
try {
timeUnit.sleep(timeout);
} catch (InterruptedException e) {
// ignore interrupted exception
}
return isRunning(attempts - 1, timeout, timeUnit);
}
} catch (SocketConnectionException sce) {
return false;
}
}
|
java
|
public boolean isRunning(int attempts, long timeout, TimeUnit timeUnit) {
try {
HttpResponse httpResponse = sendRequest(request().withMethod("PUT").withPath(calculatePath("status")));
if (httpResponse.getStatusCode() == HttpStatusCode.OK_200.code()) {
return true;
} else if (attempts == 0) {
return false;
} else {
try {
timeUnit.sleep(timeout);
} catch (InterruptedException e) {
// ignore interrupted exception
}
return isRunning(attempts - 1, timeout, timeUnit);
}
} catch (SocketConnectionException sce) {
return false;
}
}
|
[
"public",
"boolean",
"isRunning",
"(",
"int",
"attempts",
",",
"long",
"timeout",
",",
"TimeUnit",
"timeUnit",
")",
"{",
"try",
"{",
"HttpResponse",
"httpResponse",
"=",
"sendRequest",
"(",
"request",
"(",
")",
".",
"withMethod",
"(",
"\"PUT\"",
")",
".",
"withPath",
"(",
"calculatePath",
"(",
"\"status\"",
")",
")",
")",
";",
"if",
"(",
"httpResponse",
".",
"getStatusCode",
"(",
")",
"==",
"HttpStatusCode",
".",
"OK_200",
".",
"code",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"attempts",
"==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"try",
"{",
"timeUnit",
".",
"sleep",
"(",
"timeout",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"// ignore interrupted exception",
"}",
"return",
"isRunning",
"(",
"attempts",
"-",
"1",
",",
"timeout",
",",
"timeUnit",
")",
";",
"}",
"}",
"catch",
"(",
"SocketConnectionException",
"sce",
")",
"{",
"return",
"false",
";",
"}",
"}"
] |
Returns whether server MockServer is running, by polling the MockServer a configurable amount of times
|
[
"Returns",
"whether",
"server",
"MockServer",
"is",
"running",
"by",
"polling",
"the",
"MockServer",
"a",
"configurable",
"amount",
"of",
"times"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java#L198-L216
|
21,029
|
jamesdbloom/mockserver
|
mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java
|
MockServerClient.bind
|
public List<Integer> bind(Integer... ports) {
String boundPorts = sendRequest(request().withMethod("PUT").withPath(calculatePath("bind")).withBody(portBindingSerializer.serialize(portBinding(ports)), StandardCharsets.UTF_8)).getBodyAsString();
return portBindingSerializer.deserialize(boundPorts).getPorts();
}
|
java
|
public List<Integer> bind(Integer... ports) {
String boundPorts = sendRequest(request().withMethod("PUT").withPath(calculatePath("bind")).withBody(portBindingSerializer.serialize(portBinding(ports)), StandardCharsets.UTF_8)).getBodyAsString();
return portBindingSerializer.deserialize(boundPorts).getPorts();
}
|
[
"public",
"List",
"<",
"Integer",
">",
"bind",
"(",
"Integer",
"...",
"ports",
")",
"{",
"String",
"boundPorts",
"=",
"sendRequest",
"(",
"request",
"(",
")",
".",
"withMethod",
"(",
"\"PUT\"",
")",
".",
"withPath",
"(",
"calculatePath",
"(",
"\"bind\"",
")",
")",
".",
"withBody",
"(",
"portBindingSerializer",
".",
"serialize",
"(",
"portBinding",
"(",
"ports",
")",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
".",
"getBodyAsString",
"(",
")",
";",
"return",
"portBindingSerializer",
".",
"deserialize",
"(",
"boundPorts",
")",
".",
"getPorts",
"(",
")",
";",
"}"
] |
Bind new ports to listen on
|
[
"Bind",
"new",
"ports",
"to",
"listen",
"on"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java#L221-L224
|
21,030
|
jamesdbloom/mockserver
|
mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java
|
MockServerClient.reset
|
public MockServerClient reset() {
MockServerEventBus.getInstance().publish(EventType.RESET);
sendRequest(request().withMethod("PUT").withPath(calculatePath("reset")));
return clientClass.cast(this);
}
|
java
|
public MockServerClient reset() {
MockServerEventBus.getInstance().publish(EventType.RESET);
sendRequest(request().withMethod("PUT").withPath(calculatePath("reset")));
return clientClass.cast(this);
}
|
[
"public",
"MockServerClient",
"reset",
"(",
")",
"{",
"MockServerEventBus",
".",
"getInstance",
"(",
")",
".",
"publish",
"(",
"EventType",
".",
"RESET",
")",
";",
"sendRequest",
"(",
"request",
"(",
")",
".",
"withMethod",
"(",
"\"PUT\"",
")",
".",
"withPath",
"(",
"calculatePath",
"(",
"\"reset\"",
")",
")",
")",
";",
"return",
"clientClass",
".",
"cast",
"(",
"this",
")",
";",
"}"
] |
Reset MockServer by clearing all expectations
|
[
"Reset",
"MockServer",
"by",
"clearing",
"all",
"expectations"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java#L266-L270
|
21,031
|
jamesdbloom/mockserver
|
mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java
|
MockServerClient.clear
|
public MockServerClient clear(HttpRequest httpRequest) {
sendRequest(request().withMethod("PUT").withPath(calculatePath("clear")).withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8));
return clientClass.cast(this);
}
|
java
|
public MockServerClient clear(HttpRequest httpRequest) {
sendRequest(request().withMethod("PUT").withPath(calculatePath("clear")).withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8));
return clientClass.cast(this);
}
|
[
"public",
"MockServerClient",
"clear",
"(",
"HttpRequest",
"httpRequest",
")",
"{",
"sendRequest",
"(",
"request",
"(",
")",
".",
"withMethod",
"(",
"\"PUT\"",
")",
".",
"withPath",
"(",
"calculatePath",
"(",
"\"clear\"",
")",
")",
".",
"withBody",
"(",
"httpRequest",
"!=",
"null",
"?",
"httpRequestSerializer",
".",
"serialize",
"(",
"httpRequest",
")",
":",
"\"\"",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"return",
"clientClass",
".",
"cast",
"(",
"this",
")",
";",
"}"
] |
Clear all expectations and logs that match the http
@param httpRequest the http request that is matched against when deciding whether to clear each expectation if null all expectations are cleared
|
[
"Clear",
"all",
"expectations",
"and",
"logs",
"that",
"match",
"the",
"http"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java#L277-L280
|
21,032
|
jamesdbloom/mockserver
|
mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java
|
MockServerClient.clear
|
public MockServerClient clear(HttpRequest httpRequest, ClearType type) {
sendRequest(request().withMethod("PUT").withPath(calculatePath("clear")).withQueryStringParameter("type", type.name().toLowerCase()).withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8));
return clientClass.cast(this);
}
|
java
|
public MockServerClient clear(HttpRequest httpRequest, ClearType type) {
sendRequest(request().withMethod("PUT").withPath(calculatePath("clear")).withQueryStringParameter("type", type.name().toLowerCase()).withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8));
return clientClass.cast(this);
}
|
[
"public",
"MockServerClient",
"clear",
"(",
"HttpRequest",
"httpRequest",
",",
"ClearType",
"type",
")",
"{",
"sendRequest",
"(",
"request",
"(",
")",
".",
"withMethod",
"(",
"\"PUT\"",
")",
".",
"withPath",
"(",
"calculatePath",
"(",
"\"clear\"",
")",
")",
".",
"withQueryStringParameter",
"(",
"\"type\"",
",",
"type",
".",
"name",
"(",
")",
".",
"toLowerCase",
"(",
")",
")",
".",
"withBody",
"(",
"httpRequest",
"!=",
"null",
"?",
"httpRequestSerializer",
".",
"serialize",
"(",
"httpRequest",
")",
":",
"\"\"",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"return",
"clientClass",
".",
"cast",
"(",
"this",
")",
";",
"}"
] |
Clear expectations, logs or both that match the http
@param httpRequest the http request that is matched against when deciding whether to clear each expectation if null all expectations are cleared
@param type the type to clear, EXPECTATION, LOG or BOTH
|
[
"Clear",
"expectations",
"logs",
"or",
"both",
"that",
"match",
"the",
"http"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java#L288-L291
|
21,033
|
jamesdbloom/mockserver
|
mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java
|
MockServerClient.verifyZeroInteractions
|
public MockServerClient verifyZeroInteractions() throws AssertionError {
Verification verification = verification().withRequest(request()).withTimes(exactly(0));
String result = sendRequest(request().withMethod("PUT").withPath(calculatePath("verify")).withBody(verificationSerializer.serialize(verification), StandardCharsets.UTF_8)).getBodyAsString();
if (result != null && !result.isEmpty()) {
throw new AssertionError(result);
}
return clientClass.cast(this);
}
|
java
|
public MockServerClient verifyZeroInteractions() throws AssertionError {
Verification verification = verification().withRequest(request()).withTimes(exactly(0));
String result = sendRequest(request().withMethod("PUT").withPath(calculatePath("verify")).withBody(verificationSerializer.serialize(verification), StandardCharsets.UTF_8)).getBodyAsString();
if (result != null && !result.isEmpty()) {
throw new AssertionError(result);
}
return clientClass.cast(this);
}
|
[
"public",
"MockServerClient",
"verifyZeroInteractions",
"(",
")",
"throws",
"AssertionError",
"{",
"Verification",
"verification",
"=",
"verification",
"(",
")",
".",
"withRequest",
"(",
"request",
"(",
")",
")",
".",
"withTimes",
"(",
"exactly",
"(",
"0",
")",
")",
";",
"String",
"result",
"=",
"sendRequest",
"(",
"request",
"(",
")",
".",
"withMethod",
"(",
"\"PUT\"",
")",
".",
"withPath",
"(",
"calculatePath",
"(",
"\"verify\"",
")",
")",
".",
"withBody",
"(",
"verificationSerializer",
".",
"serialize",
"(",
"verification",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
".",
"getBodyAsString",
"(",
")",
";",
"if",
"(",
"result",
"!=",
"null",
"&&",
"!",
"result",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"AssertionError",
"(",
"result",
")",
";",
"}",
"return",
"clientClass",
".",
"cast",
"(",
"this",
")",
";",
"}"
] |
Verify no requests have been have been sent.
@throws AssertionError if any request has been found
|
[
"Verify",
"no",
"requests",
"have",
"been",
"have",
"been",
"sent",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java#L367-L375
|
21,034
|
jamesdbloom/mockserver
|
mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java
|
MockServerClient.retrieveRecordedExpectations
|
public Expectation[] retrieveRecordedExpectations(HttpRequest httpRequest) {
String recordedExpectations = retrieveRecordedExpectations(httpRequest, Format.JSON);
if (!Strings.isNullOrEmpty(recordedExpectations) && !recordedExpectations.equals("[]")) {
return expectationSerializer.deserializeArray(recordedExpectations);
} else {
return new Expectation[0];
}
}
|
java
|
public Expectation[] retrieveRecordedExpectations(HttpRequest httpRequest) {
String recordedExpectations = retrieveRecordedExpectations(httpRequest, Format.JSON);
if (!Strings.isNullOrEmpty(recordedExpectations) && !recordedExpectations.equals("[]")) {
return expectationSerializer.deserializeArray(recordedExpectations);
} else {
return new Expectation[0];
}
}
|
[
"public",
"Expectation",
"[",
"]",
"retrieveRecordedExpectations",
"(",
"HttpRequest",
"httpRequest",
")",
"{",
"String",
"recordedExpectations",
"=",
"retrieveRecordedExpectations",
"(",
"httpRequest",
",",
"Format",
".",
"JSON",
")",
";",
"if",
"(",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"recordedExpectations",
")",
"&&",
"!",
"recordedExpectations",
".",
"equals",
"(",
"\"[]\"",
")",
")",
"{",
"return",
"expectationSerializer",
".",
"deserializeArray",
"(",
"recordedExpectations",
")",
";",
"}",
"else",
"{",
"return",
"new",
"Expectation",
"[",
"0",
"]",
";",
"}",
"}"
] |
Retrieve the request-response combinations that have been recorded as a list of expectations, only those that match the httpRequest parameter are returned, use null to retrieve all requests
@param httpRequest the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests
@return an array of all expectations that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
|
[
"Retrieve",
"the",
"request",
"-",
"response",
"combinations",
"that",
"have",
"been",
"recorded",
"as",
"a",
"list",
"of",
"expectations",
"only",
"those",
"that",
"match",
"the",
"httpRequest",
"parameter",
"are",
"returned",
"use",
"null",
"to",
"retrieve",
"all",
"requests"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java#L417-L424
|
21,035
|
jamesdbloom/mockserver
|
mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java
|
MockServerClient.retrieveLogMessages
|
public String retrieveLogMessages(HttpRequest httpRequest) {
HttpResponse httpResponse = sendRequest(
request()
.withMethod("PUT")
.withPath(calculatePath("retrieve"))
.withQueryStringParameter("type", RetrieveType.LOGS.name())
.withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8)
);
return httpResponse.getBodyAsString();
}
|
java
|
public String retrieveLogMessages(HttpRequest httpRequest) {
HttpResponse httpResponse = sendRequest(
request()
.withMethod("PUT")
.withPath(calculatePath("retrieve"))
.withQueryStringParameter("type", RetrieveType.LOGS.name())
.withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8)
);
return httpResponse.getBodyAsString();
}
|
[
"public",
"String",
"retrieveLogMessages",
"(",
"HttpRequest",
"httpRequest",
")",
"{",
"HttpResponse",
"httpResponse",
"=",
"sendRequest",
"(",
"request",
"(",
")",
".",
"withMethod",
"(",
"\"PUT\"",
")",
".",
"withPath",
"(",
"calculatePath",
"(",
"\"retrieve\"",
")",
")",
".",
"withQueryStringParameter",
"(",
"\"type\"",
",",
"RetrieveType",
".",
"LOGS",
".",
"name",
"(",
")",
")",
".",
"withBody",
"(",
"httpRequest",
"!=",
"null",
"?",
"httpRequestSerializer",
".",
"serialize",
"(",
"httpRequest",
")",
":",
"\"\"",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"return",
"httpResponse",
".",
"getBodyAsString",
"(",
")",
";",
"}"
] |
Retrieve the logs associated to a specific requests, this shows all logs for expectation matching, verification, clearing, etc
@param httpRequest the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests
@return all log messages recorded by the MockServer when creating expectations, matching expectations, performing verification, clearing logs, etc
|
[
"Retrieve",
"the",
"logs",
"associated",
"to",
"a",
"specific",
"requests",
"this",
"shows",
"all",
"logs",
"for",
"expectation",
"matching",
"verification",
"clearing",
"etc"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java#L451-L460
|
21,036
|
jamesdbloom/mockserver
|
mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java
|
MockServerClient.retrieveActiveExpectations
|
public Expectation[] retrieveActiveExpectations(HttpRequest httpRequest) {
String activeExpectations = retrieveActiveExpectations(httpRequest, Format.JSON);
if (!Strings.isNullOrEmpty(activeExpectations) && !activeExpectations.equals("[]")) {
return expectationSerializer.deserializeArray(activeExpectations);
} else {
return new Expectation[0];
}
}
|
java
|
public Expectation[] retrieveActiveExpectations(HttpRequest httpRequest) {
String activeExpectations = retrieveActiveExpectations(httpRequest, Format.JSON);
if (!Strings.isNullOrEmpty(activeExpectations) && !activeExpectations.equals("[]")) {
return expectationSerializer.deserializeArray(activeExpectations);
} else {
return new Expectation[0];
}
}
|
[
"public",
"Expectation",
"[",
"]",
"retrieveActiveExpectations",
"(",
"HttpRequest",
"httpRequest",
")",
"{",
"String",
"activeExpectations",
"=",
"retrieveActiveExpectations",
"(",
"httpRequest",
",",
"Format",
".",
"JSON",
")",
";",
"if",
"(",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"activeExpectations",
")",
"&&",
"!",
"activeExpectations",
".",
"equals",
"(",
"\"[]\"",
")",
")",
"{",
"return",
"expectationSerializer",
".",
"deserializeArray",
"(",
"activeExpectations",
")",
";",
"}",
"else",
"{",
"return",
"new",
"Expectation",
"[",
"0",
"]",
";",
"}",
"}"
] |
Retrieve the active expectations match the httpRequest parameter, use null for the parameter to retrieve all expectations
@param httpRequest the http request that is matched against when deciding whether to return each expectation, use null for the parameter to retrieve for all requests
@return an array of all expectations that have been setup and have not expired
|
[
"Retrieve",
"the",
"active",
"expectations",
"match",
"the",
"httpRequest",
"parameter",
"use",
"null",
"for",
"the",
"parameter",
"to",
"retrieve",
"all",
"expectations"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-client-java/src/main/java/org/mockserver/client/MockServerClient.java#L563-L570
|
21,037
|
jamesdbloom/mockserver
|
mockserver-netty/src/main/java/org/mockserver/cli/Main.java
|
Main.main
|
public static void main(String... arguments) {
try {
Map<String, String> parsedArguments = parseArguments(arguments);
MOCK_SERVER_LOGGER.debug(SERVER_CONFIGURATION, "Using command line options: {}", Joiner.on(", ").withKeyValueSeparator("=").join(parsedArguments));
if (parsedArguments.size() > 0 && parsedArguments.containsKey(serverPort.name())) {
if (parsedArguments.containsKey(logLevel.name())) {
ConfigurationProperties.logLevel(parsedArguments.get(logLevel.name()));
}
Integer[] localPorts = INTEGER_STRING_LIST_PARSER.toArray(parsedArguments.get(serverPort.name()));
if (parsedArguments.containsKey(proxyRemotePort.name())) {
String remoteHost = parsedArguments.get(proxyRemoteHost.name());
if (Strings.isNullOrEmpty(remoteHost)) {
remoteHost = "localhost";
}
new MockServer(Integer.parseInt(parsedArguments.get(proxyRemotePort.name())), remoteHost, localPorts);
} else {
new MockServer(localPorts);
}
} else {
showUsage();
}
} catch (IllegalArgumentException iae) {
showUsage();
}
}
|
java
|
public static void main(String... arguments) {
try {
Map<String, String> parsedArguments = parseArguments(arguments);
MOCK_SERVER_LOGGER.debug(SERVER_CONFIGURATION, "Using command line options: {}", Joiner.on(", ").withKeyValueSeparator("=").join(parsedArguments));
if (parsedArguments.size() > 0 && parsedArguments.containsKey(serverPort.name())) {
if (parsedArguments.containsKey(logLevel.name())) {
ConfigurationProperties.logLevel(parsedArguments.get(logLevel.name()));
}
Integer[] localPorts = INTEGER_STRING_LIST_PARSER.toArray(parsedArguments.get(serverPort.name()));
if (parsedArguments.containsKey(proxyRemotePort.name())) {
String remoteHost = parsedArguments.get(proxyRemoteHost.name());
if (Strings.isNullOrEmpty(remoteHost)) {
remoteHost = "localhost";
}
new MockServer(Integer.parseInt(parsedArguments.get(proxyRemotePort.name())), remoteHost, localPorts);
} else {
new MockServer(localPorts);
}
} else {
showUsage();
}
} catch (IllegalArgumentException iae) {
showUsage();
}
}
|
[
"public",
"static",
"void",
"main",
"(",
"String",
"...",
"arguments",
")",
"{",
"try",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"parsedArguments",
"=",
"parseArguments",
"(",
"arguments",
")",
";",
"MOCK_SERVER_LOGGER",
".",
"debug",
"(",
"SERVER_CONFIGURATION",
",",
"\"Using command line options: {}\"",
",",
"Joiner",
".",
"on",
"(",
"\", \"",
")",
".",
"withKeyValueSeparator",
"(",
"\"=\"",
")",
".",
"join",
"(",
"parsedArguments",
")",
")",
";",
"if",
"(",
"parsedArguments",
".",
"size",
"(",
")",
">",
"0",
"&&",
"parsedArguments",
".",
"containsKey",
"(",
"serverPort",
".",
"name",
"(",
")",
")",
")",
"{",
"if",
"(",
"parsedArguments",
".",
"containsKey",
"(",
"logLevel",
".",
"name",
"(",
")",
")",
")",
"{",
"ConfigurationProperties",
".",
"logLevel",
"(",
"parsedArguments",
".",
"get",
"(",
"logLevel",
".",
"name",
"(",
")",
")",
")",
";",
"}",
"Integer",
"[",
"]",
"localPorts",
"=",
"INTEGER_STRING_LIST_PARSER",
".",
"toArray",
"(",
"parsedArguments",
".",
"get",
"(",
"serverPort",
".",
"name",
"(",
")",
")",
")",
";",
"if",
"(",
"parsedArguments",
".",
"containsKey",
"(",
"proxyRemotePort",
".",
"name",
"(",
")",
")",
")",
"{",
"String",
"remoteHost",
"=",
"parsedArguments",
".",
"get",
"(",
"proxyRemoteHost",
".",
"name",
"(",
")",
")",
";",
"if",
"(",
"Strings",
".",
"isNullOrEmpty",
"(",
"remoteHost",
")",
")",
"{",
"remoteHost",
"=",
"\"localhost\"",
";",
"}",
"new",
"MockServer",
"(",
"Integer",
".",
"parseInt",
"(",
"parsedArguments",
".",
"get",
"(",
"proxyRemotePort",
".",
"name",
"(",
")",
")",
")",
",",
"remoteHost",
",",
"localPorts",
")",
";",
"}",
"else",
"{",
"new",
"MockServer",
"(",
"localPorts",
")",
";",
"}",
"}",
"else",
"{",
"showUsage",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"IllegalArgumentException",
"iae",
")",
"{",
"showUsage",
"(",
")",
";",
"}",
"}"
] |
Run the MockServer directly providing the arguments as specified below.
@param arguments the entries are in pairs:
- "-serverPort" followed by the mandatory server local port,
- "-proxyRemotePort" followed by the optional proxyRemotePort port that enabled port forwarding mode,
- "-proxyRemoteHost" followed by the optional proxyRemoteHost port (ignored unless proxyRemotePort is specified)
- "-logLevel" followed by the log level
|
[
"Run",
"the",
"MockServer",
"directly",
"providing",
"the",
"arguments",
"as",
"specified",
"below",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-netty/src/main/java/org/mockserver/cli/Main.java#L68-L94
|
21,038
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/socket/tls/KeyStoreFactory.java
|
KeyStoreFactory.saveCertificateAsKeyStore
|
private static KeyStore saveCertificateAsKeyStore(KeyStore existingKeyStore, boolean deleteOnExit, String keyStoreFileName, String certificationAlias, Key privateKey, char[] keyStorePassword, Certificate[] chain, X509Certificate caCert) {
try {
KeyStore keyStore = existingKeyStore;
if (keyStore == null) {
// create new key store
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, keyStorePassword);
}
// add certificate
try {
keyStore.deleteEntry(certificationAlias);
} catch (KeyStoreException kse) {
// ignore as may not exist in keystore yet
}
keyStore.setKeyEntry(certificationAlias, privateKey, keyStorePassword, chain);
// add CA certificate
try {
keyStore.deleteEntry(KEY_STORE_CA_ALIAS);
} catch (KeyStoreException kse) {
// ignore as may not exist in keystore yet
}
keyStore.setCertificateEntry(KEY_STORE_CA_ALIAS, caCert);
// save as JKS file
String keyStoreFileAbsolutePath = new File(keyStoreFileName).getAbsolutePath();
try (FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFileAbsolutePath)) {
keyStore.store(fileOutputStream, keyStorePassword);
MOCK_SERVER_LOGGER.trace("Saving key store to file [" + keyStoreFileAbsolutePath + "]");
}
if (deleteOnExit) {
new File(keyStoreFileAbsolutePath).deleteOnExit();
}
return keyStore;
} catch (Exception e) {
throw new RuntimeException("Exception while saving KeyStore", e);
}
}
|
java
|
private static KeyStore saveCertificateAsKeyStore(KeyStore existingKeyStore, boolean deleteOnExit, String keyStoreFileName, String certificationAlias, Key privateKey, char[] keyStorePassword, Certificate[] chain, X509Certificate caCert) {
try {
KeyStore keyStore = existingKeyStore;
if (keyStore == null) {
// create new key store
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, keyStorePassword);
}
// add certificate
try {
keyStore.deleteEntry(certificationAlias);
} catch (KeyStoreException kse) {
// ignore as may not exist in keystore yet
}
keyStore.setKeyEntry(certificationAlias, privateKey, keyStorePassword, chain);
// add CA certificate
try {
keyStore.deleteEntry(KEY_STORE_CA_ALIAS);
} catch (KeyStoreException kse) {
// ignore as may not exist in keystore yet
}
keyStore.setCertificateEntry(KEY_STORE_CA_ALIAS, caCert);
// save as JKS file
String keyStoreFileAbsolutePath = new File(keyStoreFileName).getAbsolutePath();
try (FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFileAbsolutePath)) {
keyStore.store(fileOutputStream, keyStorePassword);
MOCK_SERVER_LOGGER.trace("Saving key store to file [" + keyStoreFileAbsolutePath + "]");
}
if (deleteOnExit) {
new File(keyStoreFileAbsolutePath).deleteOnExit();
}
return keyStore;
} catch (Exception e) {
throw new RuntimeException("Exception while saving KeyStore", e);
}
}
|
[
"private",
"static",
"KeyStore",
"saveCertificateAsKeyStore",
"(",
"KeyStore",
"existingKeyStore",
",",
"boolean",
"deleteOnExit",
",",
"String",
"keyStoreFileName",
",",
"String",
"certificationAlias",
",",
"Key",
"privateKey",
",",
"char",
"[",
"]",
"keyStorePassword",
",",
"Certificate",
"[",
"]",
"chain",
",",
"X509Certificate",
"caCert",
")",
"{",
"try",
"{",
"KeyStore",
"keyStore",
"=",
"existingKeyStore",
";",
"if",
"(",
"keyStore",
"==",
"null",
")",
"{",
"// create new key store",
"keyStore",
"=",
"KeyStore",
".",
"getInstance",
"(",
"KeyStore",
".",
"getDefaultType",
"(",
")",
")",
";",
"keyStore",
".",
"load",
"(",
"null",
",",
"keyStorePassword",
")",
";",
"}",
"// add certificate",
"try",
"{",
"keyStore",
".",
"deleteEntry",
"(",
"certificationAlias",
")",
";",
"}",
"catch",
"(",
"KeyStoreException",
"kse",
")",
"{",
"// ignore as may not exist in keystore yet",
"}",
"keyStore",
".",
"setKeyEntry",
"(",
"certificationAlias",
",",
"privateKey",
",",
"keyStorePassword",
",",
"chain",
")",
";",
"// add CA certificate",
"try",
"{",
"keyStore",
".",
"deleteEntry",
"(",
"KEY_STORE_CA_ALIAS",
")",
";",
"}",
"catch",
"(",
"KeyStoreException",
"kse",
")",
"{",
"// ignore as may not exist in keystore yet",
"}",
"keyStore",
".",
"setCertificateEntry",
"(",
"KEY_STORE_CA_ALIAS",
",",
"caCert",
")",
";",
"// save as JKS file",
"String",
"keyStoreFileAbsolutePath",
"=",
"new",
"File",
"(",
"keyStoreFileName",
")",
".",
"getAbsolutePath",
"(",
")",
";",
"try",
"(",
"FileOutputStream",
"fileOutputStream",
"=",
"new",
"FileOutputStream",
"(",
"keyStoreFileAbsolutePath",
")",
")",
"{",
"keyStore",
".",
"store",
"(",
"fileOutputStream",
",",
"keyStorePassword",
")",
";",
"MOCK_SERVER_LOGGER",
".",
"trace",
"(",
"\"Saving key store to file [\"",
"+",
"keyStoreFileAbsolutePath",
"+",
"\"]\"",
")",
";",
"}",
"if",
"(",
"deleteOnExit",
")",
"{",
"new",
"File",
"(",
"keyStoreFileAbsolutePath",
")",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"return",
"keyStore",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Exception while saving KeyStore\"",
",",
"e",
")",
";",
"}",
"}"
] |
Save X509Certificate in KeyStore file.
|
[
"Save",
"X509Certificate",
"in",
"KeyStore",
"file",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/socket/tls/KeyStoreFactory.java#L76-L114
|
21,039
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java
|
HttpRequest.withBody
|
public HttpRequest withBody(String body, Charset charset) {
if (body != null) {
this.body = new StringBody(body, charset);
}
return this;
}
|
java
|
public HttpRequest withBody(String body, Charset charset) {
if (body != null) {
this.body = new StringBody(body, charset);
}
return this;
}
|
[
"public",
"HttpRequest",
"withBody",
"(",
"String",
"body",
",",
"Charset",
"charset",
")",
"{",
"if",
"(",
"body",
"!=",
"null",
")",
"{",
"this",
".",
"body",
"=",
"new",
"StringBody",
"(",
"body",
",",
"charset",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
The exact string body to match on such as "this is an exact string body"
@param body the body on such as "this is an exact string body"
@param charset character set the string will be encoded in
|
[
"The",
"exact",
"string",
"body",
"to",
"match",
"on",
"such",
"as",
"this",
"is",
"an",
"exact",
"string",
"body"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java#L249-L254
|
21,040
|
jamesdbloom/mockserver
|
mockserver-netty/src/main/java/org/mockserver/exception/ExceptionHandler.java
|
ExceptionHandler.shouldNotIgnoreException
|
public static boolean shouldNotIgnoreException(Throwable cause) {
String message = String.valueOf(cause.getMessage()).toLowerCase();
// is ssl exception
if (cause.getCause() instanceof SSLException || cause instanceof DecoderException | cause instanceof NotSslRecordException) {
return false;
}
// first try to match connection reset / broke peer based on the regex.
// This is the fastest way but may fail on different jdk impls or OS's
if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
return false;
}
// Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not
StackTraceElement[] elements = cause.getStackTrace();
for (StackTraceElement element : elements) {
String classname = element.getClassName();
String methodname = element.getMethodName();
// skip all classes that belong to the io.netty package
if (classname.startsWith("io.netty.")) {
continue;
}
// check if the method name is read if not skip it
if (!"read".equals(methodname)) {
continue;
}
// This will also match against SocketInputStream which is used by openjdk 7 and maybe
// also others
if (IGNORABLE_CLASS_IN_STACK.matcher(classname).matches()) {
return false;
}
try {
// No match by now.. Try to load the class via classloader and inspect it.
// This is mainly done as other JDK implementations may differ in name of
// the impl.
Class<?> clazz = PlatformDependent.getClassLoader(ExceptionHandler.class).loadClass(classname);
if (SocketChannel.class.isAssignableFrom(clazz)
|| DatagramChannel.class.isAssignableFrom(clazz)) {
return false;
}
// also match against SctpChannel via String matching as it may not present.
if (PlatformDependent.javaVersion() >= 7
&& "com.sun.nio.sctp.SctpChannel".equals(clazz.getSuperclass().getName())) {
return false;
}
} catch (ClassNotFoundException e) {
// This should not happen just ignore
}
}
return true;
}
|
java
|
public static boolean shouldNotIgnoreException(Throwable cause) {
String message = String.valueOf(cause.getMessage()).toLowerCase();
// is ssl exception
if (cause.getCause() instanceof SSLException || cause instanceof DecoderException | cause instanceof NotSslRecordException) {
return false;
}
// first try to match connection reset / broke peer based on the regex.
// This is the fastest way but may fail on different jdk impls or OS's
if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
return false;
}
// Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not
StackTraceElement[] elements = cause.getStackTrace();
for (StackTraceElement element : elements) {
String classname = element.getClassName();
String methodname = element.getMethodName();
// skip all classes that belong to the io.netty package
if (classname.startsWith("io.netty.")) {
continue;
}
// check if the method name is read if not skip it
if (!"read".equals(methodname)) {
continue;
}
// This will also match against SocketInputStream which is used by openjdk 7 and maybe
// also others
if (IGNORABLE_CLASS_IN_STACK.matcher(classname).matches()) {
return false;
}
try {
// No match by now.. Try to load the class via classloader and inspect it.
// This is mainly done as other JDK implementations may differ in name of
// the impl.
Class<?> clazz = PlatformDependent.getClassLoader(ExceptionHandler.class).loadClass(classname);
if (SocketChannel.class.isAssignableFrom(clazz)
|| DatagramChannel.class.isAssignableFrom(clazz)) {
return false;
}
// also match against SctpChannel via String matching as it may not present.
if (PlatformDependent.javaVersion() >= 7
&& "com.sun.nio.sctp.SctpChannel".equals(clazz.getSuperclass().getName())) {
return false;
}
} catch (ClassNotFoundException e) {
// This should not happen just ignore
}
}
return true;
}
|
[
"public",
"static",
"boolean",
"shouldNotIgnoreException",
"(",
"Throwable",
"cause",
")",
"{",
"String",
"message",
"=",
"String",
".",
"valueOf",
"(",
"cause",
".",
"getMessage",
"(",
")",
")",
".",
"toLowerCase",
"(",
")",
";",
"// is ssl exception",
"if",
"(",
"cause",
".",
"getCause",
"(",
")",
"instanceof",
"SSLException",
"||",
"cause",
"instanceof",
"DecoderException",
"|",
"cause",
"instanceof",
"NotSslRecordException",
")",
"{",
"return",
"false",
";",
"}",
"// first try to match connection reset / broke peer based on the regex.",
"// This is the fastest way but may fail on different jdk impls or OS's",
"if",
"(",
"IGNORABLE_ERROR_MESSAGE",
".",
"matcher",
"(",
"message",
")",
".",
"matches",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not",
"StackTraceElement",
"[",
"]",
"elements",
"=",
"cause",
".",
"getStackTrace",
"(",
")",
";",
"for",
"(",
"StackTraceElement",
"element",
":",
"elements",
")",
"{",
"String",
"classname",
"=",
"element",
".",
"getClassName",
"(",
")",
";",
"String",
"methodname",
"=",
"element",
".",
"getMethodName",
"(",
")",
";",
"// skip all classes that belong to the io.netty package",
"if",
"(",
"classname",
".",
"startsWith",
"(",
"\"io.netty.\"",
")",
")",
"{",
"continue",
";",
"}",
"// check if the method name is read if not skip it",
"if",
"(",
"!",
"\"read\"",
".",
"equals",
"(",
"methodname",
")",
")",
"{",
"continue",
";",
"}",
"// This will also match against SocketInputStream which is used by openjdk 7 and maybe",
"// also others",
"if",
"(",
"IGNORABLE_CLASS_IN_STACK",
".",
"matcher",
"(",
"classname",
")",
".",
"matches",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"// No match by now.. Try to load the class via classloader and inspect it.",
"// This is mainly done as other JDK implementations may differ in name of",
"// the impl.",
"Class",
"<",
"?",
">",
"clazz",
"=",
"PlatformDependent",
".",
"getClassLoader",
"(",
"ExceptionHandler",
".",
"class",
")",
".",
"loadClass",
"(",
"classname",
")",
";",
"if",
"(",
"SocketChannel",
".",
"class",
".",
"isAssignableFrom",
"(",
"clazz",
")",
"||",
"DatagramChannel",
".",
"class",
".",
"isAssignableFrom",
"(",
"clazz",
")",
")",
"{",
"return",
"false",
";",
"}",
"// also match against SctpChannel via String matching as it may not present.",
"if",
"(",
"PlatformDependent",
".",
"javaVersion",
"(",
")",
">=",
"7",
"&&",
"\"com.sun.nio.sctp.SctpChannel\"",
".",
"equals",
"(",
"clazz",
".",
"getSuperclass",
"(",
")",
".",
"getName",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"catch",
"(",
"ClassNotFoundException",
"e",
")",
"{",
"// This should not happen just ignore",
"}",
"}",
"return",
"true",
";",
"}"
] |
returns true is the exception was caused by the connection being closed
|
[
"returns",
"true",
"is",
"the",
"exception",
"was",
"caused",
"by",
"the",
"connection",
"being",
"closed"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-netty/src/main/java/org/mockserver/exception/ExceptionHandler.java#L34-L91
|
21,041
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/configuration/ConfigurationProperties.java
|
ConfigurationProperties.logLevel
|
public static void logLevel(String level) {
if (!Arrays.asList("TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF").contains(level)) {
throw new IllegalArgumentException("log level \"" + level + "\" is not legal it must be one of \"TRACE\", \"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"OFF\"");
}
System.setProperty(MOCKSERVER_LOG_LEVEL, level);
MockServerLogger.initialiseLogLevels();
}
|
java
|
public static void logLevel(String level) {
if (!Arrays.asList("TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF").contains(level)) {
throw new IllegalArgumentException("log level \"" + level + "\" is not legal it must be one of \"TRACE\", \"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"OFF\"");
}
System.setProperty(MOCKSERVER_LOG_LEVEL, level);
MockServerLogger.initialiseLogLevels();
}
|
[
"public",
"static",
"void",
"logLevel",
"(",
"String",
"level",
")",
"{",
"if",
"(",
"!",
"Arrays",
".",
"asList",
"(",
"\"TRACE\"",
",",
"\"DEBUG\"",
",",
"\"INFO\"",
",",
"\"WARN\"",
",",
"\"ERROR\"",
",",
"\"OFF\"",
")",
".",
"contains",
"(",
"level",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"log level \\\"\"",
"+",
"level",
"+",
"\"\\\" is not legal it must be one of \\\"TRACE\\\", \\\"DEBUG\\\", \\\"INFO\\\", \\\"WARN\\\", \\\"ERROR\\\", \\\"OFF\\\"\"",
")",
";",
"}",
"System",
".",
"setProperty",
"(",
"MOCKSERVER_LOG_LEVEL",
",",
"level",
")",
";",
"MockServerLogger",
".",
"initialiseLogLevels",
"(",
")",
";",
"}"
] |
Override the default logging level of INFO
@param level the log level, which can be TRACE, DEBUG, INFO, WARN, ERROR, OFF
|
[
"Override",
"the",
"default",
"logging",
"level",
"of",
"INFO"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/configuration/ConfigurationProperties.java#L286-L292
|
21,042
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java
|
KeyAndCertificateFactory.generateKeyPair
|
KeyPair generateKeyPair(int keySize) throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_GENERATION_ALGORITHM, PROVIDER_NAME);
generator.initialize(keySize, new SecureRandom());
return generator.generateKeyPair();
}
|
java
|
KeyPair generateKeyPair(int keySize) throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_GENERATION_ALGORITHM, PROVIDER_NAME);
generator.initialize(keySize, new SecureRandom());
return generator.generateKeyPair();
}
|
[
"KeyPair",
"generateKeyPair",
"(",
"int",
"keySize",
")",
"throws",
"Exception",
"{",
"KeyPairGenerator",
"generator",
"=",
"KeyPairGenerator",
".",
"getInstance",
"(",
"KEY_GENERATION_ALGORITHM",
",",
"PROVIDER_NAME",
")",
";",
"generator",
".",
"initialize",
"(",
"keySize",
",",
"new",
"SecureRandom",
"(",
")",
")",
";",
"return",
"generator",
".",
"generateKeyPair",
"(",
")",
";",
"}"
] |
Create a random 2048 bit RSA key pair with the given length
|
[
"Create",
"a",
"random",
"2048",
"bit",
"RSA",
"key",
"pair",
"with",
"the",
"given",
"length"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java#L129-L133
|
21,043
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java
|
KeyAndCertificateFactory.createCACert
|
private X509Certificate createCACert(PublicKey publicKey, PrivateKey privateKey) throws Exception {
// signers name
X500Name issuerName = new X500Name("CN=www.mockserver.com, O=MockServer, L=London, ST=England, C=UK");
// subjects name - the same as we are self signed.
X500Name subjectName = issuerName;
// serial
BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));
// create the certificate - version 3
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, publicKey);
builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
builder.addExtension(Extension.keyUsage, false, usage);
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));
X509Certificate cert = signCertificate(builder, privateKey);
cert.checkValidity(new Date());
cert.verify(publicKey);
return cert;
}
|
java
|
private X509Certificate createCACert(PublicKey publicKey, PrivateKey privateKey) throws Exception {
// signers name
X500Name issuerName = new X500Name("CN=www.mockserver.com, O=MockServer, L=London, ST=England, C=UK");
// subjects name - the same as we are self signed.
X500Name subjectName = issuerName;
// serial
BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));
// create the certificate - version 3
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, publicKey);
builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
builder.addExtension(Extension.keyUsage, false, usage);
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));
X509Certificate cert = signCertificate(builder, privateKey);
cert.checkValidity(new Date());
cert.verify(publicKey);
return cert;
}
|
[
"private",
"X509Certificate",
"createCACert",
"(",
"PublicKey",
"publicKey",
",",
"PrivateKey",
"privateKey",
")",
"throws",
"Exception",
"{",
"// signers name",
"X500Name",
"issuerName",
"=",
"new",
"X500Name",
"(",
"\"CN=www.mockserver.com, O=MockServer, L=London, ST=England, C=UK\"",
")",
";",
"// subjects name - the same as we are self signed.",
"X500Name",
"subjectName",
"=",
"issuerName",
";",
"// serial",
"BigInteger",
"serial",
"=",
"BigInteger",
".",
"valueOf",
"(",
"new",
"Random",
"(",
")",
".",
"nextInt",
"(",
"Integer",
".",
"MAX_VALUE",
")",
")",
";",
"// create the certificate - version 3",
"X509v3CertificateBuilder",
"builder",
"=",
"new",
"JcaX509v3CertificateBuilder",
"(",
"issuerName",
",",
"serial",
",",
"NOT_BEFORE",
",",
"NOT_AFTER",
",",
"subjectName",
",",
"publicKey",
")",
";",
"builder",
".",
"addExtension",
"(",
"Extension",
".",
"subjectKeyIdentifier",
",",
"false",
",",
"createSubjectKeyIdentifier",
"(",
"publicKey",
")",
")",
";",
"builder",
".",
"addExtension",
"(",
"Extension",
".",
"basicConstraints",
",",
"true",
",",
"new",
"BasicConstraints",
"(",
"true",
")",
")",
";",
"KeyUsage",
"usage",
"=",
"new",
"KeyUsage",
"(",
"KeyUsage",
".",
"keyCertSign",
"|",
"KeyUsage",
".",
"digitalSignature",
"|",
"KeyUsage",
".",
"keyEncipherment",
"|",
"KeyUsage",
".",
"dataEncipherment",
"|",
"KeyUsage",
".",
"cRLSign",
")",
";",
"builder",
".",
"addExtension",
"(",
"Extension",
".",
"keyUsage",
",",
"false",
",",
"usage",
")",
";",
"ASN1EncodableVector",
"purposes",
"=",
"new",
"ASN1EncodableVector",
"(",
")",
";",
"purposes",
".",
"add",
"(",
"KeyPurposeId",
".",
"id_kp_serverAuth",
")",
";",
"purposes",
".",
"add",
"(",
"KeyPurposeId",
".",
"id_kp_clientAuth",
")",
";",
"purposes",
".",
"add",
"(",
"KeyPurposeId",
".",
"anyExtendedKeyUsage",
")",
";",
"builder",
".",
"addExtension",
"(",
"Extension",
".",
"extendedKeyUsage",
",",
"false",
",",
"new",
"DERSequence",
"(",
"purposes",
")",
")",
";",
"X509Certificate",
"cert",
"=",
"signCertificate",
"(",
"builder",
",",
"privateKey",
")",
";",
"cert",
".",
"checkValidity",
"(",
"new",
"Date",
"(",
")",
")",
";",
"cert",
".",
"verify",
"(",
"publicKey",
")",
";",
"return",
"cert",
";",
"}"
] |
Create a certificate to use by a Certificate Authority, signed by a self signed certificate.
|
[
"Create",
"a",
"certificate",
"to",
"use",
"by",
"a",
"Certificate",
"Authority",
"signed",
"by",
"a",
"self",
"signed",
"certificate",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java#L138-L168
|
21,044
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java
|
KeyAndCertificateFactory.createCASignedCert
|
private X509Certificate createCASignedCert(PublicKey publicKey, X509Certificate certificateAuthorityCert, PrivateKey certificateAuthorityPrivateKey, PublicKey certificateAuthorityPublicKey, String domain, String[] subjectAlternativeNameDomains, String[] subjectAlternativeNameIps) throws Exception {
// signers name
X500Name issuer = new X509CertificateHolder(certificateAuthorityCert.getEncoded()).getSubject();
// subjects name - the same as we are self signed.
X500Name subject = new X500Name("CN=" + domain + ", O=MockServer, L=London, ST=England, C=UK");
// serial
BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));
// create the certificate - version 3
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, publicKey);
builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
// subject alternative name
List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
if (subjectAlternativeNameDomains != null) {
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, domain));
for (String subjectAlternativeNameDomain : subjectAlternativeNameDomains) {
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, subjectAlternativeNameDomain));
}
}
if (subjectAlternativeNameIps != null) {
for (String subjectAlternativeNameIp : subjectAlternativeNameIps) {
if (IPAddress.isValidIPv6WithNetmask(subjectAlternativeNameIp)
|| IPAddress.isValidIPv6(subjectAlternativeNameIp)
|| IPAddress.isValidIPv4WithNetmask(subjectAlternativeNameIp)
|| IPAddress.isValidIPv4(subjectAlternativeNameIp)) {
subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, subjectAlternativeNameIp));
}
}
}
if (subjectAlternativeNames.size() > 0) {
DERSequence subjectAlternativeNamesExtension = new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()]));
builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNamesExtension);
}
X509Certificate cert = signCertificate(builder, certificateAuthorityPrivateKey);
cert.checkValidity(new Date());
cert.verify(certificateAuthorityPublicKey);
return cert;
}
|
java
|
private X509Certificate createCASignedCert(PublicKey publicKey, X509Certificate certificateAuthorityCert, PrivateKey certificateAuthorityPrivateKey, PublicKey certificateAuthorityPublicKey, String domain, String[] subjectAlternativeNameDomains, String[] subjectAlternativeNameIps) throws Exception {
// signers name
X500Name issuer = new X509CertificateHolder(certificateAuthorityCert.getEncoded()).getSubject();
// subjects name - the same as we are self signed.
X500Name subject = new X500Name("CN=" + domain + ", O=MockServer, L=London, ST=England, C=UK");
// serial
BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));
// create the certificate - version 3
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, publicKey);
builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
// subject alternative name
List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
if (subjectAlternativeNameDomains != null) {
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, domain));
for (String subjectAlternativeNameDomain : subjectAlternativeNameDomains) {
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, subjectAlternativeNameDomain));
}
}
if (subjectAlternativeNameIps != null) {
for (String subjectAlternativeNameIp : subjectAlternativeNameIps) {
if (IPAddress.isValidIPv6WithNetmask(subjectAlternativeNameIp)
|| IPAddress.isValidIPv6(subjectAlternativeNameIp)
|| IPAddress.isValidIPv4WithNetmask(subjectAlternativeNameIp)
|| IPAddress.isValidIPv4(subjectAlternativeNameIp)) {
subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, subjectAlternativeNameIp));
}
}
}
if (subjectAlternativeNames.size() > 0) {
DERSequence subjectAlternativeNamesExtension = new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()]));
builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNamesExtension);
}
X509Certificate cert = signCertificate(builder, certificateAuthorityPrivateKey);
cert.checkValidity(new Date());
cert.verify(certificateAuthorityPublicKey);
return cert;
}
|
[
"private",
"X509Certificate",
"createCASignedCert",
"(",
"PublicKey",
"publicKey",
",",
"X509Certificate",
"certificateAuthorityCert",
",",
"PrivateKey",
"certificateAuthorityPrivateKey",
",",
"PublicKey",
"certificateAuthorityPublicKey",
",",
"String",
"domain",
",",
"String",
"[",
"]",
"subjectAlternativeNameDomains",
",",
"String",
"[",
"]",
"subjectAlternativeNameIps",
")",
"throws",
"Exception",
"{",
"// signers name",
"X500Name",
"issuer",
"=",
"new",
"X509CertificateHolder",
"(",
"certificateAuthorityCert",
".",
"getEncoded",
"(",
")",
")",
".",
"getSubject",
"(",
")",
";",
"// subjects name - the same as we are self signed.",
"X500Name",
"subject",
"=",
"new",
"X500Name",
"(",
"\"CN=\"",
"+",
"domain",
"+",
"\", O=MockServer, L=London, ST=England, C=UK\"",
")",
";",
"// serial",
"BigInteger",
"serial",
"=",
"BigInteger",
".",
"valueOf",
"(",
"new",
"Random",
"(",
")",
".",
"nextInt",
"(",
"Integer",
".",
"MAX_VALUE",
")",
")",
";",
"// create the certificate - version 3",
"X509v3CertificateBuilder",
"builder",
"=",
"new",
"JcaX509v3CertificateBuilder",
"(",
"issuer",
",",
"serial",
",",
"NOT_BEFORE",
",",
"NOT_AFTER",
",",
"subject",
",",
"publicKey",
")",
";",
"builder",
".",
"addExtension",
"(",
"Extension",
".",
"subjectKeyIdentifier",
",",
"false",
",",
"createSubjectKeyIdentifier",
"(",
"publicKey",
")",
")",
";",
"builder",
".",
"addExtension",
"(",
"Extension",
".",
"basicConstraints",
",",
"false",
",",
"new",
"BasicConstraints",
"(",
"false",
")",
")",
";",
"// subject alternative name",
"List",
"<",
"ASN1Encodable",
">",
"subjectAlternativeNames",
"=",
"new",
"ArrayList",
"<",
"ASN1Encodable",
">",
"(",
")",
";",
"if",
"(",
"subjectAlternativeNameDomains",
"!=",
"null",
")",
"{",
"subjectAlternativeNames",
".",
"add",
"(",
"new",
"GeneralName",
"(",
"GeneralName",
".",
"dNSName",
",",
"domain",
")",
")",
";",
"for",
"(",
"String",
"subjectAlternativeNameDomain",
":",
"subjectAlternativeNameDomains",
")",
"{",
"subjectAlternativeNames",
".",
"add",
"(",
"new",
"GeneralName",
"(",
"GeneralName",
".",
"dNSName",
",",
"subjectAlternativeNameDomain",
")",
")",
";",
"}",
"}",
"if",
"(",
"subjectAlternativeNameIps",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"subjectAlternativeNameIp",
":",
"subjectAlternativeNameIps",
")",
"{",
"if",
"(",
"IPAddress",
".",
"isValidIPv6WithNetmask",
"(",
"subjectAlternativeNameIp",
")",
"||",
"IPAddress",
".",
"isValidIPv6",
"(",
"subjectAlternativeNameIp",
")",
"||",
"IPAddress",
".",
"isValidIPv4WithNetmask",
"(",
"subjectAlternativeNameIp",
")",
"||",
"IPAddress",
".",
"isValidIPv4",
"(",
"subjectAlternativeNameIp",
")",
")",
"{",
"subjectAlternativeNames",
".",
"add",
"(",
"new",
"GeneralName",
"(",
"GeneralName",
".",
"iPAddress",
",",
"subjectAlternativeNameIp",
")",
")",
";",
"}",
"}",
"}",
"if",
"(",
"subjectAlternativeNames",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"DERSequence",
"subjectAlternativeNamesExtension",
"=",
"new",
"DERSequence",
"(",
"subjectAlternativeNames",
".",
"toArray",
"(",
"new",
"ASN1Encodable",
"[",
"subjectAlternativeNames",
".",
"size",
"(",
")",
"]",
")",
")",
";",
"builder",
".",
"addExtension",
"(",
"Extension",
".",
"subjectAlternativeName",
",",
"false",
",",
"subjectAlternativeNamesExtension",
")",
";",
"}",
"X509Certificate",
"cert",
"=",
"signCertificate",
"(",
"builder",
",",
"certificateAuthorityPrivateKey",
")",
";",
"cert",
".",
"checkValidity",
"(",
"new",
"Date",
"(",
")",
")",
";",
"cert",
".",
"verify",
"(",
"certificateAuthorityPublicKey",
")",
";",
"return",
"cert",
";",
"}"
] |
Create a server certificate for the given domain and subject alternative names, signed by the given Certificate Authority.
|
[
"Create",
"a",
"server",
"certificate",
"for",
"the",
"given",
"domain",
"and",
"subject",
"alternative",
"names",
"signed",
"by",
"the",
"given",
"Certificate",
"Authority",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java#L173-L218
|
21,045
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java
|
KeyAndCertificateFactory.saveCertificateAsPEMFile
|
private String saveCertificateAsPEMFile(Object x509Certificate, String filename, boolean deleteOnExit) throws IOException {
File pemFile = File.createTempFile(filename, null);
try (FileWriter pemfileWriter = new FileWriter(pemFile)) {
try (JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(pemfileWriter)) {
jcaPEMWriter.writeObject(x509Certificate);
}
}
if (deleteOnExit) {
pemFile.deleteOnExit();
}
return pemFile.getAbsolutePath();
}
|
java
|
private String saveCertificateAsPEMFile(Object x509Certificate, String filename, boolean deleteOnExit) throws IOException {
File pemFile = File.createTempFile(filename, null);
try (FileWriter pemfileWriter = new FileWriter(pemFile)) {
try (JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(pemfileWriter)) {
jcaPEMWriter.writeObject(x509Certificate);
}
}
if (deleteOnExit) {
pemFile.deleteOnExit();
}
return pemFile.getAbsolutePath();
}
|
[
"private",
"String",
"saveCertificateAsPEMFile",
"(",
"Object",
"x509Certificate",
",",
"String",
"filename",
",",
"boolean",
"deleteOnExit",
")",
"throws",
"IOException",
"{",
"File",
"pemFile",
"=",
"File",
".",
"createTempFile",
"(",
"filename",
",",
"null",
")",
";",
"try",
"(",
"FileWriter",
"pemfileWriter",
"=",
"new",
"FileWriter",
"(",
"pemFile",
")",
")",
"{",
"try",
"(",
"JcaPEMWriter",
"jcaPEMWriter",
"=",
"new",
"JcaPEMWriter",
"(",
"pemfileWriter",
")",
")",
"{",
"jcaPEMWriter",
".",
"writeObject",
"(",
"x509Certificate",
")",
";",
"}",
"}",
"if",
"(",
"deleteOnExit",
")",
"{",
"pemFile",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"return",
"pemFile",
".",
"getAbsolutePath",
"(",
")",
";",
"}"
] |
Saves X509Certificate as Base-64 encoded PEM file.
|
[
"Saves",
"X509Certificate",
"as",
"Base",
"-",
"64",
"encoded",
"PEM",
"file",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java#L272-L283
|
21,046
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java
|
KeyAndCertificateFactory.loadPrivateKeyFromPEMFile
|
private RSAPrivateKey loadPrivateKeyFromPEMFile(String filename) {
try {
String publicKeyFile = FileReader.readFileFromClassPathOrPath(filename);
byte[] publicKeyBytes = DatatypeConverter.parseBase64Binary(publicKeyFile.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", ""));
return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(publicKeyBytes));
} catch (Exception e) {
throw new RuntimeException("Exception reading private key from PEM file", e);
}
}
|
java
|
private RSAPrivateKey loadPrivateKeyFromPEMFile(String filename) {
try {
String publicKeyFile = FileReader.readFileFromClassPathOrPath(filename);
byte[] publicKeyBytes = DatatypeConverter.parseBase64Binary(publicKeyFile.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", ""));
return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(publicKeyBytes));
} catch (Exception e) {
throw new RuntimeException("Exception reading private key from PEM file", e);
}
}
|
[
"private",
"RSAPrivateKey",
"loadPrivateKeyFromPEMFile",
"(",
"String",
"filename",
")",
"{",
"try",
"{",
"String",
"publicKeyFile",
"=",
"FileReader",
".",
"readFileFromClassPathOrPath",
"(",
"filename",
")",
";",
"byte",
"[",
"]",
"publicKeyBytes",
"=",
"DatatypeConverter",
".",
"parseBase64Binary",
"(",
"publicKeyFile",
".",
"replace",
"(",
"\"-----BEGIN RSA PRIVATE KEY-----\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"-----END RSA PRIVATE KEY-----\"",
",",
"\"\"",
")",
")",
";",
"return",
"(",
"RSAPrivateKey",
")",
"KeyFactory",
".",
"getInstance",
"(",
"\"RSA\"",
")",
".",
"generatePrivate",
"(",
"new",
"PKCS8EncodedKeySpec",
"(",
"publicKeyBytes",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Exception reading private key from PEM file\"",
",",
"e",
")",
";",
"}",
"}"
] |
Load PrivateKey from PEM file.
|
[
"Load",
"PrivateKey",
"from",
"PEM",
"file",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java#L300-L308
|
21,047
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java
|
KeyAndCertificateFactory.loadX509FromPEMFile
|
private X509Certificate loadX509FromPEMFile(String filename) {
try {
return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(FileReader.openStreamToFileFromClassPathOrPath(filename));
} catch (Exception e) {
throw new RuntimeException("Exception reading X509 from PEM file", e);
}
}
|
java
|
private X509Certificate loadX509FromPEMFile(String filename) {
try {
return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(FileReader.openStreamToFileFromClassPathOrPath(filename));
} catch (Exception e) {
throw new RuntimeException("Exception reading X509 from PEM file", e);
}
}
|
[
"private",
"X509Certificate",
"loadX509FromPEMFile",
"(",
"String",
"filename",
")",
"{",
"try",
"{",
"return",
"(",
"X509Certificate",
")",
"CertificateFactory",
".",
"getInstance",
"(",
"\"X.509\"",
")",
".",
"generateCertificate",
"(",
"FileReader",
".",
"openStreamToFileFromClassPathOrPath",
"(",
"filename",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Exception reading X509 from PEM file\"",
",",
"e",
")",
";",
"}",
"}"
] |
Load X509 from PEM file.
|
[
"Load",
"X509",
"from",
"PEM",
"file",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/socket/tls/KeyAndCertificateFactory.java#L313-L319
|
21,048
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java
|
HttpResponse.response
|
public static HttpResponse response(String body) {
return new HttpResponse().withStatusCode(OK_200.code()).withReasonPhrase(OK_200.reasonPhrase()).withBody(body);
}
|
java
|
public static HttpResponse response(String body) {
return new HttpResponse().withStatusCode(OK_200.code()).withReasonPhrase(OK_200.reasonPhrase()).withBody(body);
}
|
[
"public",
"static",
"HttpResponse",
"response",
"(",
"String",
"body",
")",
"{",
"return",
"new",
"HttpResponse",
"(",
")",
".",
"withStatusCode",
"(",
"OK_200",
".",
"code",
"(",
")",
")",
".",
"withReasonPhrase",
"(",
"OK_200",
".",
"reasonPhrase",
"(",
")",
")",
".",
"withBody",
"(",
"body",
")",
";",
"}"
] |
Static builder to create a response with a 200 status code and the string response body.
@param body a string
|
[
"Static",
"builder",
"to",
"create",
"a",
"response",
"with",
"a",
"200",
"status",
"code",
"and",
"the",
"string",
"response",
"body",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java#L37-L39
|
21,049
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java
|
HttpResponse.replaceHeader
|
public HttpResponse replaceHeader(String name, String... values) {
this.headers.replaceEntry(name, values);
return this;
}
|
java
|
public HttpResponse replaceHeader(String name, String... values) {
this.headers.replaceEntry(name, values);
return this;
}
|
[
"public",
"HttpResponse",
"replaceHeader",
"(",
"String",
"name",
",",
"String",
"...",
"values",
")",
"{",
"this",
".",
"headers",
".",
"replaceEntry",
"(",
"name",
",",
"values",
")",
";",
"return",
"this",
";",
"}"
] |
Update header to return as a Header object, if a header with
the same name already exists it will be modified
@param name the header name
@param values the header values
|
[
"Update",
"header",
"to",
"return",
"as",
"a",
"Header",
"object",
"if",
"a",
"header",
"with",
"the",
"same",
"name",
"already",
"exists",
"it",
"will",
"be",
"modified"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java#L258-L261
|
21,050
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java
|
HttpResponse.withCookie
|
public HttpResponse withCookie(String name, String value) {
this.cookies.withEntry(name, value);
return this;
}
|
java
|
public HttpResponse withCookie(String name, String value) {
this.cookies.withEntry(name, value);
return this;
}
|
[
"public",
"HttpResponse",
"withCookie",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"this",
".",
"cookies",
".",
"withEntry",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] |
Add cookie to return as Set-Cookie header
@param name the cookies name
@param value the cookies value
|
[
"Add",
"cookie",
"to",
"return",
"as",
"Set",
"-",
"Cookie",
"header"
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java#L351-L354
|
21,051
|
jamesdbloom/mockserver
|
mockserver-core/src/main/java/org/mockserver/model/HttpTemplate.java
|
HttpTemplate.template
|
public static HttpTemplate template(TemplateType type, String template) {
return new HttpTemplate(type).withTemplate(template);
}
|
java
|
public static HttpTemplate template(TemplateType type, String template) {
return new HttpTemplate(type).withTemplate(template);
}
|
[
"public",
"static",
"HttpTemplate",
"template",
"(",
"TemplateType",
"type",
",",
"String",
"template",
")",
"{",
"return",
"new",
"HttpTemplate",
"(",
"type",
")",
".",
"withTemplate",
"(",
"template",
")",
";",
"}"
] |
Static builder to create an template for responding or forwarding requests.
@param template the template for the response or request
|
[
"Static",
"builder",
"to",
"create",
"an",
"template",
"for",
"responding",
"or",
"forwarding",
"requests",
"."
] |
8b84fdd877e57b4eb780c9f8c8b1d65bcb448025
|
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpTemplate.java#L31-L33
|
21,052
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/routing/weighting/AbstractWeighting.java
|
AbstractWeighting.weightingToFileName
|
public static String weightingToFileName(Weighting w, boolean edgeBased) {
return toLowerCase(w.toString()).replaceAll("\\|", "_") + (edgeBased ? "_edge" : "_node");
}
|
java
|
public static String weightingToFileName(Weighting w, boolean edgeBased) {
return toLowerCase(w.toString()).replaceAll("\\|", "_") + (edgeBased ? "_edge" : "_node");
}
|
[
"public",
"static",
"String",
"weightingToFileName",
"(",
"Weighting",
"w",
",",
"boolean",
"edgeBased",
")",
"{",
"return",
"toLowerCase",
"(",
"w",
".",
"toString",
"(",
")",
")",
".",
"replaceAll",
"(",
"\"\\\\|\"",
",",
"\"_\"",
")",
"+",
"(",
"edgeBased",
"?",
"\"_edge\"",
":",
"\"_node\"",
")",
";",
"}"
] |
Replaces all characters which are not numbers, characters or underscores with underscores
|
[
"Replaces",
"all",
"characters",
"which",
"are",
"not",
"numbers",
"characters",
"or",
"underscores",
"with",
"underscores"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/weighting/AbstractWeighting.java#L101-L103
|
21,053
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/storage/index/QueryResult.java
|
QueryResult.calcSnappedPoint
|
public void calcSnappedPoint(DistanceCalc distCalc) {
if (closestEdge == null)
throw new IllegalStateException("No closest edge?");
if (snappedPoint != null)
throw new IllegalStateException("Calculate snapped point only once");
PointList fullPL = getClosestEdge().fetchWayGeometry(3);
double tmpLat = fullPL.getLatitude(wayIndex);
double tmpLon = fullPL.getLongitude(wayIndex);
double tmpEle = fullPL.getElevation(wayIndex);
if (snappedPosition != Position.EDGE) {
snappedPoint = new GHPoint3D(tmpLat, tmpLon, tmpEle);
return;
}
double queryLat = getQueryPoint().lat, queryLon = getQueryPoint().lon;
double adjLat = fullPL.getLatitude(wayIndex + 1), adjLon = fullPL.getLongitude(wayIndex + 1);
if (distCalc.validEdgeDistance(queryLat, queryLon, tmpLat, tmpLon, adjLat, adjLon)) {
GHPoint tmpPoint = distCalc.calcCrossingPointToEdge(queryLat, queryLon, tmpLat, tmpLon, adjLat, adjLon);
double adjEle = fullPL.getElevation(wayIndex + 1);
snappedPoint = new GHPoint3D(tmpPoint.lat, tmpPoint.lon, (tmpEle + adjEle) / 2);
} else
// outside of edge boundaries
snappedPoint = new GHPoint3D(tmpLat, tmpLon, tmpEle);
}
|
java
|
public void calcSnappedPoint(DistanceCalc distCalc) {
if (closestEdge == null)
throw new IllegalStateException("No closest edge?");
if (snappedPoint != null)
throw new IllegalStateException("Calculate snapped point only once");
PointList fullPL = getClosestEdge().fetchWayGeometry(3);
double tmpLat = fullPL.getLatitude(wayIndex);
double tmpLon = fullPL.getLongitude(wayIndex);
double tmpEle = fullPL.getElevation(wayIndex);
if (snappedPosition != Position.EDGE) {
snappedPoint = new GHPoint3D(tmpLat, tmpLon, tmpEle);
return;
}
double queryLat = getQueryPoint().lat, queryLon = getQueryPoint().lon;
double adjLat = fullPL.getLatitude(wayIndex + 1), adjLon = fullPL.getLongitude(wayIndex + 1);
if (distCalc.validEdgeDistance(queryLat, queryLon, tmpLat, tmpLon, adjLat, adjLon)) {
GHPoint tmpPoint = distCalc.calcCrossingPointToEdge(queryLat, queryLon, tmpLat, tmpLon, adjLat, adjLon);
double adjEle = fullPL.getElevation(wayIndex + 1);
snappedPoint = new GHPoint3D(tmpPoint.lat, tmpPoint.lon, (tmpEle + adjEle) / 2);
} else
// outside of edge boundaries
snappedPoint = new GHPoint3D(tmpLat, tmpLon, tmpEle);
}
|
[
"public",
"void",
"calcSnappedPoint",
"(",
"DistanceCalc",
"distCalc",
")",
"{",
"if",
"(",
"closestEdge",
"==",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"No closest edge?\"",
")",
";",
"if",
"(",
"snappedPoint",
"!=",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Calculate snapped point only once\"",
")",
";",
"PointList",
"fullPL",
"=",
"getClosestEdge",
"(",
")",
".",
"fetchWayGeometry",
"(",
"3",
")",
";",
"double",
"tmpLat",
"=",
"fullPL",
".",
"getLatitude",
"(",
"wayIndex",
")",
";",
"double",
"tmpLon",
"=",
"fullPL",
".",
"getLongitude",
"(",
"wayIndex",
")",
";",
"double",
"tmpEle",
"=",
"fullPL",
".",
"getElevation",
"(",
"wayIndex",
")",
";",
"if",
"(",
"snappedPosition",
"!=",
"Position",
".",
"EDGE",
")",
"{",
"snappedPoint",
"=",
"new",
"GHPoint3D",
"(",
"tmpLat",
",",
"tmpLon",
",",
"tmpEle",
")",
";",
"return",
";",
"}",
"double",
"queryLat",
"=",
"getQueryPoint",
"(",
")",
".",
"lat",
",",
"queryLon",
"=",
"getQueryPoint",
"(",
")",
".",
"lon",
";",
"double",
"adjLat",
"=",
"fullPL",
".",
"getLatitude",
"(",
"wayIndex",
"+",
"1",
")",
",",
"adjLon",
"=",
"fullPL",
".",
"getLongitude",
"(",
"wayIndex",
"+",
"1",
")",
";",
"if",
"(",
"distCalc",
".",
"validEdgeDistance",
"(",
"queryLat",
",",
"queryLon",
",",
"tmpLat",
",",
"tmpLon",
",",
"adjLat",
",",
"adjLon",
")",
")",
"{",
"GHPoint",
"tmpPoint",
"=",
"distCalc",
".",
"calcCrossingPointToEdge",
"(",
"queryLat",
",",
"queryLon",
",",
"tmpLat",
",",
"tmpLon",
",",
"adjLat",
",",
"adjLon",
")",
";",
"double",
"adjEle",
"=",
"fullPL",
".",
"getElevation",
"(",
"wayIndex",
"+",
"1",
")",
";",
"snappedPoint",
"=",
"new",
"GHPoint3D",
"(",
"tmpPoint",
".",
"lat",
",",
"tmpPoint",
".",
"lon",
",",
"(",
"tmpEle",
"+",
"adjEle",
")",
"/",
"2",
")",
";",
"}",
"else",
"// outside of edge boundaries",
"snappedPoint",
"=",
"new",
"GHPoint3D",
"(",
"tmpLat",
",",
"tmpLon",
",",
"tmpEle",
")",
";",
"}"
] |
Calculates the closet point on the edge from the query point.
|
[
"Calculates",
"the",
"closet",
"point",
"on",
"the",
"edge",
"from",
"the",
"query",
"point",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/index/QueryResult.java#L138-L162
|
21,054
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/routing/QueryGraph.java
|
QueryGraph.lookup
|
public QueryGraph lookup(QueryResult fromRes, QueryResult toRes) {
List<QueryResult> results = new ArrayList<>(2);
results.add(fromRes);
results.add(toRes);
lookup(results);
return this;
}
|
java
|
public QueryGraph lookup(QueryResult fromRes, QueryResult toRes) {
List<QueryResult> results = new ArrayList<>(2);
results.add(fromRes);
results.add(toRes);
lookup(results);
return this;
}
|
[
"public",
"QueryGraph",
"lookup",
"(",
"QueryResult",
"fromRes",
",",
"QueryResult",
"toRes",
")",
"{",
"List",
"<",
"QueryResult",
">",
"results",
"=",
"new",
"ArrayList",
"<>",
"(",
"2",
")",
";",
"results",
".",
"add",
"(",
"fromRes",
")",
";",
"results",
".",
"add",
"(",
"toRes",
")",
";",
"lookup",
"(",
"results",
")",
";",
"return",
"this",
";",
"}"
] |
Convenient method to initialize this QueryGraph with the two specified query results.
@see #lookup(List)
|
[
"Convenient",
"method",
"to",
"initialize",
"this",
"QueryGraph",
"with",
"the",
"two",
"specified",
"query",
"results",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/QueryGraph.java#L189-L195
|
21,055
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/routing/QueryGraph.java
|
QueryGraph.addVirtualEdges
|
private void addVirtualEdges(IntObjectMap<VirtualEdgeIterator> node2EdgeMap, EdgeFilter filter, boolean base,
int node, int virtNode) {
VirtualEdgeIterator existingIter = node2EdgeMap.get(node);
if (existingIter == null) {
existingIter = new VirtualEdgeIterator(10);
node2EdgeMap.put(node, existingIter);
}
EdgeIteratorState edge = base
? virtualEdges.get(virtNode * 4 + VE_BASE)
: virtualEdges.get(virtNode * 4 + VE_ADJ_REV);
if (filter.accept(edge))
existingIter.add(edge);
}
|
java
|
private void addVirtualEdges(IntObjectMap<VirtualEdgeIterator> node2EdgeMap, EdgeFilter filter, boolean base,
int node, int virtNode) {
VirtualEdgeIterator existingIter = node2EdgeMap.get(node);
if (existingIter == null) {
existingIter = new VirtualEdgeIterator(10);
node2EdgeMap.put(node, existingIter);
}
EdgeIteratorState edge = base
? virtualEdges.get(virtNode * 4 + VE_BASE)
: virtualEdges.get(virtNode * 4 + VE_ADJ_REV);
if (filter.accept(edge))
existingIter.add(edge);
}
|
[
"private",
"void",
"addVirtualEdges",
"(",
"IntObjectMap",
"<",
"VirtualEdgeIterator",
">",
"node2EdgeMap",
",",
"EdgeFilter",
"filter",
",",
"boolean",
"base",
",",
"int",
"node",
",",
"int",
"virtNode",
")",
"{",
"VirtualEdgeIterator",
"existingIter",
"=",
"node2EdgeMap",
".",
"get",
"(",
"node",
")",
";",
"if",
"(",
"existingIter",
"==",
"null",
")",
"{",
"existingIter",
"=",
"new",
"VirtualEdgeIterator",
"(",
"10",
")",
";",
"node2EdgeMap",
".",
"put",
"(",
"node",
",",
"existingIter",
")",
";",
"}",
"EdgeIteratorState",
"edge",
"=",
"base",
"?",
"virtualEdges",
".",
"get",
"(",
"virtNode",
"*",
"4",
"+",
"VE_BASE",
")",
":",
"virtualEdges",
".",
"get",
"(",
"virtNode",
"*",
"4",
"+",
"VE_ADJ_REV",
")",
";",
"if",
"(",
"filter",
".",
"accept",
"(",
"edge",
")",
")",
"existingIter",
".",
"add",
"(",
"edge",
")",
";",
"}"
] |
Creates a fake edge iterator pointing to multiple edge states.
|
[
"Creates",
"a",
"fake",
"edge",
"iterator",
"pointing",
"to",
"multiple",
"edge",
"states",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/QueryGraph.java#L674-L686
|
21,056
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/debatty/java/stringsimilarity/JaroWinkler.java
|
JaroWinkler.similarity
|
public final double similarity(final String s1, final String s2) {
int[] mtp = matches(s1, s2);
float m = mtp[0];
if (m == 0) {
return 0f;
}
double j = ((m / s1.length() + m / s2.length() + (m - mtp[1]) / m))
/ THREE;
double jw = j;
if (j > getThreshold()) {
jw = j + Math.min(JW_COEF, 1.0 / mtp[THREE]) * mtp[2] * (1 - j);
}
return jw;
}
|
java
|
public final double similarity(final String s1, final String s2) {
int[] mtp = matches(s1, s2);
float m = mtp[0];
if (m == 0) {
return 0f;
}
double j = ((m / s1.length() + m / s2.length() + (m - mtp[1]) / m))
/ THREE;
double jw = j;
if (j > getThreshold()) {
jw = j + Math.min(JW_COEF, 1.0 / mtp[THREE]) * mtp[2] * (1 - j);
}
return jw;
}
|
[
"public",
"final",
"double",
"similarity",
"(",
"final",
"String",
"s1",
",",
"final",
"String",
"s2",
")",
"{",
"int",
"[",
"]",
"mtp",
"=",
"matches",
"(",
"s1",
",",
"s2",
")",
";",
"float",
"m",
"=",
"mtp",
"[",
"0",
"]",
";",
"if",
"(",
"m",
"==",
"0",
")",
"{",
"return",
"0f",
";",
"}",
"double",
"j",
"=",
"(",
"(",
"m",
"/",
"s1",
".",
"length",
"(",
")",
"+",
"m",
"/",
"s2",
".",
"length",
"(",
")",
"+",
"(",
"m",
"-",
"mtp",
"[",
"1",
"]",
")",
"/",
"m",
")",
")",
"/",
"THREE",
";",
"double",
"jw",
"=",
"j",
";",
"if",
"(",
"j",
">",
"getThreshold",
"(",
")",
")",
"{",
"jw",
"=",
"j",
"+",
"Math",
".",
"min",
"(",
"JW_COEF",
",",
"1.0",
"/",
"mtp",
"[",
"THREE",
"]",
")",
"*",
"mtp",
"[",
"2",
"]",
"*",
"(",
"1",
"-",
"j",
")",
";",
"}",
"return",
"jw",
";",
"}"
] |
Compute JW similarity.
|
[
"Compute",
"JW",
"similarity",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/debatty/java/stringsimilarity/JaroWinkler.java#L72-L86
|
21,057
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/Instruction.java
|
Instruction.calcDirection
|
public String calcDirection(Instruction nextI) {
double azimuth = calcAzimuth(nextI);
if (Double.isNaN(azimuth))
return "";
return AC.azimuth2compassPoint(azimuth);
}
|
java
|
public String calcDirection(Instruction nextI) {
double azimuth = calcAzimuth(nextI);
if (Double.isNaN(azimuth))
return "";
return AC.azimuth2compassPoint(azimuth);
}
|
[
"public",
"String",
"calcDirection",
"(",
"Instruction",
"nextI",
")",
"{",
"double",
"azimuth",
"=",
"calcAzimuth",
"(",
"nextI",
")",
";",
"if",
"(",
"Double",
".",
"isNaN",
"(",
"azimuth",
")",
")",
"return",
"\"\"",
";",
"return",
"AC",
".",
"azimuth2compassPoint",
"(",
"azimuth",
")",
";",
"}"
] |
Return the direction like 'NE' based on the first tracksegment of the instruction. If
Instruction does not contain enough coordinate points, an empty string will be returned.
|
[
"Return",
"the",
"direction",
"like",
"NE",
"based",
"on",
"the",
"first",
"tracksegment",
"of",
"the",
"instruction",
".",
"If",
"Instruction",
"does",
"not",
"contain",
"enough",
"coordinate",
"points",
"an",
"empty",
"string",
"will",
"be",
"returned",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/Instruction.java#L156-L162
|
21,058
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/Instruction.java
|
Instruction.calcAzimuth
|
public double calcAzimuth(Instruction nextI) {
double nextLat;
double nextLon;
if (points.getSize() >= 2) {
nextLat = points.getLatitude(1);
nextLon = points.getLongitude(1);
} else if (nextI != null && points.getSize() == 1) {
nextLat = nextI.points.getLatitude(0);
nextLon = nextI.points.getLongitude(0);
} else {
return Double.NaN;
}
double lat = points.getLatitude(0);
double lon = points.getLongitude(0);
return AC.calcAzimuth(lat, lon, nextLat, nextLon);
}
|
java
|
public double calcAzimuth(Instruction nextI) {
double nextLat;
double nextLon;
if (points.getSize() >= 2) {
nextLat = points.getLatitude(1);
nextLon = points.getLongitude(1);
} else if (nextI != null && points.getSize() == 1) {
nextLat = nextI.points.getLatitude(0);
nextLon = nextI.points.getLongitude(0);
} else {
return Double.NaN;
}
double lat = points.getLatitude(0);
double lon = points.getLongitude(0);
return AC.calcAzimuth(lat, lon, nextLat, nextLon);
}
|
[
"public",
"double",
"calcAzimuth",
"(",
"Instruction",
"nextI",
")",
"{",
"double",
"nextLat",
";",
"double",
"nextLon",
";",
"if",
"(",
"points",
".",
"getSize",
"(",
")",
">=",
"2",
")",
"{",
"nextLat",
"=",
"points",
".",
"getLatitude",
"(",
"1",
")",
";",
"nextLon",
"=",
"points",
".",
"getLongitude",
"(",
"1",
")",
";",
"}",
"else",
"if",
"(",
"nextI",
"!=",
"null",
"&&",
"points",
".",
"getSize",
"(",
")",
"==",
"1",
")",
"{",
"nextLat",
"=",
"nextI",
".",
"points",
".",
"getLatitude",
"(",
"0",
")",
";",
"nextLon",
"=",
"nextI",
".",
"points",
".",
"getLongitude",
"(",
"0",
")",
";",
"}",
"else",
"{",
"return",
"Double",
".",
"NaN",
";",
"}",
"double",
"lat",
"=",
"points",
".",
"getLatitude",
"(",
"0",
")",
";",
"double",
"lon",
"=",
"points",
".",
"getLongitude",
"(",
"0",
")",
";",
"return",
"AC",
".",
"calcAzimuth",
"(",
"lat",
",",
"lon",
",",
"nextLat",
",",
"nextLon",
")",
";",
"}"
] |
Return the azimuth in degree based on the first tracksegment of this instruction. If this
instruction contains less than 2 points then NaN will be returned or the specified
instruction will be used if that is the finish instruction.
|
[
"Return",
"the",
"azimuth",
"in",
"degree",
"based",
"on",
"the",
"first",
"tracksegment",
"of",
"this",
"instruction",
".",
"If",
"this",
"instruction",
"contains",
"less",
"than",
"2",
"points",
"then",
"NaN",
"will",
"be",
"returned",
"or",
"the",
"specified",
"instruction",
"will",
"be",
"used",
"if",
"that",
"is",
"the",
"finish",
"instruction",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/Instruction.java#L169-L186
|
21,059
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/routing/PathBidirRef.java
|
PathBidirRef.extract
|
@Override
public Path extract() {
if (sptEntry == null || edgeTo == null)
return this;
if (sptEntry.adjNode != edgeTo.adjNode)
throw new IllegalStateException("Locations of the 'to'- and 'from'-Edge have to be the same. " + toString() + ", fromEntry:" + sptEntry + ", toEntry:" + edgeTo);
extractSW.start();
if (switchFromAndToSPTEntry) {
SPTEntry ee = sptEntry;
sptEntry = edgeTo;
edgeTo = ee;
}
SPTEntry currEdge = sptEntry;
boolean nextEdgeValid = EdgeIterator.Edge.isValid(currEdge.edge);
int nextEdge;
while (nextEdgeValid) {
// the reverse search needs the next edge
nextEdgeValid = EdgeIterator.Edge.isValid(currEdge.parent.edge);
nextEdge = nextEdgeValid ? currEdge.parent.edge : EdgeIterator.NO_EDGE;
processEdge(currEdge.edge, currEdge.adjNode, nextEdge);
currEdge = currEdge.parent;
}
setFromNode(currEdge.adjNode);
reverseOrder();
currEdge = edgeTo;
int prevEdge = EdgeIterator.Edge.isValid(sptEntry.edge) ? sptEntry.edge : EdgeIterator.NO_EDGE;
int tmpEdge = currEdge.edge;
while (EdgeIterator.Edge.isValid(tmpEdge)) {
currEdge = currEdge.parent;
processEdge(tmpEdge, currEdge.adjNode, prevEdge);
prevEdge = tmpEdge;
tmpEdge = currEdge.edge;
}
setEndNode(currEdge.adjNode);
extractSW.stop();
return setFound(true);
}
|
java
|
@Override
public Path extract() {
if (sptEntry == null || edgeTo == null)
return this;
if (sptEntry.adjNode != edgeTo.adjNode)
throw new IllegalStateException("Locations of the 'to'- and 'from'-Edge have to be the same. " + toString() + ", fromEntry:" + sptEntry + ", toEntry:" + edgeTo);
extractSW.start();
if (switchFromAndToSPTEntry) {
SPTEntry ee = sptEntry;
sptEntry = edgeTo;
edgeTo = ee;
}
SPTEntry currEdge = sptEntry;
boolean nextEdgeValid = EdgeIterator.Edge.isValid(currEdge.edge);
int nextEdge;
while (nextEdgeValid) {
// the reverse search needs the next edge
nextEdgeValid = EdgeIterator.Edge.isValid(currEdge.parent.edge);
nextEdge = nextEdgeValid ? currEdge.parent.edge : EdgeIterator.NO_EDGE;
processEdge(currEdge.edge, currEdge.adjNode, nextEdge);
currEdge = currEdge.parent;
}
setFromNode(currEdge.adjNode);
reverseOrder();
currEdge = edgeTo;
int prevEdge = EdgeIterator.Edge.isValid(sptEntry.edge) ? sptEntry.edge : EdgeIterator.NO_EDGE;
int tmpEdge = currEdge.edge;
while (EdgeIterator.Edge.isValid(tmpEdge)) {
currEdge = currEdge.parent;
processEdge(tmpEdge, currEdge.adjNode, prevEdge);
prevEdge = tmpEdge;
tmpEdge = currEdge.edge;
}
setEndNode(currEdge.adjNode);
extractSW.stop();
return setFound(true);
}
|
[
"@",
"Override",
"public",
"Path",
"extract",
"(",
")",
"{",
"if",
"(",
"sptEntry",
"==",
"null",
"||",
"edgeTo",
"==",
"null",
")",
"return",
"this",
";",
"if",
"(",
"sptEntry",
".",
"adjNode",
"!=",
"edgeTo",
".",
"adjNode",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Locations of the 'to'- and 'from'-Edge have to be the same. \"",
"+",
"toString",
"(",
")",
"+",
"\", fromEntry:\"",
"+",
"sptEntry",
"+",
"\", toEntry:\"",
"+",
"edgeTo",
")",
";",
"extractSW",
".",
"start",
"(",
")",
";",
"if",
"(",
"switchFromAndToSPTEntry",
")",
"{",
"SPTEntry",
"ee",
"=",
"sptEntry",
";",
"sptEntry",
"=",
"edgeTo",
";",
"edgeTo",
"=",
"ee",
";",
"}",
"SPTEntry",
"currEdge",
"=",
"sptEntry",
";",
"boolean",
"nextEdgeValid",
"=",
"EdgeIterator",
".",
"Edge",
".",
"isValid",
"(",
"currEdge",
".",
"edge",
")",
";",
"int",
"nextEdge",
";",
"while",
"(",
"nextEdgeValid",
")",
"{",
"// the reverse search needs the next edge",
"nextEdgeValid",
"=",
"EdgeIterator",
".",
"Edge",
".",
"isValid",
"(",
"currEdge",
".",
"parent",
".",
"edge",
")",
";",
"nextEdge",
"=",
"nextEdgeValid",
"?",
"currEdge",
".",
"parent",
".",
"edge",
":",
"EdgeIterator",
".",
"NO_EDGE",
";",
"processEdge",
"(",
"currEdge",
".",
"edge",
",",
"currEdge",
".",
"adjNode",
",",
"nextEdge",
")",
";",
"currEdge",
"=",
"currEdge",
".",
"parent",
";",
"}",
"setFromNode",
"(",
"currEdge",
".",
"adjNode",
")",
";",
"reverseOrder",
"(",
")",
";",
"currEdge",
"=",
"edgeTo",
";",
"int",
"prevEdge",
"=",
"EdgeIterator",
".",
"Edge",
".",
"isValid",
"(",
"sptEntry",
".",
"edge",
")",
"?",
"sptEntry",
".",
"edge",
":",
"EdgeIterator",
".",
"NO_EDGE",
";",
"int",
"tmpEdge",
"=",
"currEdge",
".",
"edge",
";",
"while",
"(",
"EdgeIterator",
".",
"Edge",
".",
"isValid",
"(",
"tmpEdge",
")",
")",
"{",
"currEdge",
"=",
"currEdge",
".",
"parent",
";",
"processEdge",
"(",
"tmpEdge",
",",
"currEdge",
".",
"adjNode",
",",
"prevEdge",
")",
";",
"prevEdge",
"=",
"tmpEdge",
";",
"tmpEdge",
"=",
"currEdge",
".",
"edge",
";",
"}",
"setEndNode",
"(",
"currEdge",
".",
"adjNode",
")",
";",
"extractSW",
".",
"stop",
"(",
")",
";",
"return",
"setFound",
"(",
"true",
")",
";",
"}"
] |
Extracts path from two shortest-path-tree
|
[
"Extracts",
"path",
"from",
"two",
"shortest",
"-",
"path",
"-",
"tree"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/PathBidirRef.java#L58-L97
|
21,060
|
graphhopper/graphhopper
|
reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java
|
GTFSFeed.loadFromFile
|
public void loadFromFile(ZipFile zip, String fid) throws IOException {
if (this.loaded) throw new UnsupportedOperationException("Attempt to load GTFS into existing database");
// NB we don't have a single CRC for the file, so we combine all the CRCs of the component files. NB we are not
// simply summing the CRCs because CRCs are (I assume) uniformly randomly distributed throughout the width of a
// long, so summing them is a convolution which moves towards a Gaussian with mean 0 (i.e. more concentrated
// probability in the center), degrading the quality of the hash. Instead we XOR. Assuming each bit is independent,
// this will yield a nice uniformly distributed result, because when combining two bits there is an equal
// probability of any input, which means an equal probability of any output. At least I think that's all correct.
// Repeated XOR is not commutative but zip.stream returns files in the order they are in the central directory
// of the zip file, so that's not a problem.
checksum = zip.stream().mapToLong(ZipEntry::getCrc).reduce((l1, l2) -> l1 ^ l2).getAsLong();
db.getAtomicLong("checksum").set(checksum);
new FeedInfo.Loader(this).loadTable(zip);
// maybe we should just point to the feed object itself instead of its ID, and null out its stoptimes map after loading
if (fid != null) {
feedId = fid;
LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID
}
else if (feedId == null || feedId.isEmpty()) {
feedId = new File(zip.getName()).getName().replaceAll("\\.zip$", "");
LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID
}
else {
LOG.info("Feed ID is '{}'.", feedId);
}
db.getAtomicString("feed_id").set(feedId);
new Agency.Loader(this).loadTable(zip);
if (agency.isEmpty()) {
errors.add(new GeneralError("agency", 0, "agency_id", "Need at least one agency."));
}
// calendars and calendar dates are joined into services. This means a lot of manipulating service objects as
// they are loaded; since mapdb keys/values are immutable, load them in memory then copy them to MapDB once
// we're done loading them
Map<String, Service> serviceTable = new HashMap<>();
new Calendar.Loader(this, serviceTable).loadTable(zip);
new CalendarDate.Loader(this, serviceTable).loadTable(zip);
this.services.putAll(serviceTable);
serviceTable = null; // free memory
// Same deal
Map<String, Fare> fares = new HashMap<>();
new FareAttribute.Loader(this, fares).loadTable(zip);
new FareRule.Loader(this, fares).loadTable(zip);
this.fares.putAll(fares);
fares = null; // free memory
new Route.Loader(this).loadTable(zip);
new ShapePoint.Loader(this).loadTable(zip);
new Stop.Loader(this).loadTable(zip);
new Transfer.Loader(this).loadTable(zip);
new Trip.Loader(this).loadTable(zip);
new Frequency.Loader(this).loadTable(zip);
new StopTime.Loader(this).loadTable(zip); // comment out this line for quick testing using NL feed
loaded = true;
}
|
java
|
public void loadFromFile(ZipFile zip, String fid) throws IOException {
if (this.loaded) throw new UnsupportedOperationException("Attempt to load GTFS into existing database");
// NB we don't have a single CRC for the file, so we combine all the CRCs of the component files. NB we are not
// simply summing the CRCs because CRCs are (I assume) uniformly randomly distributed throughout the width of a
// long, so summing them is a convolution which moves towards a Gaussian with mean 0 (i.e. more concentrated
// probability in the center), degrading the quality of the hash. Instead we XOR. Assuming each bit is independent,
// this will yield a nice uniformly distributed result, because when combining two bits there is an equal
// probability of any input, which means an equal probability of any output. At least I think that's all correct.
// Repeated XOR is not commutative but zip.stream returns files in the order they are in the central directory
// of the zip file, so that's not a problem.
checksum = zip.stream().mapToLong(ZipEntry::getCrc).reduce((l1, l2) -> l1 ^ l2).getAsLong();
db.getAtomicLong("checksum").set(checksum);
new FeedInfo.Loader(this).loadTable(zip);
// maybe we should just point to the feed object itself instead of its ID, and null out its stoptimes map after loading
if (fid != null) {
feedId = fid;
LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID
}
else if (feedId == null || feedId.isEmpty()) {
feedId = new File(zip.getName()).getName().replaceAll("\\.zip$", "");
LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID
}
else {
LOG.info("Feed ID is '{}'.", feedId);
}
db.getAtomicString("feed_id").set(feedId);
new Agency.Loader(this).loadTable(zip);
if (agency.isEmpty()) {
errors.add(new GeneralError("agency", 0, "agency_id", "Need at least one agency."));
}
// calendars and calendar dates are joined into services. This means a lot of manipulating service objects as
// they are loaded; since mapdb keys/values are immutable, load them in memory then copy them to MapDB once
// we're done loading them
Map<String, Service> serviceTable = new HashMap<>();
new Calendar.Loader(this, serviceTable).loadTable(zip);
new CalendarDate.Loader(this, serviceTable).loadTable(zip);
this.services.putAll(serviceTable);
serviceTable = null; // free memory
// Same deal
Map<String, Fare> fares = new HashMap<>();
new FareAttribute.Loader(this, fares).loadTable(zip);
new FareRule.Loader(this, fares).loadTable(zip);
this.fares.putAll(fares);
fares = null; // free memory
new Route.Loader(this).loadTable(zip);
new ShapePoint.Loader(this).loadTable(zip);
new Stop.Loader(this).loadTable(zip);
new Transfer.Loader(this).loadTable(zip);
new Trip.Loader(this).loadTable(zip);
new Frequency.Loader(this).loadTable(zip);
new StopTime.Loader(this).loadTable(zip); // comment out this line for quick testing using NL feed
loaded = true;
}
|
[
"public",
"void",
"loadFromFile",
"(",
"ZipFile",
"zip",
",",
"String",
"fid",
")",
"throws",
"IOException",
"{",
"if",
"(",
"this",
".",
"loaded",
")",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Attempt to load GTFS into existing database\"",
")",
";",
"// NB we don't have a single CRC for the file, so we combine all the CRCs of the component files. NB we are not",
"// simply summing the CRCs because CRCs are (I assume) uniformly randomly distributed throughout the width of a",
"// long, so summing them is a convolution which moves towards a Gaussian with mean 0 (i.e. more concentrated",
"// probability in the center), degrading the quality of the hash. Instead we XOR. Assuming each bit is independent,",
"// this will yield a nice uniformly distributed result, because when combining two bits there is an equal",
"// probability of any input, which means an equal probability of any output. At least I think that's all correct.",
"// Repeated XOR is not commutative but zip.stream returns files in the order they are in the central directory",
"// of the zip file, so that's not a problem.",
"checksum",
"=",
"zip",
".",
"stream",
"(",
")",
".",
"mapToLong",
"(",
"ZipEntry",
"::",
"getCrc",
")",
".",
"reduce",
"(",
"(",
"l1",
",",
"l2",
")",
"->",
"l1",
"^",
"l2",
")",
".",
"getAsLong",
"(",
")",
";",
"db",
".",
"getAtomicLong",
"(",
"\"checksum\"",
")",
".",
"set",
"(",
"checksum",
")",
";",
"new",
"FeedInfo",
".",
"Loader",
"(",
"this",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"// maybe we should just point to the feed object itself instead of its ID, and null out its stoptimes map after loading",
"if",
"(",
"fid",
"!=",
"null",
")",
"{",
"feedId",
"=",
"fid",
";",
"LOG",
".",
"info",
"(",
"\"Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.\"",
",",
"feedId",
")",
";",
"// TODO log an error, ideally feeds should include a feedID",
"}",
"else",
"if",
"(",
"feedId",
"==",
"null",
"||",
"feedId",
".",
"isEmpty",
"(",
")",
")",
"{",
"feedId",
"=",
"new",
"File",
"(",
"zip",
".",
"getName",
"(",
")",
")",
".",
"getName",
"(",
")",
".",
"replaceAll",
"(",
"\"\\\\.zip$\"",
",",
"\"\"",
")",
";",
"LOG",
".",
"info",
"(",
"\"Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.\"",
",",
"feedId",
")",
";",
"// TODO log an error, ideally feeds should include a feedID",
"}",
"else",
"{",
"LOG",
".",
"info",
"(",
"\"Feed ID is '{}'.\"",
",",
"feedId",
")",
";",
"}",
"db",
".",
"getAtomicString",
"(",
"\"feed_id\"",
")",
".",
"set",
"(",
"feedId",
")",
";",
"new",
"Agency",
".",
"Loader",
"(",
"this",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"if",
"(",
"agency",
".",
"isEmpty",
"(",
")",
")",
"{",
"errors",
".",
"add",
"(",
"new",
"GeneralError",
"(",
"\"agency\"",
",",
"0",
",",
"\"agency_id\"",
",",
"\"Need at least one agency.\"",
")",
")",
";",
"}",
"// calendars and calendar dates are joined into services. This means a lot of manipulating service objects as",
"// they are loaded; since mapdb keys/values are immutable, load them in memory then copy them to MapDB once",
"// we're done loading them",
"Map",
"<",
"String",
",",
"Service",
">",
"serviceTable",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"new",
"Calendar",
".",
"Loader",
"(",
"this",
",",
"serviceTable",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"new",
"CalendarDate",
".",
"Loader",
"(",
"this",
",",
"serviceTable",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"this",
".",
"services",
".",
"putAll",
"(",
"serviceTable",
")",
";",
"serviceTable",
"=",
"null",
";",
"// free memory",
"// Same deal",
"Map",
"<",
"String",
",",
"Fare",
">",
"fares",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"new",
"FareAttribute",
".",
"Loader",
"(",
"this",
",",
"fares",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"new",
"FareRule",
".",
"Loader",
"(",
"this",
",",
"fares",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"this",
".",
"fares",
".",
"putAll",
"(",
"fares",
")",
";",
"fares",
"=",
"null",
";",
"// free memory",
"new",
"Route",
".",
"Loader",
"(",
"this",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"new",
"ShapePoint",
".",
"Loader",
"(",
"this",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"new",
"Stop",
".",
"Loader",
"(",
"this",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"new",
"Transfer",
".",
"Loader",
"(",
"this",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"new",
"Trip",
".",
"Loader",
"(",
"this",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"new",
"Frequency",
".",
"Loader",
"(",
"this",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"new",
"StopTime",
".",
"Loader",
"(",
"this",
")",
".",
"loadTable",
"(",
"zip",
")",
";",
"// comment out this line for quick testing using NL feed",
"loaded",
"=",
"true",
";",
"}"
] |
The order in which we load the tables is important for two reasons.
1. We must load feed_info first so we know the feed ID before loading any other entities. This could be relaxed
by having entities point to the feed object rather than its ID String.
2. Referenced entities must be loaded before any entities that reference them. This is because we check
referential integrity while the files are being loaded. This is done on the fly during loading because it allows
us to associate a line number with errors in objects that don't have any other clear identifier.
Interestingly, all references are resolvable when tables are loaded in alphabetical order.
|
[
"The",
"order",
"in",
"which",
"we",
"load",
"the",
"tables",
"is",
"important",
"for",
"two",
"reasons",
".",
"1",
".",
"We",
"must",
"load",
"feed_info",
"first",
"so",
"we",
"know",
"the",
"feed",
"ID",
"before",
"loading",
"any",
"other",
"entities",
".",
"This",
"could",
"be",
"relaxed",
"by",
"having",
"entities",
"point",
"to",
"the",
"feed",
"object",
"rather",
"than",
"its",
"ID",
"String",
".",
"2",
".",
"Referenced",
"entities",
"must",
"be",
"loaded",
"before",
"any",
"entities",
"that",
"reference",
"them",
".",
"This",
"is",
"because",
"we",
"check",
"referential",
"integrity",
"while",
"the",
"files",
"are",
"being",
"loaded",
".",
"This",
"is",
"done",
"on",
"the",
"fly",
"during",
"loading",
"because",
"it",
"allows",
"us",
"to",
"associate",
"a",
"line",
"number",
"with",
"errors",
"in",
"objects",
"that",
"don",
"t",
"have",
"any",
"other",
"clear",
"identifier",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java#L112-L172
|
21,061
|
graphhopper/graphhopper
|
reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java
|
GTFSFeed.getOrderedStopTimesForTrip
|
public Iterable<StopTime> getOrderedStopTimesForTrip (String trip_id) {
Map<Fun.Tuple2, StopTime> tripStopTimes =
stop_times.subMap(
Fun.t2(trip_id, null),
Fun.t2(trip_id, Fun.HI)
);
return tripStopTimes.values();
}
|
java
|
public Iterable<StopTime> getOrderedStopTimesForTrip (String trip_id) {
Map<Fun.Tuple2, StopTime> tripStopTimes =
stop_times.subMap(
Fun.t2(trip_id, null),
Fun.t2(trip_id, Fun.HI)
);
return tripStopTimes.values();
}
|
[
"public",
"Iterable",
"<",
"StopTime",
">",
"getOrderedStopTimesForTrip",
"(",
"String",
"trip_id",
")",
"{",
"Map",
"<",
"Fun",
".",
"Tuple2",
",",
"StopTime",
">",
"tripStopTimes",
"=",
"stop_times",
".",
"subMap",
"(",
"Fun",
".",
"t2",
"(",
"trip_id",
",",
"null",
")",
",",
"Fun",
".",
"t2",
"(",
"trip_id",
",",
"Fun",
".",
"HI",
")",
")",
";",
"return",
"tripStopTimes",
".",
"values",
"(",
")",
";",
"}"
] |
For the given trip ID, fetch all the stop times in order of increasing stop_sequence.
This is an efficient iteration over a tree map.
|
[
"For",
"the",
"given",
"trip",
"ID",
"fetch",
"all",
"the",
"stop",
"times",
"in",
"order",
"of",
"increasing",
"stop_sequence",
".",
"This",
"is",
"an",
"efficient",
"iteration",
"over",
"a",
"tree",
"map",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java#L193-L200
|
21,062
|
graphhopper/graphhopper
|
reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java
|
GTFSFeed.getShape
|
public Shape getShape (String shape_id) {
Shape shape = new Shape(this, shape_id);
return shape.shape_dist_traveled.length > 0 ? shape : null;
}
|
java
|
public Shape getShape (String shape_id) {
Shape shape = new Shape(this, shape_id);
return shape.shape_dist_traveled.length > 0 ? shape : null;
}
|
[
"public",
"Shape",
"getShape",
"(",
"String",
"shape_id",
")",
"{",
"Shape",
"shape",
"=",
"new",
"Shape",
"(",
"this",
",",
"shape_id",
")",
";",
"return",
"shape",
".",
"shape_dist_traveled",
".",
"length",
">",
"0",
"?",
"shape",
":",
"null",
";",
"}"
] |
Get the shape for the given shape ID
|
[
"Get",
"the",
"shape",
"for",
"the",
"given",
"shape",
"ID"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java#L203-L206
|
21,063
|
graphhopper/graphhopper
|
reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java
|
GTFSFeed.getInterpolatedStopTimesForTrip
|
public Iterable<StopTime> getInterpolatedStopTimesForTrip (String trip_id) throws FirstAndLastStopsDoNotHaveTimes {
// clone stop times so as not to modify base GTFS structures
StopTime[] stopTimes = StreamSupport.stream(getOrderedStopTimesForTrip(trip_id).spliterator(), false)
.map(st -> st.clone())
.toArray(i -> new StopTime[i]);
// avoid having to make sure that the array has length below.
if (stopTimes.length == 0) return Collections.emptyList();
// first pass: set all partially filled stop times
for (StopTime st : stopTimes) {
if (st.arrival_time != Entity.INT_MISSING && st.departure_time == Entity.INT_MISSING) {
st.departure_time = st.arrival_time;
}
if (st.arrival_time == Entity.INT_MISSING && st.departure_time != Entity.INT_MISSING) {
st.arrival_time = st.departure_time;
}
}
// quick check: ensure that first and last stops have times.
// technically GTFS requires that both arrival_time and departure_time be filled at both the first and last stop,
// but we are slightly more lenient and only insist that one of them be filled at both the first and last stop.
// The meaning of the first stop's arrival time is unclear, and same for the last stop's departure time (except
// in the case of interlining).
// it's fine to just check departure time, as the above pass ensures that all stop times have either both
// arrival and departure times, or neither
if (stopTimes[0].departure_time == Entity.INT_MISSING || stopTimes[stopTimes.length - 1].departure_time == Entity.INT_MISSING) {
throw new FirstAndLastStopsDoNotHaveTimes();
}
// second pass: fill complete stop times
int startOfInterpolatedBlock = -1;
for (int stopTime = 0; stopTime < stopTimes.length; stopTime++) {
if (stopTimes[stopTime].departure_time == Entity.INT_MISSING && startOfInterpolatedBlock == -1) {
startOfInterpolatedBlock = stopTime;
}
else if (stopTimes[stopTime].departure_time != Entity.INT_MISSING && startOfInterpolatedBlock != -1) {
throw new RuntimeException("Missing stop times not supported.");
}
}
return Arrays.asList(stopTimes);
}
|
java
|
public Iterable<StopTime> getInterpolatedStopTimesForTrip (String trip_id) throws FirstAndLastStopsDoNotHaveTimes {
// clone stop times so as not to modify base GTFS structures
StopTime[] stopTimes = StreamSupport.stream(getOrderedStopTimesForTrip(trip_id).spliterator(), false)
.map(st -> st.clone())
.toArray(i -> new StopTime[i]);
// avoid having to make sure that the array has length below.
if (stopTimes.length == 0) return Collections.emptyList();
// first pass: set all partially filled stop times
for (StopTime st : stopTimes) {
if (st.arrival_time != Entity.INT_MISSING && st.departure_time == Entity.INT_MISSING) {
st.departure_time = st.arrival_time;
}
if (st.arrival_time == Entity.INT_MISSING && st.departure_time != Entity.INT_MISSING) {
st.arrival_time = st.departure_time;
}
}
// quick check: ensure that first and last stops have times.
// technically GTFS requires that both arrival_time and departure_time be filled at both the first and last stop,
// but we are slightly more lenient and only insist that one of them be filled at both the first and last stop.
// The meaning of the first stop's arrival time is unclear, and same for the last stop's departure time (except
// in the case of interlining).
// it's fine to just check departure time, as the above pass ensures that all stop times have either both
// arrival and departure times, or neither
if (stopTimes[0].departure_time == Entity.INT_MISSING || stopTimes[stopTimes.length - 1].departure_time == Entity.INT_MISSING) {
throw new FirstAndLastStopsDoNotHaveTimes();
}
// second pass: fill complete stop times
int startOfInterpolatedBlock = -1;
for (int stopTime = 0; stopTime < stopTimes.length; stopTime++) {
if (stopTimes[stopTime].departure_time == Entity.INT_MISSING && startOfInterpolatedBlock == -1) {
startOfInterpolatedBlock = stopTime;
}
else if (stopTimes[stopTime].departure_time != Entity.INT_MISSING && startOfInterpolatedBlock != -1) {
throw new RuntimeException("Missing stop times not supported.");
}
}
return Arrays.asList(stopTimes);
}
|
[
"public",
"Iterable",
"<",
"StopTime",
">",
"getInterpolatedStopTimesForTrip",
"(",
"String",
"trip_id",
")",
"throws",
"FirstAndLastStopsDoNotHaveTimes",
"{",
"// clone stop times so as not to modify base GTFS structures",
"StopTime",
"[",
"]",
"stopTimes",
"=",
"StreamSupport",
".",
"stream",
"(",
"getOrderedStopTimesForTrip",
"(",
"trip_id",
")",
".",
"spliterator",
"(",
")",
",",
"false",
")",
".",
"map",
"(",
"st",
"->",
"st",
".",
"clone",
"(",
")",
")",
".",
"toArray",
"(",
"i",
"->",
"new",
"StopTime",
"[",
"i",
"]",
")",
";",
"// avoid having to make sure that the array has length below.",
"if",
"(",
"stopTimes",
".",
"length",
"==",
"0",
")",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"// first pass: set all partially filled stop times",
"for",
"(",
"StopTime",
"st",
":",
"stopTimes",
")",
"{",
"if",
"(",
"st",
".",
"arrival_time",
"!=",
"Entity",
".",
"INT_MISSING",
"&&",
"st",
".",
"departure_time",
"==",
"Entity",
".",
"INT_MISSING",
")",
"{",
"st",
".",
"departure_time",
"=",
"st",
".",
"arrival_time",
";",
"}",
"if",
"(",
"st",
".",
"arrival_time",
"==",
"Entity",
".",
"INT_MISSING",
"&&",
"st",
".",
"departure_time",
"!=",
"Entity",
".",
"INT_MISSING",
")",
"{",
"st",
".",
"arrival_time",
"=",
"st",
".",
"departure_time",
";",
"}",
"}",
"// quick check: ensure that first and last stops have times.",
"// technically GTFS requires that both arrival_time and departure_time be filled at both the first and last stop,",
"// but we are slightly more lenient and only insist that one of them be filled at both the first and last stop.",
"// The meaning of the first stop's arrival time is unclear, and same for the last stop's departure time (except",
"// in the case of interlining).",
"// it's fine to just check departure time, as the above pass ensures that all stop times have either both",
"// arrival and departure times, or neither",
"if",
"(",
"stopTimes",
"[",
"0",
"]",
".",
"departure_time",
"==",
"Entity",
".",
"INT_MISSING",
"||",
"stopTimes",
"[",
"stopTimes",
".",
"length",
"-",
"1",
"]",
".",
"departure_time",
"==",
"Entity",
".",
"INT_MISSING",
")",
"{",
"throw",
"new",
"FirstAndLastStopsDoNotHaveTimes",
"(",
")",
";",
"}",
"// second pass: fill complete stop times",
"int",
"startOfInterpolatedBlock",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"stopTime",
"=",
"0",
";",
"stopTime",
"<",
"stopTimes",
".",
"length",
";",
"stopTime",
"++",
")",
"{",
"if",
"(",
"stopTimes",
"[",
"stopTime",
"]",
".",
"departure_time",
"==",
"Entity",
".",
"INT_MISSING",
"&&",
"startOfInterpolatedBlock",
"==",
"-",
"1",
")",
"{",
"startOfInterpolatedBlock",
"=",
"stopTime",
";",
"}",
"else",
"if",
"(",
"stopTimes",
"[",
"stopTime",
"]",
".",
"departure_time",
"!=",
"Entity",
".",
"INT_MISSING",
"&&",
"startOfInterpolatedBlock",
"!=",
"-",
"1",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Missing stop times not supported.\"",
")",
";",
"}",
"}",
"return",
"Arrays",
".",
"asList",
"(",
"stopTimes",
")",
";",
"}"
] |
For the given trip ID, fetch all the stop times in order, and interpolate stop-to-stop travel times.
|
[
"For",
"the",
"given",
"trip",
"ID",
"fetch",
"all",
"the",
"stop",
"times",
"in",
"order",
"and",
"interpolate",
"stop",
"-",
"to",
"-",
"stop",
"travel",
"times",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java#L211-L256
|
21,064
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/storage/change/ChangeGraphHelper.java
|
ChangeGraphHelper.applyChanges
|
public long applyChanges(EncodingManager em, Collection<JsonFeature> features) {
if (em == null)
throw new NullPointerException("EncodingManager cannot be null to change existing graph");
long updates = 0;
for (JsonFeature jsonFeature : features) {
if (!jsonFeature.hasProperties())
throw new IllegalArgumentException("One feature has no properties, please specify properties e.g. speed or access");
List<String> encodersAsStr = (List) jsonFeature.getProperty("vehicles");
if (encodersAsStr == null) {
for (FlagEncoder encoder : em.fetchEdgeEncoders()) {
updates += applyChange(jsonFeature, encoder);
}
} else {
for (String encoderStr : encodersAsStr) {
updates += applyChange(jsonFeature, em.getEncoder(encoderStr));
}
}
}
return updates;
}
|
java
|
public long applyChanges(EncodingManager em, Collection<JsonFeature> features) {
if (em == null)
throw new NullPointerException("EncodingManager cannot be null to change existing graph");
long updates = 0;
for (JsonFeature jsonFeature : features) {
if (!jsonFeature.hasProperties())
throw new IllegalArgumentException("One feature has no properties, please specify properties e.g. speed or access");
List<String> encodersAsStr = (List) jsonFeature.getProperty("vehicles");
if (encodersAsStr == null) {
for (FlagEncoder encoder : em.fetchEdgeEncoders()) {
updates += applyChange(jsonFeature, encoder);
}
} else {
for (String encoderStr : encodersAsStr) {
updates += applyChange(jsonFeature, em.getEncoder(encoderStr));
}
}
}
return updates;
}
|
[
"public",
"long",
"applyChanges",
"(",
"EncodingManager",
"em",
",",
"Collection",
"<",
"JsonFeature",
">",
"features",
")",
"{",
"if",
"(",
"em",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"EncodingManager cannot be null to change existing graph\"",
")",
";",
"long",
"updates",
"=",
"0",
";",
"for",
"(",
"JsonFeature",
"jsonFeature",
":",
"features",
")",
"{",
"if",
"(",
"!",
"jsonFeature",
".",
"hasProperties",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"One feature has no properties, please specify properties e.g. speed or access\"",
")",
";",
"List",
"<",
"String",
">",
"encodersAsStr",
"=",
"(",
"List",
")",
"jsonFeature",
".",
"getProperty",
"(",
"\"vehicles\"",
")",
";",
"if",
"(",
"encodersAsStr",
"==",
"null",
")",
"{",
"for",
"(",
"FlagEncoder",
"encoder",
":",
"em",
".",
"fetchEdgeEncoders",
"(",
")",
")",
"{",
"updates",
"+=",
"applyChange",
"(",
"jsonFeature",
",",
"encoder",
")",
";",
"}",
"}",
"else",
"{",
"for",
"(",
"String",
"encoderStr",
":",
"encodersAsStr",
")",
"{",
"updates",
"+=",
"applyChange",
"(",
"jsonFeature",
",",
"em",
".",
"getEncoder",
"(",
"encoderStr",
")",
")",
";",
"}",
"}",
"}",
"return",
"updates",
";",
"}"
] |
This method applies changes to the graph, specified by the json features.
@return number of successfully applied edge changes
|
[
"This",
"method",
"applies",
"changes",
"to",
"the",
"graph",
"specified",
"by",
"the",
"json",
"features",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/change/ChangeGraphHelper.java#L68-L90
|
21,065
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/shapes/BBox.java
|
BBox.createInverse
|
public static BBox createInverse(boolean elevation) {
if (elevation) {
return new BBox(Double.MAX_VALUE, -Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE,
Double.MAX_VALUE, -Double.MAX_VALUE, true);
} else {
return new BBox(Double.MAX_VALUE, -Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE,
Double.NaN, Double.NaN, false);
}
}
|
java
|
public static BBox createInverse(boolean elevation) {
if (elevation) {
return new BBox(Double.MAX_VALUE, -Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE,
Double.MAX_VALUE, -Double.MAX_VALUE, true);
} else {
return new BBox(Double.MAX_VALUE, -Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE,
Double.NaN, Double.NaN, false);
}
}
|
[
"public",
"static",
"BBox",
"createInverse",
"(",
"boolean",
"elevation",
")",
"{",
"if",
"(",
"elevation",
")",
"{",
"return",
"new",
"BBox",
"(",
"Double",
".",
"MAX_VALUE",
",",
"-",
"Double",
".",
"MAX_VALUE",
",",
"Double",
".",
"MAX_VALUE",
",",
"-",
"Double",
".",
"MAX_VALUE",
",",
"Double",
".",
"MAX_VALUE",
",",
"-",
"Double",
".",
"MAX_VALUE",
",",
"true",
")",
";",
"}",
"else",
"{",
"return",
"new",
"BBox",
"(",
"Double",
".",
"MAX_VALUE",
",",
"-",
"Double",
".",
"MAX_VALUE",
",",
"Double",
".",
"MAX_VALUE",
",",
"-",
"Double",
".",
"MAX_VALUE",
",",
"Double",
".",
"NaN",
",",
"Double",
".",
"NaN",
",",
"false",
")",
";",
"}",
"}"
] |
Prefills BBox with minimum values so that it can increase.
|
[
"Prefills",
"BBox",
"with",
"minimum",
"values",
"so",
"that",
"it",
"can",
"increase",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/shapes/BBox.java#L74-L82
|
21,066
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/shapes/BBox.java
|
BBox.calculateIntersection
|
public BBox calculateIntersection(BBox bBox) {
if (!this.intersects(bBox))
return null;
double minLon = Math.max(this.minLon, bBox.minLon);
double maxLon = Math.min(this.maxLon, bBox.maxLon);
double minLat = Math.max(this.minLat, bBox.minLat);
double maxLat = Math.min(this.maxLat, bBox.maxLat);
return new BBox(minLon, maxLon, minLat, maxLat);
}
|
java
|
public BBox calculateIntersection(BBox bBox) {
if (!this.intersects(bBox))
return null;
double minLon = Math.max(this.minLon, bBox.minLon);
double maxLon = Math.min(this.maxLon, bBox.maxLon);
double minLat = Math.max(this.minLat, bBox.minLat);
double maxLat = Math.min(this.maxLat, bBox.maxLat);
return new BBox(minLon, maxLon, minLat, maxLat);
}
|
[
"public",
"BBox",
"calculateIntersection",
"(",
"BBox",
"bBox",
")",
"{",
"if",
"(",
"!",
"this",
".",
"intersects",
"(",
"bBox",
")",
")",
"return",
"null",
";",
"double",
"minLon",
"=",
"Math",
".",
"max",
"(",
"this",
".",
"minLon",
",",
"bBox",
".",
"minLon",
")",
";",
"double",
"maxLon",
"=",
"Math",
".",
"min",
"(",
"this",
".",
"maxLon",
",",
"bBox",
".",
"maxLon",
")",
";",
"double",
"minLat",
"=",
"Math",
".",
"max",
"(",
"this",
".",
"minLat",
",",
"bBox",
".",
"minLat",
")",
";",
"double",
"maxLat",
"=",
"Math",
".",
"min",
"(",
"this",
".",
"maxLat",
",",
"bBox",
".",
"maxLat",
")",
";",
"return",
"new",
"BBox",
"(",
"minLon",
",",
"maxLon",
",",
"minLat",
",",
"maxLat",
")",
";",
"}"
] |
Calculates the intersecting BBox between this and the specified BBox
@return the intersecting BBox or null if not intersecting
|
[
"Calculates",
"the",
"intersecting",
"BBox",
"between",
"this",
"and",
"the",
"specified",
"BBox"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/shapes/BBox.java#L125-L135
|
21,067
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/shapes/BBox.java
|
BBox.parseTwoPoints
|
public static BBox parseTwoPoints(String objectAsString) {
String[] splittedObject = objectAsString.split(",");
if (splittedObject.length != 4)
throw new IllegalArgumentException("BBox should have 4 parts but was " + objectAsString);
double minLat = Double.parseDouble(splittedObject[0]);
double minLon = Double.parseDouble(splittedObject[1]);
double maxLat = Double.parseDouble(splittedObject[2]);
double maxLon = Double.parseDouble(splittedObject[3]);
if (minLat > maxLat) {
double tmp = minLat;
minLat = maxLat;
maxLat = tmp;
}
if (minLon > maxLon) {
double tmp = minLon;
minLon = maxLon;
maxLon = tmp;
}
return new BBox(minLon, maxLon, minLat, maxLat);
}
|
java
|
public static BBox parseTwoPoints(String objectAsString) {
String[] splittedObject = objectAsString.split(",");
if (splittedObject.length != 4)
throw new IllegalArgumentException("BBox should have 4 parts but was " + objectAsString);
double minLat = Double.parseDouble(splittedObject[0]);
double minLon = Double.parseDouble(splittedObject[1]);
double maxLat = Double.parseDouble(splittedObject[2]);
double maxLon = Double.parseDouble(splittedObject[3]);
if (minLat > maxLat) {
double tmp = minLat;
minLat = maxLat;
maxLat = tmp;
}
if (minLon > maxLon) {
double tmp = minLon;
minLon = maxLon;
maxLon = tmp;
}
return new BBox(minLon, maxLon, minLat, maxLat);
}
|
[
"public",
"static",
"BBox",
"parseTwoPoints",
"(",
"String",
"objectAsString",
")",
"{",
"String",
"[",
"]",
"splittedObject",
"=",
"objectAsString",
".",
"split",
"(",
"\",\"",
")",
";",
"if",
"(",
"splittedObject",
".",
"length",
"!=",
"4",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"BBox should have 4 parts but was \"",
"+",
"objectAsString",
")",
";",
"double",
"minLat",
"=",
"Double",
".",
"parseDouble",
"(",
"splittedObject",
"[",
"0",
"]",
")",
";",
"double",
"minLon",
"=",
"Double",
".",
"parseDouble",
"(",
"splittedObject",
"[",
"1",
"]",
")",
";",
"double",
"maxLat",
"=",
"Double",
".",
"parseDouble",
"(",
"splittedObject",
"[",
"2",
"]",
")",
";",
"double",
"maxLon",
"=",
"Double",
".",
"parseDouble",
"(",
"splittedObject",
"[",
"3",
"]",
")",
";",
"if",
"(",
"minLat",
">",
"maxLat",
")",
"{",
"double",
"tmp",
"=",
"minLat",
";",
"minLat",
"=",
"maxLat",
";",
"maxLat",
"=",
"tmp",
";",
"}",
"if",
"(",
"minLon",
">",
"maxLon",
")",
"{",
"double",
"tmp",
"=",
"minLon",
";",
"minLon",
"=",
"maxLon",
";",
"maxLon",
"=",
"tmp",
";",
"}",
"return",
"new",
"BBox",
"(",
"minLon",
",",
"maxLon",
",",
"minLat",
",",
"maxLat",
")",
";",
"}"
] |
This method creates a BBox out of a string in format lat1,lon1,lat2,lon2
|
[
"This",
"method",
"creates",
"a",
"BBox",
"out",
"of",
"a",
"string",
"in",
"format",
"lat1",
"lon1",
"lat2",
"lon2"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/shapes/BBox.java#L304-L329
|
21,068
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/shapes/BBox.java
|
BBox.parseBBoxString
|
public static BBox parseBBoxString(String objectAsString) {
String[] splittedObject = objectAsString.split(",");
if (splittedObject.length != 4)
throw new IllegalArgumentException("BBox should have 4 parts but was " + objectAsString);
double minLon = Double.parseDouble(splittedObject[0]);
double maxLon = Double.parseDouble(splittedObject[1]);
double minLat = Double.parseDouble(splittedObject[2]);
double maxLat = Double.parseDouble(splittedObject[3]);
return new BBox(minLon, maxLon, minLat, maxLat);
}
|
java
|
public static BBox parseBBoxString(String objectAsString) {
String[] splittedObject = objectAsString.split(",");
if (splittedObject.length != 4)
throw new IllegalArgumentException("BBox should have 4 parts but was " + objectAsString);
double minLon = Double.parseDouble(splittedObject[0]);
double maxLon = Double.parseDouble(splittedObject[1]);
double minLat = Double.parseDouble(splittedObject[2]);
double maxLat = Double.parseDouble(splittedObject[3]);
return new BBox(minLon, maxLon, minLat, maxLat);
}
|
[
"public",
"static",
"BBox",
"parseBBoxString",
"(",
"String",
"objectAsString",
")",
"{",
"String",
"[",
"]",
"splittedObject",
"=",
"objectAsString",
".",
"split",
"(",
"\",\"",
")",
";",
"if",
"(",
"splittedObject",
".",
"length",
"!=",
"4",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"BBox should have 4 parts but was \"",
"+",
"objectAsString",
")",
";",
"double",
"minLon",
"=",
"Double",
".",
"parseDouble",
"(",
"splittedObject",
"[",
"0",
"]",
")",
";",
"double",
"maxLon",
"=",
"Double",
".",
"parseDouble",
"(",
"splittedObject",
"[",
"1",
"]",
")",
";",
"double",
"minLat",
"=",
"Double",
".",
"parseDouble",
"(",
"splittedObject",
"[",
"2",
"]",
")",
";",
"double",
"maxLat",
"=",
"Double",
".",
"parseDouble",
"(",
"splittedObject",
"[",
"3",
"]",
")",
";",
"return",
"new",
"BBox",
"(",
"minLon",
",",
"maxLon",
",",
"minLat",
",",
"maxLat",
")",
";",
"}"
] |
This method creates a BBox out of a string in format lon1,lon2,lat1,lat2
|
[
"This",
"method",
"creates",
"a",
"BBox",
"out",
"of",
"a",
"string",
"in",
"format",
"lon1",
"lon2",
"lat1",
"lat2"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/shapes/BBox.java#L334-L347
|
21,069
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/routing/ch/NodeBasedNodeContractor.java
|
NodeBasedNodeContractor.addShortcuts
|
private int addShortcuts(Collection<Shortcut> shortcuts) {
int tmpNewShortcuts = 0;
NEXT_SC:
for (Shortcut sc : shortcuts) {
boolean updatedInGraph = false;
// check if we need to update some existing shortcut in the graph
CHEdgeIterator iter = outEdgeExplorer.setBaseNode(sc.from);
while (iter.next()) {
if (iter.isShortcut() && iter.getAdjNode() == sc.to) {
int status = iter.getMergeStatus(sc.flags);
if (status == 0)
continue;
if (sc.weight >= prepareWeighting.calcWeight(iter, false, EdgeIterator.NO_EDGE)) {
// special case if a bidirectional shortcut has worse weight and still has to be added as otherwise the opposite direction would be missing
// see testShortcutMergeBug
if (status == 2)
break;
continue NEXT_SC;
}
if (iter.getEdge() == sc.skippedEdge1 || iter.getEdge() == sc.skippedEdge2) {
throw new IllegalStateException("Shortcut cannot update itself! " + iter.getEdge()
+ ", skipEdge1:" + sc.skippedEdge1 + ", skipEdge2:" + sc.skippedEdge2
+ ", edge " + iter + ":" + getCoords(iter, prepareGraph)
+ ", sc:" + sc
+ ", skippedEdge1: " + getCoords(prepareGraph.getEdgeIteratorState(sc.skippedEdge1, sc.from), prepareGraph)
+ ", skippedEdge2: " + getCoords(prepareGraph.getEdgeIteratorState(sc.skippedEdge2, sc.to), prepareGraph)
+ ", neighbors:" + GHUtility.getNeighbors(iter));
}
iter.setFlagsAndWeight(sc.flags, sc.weight);
iter.setDistance(sc.dist);
iter.setSkippedEdges(sc.skippedEdge1, sc.skippedEdge2);
setOrigEdgeCount(iter.getEdge(), sc.originalEdges);
updatedInGraph = true;
break;
}
}
if (!updatedInGraph) {
int scId = prepareGraph.shortcut(sc.from, sc.to, sc.flags, sc.weight, sc.dist, sc.skippedEdge1, sc.skippedEdge2);
setOrigEdgeCount(scId, sc.originalEdges);
tmpNewShortcuts++;
}
}
return tmpNewShortcuts;
}
|
java
|
private int addShortcuts(Collection<Shortcut> shortcuts) {
int tmpNewShortcuts = 0;
NEXT_SC:
for (Shortcut sc : shortcuts) {
boolean updatedInGraph = false;
// check if we need to update some existing shortcut in the graph
CHEdgeIterator iter = outEdgeExplorer.setBaseNode(sc.from);
while (iter.next()) {
if (iter.isShortcut() && iter.getAdjNode() == sc.to) {
int status = iter.getMergeStatus(sc.flags);
if (status == 0)
continue;
if (sc.weight >= prepareWeighting.calcWeight(iter, false, EdgeIterator.NO_EDGE)) {
// special case if a bidirectional shortcut has worse weight and still has to be added as otherwise the opposite direction would be missing
// see testShortcutMergeBug
if (status == 2)
break;
continue NEXT_SC;
}
if (iter.getEdge() == sc.skippedEdge1 || iter.getEdge() == sc.skippedEdge2) {
throw new IllegalStateException("Shortcut cannot update itself! " + iter.getEdge()
+ ", skipEdge1:" + sc.skippedEdge1 + ", skipEdge2:" + sc.skippedEdge2
+ ", edge " + iter + ":" + getCoords(iter, prepareGraph)
+ ", sc:" + sc
+ ", skippedEdge1: " + getCoords(prepareGraph.getEdgeIteratorState(sc.skippedEdge1, sc.from), prepareGraph)
+ ", skippedEdge2: " + getCoords(prepareGraph.getEdgeIteratorState(sc.skippedEdge2, sc.to), prepareGraph)
+ ", neighbors:" + GHUtility.getNeighbors(iter));
}
iter.setFlagsAndWeight(sc.flags, sc.weight);
iter.setDistance(sc.dist);
iter.setSkippedEdges(sc.skippedEdge1, sc.skippedEdge2);
setOrigEdgeCount(iter.getEdge(), sc.originalEdges);
updatedInGraph = true;
break;
}
}
if (!updatedInGraph) {
int scId = prepareGraph.shortcut(sc.from, sc.to, sc.flags, sc.weight, sc.dist, sc.skippedEdge1, sc.skippedEdge2);
setOrigEdgeCount(scId, sc.originalEdges);
tmpNewShortcuts++;
}
}
return tmpNewShortcuts;
}
|
[
"private",
"int",
"addShortcuts",
"(",
"Collection",
"<",
"Shortcut",
">",
"shortcuts",
")",
"{",
"int",
"tmpNewShortcuts",
"=",
"0",
";",
"NEXT_SC",
":",
"for",
"(",
"Shortcut",
"sc",
":",
"shortcuts",
")",
"{",
"boolean",
"updatedInGraph",
"=",
"false",
";",
"// check if we need to update some existing shortcut in the graph",
"CHEdgeIterator",
"iter",
"=",
"outEdgeExplorer",
".",
"setBaseNode",
"(",
"sc",
".",
"from",
")",
";",
"while",
"(",
"iter",
".",
"next",
"(",
")",
")",
"{",
"if",
"(",
"iter",
".",
"isShortcut",
"(",
")",
"&&",
"iter",
".",
"getAdjNode",
"(",
")",
"==",
"sc",
".",
"to",
")",
"{",
"int",
"status",
"=",
"iter",
".",
"getMergeStatus",
"(",
"sc",
".",
"flags",
")",
";",
"if",
"(",
"status",
"==",
"0",
")",
"continue",
";",
"if",
"(",
"sc",
".",
"weight",
">=",
"prepareWeighting",
".",
"calcWeight",
"(",
"iter",
",",
"false",
",",
"EdgeIterator",
".",
"NO_EDGE",
")",
")",
"{",
"// special case if a bidirectional shortcut has worse weight and still has to be added as otherwise the opposite direction would be missing",
"// see testShortcutMergeBug",
"if",
"(",
"status",
"==",
"2",
")",
"break",
";",
"continue",
"NEXT_SC",
";",
"}",
"if",
"(",
"iter",
".",
"getEdge",
"(",
")",
"==",
"sc",
".",
"skippedEdge1",
"||",
"iter",
".",
"getEdge",
"(",
")",
"==",
"sc",
".",
"skippedEdge2",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Shortcut cannot update itself! \"",
"+",
"iter",
".",
"getEdge",
"(",
")",
"+",
"\", skipEdge1:\"",
"+",
"sc",
".",
"skippedEdge1",
"+",
"\", skipEdge2:\"",
"+",
"sc",
".",
"skippedEdge2",
"+",
"\", edge \"",
"+",
"iter",
"+",
"\":\"",
"+",
"getCoords",
"(",
"iter",
",",
"prepareGraph",
")",
"+",
"\", sc:\"",
"+",
"sc",
"+",
"\", skippedEdge1: \"",
"+",
"getCoords",
"(",
"prepareGraph",
".",
"getEdgeIteratorState",
"(",
"sc",
".",
"skippedEdge1",
",",
"sc",
".",
"from",
")",
",",
"prepareGraph",
")",
"+",
"\", skippedEdge2: \"",
"+",
"getCoords",
"(",
"prepareGraph",
".",
"getEdgeIteratorState",
"(",
"sc",
".",
"skippedEdge2",
",",
"sc",
".",
"to",
")",
",",
"prepareGraph",
")",
"+",
"\", neighbors:\"",
"+",
"GHUtility",
".",
"getNeighbors",
"(",
"iter",
")",
")",
";",
"}",
"iter",
".",
"setFlagsAndWeight",
"(",
"sc",
".",
"flags",
",",
"sc",
".",
"weight",
")",
";",
"iter",
".",
"setDistance",
"(",
"sc",
".",
"dist",
")",
";",
"iter",
".",
"setSkippedEdges",
"(",
"sc",
".",
"skippedEdge1",
",",
"sc",
".",
"skippedEdge2",
")",
";",
"setOrigEdgeCount",
"(",
"iter",
".",
"getEdge",
"(",
")",
",",
"sc",
".",
"originalEdges",
")",
";",
"updatedInGraph",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"updatedInGraph",
")",
"{",
"int",
"scId",
"=",
"prepareGraph",
".",
"shortcut",
"(",
"sc",
".",
"from",
",",
"sc",
".",
"to",
",",
"sc",
".",
"flags",
",",
"sc",
".",
"weight",
",",
"sc",
".",
"dist",
",",
"sc",
".",
"skippedEdge1",
",",
"sc",
".",
"skippedEdge2",
")",
";",
"setOrigEdgeCount",
"(",
"scId",
",",
"sc",
".",
"originalEdges",
")",
";",
"tmpNewShortcuts",
"++",
";",
"}",
"}",
"return",
"tmpNewShortcuts",
";",
"}"
] |
Adds the given shortcuts to the graph.
@return the actual number of shortcuts that were added to the graph
|
[
"Adds",
"the",
"given",
"shortcuts",
"to",
"the",
"graph",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/ch/NodeBasedNodeContractor.java#L234-L283
|
21,070
|
graphhopper/graphhopper
|
reader-gtfs/src/main/java/com/conveyal/gtfs/model/Entity.java
|
Entity.human
|
private static final String human (long n) {
if (n >= 1000000) return String.format(Locale.getDefault(), "%.1fM", n/1000000.0);
if (n >= 1000) return String.format(Locale.getDefault(), "%.1fk", n/1000.0);
else return String.format(Locale.getDefault(), "%d", n);
}
|
java
|
private static final String human (long n) {
if (n >= 1000000) return String.format(Locale.getDefault(), "%.1fM", n/1000000.0);
if (n >= 1000) return String.format(Locale.getDefault(), "%.1fk", n/1000.0);
else return String.format(Locale.getDefault(), "%d", n);
}
|
[
"private",
"static",
"final",
"String",
"human",
"(",
"long",
"n",
")",
"{",
"if",
"(",
"n",
">=",
"1000000",
")",
"return",
"String",
".",
"format",
"(",
"Locale",
".",
"getDefault",
"(",
")",
",",
"\"%.1fM\"",
",",
"n",
"/",
"1000000.0",
")",
";",
"if",
"(",
"n",
">=",
"1000",
")",
"return",
"String",
".",
"format",
"(",
"Locale",
".",
"getDefault",
"(",
")",
",",
"\"%.1fk\"",
",",
"n",
"/",
"1000.0",
")",
";",
"else",
"return",
"String",
".",
"format",
"(",
"Locale",
".",
"getDefault",
"(",
")",
",",
"\"%d\"",
",",
"n",
")",
";",
"}"
] |
shared code between reading and writing
|
[
"shared",
"code",
"between",
"reading",
"and",
"writing"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Entity.java#L443-L447
|
21,071
|
graphhopper/graphhopper
|
tools/src/main/java/com/graphhopper/tools/Measurement.java
|
Measurement.writeSummary
|
private void writeSummary(String summaryLocation, String propLocation) {
logger.info("writing summary to " + summaryLocation);
// choose properties that should be in summary here
String[] properties = {
"graph.nodes",
"graph.edges",
"graph.import_time",
CH.PREPARE + "time",
CH.PREPARE + "node.shortcuts",
CH.PREPARE + "edge.shortcuts",
Landmark.PREPARE + "time",
"routing.distance_mean",
"routing.mean",
"routing.visited_nodes_mean",
"routingCH.distance_mean",
"routingCH.mean",
"routingCH.visited_nodes_mean",
"routingCH_no_instr.mean",
"routingCH_edge.distance_mean",
"routingCH_edge.mean",
"routingCH_edge.visited_nodes_mean",
"routingCH_edge_no_instr.mean",
"routingLM8.distance_mean",
"routingLM8.mean",
"routingLM8.visited_nodes_mean",
"measurement.seed",
"measurement.gitinfo",
"measurement.timestamp"
};
File f = new File(summaryLocation);
boolean writeHeader = !f.exists();
try (FileWriter writer = new FileWriter(f, true)) {
if (writeHeader)
writer.write(getSummaryHeader(properties));
writer.write(getSummaryLogLine(properties, propLocation));
} catch (IOException e) {
logger.error("Could not write summary to file '{}'", summaryLocation, e);
}
}
|
java
|
private void writeSummary(String summaryLocation, String propLocation) {
logger.info("writing summary to " + summaryLocation);
// choose properties that should be in summary here
String[] properties = {
"graph.nodes",
"graph.edges",
"graph.import_time",
CH.PREPARE + "time",
CH.PREPARE + "node.shortcuts",
CH.PREPARE + "edge.shortcuts",
Landmark.PREPARE + "time",
"routing.distance_mean",
"routing.mean",
"routing.visited_nodes_mean",
"routingCH.distance_mean",
"routingCH.mean",
"routingCH.visited_nodes_mean",
"routingCH_no_instr.mean",
"routingCH_edge.distance_mean",
"routingCH_edge.mean",
"routingCH_edge.visited_nodes_mean",
"routingCH_edge_no_instr.mean",
"routingLM8.distance_mean",
"routingLM8.mean",
"routingLM8.visited_nodes_mean",
"measurement.seed",
"measurement.gitinfo",
"measurement.timestamp"
};
File f = new File(summaryLocation);
boolean writeHeader = !f.exists();
try (FileWriter writer = new FileWriter(f, true)) {
if (writeHeader)
writer.write(getSummaryHeader(properties));
writer.write(getSummaryLogLine(properties, propLocation));
} catch (IOException e) {
logger.error("Could not write summary to file '{}'", summaryLocation, e);
}
}
|
[
"private",
"void",
"writeSummary",
"(",
"String",
"summaryLocation",
",",
"String",
"propLocation",
")",
"{",
"logger",
".",
"info",
"(",
"\"writing summary to \"",
"+",
"summaryLocation",
")",
";",
"// choose properties that should be in summary here",
"String",
"[",
"]",
"properties",
"=",
"{",
"\"graph.nodes\"",
",",
"\"graph.edges\"",
",",
"\"graph.import_time\"",
",",
"CH",
".",
"PREPARE",
"+",
"\"time\"",
",",
"CH",
".",
"PREPARE",
"+",
"\"node.shortcuts\"",
",",
"CH",
".",
"PREPARE",
"+",
"\"edge.shortcuts\"",
",",
"Landmark",
".",
"PREPARE",
"+",
"\"time\"",
",",
"\"routing.distance_mean\"",
",",
"\"routing.mean\"",
",",
"\"routing.visited_nodes_mean\"",
",",
"\"routingCH.distance_mean\"",
",",
"\"routingCH.mean\"",
",",
"\"routingCH.visited_nodes_mean\"",
",",
"\"routingCH_no_instr.mean\"",
",",
"\"routingCH_edge.distance_mean\"",
",",
"\"routingCH_edge.mean\"",
",",
"\"routingCH_edge.visited_nodes_mean\"",
",",
"\"routingCH_edge_no_instr.mean\"",
",",
"\"routingLM8.distance_mean\"",
",",
"\"routingLM8.mean\"",
",",
"\"routingLM8.visited_nodes_mean\"",
",",
"\"measurement.seed\"",
",",
"\"measurement.gitinfo\"",
",",
"\"measurement.timestamp\"",
"}",
";",
"File",
"f",
"=",
"new",
"File",
"(",
"summaryLocation",
")",
";",
"boolean",
"writeHeader",
"=",
"!",
"f",
".",
"exists",
"(",
")",
";",
"try",
"(",
"FileWriter",
"writer",
"=",
"new",
"FileWriter",
"(",
"f",
",",
"true",
")",
")",
"{",
"if",
"(",
"writeHeader",
")",
"writer",
".",
"write",
"(",
"getSummaryHeader",
"(",
"properties",
")",
")",
";",
"writer",
".",
"write",
"(",
"getSummaryLogLine",
"(",
"properties",
",",
"propLocation",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"Could not write summary to file '{}'\"",
",",
"summaryLocation",
",",
"e",
")",
";",
"}",
"}"
] |
Writes a selection of measurement results to a single line in
a file. Each run of the measurement class will append a new line.
|
[
"Writes",
"a",
"selection",
"of",
"measurement",
"results",
"to",
"a",
"single",
"line",
"in",
"a",
"file",
".",
"Each",
"run",
"of",
"the",
"measurement",
"class",
"will",
"append",
"a",
"new",
"line",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/tools/src/main/java/com/graphhopper/tools/Measurement.java#L558-L596
|
21,072
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/util/EngineWarmUp.java
|
EngineWarmUp.warmUp
|
public static void warmUp(GraphHopper graphHopper, int iterations) {
GraphHopperStorage ghStorage = graphHopper.getGraphHopperStorage();
if (ghStorage == null)
throw new IllegalArgumentException("The storage of GraphHopper must not be empty");
try {
if (ghStorage.isCHPossible())
warmUpCHSubNetwork(graphHopper, iterations);
else
warmUpNonCHSubNetwork(graphHopper, iterations);
} catch (Exception ex) {
LOGGER.warn("Problem while sending warm up queries", ex);
}
}
|
java
|
public static void warmUp(GraphHopper graphHopper, int iterations) {
GraphHopperStorage ghStorage = graphHopper.getGraphHopperStorage();
if (ghStorage == null)
throw new IllegalArgumentException("The storage of GraphHopper must not be empty");
try {
if (ghStorage.isCHPossible())
warmUpCHSubNetwork(graphHopper, iterations);
else
warmUpNonCHSubNetwork(graphHopper, iterations);
} catch (Exception ex) {
LOGGER.warn("Problem while sending warm up queries", ex);
}
}
|
[
"public",
"static",
"void",
"warmUp",
"(",
"GraphHopper",
"graphHopper",
",",
"int",
"iterations",
")",
"{",
"GraphHopperStorage",
"ghStorage",
"=",
"graphHopper",
".",
"getGraphHopperStorage",
"(",
")",
";",
"if",
"(",
"ghStorage",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The storage of GraphHopper must not be empty\"",
")",
";",
"try",
"{",
"if",
"(",
"ghStorage",
".",
"isCHPossible",
"(",
")",
")",
"warmUpCHSubNetwork",
"(",
"graphHopper",
",",
"iterations",
")",
";",
"else",
"warmUpNonCHSubNetwork",
"(",
"graphHopper",
",",
"iterations",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Problem while sending warm up queries\"",
",",
"ex",
")",
";",
"}",
"}"
] |
Do the 'warm up' for the specified GraphHopper instance.
@param iterations the 'intensity' of the warm up procedure
|
[
"Do",
"the",
"warm",
"up",
"for",
"the",
"specified",
"GraphHopper",
"instance",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/EngineWarmUp.java#L40-L53
|
21,073
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/routing/util/EncodingManager.java
|
EncodingManager.create
|
public static EncodingManager create(FlagEncoderFactory factory, String ghLoc) {
Directory dir = new RAMDirectory(ghLoc, true);
StorableProperties properties = new StorableProperties(dir);
if (!properties.loadExisting())
throw new IllegalStateException("Cannot load properties to fetch EncodingManager configuration at: "
+ dir.getLocation());
// check encoding for compatibility
properties.checkVersions(false);
String acceptStr = properties.get("graph.flag_encoders");
if (acceptStr.isEmpty())
throw new IllegalStateException("EncodingManager was not configured. And no one was found in the graph: "
+ dir.getLocation());
int bytesForFlags = 4;
try {
bytesForFlags = Integer.parseInt(properties.get("graph.bytes_for_flags"));
} catch (NumberFormatException ex) {
}
return createBuilder(factory, acceptStr, bytesForFlags).build();
}
|
java
|
public static EncodingManager create(FlagEncoderFactory factory, String ghLoc) {
Directory dir = new RAMDirectory(ghLoc, true);
StorableProperties properties = new StorableProperties(dir);
if (!properties.loadExisting())
throw new IllegalStateException("Cannot load properties to fetch EncodingManager configuration at: "
+ dir.getLocation());
// check encoding for compatibility
properties.checkVersions(false);
String acceptStr = properties.get("graph.flag_encoders");
if (acceptStr.isEmpty())
throw new IllegalStateException("EncodingManager was not configured. And no one was found in the graph: "
+ dir.getLocation());
int bytesForFlags = 4;
try {
bytesForFlags = Integer.parseInt(properties.get("graph.bytes_for_flags"));
} catch (NumberFormatException ex) {
}
return createBuilder(factory, acceptStr, bytesForFlags).build();
}
|
[
"public",
"static",
"EncodingManager",
"create",
"(",
"FlagEncoderFactory",
"factory",
",",
"String",
"ghLoc",
")",
"{",
"Directory",
"dir",
"=",
"new",
"RAMDirectory",
"(",
"ghLoc",
",",
"true",
")",
";",
"StorableProperties",
"properties",
"=",
"new",
"StorableProperties",
"(",
"dir",
")",
";",
"if",
"(",
"!",
"properties",
".",
"loadExisting",
"(",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot load properties to fetch EncodingManager configuration at: \"",
"+",
"dir",
".",
"getLocation",
"(",
")",
")",
";",
"// check encoding for compatibility",
"properties",
".",
"checkVersions",
"(",
"false",
")",
";",
"String",
"acceptStr",
"=",
"properties",
".",
"get",
"(",
"\"graph.flag_encoders\"",
")",
";",
"if",
"(",
"acceptStr",
".",
"isEmpty",
"(",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"EncodingManager was not configured. And no one was found in the graph: \"",
"+",
"dir",
".",
"getLocation",
"(",
")",
")",
";",
"int",
"bytesForFlags",
"=",
"4",
";",
"try",
"{",
"bytesForFlags",
"=",
"Integer",
".",
"parseInt",
"(",
"properties",
".",
"get",
"(",
"\"graph.bytes_for_flags\"",
")",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"ex",
")",
"{",
"}",
"return",
"createBuilder",
"(",
"factory",
",",
"acceptStr",
",",
"bytesForFlags",
")",
".",
"build",
"(",
")",
";",
"}"
] |
Create the EncodingManager from the provided GraphHopper location. Throws an
IllegalStateException if it fails. Used if no EncodingManager specified on load.
|
[
"Create",
"the",
"EncodingManager",
"from",
"the",
"provided",
"GraphHopper",
"location",
".",
"Throws",
"an",
"IllegalStateException",
"if",
"it",
"fails",
".",
"Used",
"if",
"no",
"EncodingManager",
"specified",
"on",
"load",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/EncodingManager.java#L117-L138
|
21,074
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/routing/util/EncodingManager.java
|
EncodingManager.acceptWay
|
public boolean acceptWay(ReaderWay way, AcceptWay acceptWay) {
if (!acceptWay.isEmpty())
throw new IllegalArgumentException("AcceptWay must be empty");
for (AbstractFlagEncoder encoder : edgeEncoders) {
acceptWay.put(encoder.toString(), encoder.getAccess(way));
}
return acceptWay.hasAccepted();
}
|
java
|
public boolean acceptWay(ReaderWay way, AcceptWay acceptWay) {
if (!acceptWay.isEmpty())
throw new IllegalArgumentException("AcceptWay must be empty");
for (AbstractFlagEncoder encoder : edgeEncoders) {
acceptWay.put(encoder.toString(), encoder.getAccess(way));
}
return acceptWay.hasAccepted();
}
|
[
"public",
"boolean",
"acceptWay",
"(",
"ReaderWay",
"way",
",",
"AcceptWay",
"acceptWay",
")",
"{",
"if",
"(",
"!",
"acceptWay",
".",
"isEmpty",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"AcceptWay must be empty\"",
")",
";",
"for",
"(",
"AbstractFlagEncoder",
"encoder",
":",
"edgeEncoders",
")",
"{",
"acceptWay",
".",
"put",
"(",
"encoder",
".",
"toString",
"(",
")",
",",
"encoder",
".",
"getAccess",
"(",
"way",
")",
")",
";",
"}",
"return",
"acceptWay",
".",
"hasAccepted",
"(",
")",
";",
"}"
] |
Determine whether a way is routable for one of the added encoders.
@return if at least one encoder consumes the specified way. Additionally the specified acceptWay is changed
to provide more details.
|
[
"Determine",
"whether",
"a",
"way",
"is",
"routable",
"for",
"one",
"of",
"the",
"added",
"encoders",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/EncodingManager.java#L384-L392
|
21,075
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/routing/util/EncodingManager.java
|
EncodingManager.handleWayTags
|
public IntsRef handleWayTags(ReaderWay way, AcceptWay acceptWay, long relationFlags) {
IntsRef edgeFlags = createEdgeFlags();
// return if way or ferry
Access access = acceptWay.getAccess();
for (TagParser parser : sharedEncodedValueMap.values()) {
parser.handleWayTags(edgeFlags, way, access, relationFlags);
}
for (AbstractFlagEncoder encoder : edgeEncoders) {
encoder.handleWayTags(edgeFlags, way, acceptWay.get(encoder.toString()), relationFlags & encoder.getRelBitMask());
}
return edgeFlags;
}
|
java
|
public IntsRef handleWayTags(ReaderWay way, AcceptWay acceptWay, long relationFlags) {
IntsRef edgeFlags = createEdgeFlags();
// return if way or ferry
Access access = acceptWay.getAccess();
for (TagParser parser : sharedEncodedValueMap.values()) {
parser.handleWayTags(edgeFlags, way, access, relationFlags);
}
for (AbstractFlagEncoder encoder : edgeEncoders) {
encoder.handleWayTags(edgeFlags, way, acceptWay.get(encoder.toString()), relationFlags & encoder.getRelBitMask());
}
return edgeFlags;
}
|
[
"public",
"IntsRef",
"handleWayTags",
"(",
"ReaderWay",
"way",
",",
"AcceptWay",
"acceptWay",
",",
"long",
"relationFlags",
")",
"{",
"IntsRef",
"edgeFlags",
"=",
"createEdgeFlags",
"(",
")",
";",
"// return if way or ferry",
"Access",
"access",
"=",
"acceptWay",
".",
"getAccess",
"(",
")",
";",
"for",
"(",
"TagParser",
"parser",
":",
"sharedEncodedValueMap",
".",
"values",
"(",
")",
")",
"{",
"parser",
".",
"handleWayTags",
"(",
"edgeFlags",
",",
"way",
",",
"access",
",",
"relationFlags",
")",
";",
"}",
"for",
"(",
"AbstractFlagEncoder",
"encoder",
":",
"edgeEncoders",
")",
"{",
"encoder",
".",
"handleWayTags",
"(",
"edgeFlags",
",",
"way",
",",
"acceptWay",
".",
"get",
"(",
"encoder",
".",
"toString",
"(",
")",
")",
",",
"relationFlags",
"&",
"encoder",
".",
"getRelBitMask",
"(",
")",
")",
";",
"}",
"return",
"edgeFlags",
";",
"}"
] |
Processes way properties of different kind to determine speed and direction. Properties are
directly encoded in 8 bytes.
@param relationFlags The preprocessed relation flags is used to influence the way properties.
|
[
"Processes",
"way",
"properties",
"of",
"different",
"kind",
"to",
"determine",
"speed",
"and",
"direction",
".",
"Properties",
"are",
"directly",
"encoded",
"in",
"8",
"bytes",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/EncodingManager.java#L471-L482
|
21,076
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/Helper.java
|
Helper.isFileMapped
|
public static boolean isFileMapped(ByteBuffer bb) {
if (bb instanceof MappedByteBuffer) {
try {
((MappedByteBuffer) bb).isLoaded();
return true;
} catch (UnsupportedOperationException ex) {
}
}
return false;
}
|
java
|
public static boolean isFileMapped(ByteBuffer bb) {
if (bb instanceof MappedByteBuffer) {
try {
((MappedByteBuffer) bb).isLoaded();
return true;
} catch (UnsupportedOperationException ex) {
}
}
return false;
}
|
[
"public",
"static",
"boolean",
"isFileMapped",
"(",
"ByteBuffer",
"bb",
")",
"{",
"if",
"(",
"bb",
"instanceof",
"MappedByteBuffer",
")",
"{",
"try",
"{",
"(",
"(",
"MappedByteBuffer",
")",
"bb",
")",
".",
"isLoaded",
"(",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"UnsupportedOperationException",
"ex",
")",
"{",
"}",
"}",
"return",
"false",
";",
"}"
] |
Determines if the specified ByteBuffer is one which maps to a file!
|
[
"Determines",
"if",
"the",
"specified",
"ByteBuffer",
"is",
"one",
"which",
"maps",
"to",
"a",
"file!"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/Helper.java#L233-L242
|
21,077
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/Helper.java
|
Helper.keepIn
|
public static final double keepIn(double value, double min, double max) {
return Math.max(min, Math.min(value, max));
}
|
java
|
public static final double keepIn(double value, double min, double max) {
return Math.max(min, Math.min(value, max));
}
|
[
"public",
"static",
"final",
"double",
"keepIn",
"(",
"double",
"value",
",",
"double",
"min",
",",
"double",
"max",
")",
"{",
"return",
"Math",
".",
"max",
"(",
"min",
",",
"Math",
".",
"min",
"(",
"value",
",",
"max",
")",
")",
";",
"}"
] |
This methods returns the value or min if too small or max if too big.
|
[
"This",
"methods",
"returns",
"the",
"value",
"or",
"min",
"if",
"too",
"small",
"or",
"max",
"if",
"too",
"big",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/Helper.java#L370-L372
|
21,078
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/Helper.java
|
Helper.round
|
public static double round(double value, int exponent) {
double factor = Math.pow(10, exponent);
return Math.round(value * factor) / factor;
}
|
java
|
public static double round(double value, int exponent) {
double factor = Math.pow(10, exponent);
return Math.round(value * factor) / factor;
}
|
[
"public",
"static",
"double",
"round",
"(",
"double",
"value",
",",
"int",
"exponent",
")",
"{",
"double",
"factor",
"=",
"Math",
".",
"pow",
"(",
"10",
",",
"exponent",
")",
";",
"return",
"Math",
".",
"round",
"(",
"value",
"*",
"factor",
")",
"/",
"factor",
";",
"}"
] |
Round the value to the specified exponent
|
[
"Round",
"the",
"value",
"to",
"the",
"specified",
"exponent"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/Helper.java#L377-L380
|
21,079
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/Helper.java
|
Helper.createFormatter
|
public static DateFormat createFormatter(String str) {
DateFormat df = new SimpleDateFormat(str, Locale.UK);
df.setTimeZone(UTC);
return df;
}
|
java
|
public static DateFormat createFormatter(String str) {
DateFormat df = new SimpleDateFormat(str, Locale.UK);
df.setTimeZone(UTC);
return df;
}
|
[
"public",
"static",
"DateFormat",
"createFormatter",
"(",
"String",
"str",
")",
"{",
"DateFormat",
"df",
"=",
"new",
"SimpleDateFormat",
"(",
"str",
",",
"Locale",
".",
"UK",
")",
";",
"df",
".",
"setTimeZone",
"(",
"UTC",
")",
";",
"return",
"df",
";",
"}"
] |
Creates a SimpleDateFormat with the UK locale.
|
[
"Creates",
"a",
"SimpleDateFormat",
"with",
"the",
"UK",
"locale",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/Helper.java#L405-L409
|
21,080
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/GHResponse.java
|
GHResponse.hasErrors
|
public boolean hasErrors() {
if (!errors.isEmpty())
return true;
for (PathWrapper ar : pathWrappers) {
if (ar.hasErrors())
return true;
}
return false;
}
|
java
|
public boolean hasErrors() {
if (!errors.isEmpty())
return true;
for (PathWrapper ar : pathWrappers) {
if (ar.hasErrors())
return true;
}
return false;
}
|
[
"public",
"boolean",
"hasErrors",
"(",
")",
"{",
"if",
"(",
"!",
"errors",
".",
"isEmpty",
"(",
")",
")",
"return",
"true",
";",
"for",
"(",
"PathWrapper",
"ar",
":",
"pathWrappers",
")",
"{",
"if",
"(",
"ar",
".",
"hasErrors",
"(",
")",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
This method returns true if one of the paths has an error or if the response itself is
erroneous.
|
[
"This",
"method",
"returns",
"true",
"if",
"one",
"of",
"the",
"paths",
"has",
"an",
"error",
"or",
"if",
"the",
"response",
"itself",
"is",
"erroneous",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/GHResponse.java#L93-L103
|
21,081
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/GHResponse.java
|
GHResponse.getErrors
|
public List<Throwable> getErrors() {
List<Throwable> list = new ArrayList<>();
list.addAll(errors);
for (PathWrapper ar : pathWrappers) {
list.addAll(ar.getErrors());
}
return list;
}
|
java
|
public List<Throwable> getErrors() {
List<Throwable> list = new ArrayList<>();
list.addAll(errors);
for (PathWrapper ar : pathWrappers) {
list.addAll(ar.getErrors());
}
return list;
}
|
[
"public",
"List",
"<",
"Throwable",
">",
"getErrors",
"(",
")",
"{",
"List",
"<",
"Throwable",
">",
"list",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"list",
".",
"addAll",
"(",
"errors",
")",
";",
"for",
"(",
"PathWrapper",
"ar",
":",
"pathWrappers",
")",
"{",
"list",
".",
"addAll",
"(",
"ar",
".",
"getErrors",
"(",
")",
")",
";",
"}",
"return",
"list",
";",
"}"
] |
This method returns all the explicitly added errors and the errors of all paths.
|
[
"This",
"method",
"returns",
"all",
"the",
"explicitly",
"added",
"errors",
"and",
"the",
"errors",
"of",
"all",
"paths",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/GHResponse.java#L108-L115
|
21,082
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/util/TranslationMap.java
|
TranslationMap.doImport
|
public TranslationMap doImport(File folder) {
try {
for (String locale : LOCALES) {
TranslationHashMap trMap = new TranslationHashMap(getLocale(locale));
trMap.doImport(new FileInputStream(new File(folder, locale + ".txt")));
add(trMap);
}
postImportHook();
return this;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
|
java
|
public TranslationMap doImport(File folder) {
try {
for (String locale : LOCALES) {
TranslationHashMap trMap = new TranslationHashMap(getLocale(locale));
trMap.doImport(new FileInputStream(new File(folder, locale + ".txt")));
add(trMap);
}
postImportHook();
return this;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
|
[
"public",
"TranslationMap",
"doImport",
"(",
"File",
"folder",
")",
"{",
"try",
"{",
"for",
"(",
"String",
"locale",
":",
"LOCALES",
")",
"{",
"TranslationHashMap",
"trMap",
"=",
"new",
"TranslationHashMap",
"(",
"getLocale",
"(",
"locale",
")",
")",
";",
"trMap",
".",
"doImport",
"(",
"new",
"FileInputStream",
"(",
"new",
"File",
"(",
"folder",
",",
"locale",
"+",
"\".txt\"",
")",
")",
")",
";",
"add",
"(",
"trMap",
")",
";",
"}",
"postImportHook",
"(",
")",
";",
"return",
"this",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"ex",
")",
";",
"}",
"}"
] |
This loads the translation files from the specified folder.
|
[
"This",
"loads",
"the",
"translation",
"files",
"from",
"the",
"specified",
"folder",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/TranslationMap.java#L51-L63
|
21,083
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/util/TranslationMap.java
|
TranslationMap.doImport
|
public TranslationMap doImport() {
try {
for (String locale : LOCALES) {
TranslationHashMap trMap = new TranslationHashMap(getLocale(locale));
trMap.doImport(TranslationMap.class.getResourceAsStream(locale + ".txt"));
add(trMap);
}
postImportHook();
return this;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
|
java
|
public TranslationMap doImport() {
try {
for (String locale : LOCALES) {
TranslationHashMap trMap = new TranslationHashMap(getLocale(locale));
trMap.doImport(TranslationMap.class.getResourceAsStream(locale + ".txt"));
add(trMap);
}
postImportHook();
return this;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
|
[
"public",
"TranslationMap",
"doImport",
"(",
")",
"{",
"try",
"{",
"for",
"(",
"String",
"locale",
":",
"LOCALES",
")",
"{",
"TranslationHashMap",
"trMap",
"=",
"new",
"TranslationHashMap",
"(",
"getLocale",
"(",
"locale",
")",
")",
";",
"trMap",
".",
"doImport",
"(",
"TranslationMap",
".",
"class",
".",
"getResourceAsStream",
"(",
"locale",
"+",
"\".txt\"",
")",
")",
";",
"add",
"(",
"trMap",
")",
";",
"}",
"postImportHook",
"(",
")",
";",
"return",
"this",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"ex",
")",
";",
"}",
"}"
] |
This loads the translation files from classpath.
|
[
"This",
"loads",
"the",
"translation",
"files",
"from",
"classpath",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/TranslationMap.java#L68-L80
|
21,084
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/util/TranslationMap.java
|
TranslationMap.getWithFallBack
|
public Translation getWithFallBack(Locale locale) {
Translation tr = get(locale.toString());
if (tr == null) {
tr = get(locale.getLanguage());
if (tr == null)
tr = get("en");
}
return tr;
}
|
java
|
public Translation getWithFallBack(Locale locale) {
Translation tr = get(locale.toString());
if (tr == null) {
tr = get(locale.getLanguage());
if (tr == null)
tr = get("en");
}
return tr;
}
|
[
"public",
"Translation",
"getWithFallBack",
"(",
"Locale",
"locale",
")",
"{",
"Translation",
"tr",
"=",
"get",
"(",
"locale",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"tr",
"==",
"null",
")",
"{",
"tr",
"=",
"get",
"(",
"locale",
".",
"getLanguage",
"(",
")",
")",
";",
"if",
"(",
"tr",
"==",
"null",
")",
"tr",
"=",
"get",
"(",
"\"en\"",
")",
";",
"}",
"return",
"tr",
";",
"}"
] |
Returns the Translation object for the specified locale and falls back to English if the
locale was not found.
|
[
"Returns",
"the",
"Translation",
"object",
"for",
"the",
"specified",
"locale",
"and",
"falls",
"back",
"to",
"English",
"if",
"the",
"locale",
"was",
"not",
"found",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/TranslationMap.java#L102-L110
|
21,085
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/util/TranslationMap.java
|
TranslationMap.get
|
public Translation get(String locale) {
locale = locale.replace("-", "_");
Translation tr = translations.get(locale);
if (locale.contains("_") && tr == null)
tr = translations.get(locale.substring(0, 2));
return tr;
}
|
java
|
public Translation get(String locale) {
locale = locale.replace("-", "_");
Translation tr = translations.get(locale);
if (locale.contains("_") && tr == null)
tr = translations.get(locale.substring(0, 2));
return tr;
}
|
[
"public",
"Translation",
"get",
"(",
"String",
"locale",
")",
"{",
"locale",
"=",
"locale",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
";",
"Translation",
"tr",
"=",
"translations",
".",
"get",
"(",
"locale",
")",
";",
"if",
"(",
"locale",
".",
"contains",
"(",
"\"_\"",
")",
"&&",
"tr",
"==",
"null",
")",
"tr",
"=",
"translations",
".",
"get",
"(",
"locale",
".",
"substring",
"(",
"0",
",",
"2",
")",
")",
";",
"return",
"tr",
";",
"}"
] |
Returns the Translation object for the specified locale and returns null if not found.
|
[
"Returns",
"the",
"Translation",
"object",
"for",
"the",
"specified",
"locale",
"and",
"returns",
"null",
"if",
"not",
"found",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/TranslationMap.java#L115-L122
|
21,086
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/util/TranslationMap.java
|
TranslationMap.postImportHook
|
private void postImportHook() {
Map<String, String> enMap = get("en").asMap();
StringBuilder sb = new StringBuilder();
for (Translation tr : translations.values()) {
Map<String, String> trMap = tr.asMap();
for (Entry<String, String> enEntry : enMap.entrySet()) {
String value = trMap.get(enEntry.getKey());
if (isEmpty(value)) {
trMap.put(enEntry.getKey(), enEntry.getValue());
continue;
}
int expectedCount = countOccurence(enEntry.getValue(), "\\%");
if (expectedCount != countOccurence(value, "\\%")) {
sb.append(tr.getLocale()).append(" - error in ").
append(enEntry.getKey()).append("->").
append(value).append("\n");
} else {
// try if formatting works, many times e.g. '%1$' instead of '%1$s'
Object[] strs = new String[expectedCount];
Arrays.fill(strs, "tmp");
try {
String.format(Locale.ROOT, value, strs);
} catch (Exception ex) {
sb.append(tr.getLocale()).append(" - error ").append(ex.getMessage()).append("in ").
append(enEntry.getKey()).append("->").
append(value).append("\n");
}
}
}
}
if (sb.length() > 0) {
System.out.println(sb);
throw new IllegalStateException(sb.toString());
}
}
|
java
|
private void postImportHook() {
Map<String, String> enMap = get("en").asMap();
StringBuilder sb = new StringBuilder();
for (Translation tr : translations.values()) {
Map<String, String> trMap = tr.asMap();
for (Entry<String, String> enEntry : enMap.entrySet()) {
String value = trMap.get(enEntry.getKey());
if (isEmpty(value)) {
trMap.put(enEntry.getKey(), enEntry.getValue());
continue;
}
int expectedCount = countOccurence(enEntry.getValue(), "\\%");
if (expectedCount != countOccurence(value, "\\%")) {
sb.append(tr.getLocale()).append(" - error in ").
append(enEntry.getKey()).append("->").
append(value).append("\n");
} else {
// try if formatting works, many times e.g. '%1$' instead of '%1$s'
Object[] strs = new String[expectedCount];
Arrays.fill(strs, "tmp");
try {
String.format(Locale.ROOT, value, strs);
} catch (Exception ex) {
sb.append(tr.getLocale()).append(" - error ").append(ex.getMessage()).append("in ").
append(enEntry.getKey()).append("->").
append(value).append("\n");
}
}
}
}
if (sb.length() > 0) {
System.out.println(sb);
throw new IllegalStateException(sb.toString());
}
}
|
[
"private",
"void",
"postImportHook",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"enMap",
"=",
"get",
"(",
"\"en\"",
")",
".",
"asMap",
"(",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Translation",
"tr",
":",
"translations",
".",
"values",
"(",
")",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"trMap",
"=",
"tr",
".",
"asMap",
"(",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"String",
">",
"enEntry",
":",
"enMap",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"value",
"=",
"trMap",
".",
"get",
"(",
"enEntry",
".",
"getKey",
"(",
")",
")",
";",
"if",
"(",
"isEmpty",
"(",
"value",
")",
")",
"{",
"trMap",
".",
"put",
"(",
"enEntry",
".",
"getKey",
"(",
")",
",",
"enEntry",
".",
"getValue",
"(",
")",
")",
";",
"continue",
";",
"}",
"int",
"expectedCount",
"=",
"countOccurence",
"(",
"enEntry",
".",
"getValue",
"(",
")",
",",
"\"\\\\%\"",
")",
";",
"if",
"(",
"expectedCount",
"!=",
"countOccurence",
"(",
"value",
",",
"\"\\\\%\"",
")",
")",
"{",
"sb",
".",
"append",
"(",
"tr",
".",
"getLocale",
"(",
")",
")",
".",
"append",
"(",
"\" - error in \"",
")",
".",
"append",
"(",
"enEntry",
".",
"getKey",
"(",
")",
")",
".",
"append",
"(",
"\"->\"",
")",
".",
"append",
"(",
"value",
")",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"}",
"else",
"{",
"// try if formatting works, many times e.g. '%1$' instead of '%1$s'",
"Object",
"[",
"]",
"strs",
"=",
"new",
"String",
"[",
"expectedCount",
"]",
";",
"Arrays",
".",
"fill",
"(",
"strs",
",",
"\"tmp\"",
")",
";",
"try",
"{",
"String",
".",
"format",
"(",
"Locale",
".",
"ROOT",
",",
"value",
",",
"strs",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"sb",
".",
"append",
"(",
"tr",
".",
"getLocale",
"(",
")",
")",
".",
"append",
"(",
"\" - error \"",
")",
".",
"append",
"(",
"ex",
".",
"getMessage",
"(",
")",
")",
".",
"append",
"(",
"\"in \"",
")",
".",
"append",
"(",
"enEntry",
".",
"getKey",
"(",
")",
")",
".",
"append",
"(",
"\"->\"",
")",
".",
"append",
"(",
"value",
")",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"sb",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"sb",
")",
";",
"throw",
"new",
"IllegalStateException",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"}"
] |
This method does some checks and fills missing translation from en
|
[
"This",
"method",
"does",
"some",
"checks",
"and",
"fills",
"missing",
"translation",
"from",
"en"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/TranslationMap.java#L127-L163
|
21,087
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/storage/DAType.java
|
DAType.getPreferredInt
|
public static DAType getPreferredInt(DAType type) {
if (type.isInMemory())
return type.isStoring() ? RAM_INT_STORE : RAM_INT;
return type;
}
|
java
|
public static DAType getPreferredInt(DAType type) {
if (type.isInMemory())
return type.isStoring() ? RAM_INT_STORE : RAM_INT;
return type;
}
|
[
"public",
"static",
"DAType",
"getPreferredInt",
"(",
"DAType",
"type",
")",
"{",
"if",
"(",
"type",
".",
"isInMemory",
"(",
")",
")",
"return",
"type",
".",
"isStoring",
"(",
")",
"?",
"RAM_INT_STORE",
":",
"RAM_INT",
";",
"return",
"type",
";",
"}"
] |
This method returns RAM_INT if the specified type is in-memory.
|
[
"This",
"method",
"returns",
"RAM_INT",
"if",
"the",
"specified",
"type",
"is",
"in",
"-",
"memory",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/DAType.java#L95-L99
|
21,088
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/storage/EdgeAccess.java
|
EdgeAccess.distToInt
|
private int distToInt(double distance) {
if (distance < 0)
throw new IllegalArgumentException("Distance cannot be negative: " + distance);
if (distance > MAX_DIST) {
distance = MAX_DIST;
}
int integ = (int) Math.round(distance * INT_DIST_FACTOR);
assert integ >= 0 : "distance out of range";
return integ;
}
|
java
|
private int distToInt(double distance) {
if (distance < 0)
throw new IllegalArgumentException("Distance cannot be negative: " + distance);
if (distance > MAX_DIST) {
distance = MAX_DIST;
}
int integ = (int) Math.round(distance * INT_DIST_FACTOR);
assert integ >= 0 : "distance out of range";
return integ;
}
|
[
"private",
"int",
"distToInt",
"(",
"double",
"distance",
")",
"{",
"if",
"(",
"distance",
"<",
"0",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Distance cannot be negative: \"",
"+",
"distance",
")",
";",
"if",
"(",
"distance",
">",
"MAX_DIST",
")",
"{",
"distance",
"=",
"MAX_DIST",
";",
"}",
"int",
"integ",
"=",
"(",
"int",
")",
"Math",
".",
"round",
"(",
"distance",
"*",
"INT_DIST_FACTOR",
")",
";",
"assert",
"integ",
">=",
"0",
":",
"\"distance out of range\"",
";",
"return",
"integ",
";",
"}"
] |
Translates double distance to integer in order to save it in a DataAccess object
|
[
"Translates",
"double",
"distance",
"to",
"integer",
"in",
"order",
"to",
"save",
"it",
"in",
"a",
"DataAccess",
"object"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/EdgeAccess.java#L75-L84
|
21,089
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/storage/EdgeAccess.java
|
EdgeAccess.internalEdgeAdd
|
final int internalEdgeAdd(int newEdgeId, int nodeA, int nodeB) {
writeEdge(newEdgeId, nodeA, nodeB, EdgeIterator.NO_EDGE, EdgeIterator.NO_EDGE);
long edgePointer = toPointer(newEdgeId);
int edge = getEdgeRef(nodeA);
if (edge > EdgeIterator.NO_EDGE)
edges.setInt(E_LINKA + edgePointer, edge);
setEdgeRef(nodeA, newEdgeId);
if (nodeA != nodeB) {
edge = getEdgeRef(nodeB);
if (edge > EdgeIterator.NO_EDGE)
edges.setInt(E_LINKB + edgePointer, edge);
setEdgeRef(nodeB, newEdgeId);
}
return newEdgeId;
}
|
java
|
final int internalEdgeAdd(int newEdgeId, int nodeA, int nodeB) {
writeEdge(newEdgeId, nodeA, nodeB, EdgeIterator.NO_EDGE, EdgeIterator.NO_EDGE);
long edgePointer = toPointer(newEdgeId);
int edge = getEdgeRef(nodeA);
if (edge > EdgeIterator.NO_EDGE)
edges.setInt(E_LINKA + edgePointer, edge);
setEdgeRef(nodeA, newEdgeId);
if (nodeA != nodeB) {
edge = getEdgeRef(nodeB);
if (edge > EdgeIterator.NO_EDGE)
edges.setInt(E_LINKB + edgePointer, edge);
setEdgeRef(nodeB, newEdgeId);
}
return newEdgeId;
}
|
[
"final",
"int",
"internalEdgeAdd",
"(",
"int",
"newEdgeId",
",",
"int",
"nodeA",
",",
"int",
"nodeB",
")",
"{",
"writeEdge",
"(",
"newEdgeId",
",",
"nodeA",
",",
"nodeB",
",",
"EdgeIterator",
".",
"NO_EDGE",
",",
"EdgeIterator",
".",
"NO_EDGE",
")",
";",
"long",
"edgePointer",
"=",
"toPointer",
"(",
"newEdgeId",
")",
";",
"int",
"edge",
"=",
"getEdgeRef",
"(",
"nodeA",
")",
";",
"if",
"(",
"edge",
">",
"EdgeIterator",
".",
"NO_EDGE",
")",
"edges",
".",
"setInt",
"(",
"E_LINKA",
"+",
"edgePointer",
",",
"edge",
")",
";",
"setEdgeRef",
"(",
"nodeA",
",",
"newEdgeId",
")",
";",
"if",
"(",
"nodeA",
"!=",
"nodeB",
")",
"{",
"edge",
"=",
"getEdgeRef",
"(",
"nodeB",
")",
";",
"if",
"(",
"edge",
">",
"EdgeIterator",
".",
"NO_EDGE",
")",
"edges",
".",
"setInt",
"(",
"E_LINKB",
"+",
"edgePointer",
",",
"edge",
")",
";",
"setEdgeRef",
"(",
"nodeB",
",",
"newEdgeId",
")",
";",
"}",
"return",
"newEdgeId",
";",
"}"
] |
Writes a new edge to the array of edges and adds it to the linked list of edges at nodeA and nodeB
|
[
"Writes",
"a",
"new",
"edge",
"to",
"the",
"array",
"of",
"edges",
"and",
"adds",
"it",
"to",
"the",
"linked",
"list",
"of",
"edges",
"at",
"nodeA",
"and",
"nodeB"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/EdgeAccess.java#L112-L128
|
21,090
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/storage/EdgeAccess.java
|
EdgeAccess.writeEdge
|
final long writeEdge(int edgeId, int nodeA, int nodeB, int nextEdgeA, int nextEdgeB) {
if (edgeId < 0 || edgeId == EdgeIterator.NO_EDGE)
throw new IllegalStateException("Cannot write edge with illegal ID:" + edgeId + "; nodeA:" + nodeA + ", nodeB:" + nodeB);
long edgePointer = toPointer(edgeId);
edges.setInt(edgePointer + E_NODEA, nodeA);
edges.setInt(edgePointer + E_NODEB, nodeB);
edges.setInt(edgePointer + E_LINKA, nextEdgeA);
edges.setInt(edgePointer + E_LINKB, nextEdgeB);
return edgePointer;
}
|
java
|
final long writeEdge(int edgeId, int nodeA, int nodeB, int nextEdgeA, int nextEdgeB) {
if (edgeId < 0 || edgeId == EdgeIterator.NO_EDGE)
throw new IllegalStateException("Cannot write edge with illegal ID:" + edgeId + "; nodeA:" + nodeA + ", nodeB:" + nodeB);
long edgePointer = toPointer(edgeId);
edges.setInt(edgePointer + E_NODEA, nodeA);
edges.setInt(edgePointer + E_NODEB, nodeB);
edges.setInt(edgePointer + E_LINKA, nextEdgeA);
edges.setInt(edgePointer + E_LINKB, nextEdgeB);
return edgePointer;
}
|
[
"final",
"long",
"writeEdge",
"(",
"int",
"edgeId",
",",
"int",
"nodeA",
",",
"int",
"nodeB",
",",
"int",
"nextEdgeA",
",",
"int",
"nextEdgeB",
")",
"{",
"if",
"(",
"edgeId",
"<",
"0",
"||",
"edgeId",
"==",
"EdgeIterator",
".",
"NO_EDGE",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot write edge with illegal ID:\"",
"+",
"edgeId",
"+",
"\"; nodeA:\"",
"+",
"nodeA",
"+",
"\", nodeB:\"",
"+",
"nodeB",
")",
";",
"long",
"edgePointer",
"=",
"toPointer",
"(",
"edgeId",
")",
";",
"edges",
".",
"setInt",
"(",
"edgePointer",
"+",
"E_NODEA",
",",
"nodeA",
")",
";",
"edges",
".",
"setInt",
"(",
"edgePointer",
"+",
"E_NODEB",
",",
"nodeB",
")",
";",
"edges",
".",
"setInt",
"(",
"edgePointer",
"+",
"E_LINKA",
",",
"nextEdgeA",
")",
";",
"edges",
".",
"setInt",
"(",
"edgePointer",
"+",
"E_LINKB",
",",
"nextEdgeB",
")",
";",
"return",
"edgePointer",
";",
"}"
] |
Writes plain edge information to the edges index
|
[
"Writes",
"plain",
"edge",
"information",
"to",
"the",
"edges",
"index"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/EdgeAccess.java#L154-L164
|
21,091
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/storage/EdgeAccess.java
|
EdgeAccess.internalEdgeDisconnect
|
final long internalEdgeDisconnect(int edgeToRemove, long edgeToUpdatePointer, int baseNode) {
long edgeToRemovePointer = toPointer(edgeToRemove);
// an edge is shared across the two nodes even if the edge is not in both directions
// so we need to know two edge-pointers pointing to the edge before edgeToRemovePointer
int nextEdgeId = getNodeA(edgeToRemovePointer) == baseNode ? getLinkA(edgeToRemovePointer) : getLinkB(edgeToRemovePointer);
if (edgeToUpdatePointer < 0) {
setEdgeRef(baseNode, nextEdgeId);
} else {
// adjNode is different for the edge we want to update with the new link
long link = getNodeA(edgeToUpdatePointer) == baseNode ? edgeToUpdatePointer + E_LINKA : edgeToUpdatePointer + E_LINKB;
edges.setInt(link, nextEdgeId);
}
return edgeToRemovePointer;
}
|
java
|
final long internalEdgeDisconnect(int edgeToRemove, long edgeToUpdatePointer, int baseNode) {
long edgeToRemovePointer = toPointer(edgeToRemove);
// an edge is shared across the two nodes even if the edge is not in both directions
// so we need to know two edge-pointers pointing to the edge before edgeToRemovePointer
int nextEdgeId = getNodeA(edgeToRemovePointer) == baseNode ? getLinkA(edgeToRemovePointer) : getLinkB(edgeToRemovePointer);
if (edgeToUpdatePointer < 0) {
setEdgeRef(baseNode, nextEdgeId);
} else {
// adjNode is different for the edge we want to update with the new link
long link = getNodeA(edgeToUpdatePointer) == baseNode ? edgeToUpdatePointer + E_LINKA : edgeToUpdatePointer + E_LINKB;
edges.setInt(link, nextEdgeId);
}
return edgeToRemovePointer;
}
|
[
"final",
"long",
"internalEdgeDisconnect",
"(",
"int",
"edgeToRemove",
",",
"long",
"edgeToUpdatePointer",
",",
"int",
"baseNode",
")",
"{",
"long",
"edgeToRemovePointer",
"=",
"toPointer",
"(",
"edgeToRemove",
")",
";",
"// an edge is shared across the two nodes even if the edge is not in both directions",
"// so we need to know two edge-pointers pointing to the edge before edgeToRemovePointer",
"int",
"nextEdgeId",
"=",
"getNodeA",
"(",
"edgeToRemovePointer",
")",
"==",
"baseNode",
"?",
"getLinkA",
"(",
"edgeToRemovePointer",
")",
":",
"getLinkB",
"(",
"edgeToRemovePointer",
")",
";",
"if",
"(",
"edgeToUpdatePointer",
"<",
"0",
")",
"{",
"setEdgeRef",
"(",
"baseNode",
",",
"nextEdgeId",
")",
";",
"}",
"else",
"{",
"// adjNode is different for the edge we want to update with the new link",
"long",
"link",
"=",
"getNodeA",
"(",
"edgeToUpdatePointer",
")",
"==",
"baseNode",
"?",
"edgeToUpdatePointer",
"+",
"E_LINKA",
":",
"edgeToUpdatePointer",
"+",
"E_LINKB",
";",
"edges",
".",
"setInt",
"(",
"link",
",",
"nextEdgeId",
")",
";",
"}",
"return",
"edgeToRemovePointer",
";",
"}"
] |
This method disconnects the specified edge from the list of edges of the specified node. It
does not release the freed space to be reused.
@param edgeToUpdatePointer if it is negative then the nextEdgeId will be saved to refToEdges of nodes
|
[
"This",
"method",
"disconnects",
"the",
"specified",
"edge",
"from",
"the",
"list",
"of",
"edges",
"of",
"the",
"specified",
"node",
".",
"It",
"does",
"not",
"release",
"the",
"freed",
"space",
"to",
"be",
"reused",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/EdgeAccess.java#L172-L185
|
21,092
|
graphhopper/graphhopper
|
api/src/main/java/com/graphhopper/util/AngleCalc.java
|
AngleCalc.calcAzimuth
|
public double calcAzimuth(double lat1, double lon1, double lat2, double lon2) {
double orientation = Math.PI / 2 - calcOrientation(lat1, lon1, lat2, lon2);
if (orientation < 0)
orientation += 2 * Math.PI;
return Math.toDegrees(Helper.round4(orientation)) % 360;
}
|
java
|
public double calcAzimuth(double lat1, double lon1, double lat2, double lon2) {
double orientation = Math.PI / 2 - calcOrientation(lat1, lon1, lat2, lon2);
if (orientation < 0)
orientation += 2 * Math.PI;
return Math.toDegrees(Helper.round4(orientation)) % 360;
}
|
[
"public",
"double",
"calcAzimuth",
"(",
"double",
"lat1",
",",
"double",
"lon1",
",",
"double",
"lat2",
",",
"double",
"lon2",
")",
"{",
"double",
"orientation",
"=",
"Math",
".",
"PI",
"/",
"2",
"-",
"calcOrientation",
"(",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
")",
";",
"if",
"(",
"orientation",
"<",
"0",
")",
"orientation",
"+=",
"2",
"*",
"Math",
".",
"PI",
";",
"return",
"Math",
".",
"toDegrees",
"(",
"Helper",
".",
"round4",
"(",
"orientation",
")",
")",
"%",
"360",
";",
"}"
] |
Calculate the azimuth in degree for a line given by two coordinates. Direction in 'degree'
where 0 is north, 90 is east, 180 is south and 270 is west.
|
[
"Calculate",
"the",
"azimuth",
"in",
"degree",
"for",
"a",
"line",
"given",
"by",
"two",
"coordinates",
".",
"Direction",
"in",
"degree",
"where",
"0",
"is",
"north",
"90",
"is",
"east",
"180",
"is",
"south",
"and",
"270",
"is",
"west",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/AngleCalc.java#L113-L119
|
21,093
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/util/BitUtil.java
|
BitUtil.fromBitString2Long
|
public final long fromBitString2Long(String str) {
if (str.length() > 64)
throw new UnsupportedOperationException("Strings needs to fit into a 'long' but length was " + str.length());
long res = 0;
int strLen = str.length();
for (int charIndex = 0; charIndex < strLen; charIndex++) {
res <<= 1;
if (str.charAt(charIndex) != '0')
res |= 1;
}
res <<= (64 - strLen);
return res;
}
|
java
|
public final long fromBitString2Long(String str) {
if (str.length() > 64)
throw new UnsupportedOperationException("Strings needs to fit into a 'long' but length was " + str.length());
long res = 0;
int strLen = str.length();
for (int charIndex = 0; charIndex < strLen; charIndex++) {
res <<= 1;
if (str.charAt(charIndex) != '0')
res |= 1;
}
res <<= (64 - strLen);
return res;
}
|
[
"public",
"final",
"long",
"fromBitString2Long",
"(",
"String",
"str",
")",
"{",
"if",
"(",
"str",
".",
"length",
"(",
")",
">",
"64",
")",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Strings needs to fit into a 'long' but length was \"",
"+",
"str",
".",
"length",
"(",
")",
")",
";",
"long",
"res",
"=",
"0",
";",
"int",
"strLen",
"=",
"str",
".",
"length",
"(",
")",
";",
"for",
"(",
"int",
"charIndex",
"=",
"0",
";",
"charIndex",
"<",
"strLen",
";",
"charIndex",
"++",
")",
"{",
"res",
"<<=",
"1",
";",
"if",
"(",
"str",
".",
"charAt",
"(",
"charIndex",
")",
"!=",
"'",
"'",
")",
"res",
"|=",
"1",
";",
"}",
"res",
"<<=",
"(",
"64",
"-",
"strLen",
")",
";",
"return",
"res",
";",
"}"
] |
The only purpose of this method is to test 'reverse'. toBitString is the reverse and both are
independent of the endianness.
|
[
"The",
"only",
"purpose",
"of",
"this",
"method",
"is",
"to",
"test",
"reverse",
".",
"toBitString",
"is",
"the",
"reverse",
"and",
"both",
"are",
"independent",
"of",
"the",
"endianness",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/BitUtil.java#L155-L168
|
21,094
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/routing/util/tour/TourStrategy.java
|
TourStrategy.slightlyModifyDistance
|
protected double slightlyModifyDistance(double distance) {
double distanceModification = random.nextDouble() * .1 * distance;
if (random.nextBoolean())
distanceModification = -distanceModification;
return distance + distanceModification;
}
|
java
|
protected double slightlyModifyDistance(double distance) {
double distanceModification = random.nextDouble() * .1 * distance;
if (random.nextBoolean())
distanceModification = -distanceModification;
return distance + distanceModification;
}
|
[
"protected",
"double",
"slightlyModifyDistance",
"(",
"double",
"distance",
")",
"{",
"double",
"distanceModification",
"=",
"random",
".",
"nextDouble",
"(",
")",
"*",
".1",
"*",
"distance",
";",
"if",
"(",
"random",
".",
"nextBoolean",
"(",
")",
")",
"distanceModification",
"=",
"-",
"distanceModification",
";",
"return",
"distance",
"+",
"distanceModification",
";",
"}"
] |
Modifies the Distance up to +-10%
|
[
"Modifies",
"the",
"Distance",
"up",
"to",
"+",
"-",
"10%"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/tour/TourStrategy.java#L54-L59
|
21,095
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/GraphHopper.java
|
GraphHopper.setGraphHopperLocation
|
public GraphHopper setGraphHopperLocation(String ghLocation) {
ensureNotLoaded();
if (ghLocation == null)
throw new IllegalArgumentException("graphhopper location cannot be null");
this.ghLocation = ghLocation;
return this;
}
|
java
|
public GraphHopper setGraphHopperLocation(String ghLocation) {
ensureNotLoaded();
if (ghLocation == null)
throw new IllegalArgumentException("graphhopper location cannot be null");
this.ghLocation = ghLocation;
return this;
}
|
[
"public",
"GraphHopper",
"setGraphHopperLocation",
"(",
"String",
"ghLocation",
")",
"{",
"ensureNotLoaded",
"(",
")",
";",
"if",
"(",
"ghLocation",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"graphhopper location cannot be null\"",
")",
";",
"this",
".",
"ghLocation",
"=",
"ghLocation",
";",
"return",
"this",
";",
"}"
] |
Sets the graphhopper folder.
|
[
"Sets",
"the",
"graphhopper",
"folder",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/GraphHopper.java#L384-L391
|
21,096
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/GraphHopper.java
|
GraphHopper.process
|
private GraphHopper process(String graphHopperLocation) {
setGraphHopperLocation(graphHopperLocation);
GHLock lock = null;
try {
if (ghStorage.getDirectory().getDefaultType().isStoring()) {
lockFactory.setLockDir(new File(graphHopperLocation));
lock = lockFactory.create(fileLockName, true);
if (!lock.tryLock())
throw new RuntimeException("To avoid multiple writers we need to obtain a write lock but it failed. In " + graphHopperLocation, lock.getObtainFailedReason());
}
try {
DataReader reader = importData();
DateFormat f = createFormatter();
ghStorage.getProperties().put("datareader.import.date", f.format(new Date()));
if (reader.getDataDate() != null)
ghStorage.getProperties().put("datareader.data.date", f.format(reader.getDataDate()));
} catch (IOException ex) {
throw new RuntimeException("Cannot read file " + getDataReaderFile(), ex);
}
cleanUp();
postProcessing();
flush();
} finally {
if (lock != null)
lock.release();
}
return this;
}
|
java
|
private GraphHopper process(String graphHopperLocation) {
setGraphHopperLocation(graphHopperLocation);
GHLock lock = null;
try {
if (ghStorage.getDirectory().getDefaultType().isStoring()) {
lockFactory.setLockDir(new File(graphHopperLocation));
lock = lockFactory.create(fileLockName, true);
if (!lock.tryLock())
throw new RuntimeException("To avoid multiple writers we need to obtain a write lock but it failed. In " + graphHopperLocation, lock.getObtainFailedReason());
}
try {
DataReader reader = importData();
DateFormat f = createFormatter();
ghStorage.getProperties().put("datareader.import.date", f.format(new Date()));
if (reader.getDataDate() != null)
ghStorage.getProperties().put("datareader.data.date", f.format(reader.getDataDate()));
} catch (IOException ex) {
throw new RuntimeException("Cannot read file " + getDataReaderFile(), ex);
}
cleanUp();
postProcessing();
flush();
} finally {
if (lock != null)
lock.release();
}
return this;
}
|
[
"private",
"GraphHopper",
"process",
"(",
"String",
"graphHopperLocation",
")",
"{",
"setGraphHopperLocation",
"(",
"graphHopperLocation",
")",
";",
"GHLock",
"lock",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"ghStorage",
".",
"getDirectory",
"(",
")",
".",
"getDefaultType",
"(",
")",
".",
"isStoring",
"(",
")",
")",
"{",
"lockFactory",
".",
"setLockDir",
"(",
"new",
"File",
"(",
"graphHopperLocation",
")",
")",
";",
"lock",
"=",
"lockFactory",
".",
"create",
"(",
"fileLockName",
",",
"true",
")",
";",
"if",
"(",
"!",
"lock",
".",
"tryLock",
"(",
")",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"To avoid multiple writers we need to obtain a write lock but it failed. In \"",
"+",
"graphHopperLocation",
",",
"lock",
".",
"getObtainFailedReason",
"(",
")",
")",
";",
"}",
"try",
"{",
"DataReader",
"reader",
"=",
"importData",
"(",
")",
";",
"DateFormat",
"f",
"=",
"createFormatter",
"(",
")",
";",
"ghStorage",
".",
"getProperties",
"(",
")",
".",
"put",
"(",
"\"datareader.import.date\"",
",",
"f",
".",
"format",
"(",
"new",
"Date",
"(",
")",
")",
")",
";",
"if",
"(",
"reader",
".",
"getDataDate",
"(",
")",
"!=",
"null",
")",
"ghStorage",
".",
"getProperties",
"(",
")",
".",
"put",
"(",
"\"datareader.data.date\"",
",",
"f",
".",
"format",
"(",
"reader",
".",
"getDataDate",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Cannot read file \"",
"+",
"getDataReaderFile",
"(",
")",
",",
"ex",
")",
";",
"}",
"cleanUp",
"(",
")",
";",
"postProcessing",
"(",
")",
";",
"flush",
"(",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"lock",
"!=",
"null",
")",
"lock",
".",
"release",
"(",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Creates the graph from OSM data.
|
[
"Creates",
"the",
"graph",
"from",
"OSM",
"data",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/GraphHopper.java#L613-L641
|
21,097
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/GraphHopper.java
|
GraphHopper.load
|
@Override
public boolean load(String graphHopperFolder) {
if (isEmpty(graphHopperFolder))
throw new IllegalStateException("GraphHopperLocation is not specified. Call setGraphHopperLocation or init before");
if (fullyLoaded)
throw new IllegalStateException("graph is already successfully loaded");
File tmpFileOrFolder = new File(graphHopperFolder);
if (!tmpFileOrFolder.isDirectory() && tmpFileOrFolder.exists()) {
throw new IllegalArgumentException("GraphHopperLocation cannot be an existing file. Has to be either non-existing or a folder.");
} else {
File compressed = new File(graphHopperFolder + ".ghz");
if (compressed.exists() && !compressed.isDirectory()) {
try {
new Unzipper().unzip(compressed.getAbsolutePath(), graphHopperFolder, removeZipped);
} catch (IOException ex) {
throw new RuntimeException("Couldn't extract file " + compressed.getAbsolutePath()
+ " to " + graphHopperFolder, ex);
}
}
}
setGraphHopperLocation(graphHopperFolder);
if (encodingManager == null)
setEncodingManager(EncodingManager.create(flagEncoderFactory, ghLocation));
if (!allowWrites && dataAccessType.isMMap())
dataAccessType = DAType.MMAP_RO;
GHDirectory dir = new GHDirectory(ghLocation, dataAccessType);
GraphExtension ext = encodingManager.needsTurnCostsSupport()
? new TurnCostExtension() : new GraphExtension.NoOpExtension();
if (lmFactoryDecorator.isEnabled())
initLMAlgoFactoryDecorator();
if (chFactoryDecorator.isEnabled()) {
initCHAlgoFactoryDecorator();
ghStorage = new GraphHopperStorage(chFactoryDecorator.getNodeBasedWeightings(), chFactoryDecorator.getEdgeBasedWeightings(),
dir, encodingManager, hasElevation(), ext);
} else {
ghStorage = new GraphHopperStorage(dir, encodingManager, hasElevation(), ext);
}
ghStorage.setSegmentSize(defaultSegmentSize);
if (!new File(graphHopperFolder).exists())
return false;
GHLock lock = null;
try {
// create locks only if writes are allowed, if they are not allowed a lock cannot be created
// (e.g. on a read only filesystem locks would fail)
if (ghStorage.getDirectory().getDefaultType().isStoring() && isAllowWrites()) {
lockFactory.setLockDir(new File(ghLocation));
lock = lockFactory.create(fileLockName, false);
if (!lock.tryLock())
throw new RuntimeException("To avoid reading partial data we need to obtain the read lock but it failed. In " + ghLocation, lock.getObtainFailedReason());
}
if (!ghStorage.loadExisting())
return false;
postProcessing();
fullyLoaded = true;
return true;
} finally {
if (lock != null)
lock.release();
}
}
|
java
|
@Override
public boolean load(String graphHopperFolder) {
if (isEmpty(graphHopperFolder))
throw new IllegalStateException("GraphHopperLocation is not specified. Call setGraphHopperLocation or init before");
if (fullyLoaded)
throw new IllegalStateException("graph is already successfully loaded");
File tmpFileOrFolder = new File(graphHopperFolder);
if (!tmpFileOrFolder.isDirectory() && tmpFileOrFolder.exists()) {
throw new IllegalArgumentException("GraphHopperLocation cannot be an existing file. Has to be either non-existing or a folder.");
} else {
File compressed = new File(graphHopperFolder + ".ghz");
if (compressed.exists() && !compressed.isDirectory()) {
try {
new Unzipper().unzip(compressed.getAbsolutePath(), graphHopperFolder, removeZipped);
} catch (IOException ex) {
throw new RuntimeException("Couldn't extract file " + compressed.getAbsolutePath()
+ " to " + graphHopperFolder, ex);
}
}
}
setGraphHopperLocation(graphHopperFolder);
if (encodingManager == null)
setEncodingManager(EncodingManager.create(flagEncoderFactory, ghLocation));
if (!allowWrites && dataAccessType.isMMap())
dataAccessType = DAType.MMAP_RO;
GHDirectory dir = new GHDirectory(ghLocation, dataAccessType);
GraphExtension ext = encodingManager.needsTurnCostsSupport()
? new TurnCostExtension() : new GraphExtension.NoOpExtension();
if (lmFactoryDecorator.isEnabled())
initLMAlgoFactoryDecorator();
if (chFactoryDecorator.isEnabled()) {
initCHAlgoFactoryDecorator();
ghStorage = new GraphHopperStorage(chFactoryDecorator.getNodeBasedWeightings(), chFactoryDecorator.getEdgeBasedWeightings(),
dir, encodingManager, hasElevation(), ext);
} else {
ghStorage = new GraphHopperStorage(dir, encodingManager, hasElevation(), ext);
}
ghStorage.setSegmentSize(defaultSegmentSize);
if (!new File(graphHopperFolder).exists())
return false;
GHLock lock = null;
try {
// create locks only if writes are allowed, if they are not allowed a lock cannot be created
// (e.g. on a read only filesystem locks would fail)
if (ghStorage.getDirectory().getDefaultType().isStoring() && isAllowWrites()) {
lockFactory.setLockDir(new File(ghLocation));
lock = lockFactory.create(fileLockName, false);
if (!lock.tryLock())
throw new RuntimeException("To avoid reading partial data we need to obtain the read lock but it failed. In " + ghLocation, lock.getObtainFailedReason());
}
if (!ghStorage.loadExisting())
return false;
postProcessing();
fullyLoaded = true;
return true;
} finally {
if (lock != null)
lock.release();
}
}
|
[
"@",
"Override",
"public",
"boolean",
"load",
"(",
"String",
"graphHopperFolder",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"graphHopperFolder",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"GraphHopperLocation is not specified. Call setGraphHopperLocation or init before\"",
")",
";",
"if",
"(",
"fullyLoaded",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"graph is already successfully loaded\"",
")",
";",
"File",
"tmpFileOrFolder",
"=",
"new",
"File",
"(",
"graphHopperFolder",
")",
";",
"if",
"(",
"!",
"tmpFileOrFolder",
".",
"isDirectory",
"(",
")",
"&&",
"tmpFileOrFolder",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"GraphHopperLocation cannot be an existing file. Has to be either non-existing or a folder.\"",
")",
";",
"}",
"else",
"{",
"File",
"compressed",
"=",
"new",
"File",
"(",
"graphHopperFolder",
"+",
"\".ghz\"",
")",
";",
"if",
"(",
"compressed",
".",
"exists",
"(",
")",
"&&",
"!",
"compressed",
".",
"isDirectory",
"(",
")",
")",
"{",
"try",
"{",
"new",
"Unzipper",
"(",
")",
".",
"unzip",
"(",
"compressed",
".",
"getAbsolutePath",
"(",
")",
",",
"graphHopperFolder",
",",
"removeZipped",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Couldn't extract file \"",
"+",
"compressed",
".",
"getAbsolutePath",
"(",
")",
"+",
"\" to \"",
"+",
"graphHopperFolder",
",",
"ex",
")",
";",
"}",
"}",
"}",
"setGraphHopperLocation",
"(",
"graphHopperFolder",
")",
";",
"if",
"(",
"encodingManager",
"==",
"null",
")",
"setEncodingManager",
"(",
"EncodingManager",
".",
"create",
"(",
"flagEncoderFactory",
",",
"ghLocation",
")",
")",
";",
"if",
"(",
"!",
"allowWrites",
"&&",
"dataAccessType",
".",
"isMMap",
"(",
")",
")",
"dataAccessType",
"=",
"DAType",
".",
"MMAP_RO",
";",
"GHDirectory",
"dir",
"=",
"new",
"GHDirectory",
"(",
"ghLocation",
",",
"dataAccessType",
")",
";",
"GraphExtension",
"ext",
"=",
"encodingManager",
".",
"needsTurnCostsSupport",
"(",
")",
"?",
"new",
"TurnCostExtension",
"(",
")",
":",
"new",
"GraphExtension",
".",
"NoOpExtension",
"(",
")",
";",
"if",
"(",
"lmFactoryDecorator",
".",
"isEnabled",
"(",
")",
")",
"initLMAlgoFactoryDecorator",
"(",
")",
";",
"if",
"(",
"chFactoryDecorator",
".",
"isEnabled",
"(",
")",
")",
"{",
"initCHAlgoFactoryDecorator",
"(",
")",
";",
"ghStorage",
"=",
"new",
"GraphHopperStorage",
"(",
"chFactoryDecorator",
".",
"getNodeBasedWeightings",
"(",
")",
",",
"chFactoryDecorator",
".",
"getEdgeBasedWeightings",
"(",
")",
",",
"dir",
",",
"encodingManager",
",",
"hasElevation",
"(",
")",
",",
"ext",
")",
";",
"}",
"else",
"{",
"ghStorage",
"=",
"new",
"GraphHopperStorage",
"(",
"dir",
",",
"encodingManager",
",",
"hasElevation",
"(",
")",
",",
"ext",
")",
";",
"}",
"ghStorage",
".",
"setSegmentSize",
"(",
"defaultSegmentSize",
")",
";",
"if",
"(",
"!",
"new",
"File",
"(",
"graphHopperFolder",
")",
".",
"exists",
"(",
")",
")",
"return",
"false",
";",
"GHLock",
"lock",
"=",
"null",
";",
"try",
"{",
"// create locks only if writes are allowed, if they are not allowed a lock cannot be created ",
"// (e.g. on a read only filesystem locks would fail)",
"if",
"(",
"ghStorage",
".",
"getDirectory",
"(",
")",
".",
"getDefaultType",
"(",
")",
".",
"isStoring",
"(",
")",
"&&",
"isAllowWrites",
"(",
")",
")",
"{",
"lockFactory",
".",
"setLockDir",
"(",
"new",
"File",
"(",
"ghLocation",
")",
")",
";",
"lock",
"=",
"lockFactory",
".",
"create",
"(",
"fileLockName",
",",
"false",
")",
";",
"if",
"(",
"!",
"lock",
".",
"tryLock",
"(",
")",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"To avoid reading partial data we need to obtain the read lock but it failed. In \"",
"+",
"ghLocation",
",",
"lock",
".",
"getObtainFailedReason",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"ghStorage",
".",
"loadExisting",
"(",
")",
")",
"return",
"false",
";",
"postProcessing",
"(",
")",
";",
"fullyLoaded",
"=",
"true",
";",
"return",
"true",
";",
"}",
"finally",
"{",
"if",
"(",
"lock",
"!=",
"null",
")",
"lock",
".",
"release",
"(",
")",
";",
"}",
"}"
] |
Opens existing graph folder.
@param graphHopperFolder is the folder containing graphhopper files. Can be a compressed file
too ala folder-content.ghz.
|
[
"Opens",
"existing",
"graph",
"folder",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/GraphHopper.java#L681-L754
|
21,098
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/GraphHopper.java
|
GraphHopper.postProcessing
|
public void postProcessing() {
// Later: move this into the GraphStorage.optimize method
// Or: Doing it after preparation to optimize shortcuts too. But not possible yet #12
if (sortGraph) {
if (ghStorage.isCHPossible() && isCHPrepared())
throw new IllegalArgumentException("Sorting a prepared CHGraph is not possible yet. See #12");
GraphHopperStorage newGraph = GHUtility.newStorage(ghStorage);
GHUtility.sortDFS(ghStorage, newGraph);
logger.info("graph sorted (" + getMemInfo() + ")");
ghStorage = newGraph;
}
if (hasElevation()) {
interpolateBridgesAndOrTunnels();
}
initLocationIndex();
if (chFactoryDecorator.isEnabled())
chFactoryDecorator.createPreparations(ghStorage);
if (!isCHPrepared())
prepareCH();
if (lmFactoryDecorator.isEnabled())
lmFactoryDecorator.createPreparations(ghStorage, locationIndex);
loadOrPrepareLM();
}
|
java
|
public void postProcessing() {
// Later: move this into the GraphStorage.optimize method
// Or: Doing it after preparation to optimize shortcuts too. But not possible yet #12
if (sortGraph) {
if (ghStorage.isCHPossible() && isCHPrepared())
throw new IllegalArgumentException("Sorting a prepared CHGraph is not possible yet. See #12");
GraphHopperStorage newGraph = GHUtility.newStorage(ghStorage);
GHUtility.sortDFS(ghStorage, newGraph);
logger.info("graph sorted (" + getMemInfo() + ")");
ghStorage = newGraph;
}
if (hasElevation()) {
interpolateBridgesAndOrTunnels();
}
initLocationIndex();
if (chFactoryDecorator.isEnabled())
chFactoryDecorator.createPreparations(ghStorage);
if (!isCHPrepared())
prepareCH();
if (lmFactoryDecorator.isEnabled())
lmFactoryDecorator.createPreparations(ghStorage, locationIndex);
loadOrPrepareLM();
}
|
[
"public",
"void",
"postProcessing",
"(",
")",
"{",
"// Later: move this into the GraphStorage.optimize method",
"// Or: Doing it after preparation to optimize shortcuts too. But not possible yet #12",
"if",
"(",
"sortGraph",
")",
"{",
"if",
"(",
"ghStorage",
".",
"isCHPossible",
"(",
")",
"&&",
"isCHPrepared",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Sorting a prepared CHGraph is not possible yet. See #12\"",
")",
";",
"GraphHopperStorage",
"newGraph",
"=",
"GHUtility",
".",
"newStorage",
"(",
"ghStorage",
")",
";",
"GHUtility",
".",
"sortDFS",
"(",
"ghStorage",
",",
"newGraph",
")",
";",
"logger",
".",
"info",
"(",
"\"graph sorted (\"",
"+",
"getMemInfo",
"(",
")",
"+",
"\")\"",
")",
";",
"ghStorage",
"=",
"newGraph",
";",
"}",
"if",
"(",
"hasElevation",
"(",
")",
")",
"{",
"interpolateBridgesAndOrTunnels",
"(",
")",
";",
"}",
"initLocationIndex",
"(",
")",
";",
"if",
"(",
"chFactoryDecorator",
".",
"isEnabled",
"(",
")",
")",
"chFactoryDecorator",
".",
"createPreparations",
"(",
"ghStorage",
")",
";",
"if",
"(",
"!",
"isCHPrepared",
"(",
")",
")",
"prepareCH",
"(",
")",
";",
"if",
"(",
"lmFactoryDecorator",
".",
"isEnabled",
"(",
")",
")",
"lmFactoryDecorator",
".",
"createPreparations",
"(",
"ghStorage",
",",
"locationIndex",
")",
";",
"loadOrPrepareLM",
"(",
")",
";",
"}"
] |
Does the preparation and creates the location index
|
[
"Does",
"the",
"preparation",
"and",
"creates",
"the",
"location",
"index"
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/GraphHopper.java#L813-L841
|
21,099
|
graphhopper/graphhopper
|
core/src/main/java/com/graphhopper/GraphHopper.java
|
GraphHopper.createWeighting
|
public Weighting createWeighting(HintsMap hintsMap, FlagEncoder encoder, Graph graph) {
String weightingStr = toLowerCase(hintsMap.getWeighting());
Weighting weighting = null;
if (encoder.supports(GenericWeighting.class)) {
weighting = new GenericWeighting((DataFlagEncoder) encoder, hintsMap);
} else if ("shortest".equalsIgnoreCase(weightingStr)) {
weighting = new ShortestWeighting(encoder);
} else if ("fastest".equalsIgnoreCase(weightingStr) || weightingStr.isEmpty()) {
if (encoder.supports(PriorityWeighting.class))
weighting = new PriorityWeighting(encoder, hintsMap);
else
weighting = new FastestWeighting(encoder, hintsMap);
} else if ("curvature".equalsIgnoreCase(weightingStr)) {
if (encoder.supports(CurvatureWeighting.class))
weighting = new CurvatureWeighting(encoder, hintsMap);
} else if ("short_fastest".equalsIgnoreCase(weightingStr)) {
weighting = new ShortFastestWeighting(encoder, hintsMap);
}
if (weighting == null)
throw new IllegalArgumentException("weighting " + weightingStr + " not supported");
if (hintsMap.has(Routing.BLOCK_AREA)) {
String blockAreaStr = hintsMap.get(Parameters.Routing.BLOCK_AREA, "");
GraphEdgeIdFinder.BlockArea blockArea = new GraphEdgeIdFinder(graph, locationIndex).
parseBlockArea(blockAreaStr, DefaultEdgeFilter.allEdges(encoder), hintsMap.getDouble("block_area.edge_id_max_area", 1000 * 1000));
return new BlockAreaWeighting(weighting, blockArea);
}
return weighting;
}
|
java
|
public Weighting createWeighting(HintsMap hintsMap, FlagEncoder encoder, Graph graph) {
String weightingStr = toLowerCase(hintsMap.getWeighting());
Weighting weighting = null;
if (encoder.supports(GenericWeighting.class)) {
weighting = new GenericWeighting((DataFlagEncoder) encoder, hintsMap);
} else if ("shortest".equalsIgnoreCase(weightingStr)) {
weighting = new ShortestWeighting(encoder);
} else if ("fastest".equalsIgnoreCase(weightingStr) || weightingStr.isEmpty()) {
if (encoder.supports(PriorityWeighting.class))
weighting = new PriorityWeighting(encoder, hintsMap);
else
weighting = new FastestWeighting(encoder, hintsMap);
} else if ("curvature".equalsIgnoreCase(weightingStr)) {
if (encoder.supports(CurvatureWeighting.class))
weighting = new CurvatureWeighting(encoder, hintsMap);
} else if ("short_fastest".equalsIgnoreCase(weightingStr)) {
weighting = new ShortFastestWeighting(encoder, hintsMap);
}
if (weighting == null)
throw new IllegalArgumentException("weighting " + weightingStr + " not supported");
if (hintsMap.has(Routing.BLOCK_AREA)) {
String blockAreaStr = hintsMap.get(Parameters.Routing.BLOCK_AREA, "");
GraphEdgeIdFinder.BlockArea blockArea = new GraphEdgeIdFinder(graph, locationIndex).
parseBlockArea(blockAreaStr, DefaultEdgeFilter.allEdges(encoder), hintsMap.getDouble("block_area.edge_id_max_area", 1000 * 1000));
return new BlockAreaWeighting(weighting, blockArea);
}
return weighting;
}
|
[
"public",
"Weighting",
"createWeighting",
"(",
"HintsMap",
"hintsMap",
",",
"FlagEncoder",
"encoder",
",",
"Graph",
"graph",
")",
"{",
"String",
"weightingStr",
"=",
"toLowerCase",
"(",
"hintsMap",
".",
"getWeighting",
"(",
")",
")",
";",
"Weighting",
"weighting",
"=",
"null",
";",
"if",
"(",
"encoder",
".",
"supports",
"(",
"GenericWeighting",
".",
"class",
")",
")",
"{",
"weighting",
"=",
"new",
"GenericWeighting",
"(",
"(",
"DataFlagEncoder",
")",
"encoder",
",",
"hintsMap",
")",
";",
"}",
"else",
"if",
"(",
"\"shortest\"",
".",
"equalsIgnoreCase",
"(",
"weightingStr",
")",
")",
"{",
"weighting",
"=",
"new",
"ShortestWeighting",
"(",
"encoder",
")",
";",
"}",
"else",
"if",
"(",
"\"fastest\"",
".",
"equalsIgnoreCase",
"(",
"weightingStr",
")",
"||",
"weightingStr",
".",
"isEmpty",
"(",
")",
")",
"{",
"if",
"(",
"encoder",
".",
"supports",
"(",
"PriorityWeighting",
".",
"class",
")",
")",
"weighting",
"=",
"new",
"PriorityWeighting",
"(",
"encoder",
",",
"hintsMap",
")",
";",
"else",
"weighting",
"=",
"new",
"FastestWeighting",
"(",
"encoder",
",",
"hintsMap",
")",
";",
"}",
"else",
"if",
"(",
"\"curvature\"",
".",
"equalsIgnoreCase",
"(",
"weightingStr",
")",
")",
"{",
"if",
"(",
"encoder",
".",
"supports",
"(",
"CurvatureWeighting",
".",
"class",
")",
")",
"weighting",
"=",
"new",
"CurvatureWeighting",
"(",
"encoder",
",",
"hintsMap",
")",
";",
"}",
"else",
"if",
"(",
"\"short_fastest\"",
".",
"equalsIgnoreCase",
"(",
"weightingStr",
")",
")",
"{",
"weighting",
"=",
"new",
"ShortFastestWeighting",
"(",
"encoder",
",",
"hintsMap",
")",
";",
"}",
"if",
"(",
"weighting",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"weighting \"",
"+",
"weightingStr",
"+",
"\" not supported\"",
")",
";",
"if",
"(",
"hintsMap",
".",
"has",
"(",
"Routing",
".",
"BLOCK_AREA",
")",
")",
"{",
"String",
"blockAreaStr",
"=",
"hintsMap",
".",
"get",
"(",
"Parameters",
".",
"Routing",
".",
"BLOCK_AREA",
",",
"\"\"",
")",
";",
"GraphEdgeIdFinder",
".",
"BlockArea",
"blockArea",
"=",
"new",
"GraphEdgeIdFinder",
"(",
"graph",
",",
"locationIndex",
")",
".",
"parseBlockArea",
"(",
"blockAreaStr",
",",
"DefaultEdgeFilter",
".",
"allEdges",
"(",
"encoder",
")",
",",
"hintsMap",
".",
"getDouble",
"(",
"\"block_area.edge_id_max_area\"",
",",
"1000",
"*",
"1000",
")",
")",
";",
"return",
"new",
"BlockAreaWeighting",
"(",
"weighting",
",",
"blockArea",
")",
";",
"}",
"return",
"weighting",
";",
"}"
] |
Based on the hintsMap and the specified encoder a Weighting instance can be
created. Note that all URL parameters are available in the hintsMap as String if
you use the web module.
@param hintsMap all parameters influencing the weighting. E.g. parameters coming via
GHRequest.getHints or directly via "&api.xy=" from the URL of the web UI
@param encoder the required vehicle
@param graph The Graph enables the Weighting for NodeAccess and more
@return the weighting to be used for route calculation
@see HintsMap
|
[
"Based",
"on",
"the",
"hintsMap",
"and",
"the",
"specified",
"encoder",
"a",
"Weighting",
"instance",
"can",
"be",
"created",
".",
"Note",
"that",
"all",
"URL",
"parameters",
"are",
"available",
"in",
"the",
"hintsMap",
"as",
"String",
"if",
"you",
"use",
"the",
"web",
"module",
"."
] |
c235e306e6e823043cadcc41ead0e685bdebf737
|
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/GraphHopper.java#L875-L907
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.