code
stringlengths
25
201k
docstring
stringlengths
19
96.2k
func_name
stringlengths
0
235
language
stringclasses
1 value
repo
stringlengths
8
51
path
stringlengths
11
314
url
stringlengths
62
377
license
stringclasses
7 values
protected int toInt(char character, int leftPos, int rightPos) throws CheckDigitException { if (Character.isDigit(character)) { return Character.getNumericValue(character); } throw new CheckDigitException("Invalid Character[" + leftPos + "] = '" + character + "'"); }
Convert a character at a specified position to an integer value. <p> <b>Note:</b> this implementation only handlers numeric values For non-numeric characters, override this method to provide character--&gt;integer conversion. @param character The character to convert @param leftPos The position of the character in the code, counting from left to right (for identifiying the position in the string) @param rightPos The position of the character in the code, counting from right to left (not used here) @return The integer value of the character @throws CheckDigitException if character is non-numeric
toInt
java
ragunathjawahar/android-saripaar
saripaar/src/main/java/commons/validator/routines/checkdigit/ModulusCheckDigit.java
https://github.com/ragunathjawahar/android-saripaar/blob/master/saripaar/src/main/java/commons/validator/routines/checkdigit/ModulusCheckDigit.java
Apache-2.0
protected String toCheckDigit(int charValue) throws CheckDigitException { if (charValue >= 0 && charValue <= 9) { return Integer.toString(charValue); } throw new CheckDigitException("Invalid Check Digit Value =" + + charValue); }
Convert an integer value to a check digit. <p> <b>Note:</b> this implementation only handles single-digit numeric values For non-numeric characters, override this method to provide integer--&gt;character conversion. @param charValue The integer value of the character @return The converted character @throws CheckDigitException if integer character value doesn't represent a numeric character
toCheckDigit
java
ragunathjawahar/android-saripaar
saripaar/src/main/java/commons/validator/routines/checkdigit/ModulusCheckDigit.java
https://github.com/ragunathjawahar/android-saripaar/blob/master/saripaar/src/main/java/commons/validator/routines/checkdigit/ModulusCheckDigit.java
Apache-2.0
public static int sumDigits(int number) { int total = 0; int todo = number; while (todo > 0) { total += todo % 10; todo = todo / 10; } return total; }
Add together the individual digits in a number. @param number The number whose digits are to be added @return The sum of the digits
sumDigits
java
ragunathjawahar/android-saripaar
saripaar/src/main/java/commons/validator/routines/checkdigit/ModulusCheckDigit.java
https://github.com/ragunathjawahar/android-saripaar/blob/master/saripaar/src/main/java/commons/validator/routines/checkdigit/ModulusCheckDigit.java
Apache-2.0
@SuppressWarnings("for-rollout:SystemOut") @Override public int handleExecutionException(Exception ex, CommandLine commandLine, ParseResult parseResult) throws Exception { ByteArrayOutputStream bytesStream = new ByteArrayOutputStream(); commandLine.setErr(new PrintWriter(new TeeOutputStream(System.err, bytesStream), true, StandardCharsets.UTF_8)); try { delegate.handleExecutionException(ex, commandLine, parseResult); } catch (Exception e) { thrownException = Optional.of(e); throw e; } String errorOutput = bytesStream.toString(StandardCharsets.UTF_8); if (!errorOutput.isEmpty()) { thrownException = Optional.ofNullable(new RuntimeException(errorOutput)); } return -1; }
An {@link IExecutionExceptionHandler} that captures the exception thrown by the delegate and rethrows it later. It is used by {@code inProcessExecution}s to re-throw the exceptions thrown by the command line execution.
handleExecutionException
java
palantir/conjure
conjure/src/main/java/com/palantir/conjure/cli/ThrowableExceptionHandler.java
https://github.com/palantir/conjure/blob/master/conjure/src/main/java/com/palantir/conjure/cli/ThrowableExceptionHandler.java
Apache-2.0
@Deprecated public static ConjureDefinition parse(Collection<File> files) { return parse(ConjureArgs.builder() .definitions(files) .safetyDeclarations(SafetyDeclarationRequirements.ALLOWED) .build()); }
Deserializes {@link ConjureDefinition} from their YAML representations in the given files. @deprecated in favor of {@link #parse(ConjureArgs)}
parse
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/defs/Conjure.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/defs/Conjure.java
Apache-2.0
public static ConjureDefinition parse(ConjureArgs args) { Map<String, AnnotatedConjureSourceFile> sourceFiles = ConjureParser.parseAnnotated(args.definitions()); ConjureDefinition ir = ConjureParserUtils.parseConjureDef(sourceFiles, args.safetyDeclarations()); return NormalizeDefinition.normalize(ir); }
Deserializes {@link ConjureDefinition} from their YAML representations in the given files.
parse
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/defs/Conjure.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/defs/Conjure.java
Apache-2.0
public static Set<ArgumentName> pathArgs(String httpPath) { UriTemplate uriTemplate = new UriTemplate(httpPath); return uriTemplate.getTemplateVariables().stream().map(ArgumentName::of).collect(Collectors.toSet()); }
returns path arguments of the http path.
pathArgs
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/defs/validator/HttpPathValidator.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/defs/validator/HttpPathValidator.java
Apache-2.0
@Override public void validate(ServiceDefinition definition) { Preconditions.checkState( !definition.getServiceName().getName().endsWith(RETROFIT_SUFFIX), "Service name must not end in %s: %s", RETROFIT_SUFFIX, definition.getServiceName().getName()); }
This ensures that ExperimentalFeatures.DisambiguateRetrofitServices won't cause collisions.
validate
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/defs/validator/ServiceDefinitionValidator.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/defs/validator/ServiceDefinitionValidator.java
Apache-2.0
@Override public void validate(Set<FieldName> args) { Map<FieldName, FieldName> seenNormalizedToOriginal = new HashMap<>(); for (FieldName argName : args) { FieldName normalizedName = FieldNameValidator.toCase(argName, CaseConverter.Case.LOWER_CAMEL_CASE); FieldName seenName = seenNormalizedToOriginal.get(normalizedName); Preconditions.checkArgument( seenName == null, "%s must not contain duplicate field names (modulo case normalization): %s vs %s", classSimpleName, argName.get(), seenName == null ? "" : seenName.get()); seenNormalizedToOriginal.put(normalizedName, argName); } }
Verifies that field names are unique modulo normalization to {@link CaseConverter.Case#LOWER_CAMEL_CASE lower camel case}.
validate
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/defs/validator/UniqueFieldNamesValidator.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/defs/validator/UniqueFieldNamesValidator.java
Apache-2.0
public static ConjureSourceFile parse(File file) { CachingParser parser = new CachingParser(); return parser.parse(file); }
Deserializes a {@link ConjureSourceFile} from its YAML representation in the given file.
parse
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/parser/ConjureParser.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/parser/ConjureParser.java
Apache-2.0
public static Map<String, AnnotatedConjureSourceFile> parseAnnotated(File file) { return parseAnnotated(ImmutableList.of(file)); }
Parse file {@literal &} all imports (breadth-first).
parseAnnotated
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/parser/ConjureParser.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/parser/ConjureParser.java
Apache-2.0
public PathString resolve(PathString other) { final Path newPath; if (other.path().equals(Path.ROOT_PATH)) { // special-case since Path#relativize() only works on proper prefixes newPath = path(); } else { newPath = path().resolve(Path.ROOT_PATH.relativize(other.path())); } return ImmutablePathString.builder().path(newPath).build(); }
Returns this path "concatenated" with the given other path. For example, {@code "/abc".resolve("/def")} is the path {@code /abc/def}.
resolve
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/parser/services/PathString.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/parser/services/PathString.java
Apache-2.0
static ConjureType fromString(String value) throws ParseException { return TypeParser.INSTANCE.parse(value); }
A marker interface for the type system.
fromString
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/parser/types/ConjureType.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/parser/types/ConjureType.java
Apache-2.0
@Value.Check @SuppressWarnings("Slf4jLogsafeArgs") protected final void check() { CaseConverter.Case lowerCamelCase = CaseConverter.Case.LOWER_CAMEL_CASE; CaseConverter.Case kebabCase = CaseConverter.Case.KEBAB_CASE; CaseConverter.Case snakeCase = CaseConverter.Case.SNAKE_CASE; boolean nameIsCamelCase = lowerCamelCase.getPattern().matches(name()); Preconditions.checkArgument( nameIsCamelCase || kebabCase.getPattern().matches(name()) || snakeCase.getPattern().matches(name()), "FieldName \"%s\" must follow one of the following patterns: %s %s %s", name(), lowerCamelCase, kebabCase, snakeCase); if (!nameIsCamelCase) { log.warn( "{} should be specified in lowerCamelCase. kebab-case and snake_case are supported for " + "legacy endpoints only: {}", FieldName.class, name()); } }
Represents the name of an {@link ObjectTypeDefinition#fields() field} of an {@link ObjectTypeDefinition}.
check
java
palantir/conjure
conjure-core/src/main/java/com/palantir/conjure/parser/types/names/FieldName.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/conjure/parser/types/names/FieldName.java
Apache-2.0
public static Parser<String> whitespace() { return WHITESPACE; }
Returns a whitespace parser. @return canonical whitespace parser
whitespace
java
palantir/conjure
conjure-core/src/main/java/com/palantir/parsec/Parsers.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/parsec/Parsers.java
Apache-2.0
public static <T> Parser<T> whitespace(Parser<T> parser) { return prefix(whitespace(), parser); }
Runs the whitespace parser followed by `parser`, returning result of the latter. @param <T> the type the target parser returns @param parser the target parser to run @return the specified parser
whitespace
java
palantir/conjure
conjure-core/src/main/java/com/palantir/parsec/Parsers.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/parsec/Parsers.java
Apache-2.0
public static boolean nullOrUnexpected(Object obj) { return obj == null || ExpectationResult.INCORRECT.equals(obj); }
Returns true when the argument is null or is equal to {@link ExpectationResult#INCORRECT}. @param obj object to compare @return true when the argument is null or is equal to {@link ExpectationResult#INCORRECT}
nullOrUnexpected
java
palantir/conjure
conjure-core/src/main/java/com/palantir/parsec/Parsers.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/parsec/Parsers.java
Apache-2.0
public static boolean nullOrEmpty(String string) { return string == null || string.isEmpty(); }
Returns true when the argument is null or is a String and is empty. @param string the string to test @return true when {@code string} is null or empty
nullOrEmpty
java
palantir/conjure
conjure-core/src/main/java/com/palantir/parsec/Parsers.java
https://github.com/palantir/conjure/blob/master/conjure-core/src/main/java/com/palantir/parsec/Parsers.java
Apache-2.0
public static void initialize(ErrorReporter errorReporter) { if (!initialized) { lookupHostname(errorReporter); initialized = true; } }
Initialize only once. @param errorReporter the error reporter
initialize
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/RuntimeContainer.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/RuntimeContainer.java
MIT
public static String getProperty(String key, String defaultValue) { String env = System.getenv(key); if (env != null && !"".equals(env)) { return env; } return System.getProperty(key, defaultValue); }
Lookup property from ({@link System#getenv(String)} and {@link System#getProperty(String)} as fallback. @param key the property key @param defaultValue the default value @return the property value.
getProperty
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/RuntimeContainerProperties.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/RuntimeContainerProperties.java
MIT
public static String getFilteredStackTrace(Throwable t) { return getFilteredStackTrace(t, true); }
Get a filterered stack trace. @param t the throwable @return String containing the filtered stack trace.
getFilteredStackTrace
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/StackTraceFilter.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/StackTraceFilter.java
MIT
@Deprecated public static String getFilteredStackTrace(Throwable t, boolean shouldFilter) { if (shouldFilter) { return getFilteredStackTrace(t, 0); } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.close(); return sw.getBuffer().toString(); }
Get a filterered stack trace. @param t the throwable @param shouldFilter true in case filtering should be performed. Else stack trace as string will be returned. @return String containing the stack trace. @deprecated since 1.11.1. Use {@link #getStackTrace(Throwable, int)} to get the stack trace without filtering or {@link #getFilteredStackTrace(Throwable)} to get the filtered the stack trace.
getFilteredStackTrace
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/StackTraceFilter.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/StackTraceFilter.java
MIT
public static String getFilteredStackTrace(Throwable t, int ref) { StringWriter sw = new StringWriter(); FilterWriter filterWriter = new StackTraceFilterWriter(sw); printStackTrace(t, filterWriter, ref); return sw.getBuffer().toString(); }
Filter stack trace by selecting the {@link Throwable} using a reference position. Intermediate throwables will be printed with just their header. @param t the throwable @param ref throwable reference position, see {@link #getThrowable(List, int)}. @return String containing the stack trace. @since 1.11.1
getFilteredStackTrace
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/StackTraceFilter.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/StackTraceFilter.java
MIT
public static String getStackTrace(Throwable t) { return getStackTrace(t, 0); }
Get the {@link Throwable}'s stack trace. @param t the throwable @return String containing the stack trace. @since 1.11.1
getStackTrace
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/StackTraceFilter.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/StackTraceFilter.java
MIT
public void initialize(PropertyProvider propertyProvider) { host = propertyProvider.getProperty(PropertyProvider.PROPERTY_HOST); if (host == null) { host = propertyProvider.getProperty(PropertyProvider.PROPERTY_GRAYLOG_HOST); } String port = propertyProvider.getProperty(PropertyProvider.PROPERTY_PORT); if (port == null) { port = propertyProvider.getProperty(PropertyProvider.PROPERTY_GRAYLOG_PORT); } if (port != null && !"".equals(port)) { this.port = Integer.parseInt(port); } originHost = propertyProvider.getProperty(PropertyProvider.PROPERTY_ORIGIN_HOST); setExtractStackTrace(propertyProvider.getProperty(PropertyProvider.PROPERTY_EXTRACT_STACKTRACE)); setFilterStackTrace("true".equalsIgnoreCase(propertyProvider.getProperty(PropertyProvider.PROPERTY_FILTER_STACK_TRACE))); String includeLogMessageParameters = propertyProvider .getProperty(PropertyProvider.PROPERTY_INCLUDE_LOG_MESSAGE_PARAMETERS); if (includeLogMessageParameters != null && !includeLogMessageParameters.trim().equals("")) { setIncludeLogMessageParameters("true".equalsIgnoreCase(includeLogMessageParameters)); } setupStaticFields(propertyProvider); setupAdditionalFieldTypes(propertyProvider); setupDynamicMdcFieldTypes(propertyProvider); facility = propertyProvider.getProperty(PropertyProvider.PROPERTY_FACILITY); String version = propertyProvider.getProperty(PropertyProvider.PROPERTY_VERSION); if (version != null && !"".equals(version)) { this.version = version; } String messageSize = propertyProvider.getProperty(PropertyProvider.PROPERTY_MAX_MESSAGE_SIZE); if (messageSize != null) { maximumMessageSize = Integer.parseInt(messageSize); } String timestampPattern = propertyProvider.getProperty(PropertyProvider.PROPERTY_TIMESTAMP_PATTERN); if (timestampPattern != null && !"".equals(timestampPattern)) { this.timestampPattern = timestampPattern; } }
Initialize the {@link GelfMessageAssembler} from a property provider. @param propertyProvider property provider to obtain configuration properties
initialize
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageAssembler.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageAssembler.java
MIT
public GelfMessageBuilder withVersion(String version) { this.version = version; return this; }
Set the version. @param version the version @return GelfMessageBuilder
withVersion
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withHost(String host) { this.host = host; return this; }
Set the host. @param host the host @return GelfMessageBuilder
withHost
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withShortMessage(String shortMessage) { this.shortMessage = shortMessage; return this; }
Set the short_message. @param shortMessage the short_message @return GelfMessageBuilder
withShortMessage
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withFullMessage(String fullMessage) { this.fullMessage = fullMessage; return this; }
Set the full_message. @param fullMessage the fullMessage @return GelfMessageBuilder
withFullMessage
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withLevel(String level) { this.level = level; return this; }
Set the level (severity). @param level the level @return GelfMessageBuilder
withLevel
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withFacility(String facility) { this.facility = facility; return this; }
Set the facility. @param facility the facility @return GelfMessageBuilder
withFacility
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withMaximumMessageSize(int maximumMessageSize) { this.maximumMessageSize = maximumMessageSize; return this; }
Set the max message size. @param maximumMessageSize the maximumMessageSize @return GelfMessageBuilder
withMaximumMessageSize
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withJavaTimestamp(long javaTimestamp) { this.javaTimestamp = javaTimestamp; return this; }
Set the java timestamp (millis). @param javaTimestamp the javaTimestamp @return GelfMessageBuilder
withJavaTimestamp
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withFields(Map<String, String> additionalFields) { this.additionalFields.putAll(additionalFields); return this; }
Add additional fields. @param additionalFields the additionalFields @return GelfMessageBuilder
withFields
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withField(String key, String value) { this.additionalFields.put(key, value); return this; }
Add an additional field. @param key the key @param value the value @return GelfMessageBuilder
withField
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withAdditionalFieldTypes(Map<String, String> additionalFieldTypes) { this.additionalFieldTypes.putAll(additionalFieldTypes); return this; }
Set additional field types @param additionalFieldTypes the type map @return GelfMessageBuilder
withAdditionalFieldTypes
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public GelfMessageBuilder withDynamicMdcFieldTypes(Map<Pattern, String> dynamicMdcFieldTypes) { this.dynamicMdcFieldTypes = dynamicMdcFieldTypes; return this; }
Set dynamic mdc field types @param dynamicMdcFieldTypes the type map @return GelfMessageBuilder
withDynamicMdcFieldTypes
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/GelfMessageBuilder.java
MIT
public static final void close(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { // ignore } }
Close silently the closeable. @param closeable the closeable
close
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/Closer.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/Closer.java
MIT
public static final void close(Socket socket) { try { if (socket != null) { socket.close(); } } catch (IOException e) { // ignore } }
Close silently the socket. @param socket the socket
close
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/Closer.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/Closer.java
MIT
public static void setAdditionalFields(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] properties = spec.split(MULTI_VALUE_DELIMITTER); for (String field : properties) { final int index = field.indexOf(EQ); if (-1 == index) { continue; } gelfMessageAssembler.addField(new StaticMessageField(field.substring(0, index), field.substring(index + 1))); } } }
Set the additional (static) fields. @param spec field=value,field1=value1, ... @param gelfMessageAssembler the Gelf message assembler to apply the configuration
setAdditionalFields
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
MIT
public static void setMdcFields(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] fields = spec.split(MULTI_VALUE_DELIMITTER); for (String field : fields) { gelfMessageAssembler.addField(new MdcMessageField(field.trim(), field.trim())); } } }
Set the MDC fields. @param spec field, field2, field3 @param gelfMessageAssembler the Gelf message assembler to apply the configuration
setMdcFields
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
MIT
public static void setDynamicMdcFields(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] fields = spec.split(MULTI_VALUE_DELIMITTER); for (String field : fields) { gelfMessageAssembler.addField(new DynamicMdcMessageField(field.trim())); } } }
Set the dynamic MDC fields. @param spec field, .*FieldSuffix, fieldPrefix.* @param gelfMessageAssembler the {@link GelfMessageAssembler}.
setDynamicMdcFields
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
MIT
public static void setAdditionalFieldTypes(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] properties = spec.split(MULTI_VALUE_DELIMITTER); for (String field : properties) { final int index = field.indexOf(EQ); if (-1 != index) { gelfMessageAssembler.setAdditionalFieldType(field.substring(0, index), field.substring(index + 1)); } } } }
Set the additional field types. @param spec field=String,field1=Double, ... See {@link GelfMessage} for supported types. @param gelfMessageAssembler the Gelf message assembler to apply the configuration
setAdditionalFieldTypes
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
MIT
public static void setDynamicMdcFieldTypes(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] properties = spec.split(MULTI_VALUE_DELIMITTER); for (String field : properties) { final int index = field.indexOf(EQ); if (-1 != index) { gelfMessageAssembler.setDynamicMdcFieldType(field.substring(0, index), field.substring(index + 1)); } } } }
Set the dynamic mdc field types. @param spec field=String,field1=Double, ... See {@link GelfMessage} for supported types. @param gelfMessageAssembler the Gelf message assembler to apply the configuration
setDynamicMdcFieldTypes
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
MIT
public String toJson() { return toJson("_"); }
Create a JSON representation for this {@link GelfMessage}. Additional fields are prefixed with underscore {@code _}. @return the JSON string.
toJson
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/GelfMessage.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/GelfMessage.java
MIT
private static boolean writeIfNotEmpty(OutputAccessor out, boolean hasFields, String field, Object value) { if (value == null) { return hasFields; } if (value instanceof String) { if (GelfMessage.isEmpty((String) value)) { return hasFields; } if (hasFields) { writeKeyValueSeparator(out); } writeMapEntry(out, field, value); return true; } if (hasFields) { writeKeyValueSeparator(out); } writeMapEntry(out, field, value); return true; }
Write a Value to JSON if the value is not empty.
writeIfNotEmpty
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/GelfMessage.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/GelfMessage.java
MIT
public GelfMessage addFields(Map<String, String> fields) { if (fields == null) { throw new IllegalArgumentException("fields is null"); } getAdditonalFields().putAll(fields); return this; }
Add multiple fields (key/value pairs) @param fields map of fields @return the current GelfMessage.
addFields
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/GelfMessage.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/GelfMessage.java
MIT
public static void toJSONString(OutputAccessor out, Map<String, ? extends Object> map) { writeObjectStart(out); boolean first = true; for (Map.Entry<String, ? extends Object> entry : map.entrySet()) { if (first) { first = false; } else { writeKeyValueSeparator(out); } writeMapEntry(out, entry.getKey(), entry.getValue()); } writeObjectEnd(out); }
Utility method to write a {@link Map} into a JSON representation. @param out @param map
toJSONString
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/JsonWriter.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/JsonWriter.java
MIT
public static void writeMapEntry(OutputAccessor out, String key, Object value) { out.write((byte) '\"'); if (key == null) out.write(NULL); else { writeUtf8(out, key); } out.write(Q_AND_C); toJSONString(out, value); }
Write a map entry. @param out @param key @param value
writeMapEntry
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/JsonWriter.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/JsonWriter.java
MIT
private static void escape(OutputAccessor out, int charToEscape) { out.write('\\'); out.write('u'); if (charToEscape > 0xFF) { int hi = (charToEscape >> 8) & 0xFF; out.write(HEX_BYTES[hi >> 4]); out.write(HEX_BYTES[hi & 0xF]); charToEscape &= 0xFF; } else { out.write((byte) '0'); out.write((byte) '0'); } // We know it's a control char, so only the last 2 chars are non-0 out.write(HEX_BYTES[charToEscape >> 4]); out.write(HEX_BYTES[charToEscape & 0xF]); }
Write a UTF escape sequence using either an one or two-byte seqience. @param out the output @param charToEscape the character to escape.
escape
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/JsonWriter.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/JsonWriter.java
MIT
private static boolean isSurrogate(char c) { return c >= '\uD800' && c <= '\uDFFF'; }
Determine if {@code c} lies within the range of values defined for <a href="http://unicode.org/glossary/#surrogate_code_point">Surrogate Code Point</a>. @param c the character to check. @return {@code true} if {@code c} lies within the range of values defined for <a href="http://unicode.org/glossary/#surrogate_code_point">Surrogate Code Point</a>. {@code false} otherwise.
isSurrogate
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/JsonWriter.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/JsonWriter.java
MIT
public static OutputAccessor from(OutputStream outputStream) { return new OutputStreamAccessor(outputStream); }
Create an {@link OutputAccessor} for the given {@link OutputStream}. @param outputStream @return
from
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/OutputAccessor.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/OutputAccessor.java
MIT
public static OutputAccessor from(ByteBuffer byteBuffer) { ByteBufferOutputAccessor accessor = new ByteBufferOutputAccessor(); accessor.byteBuffer = byteBuffer; return accessor; }
Create an {@link OutputAccessor} for the given {@link ByteBuffer}. Instances are pooled within the thread scope. @param byteBuffer @return
from
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/OutputAccessor.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/OutputAccessor.java
MIT
public static OutputAccessor from(OutputAccessorPoolHolder poolHolder, ByteBuffer byteBuffer) { ByteBufferOutputAccessor accessor = poolHolder.getByteBufferOutputAccessor(); accessor.byteBuffer = byteBuffer; return accessor; }
Create an {@link OutputAccessor} for the given {@link ByteBuffer}. Instances are pooled within the thread scope. @param poolHolder @param byteBuffer @return
from
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/OutputAccessor.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/OutputAccessor.java
MIT
public static OutputStream pooledStream(OutputAccessorPoolHolder poolHolder) { return poolHolder.getByteBufferOutputStream(); }
Retrieve a pooled {@link OutputStream}. @param poolHolder @return
pooledStream
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/OutputAccessor.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/OutputAccessor.java
MIT
public ByteBuffer[] getSingleBuffer() { return singleBufferPool.get(); }
@return a pooled {@link ByteBuffer}-array instance.
getSingleBuffer
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/PoolHolder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/PoolHolder.java
MIT
public static boolean usePooling() { return STATIC_POOLING || USE_POOLING_VAL.equalsIgnoreCase("true"); }
@return {@literal true} if pooling (static/instance-held pools) is enabled.
usePooling
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/PoolingGelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/PoolingGelfMessageBuilder.java
MIT
public GelfMessageBuilder recycle() { version = GelfMessage.GELF_VERSION; host = null; shortMessage = null; fullMessage = null; javaTimestamp = 0; level = null; facility = GelfMessage.DEFAULT_FACILITY; maximumMessageSize = GelfMessage.DEFAULT_MESSAGE_SIZE; additionalFields.clear(); additionalFieldTypes.clear(); return this; }
Recycle this {@link GelfMessageBuilder} to a default state. @return {@code this} {@link GelfMessageBuilder}
recycle
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/PoolingGelfMessageBuilder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/PoolingGelfMessageBuilder.java
MIT
@Override public synchronized void write(byte[] buf, int off, int len) throws IOException { super.write(buf, off, len); crc.update(buf, off, len); }
Writes array of bytes to the compressed output stream. This method will block until all the bytes are written. @param buf the data to be written @param off the start offset of the data @param len the length of the data @exception IOException If an I/O error has occurred.
write
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/ReusableGzipOutputStream.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/ReusableGzipOutputStream.java
MIT
static Result discover(String value) { long len = value.length(); if (len == 0 || len > 32) { return Result.STRING; } char firstChar = value.charAt(0); if (firstChar < '0' || firstChar > '9') { // Possible leading "+" or "-" if (firstChar == 'N' && len == 3 && value.equals("NaN")) { return Result.DOUBLE; } else if (firstChar == 'I' && len == 8 && value.equals("Infinity")) { return Result.DOUBLE; } else if (firstChar == '+' && len == 9 && value.equals("+Infinity")) { return Result.DOUBLE; } else if (firstChar == '-' && len == 9 && value.equals("-Infinity")) { return Result.DOUBLE; } if (firstChar != '-' && firstChar != '+') { return Result.STRING; } } boolean numbersOnly = true; for (int pos = 0; pos < Math.min(len, 20); pos++) { char c = value.charAt(pos); numbersOnly &= (c >= '0' && c <= '9'); if (numbersOnly) { continue; } if ((c != '+') && (c != '-') && (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') && (c != '.') && (c != 'x' && c != 'X') && (c != 'p' && c != 'P')) { return Result.STRING; } } if (numbersOnly) { if (len == 1) { return Result.LONG; } else if (len <= 19 && firstChar != '0') { return Result.LONG; } else { return Result.STRING; } } else if (longPattern.matcher(value).matches()) { return Result.LONG; } else if (doublePattern.matcher(value).matches()) { return Result.DOUBLE; } return Result.STRING; }
Data type discovery for {@link String} value types. Discovers an indicator whether a type is a {@link Result#LONG}, a {@link Result#DOUBLE} or {@link Result#STRING} type. @author <a href="mailto:mpaluch@paluch.biz">Mark Paluch</a> @author Wolfgang Jung
discover
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/ValueDiscovery.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/ValueDiscovery.java
MIT
public static String encodeString(String s) { return new String(encode(s.getBytes())); }
Encodes a string into Base64 format. No blanks or line breaks are inserted. @param s A String to be encoded. @return A String containing the Base64 encoded data.
encodeString
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/sender/Base64Coder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/sender/Base64Coder.java
MIT
public static char[] encode(byte[] in) { return encode(in, 0, in.length); }
Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. @param in An array containing the data bytes to be encoded. @return A character array containing the Base64 encoded data.
encode
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/sender/Base64Coder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/sender/Base64Coder.java
MIT
public static char[] encode(byte[] in, int iOff, int iLen) { int oDataLen = (iLen * 4 + 2) / 3; // output length without padding int oLen = ((iLen + 2) / 3) * 4; // output length including padding char[] out = new char[oLen]; int ip = iOff; int iEnd = iOff + iLen; int op = 0; while (ip < iEnd) { int i0 = in[ip++] & 0xff; int i1 = ip < iEnd ? in[ip++] & 0xff : 0; int i2 = ip < iEnd ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; }
Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. @param in An array containing the data bytes to be encoded. @param iOff Offset of the first byte in <code>in</code> to be processed. @param iLen Number of bytes to process in <code>in</code>, starting at <code>iOff</code>. @return A character array containing the Base64 encoded data.
encode
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/sender/Base64Coder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/sender/Base64Coder.java
MIT
protected static ByteBuffer[] toUDPBuffers(GelfMessage message, ThreadLocal<ByteBuffer> writeBuffers, ThreadLocal<ByteBuffer> tempBuffers) { while (true) { try { return message.toUDPBuffers(getBuffer(writeBuffers), getBuffer(tempBuffers)); } catch (BufferOverflowException e) { enlargeBuffer(writeBuffers); enlargeBuffer(tempBuffers); } } }
Create UDP buffers and apply auto-buffer-enlarging, if necessary. @param message @param writeBuffers @param tempBuffers @return
toUDPBuffers
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/sender/GelfBuffers.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/sender/GelfBuffers.java
MIT
protected SocketChannel createSocketChannel(int readTimeoutMs, boolean keepAlive) throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.socket().setKeepAlive(keepAlive); socketChannel.socket().setSoTimeout(readTimeoutMs); return socketChannel; }
@param host the host, must not be {@literal null}. @param port the port. @param connectTimeoutMs connection timeout, in {@link TimeUnit#MILLISECONDS}. @param readTimeoutMs read timeout, in {@link TimeUnit#MILLISECONDS}. @param deliveryAttempts number of delivery attempts. @param keepAlive {@literal true} to enable TCP keep-alive. @param backoff Backoff strategy to activate if a socket sender buffer is full and several attempts to write to the socket are unsuccessful due to it. @param writeBackoffThreshold attempts to write to a socket before a backoff will be activated. @param errorReporter the error reporter, must not be {@literal null}. @throws IOException in case of I/O errors
createSocketChannel
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/sender/GelfTCPSender.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/sender/GelfTCPSender.java
MIT
@Override public String getScheme() { return RedisSenderConstants.REDIS_SCHEME; }
Singleton for administration of commonly used jedis pools @author https://github.com/Batigoal/logstash-gelf.git @author Mark Paluch
getScheme
java
mp911de/logstash-gelf
src/main/java/biz/paluch/logging/gelf/intern/sender/RedisPoolHolder.java
https://github.com/mp911de/logstash-gelf/blob/master/src/main/java/biz/paluch/logging/gelf/intern/sender/RedisPoolHolder.java
MIT
@SuppressWarnings("unchecked") public static Map<String, Object> parseToMap(String jsonAsString) { try { return objectMapper.readValue(jsonAsString, Map.class); } catch (IOException e) { throw new IllegalStateException(e); } }
Parse a JSON string to a {@link Map} @param jsonAsString JSON value as {@link String}. @return object as {@link Map}.
parseToMap
java
mp911de/logstash-gelf
src/test/java/biz/paluch/logging/gelf/JsonUtil.java
https://github.com/mp911de/logstash-gelf/blob/master/src/test/java/biz/paluch/logging/gelf/JsonUtil.java
MIT
@Test void shouldReturnConstantBackoff() { ConstantBackOff backOff = new ConstantBackOff(10, TimeUnit.SECONDS); assertThat(backOff.start().nextBackOff()).isEqualTo(TimeUnit.SECONDS.toMillis(10)); }
Unit tests for {@link ConstantBackOff}. @author Mark Paluch
shouldReturnConstantBackoff
java
mp911de/logstash-gelf
src/test/java/biz/paluch/logging/gelf/intern/sender/ConstantBackOffUnitTests.java
https://github.com/mp911de/logstash-gelf/blob/master/src/test/java/biz/paluch/logging/gelf/intern/sender/ConstantBackOffUnitTests.java
MIT
@Test void shouldClosePool() { GelfREDISSender sender = new GelfREDISSender(pool, "key", errorReporter); sender.close(); verify(pool).destroy(); }
Unit tests for {@link GelfREDISSender}. @author Mark Paluch
shouldClosePool
java
mp911de/logstash-gelf
src/test/java/biz/paluch/logging/gelf/intern/sender/GelfREDISSenderUnitTests.java
https://github.com/mp911de/logstash-gelf/blob/master/src/test/java/biz/paluch/logging/gelf/intern/sender/GelfREDISSenderUnitTests.java
MIT
public static boolean isLog4jMDCAvailable() { return !Loader.isJava1(); }
@return {@literal true} if the Log4j MDC is available
isLog4jMDCAvailable
java
mp911de/logstash-gelf
src/test/java/biz/paluch/logging/gelf/log4j/Log4jUtil.java
https://github.com/mp911de/logstash-gelf/blob/master/src/test/java/biz/paluch/logging/gelf/log4j/Log4jUtil.java
MIT
@Test void testWithRawMdcFieldTypes() throws Exception { Logger logger = loggerContext.getLogger(getClass().getName()); ObjectThreadContextMap contextMap = (ObjectThreadContextMap) ThreadContext.getThreadContextMap(); contextMap.putValue("myMdcs", "String"); contextMap.putValue("myMdcl", 1); contextMap.putValue("myMdci", 2L); contextMap.putValue("myMdcd", 2.1); contextMap.putValue("myMdcf", 2.2d); logger.info(LOG_MESSAGE); assertThat(GelfTestSender.getMessages()).hasSize(1); GelfMessage gelfMessage = GelfTestSender.getMessages().get(0); Map<String, Object> jsonObject = JsonUtil.parseToMap(gelfMessage.toJson("")); assertThat(jsonObject).containsEntry("myMdcs", "String"); assertThat(jsonObject).containsEntry("myMdcl", 1); assertThat(jsonObject).containsEntry("myMdci", 2); assertThat(jsonObject).containsEntry("myMdcd", 2.1); assertThat(jsonObject).containsEntry("myMdcf", 2.2); ThreadContext.put("myMdcl", "1.1"); ThreadContext.put("myMdci", "2.1"); ThreadContext.put("myMdcd", "wrong"); ThreadContext.put("myMdcf", "wrong"); GelfTestSender.getMessages().clear(); logger.info(LOG_MESSAGE); assertThat(GelfTestSender.getMessages()).hasSize(1); gelfMessage = GelfTestSender.getMessages().get(0); jsonObject = JsonUtil.parseToMap(gelfMessage.toJson("")); assertThat(jsonObject).containsEntry("myMdcl", 1); assertThat(jsonObject).containsEntry("myMdci", 2); assertThat(jsonObject).doesNotContainKey("myMdcd"); assertThat(jsonObject).containsEntry("myMdcf", 0.0); ThreadContext.put("myMdcl", "b"); ThreadContext.put("myMdci", "a"); GelfTestSender.getMessages().clear(); logger.info(LOG_MESSAGE); assertThat(GelfTestSender.getMessages()).hasSize(1); gelfMessage = GelfTestSender.getMessages().get(0); jsonObject = JsonUtil.parseToMap(gelfMessage.toJson("")); assertThat(jsonObject).doesNotContainKey("myMdcl"); assertThat(jsonObject).containsEntry("myMdci", 0); }
Copy of GelfLogAppenderDynamicMdcTests#testWithMdcFieldTypes() with raw types instead of String values
testWithRawMdcFieldTypes
java
mp911de/logstash-gelf
src/test/java/biz/paluch/logging/gelf/log4j2/GelfLogAppenderNonStringMdcTests.java
https://github.com/mp911de/logstash-gelf/blob/master/src/test/java/biz/paluch/logging/gelf/log4j2/GelfLogAppenderNonStringMdcTests.java
MIT
@Override public String getName() { return "CTKNativeAdManager"; }
@{Map} with all registered fb ads managers
getName
java
callstack/react-native-fbads
android/app/src/main/java/suraj/tiwari/reactnativefbads/NativeAdManager.java
https://github.com/callstack/react-native-fbads/blob/master/android/app/src/main/java/suraj/tiwari/reactnativefbads/NativeAdManager.java
MIT
@ReactMethod public void setMediaCachePolicy(String placementId, String cachePolicy) { Log.w("NativeAdManager", "This method is not supported on Android"); }
Sets media cache policy @param placementId @param cachePolicy
setMediaCachePolicy
java
callstack/react-native-fbads
android/app/src/main/java/suraj/tiwari/reactnativefbads/NativeAdManager.java
https://github.com/callstack/react-native-fbads/blob/master/android/app/src/main/java/suraj/tiwari/reactnativefbads/NativeAdManager.java
MIT
public NativeAdsManager getFBAdsManager(String placementId) { return mAdsManagers.get(placementId); }
Returns FBAdsManager for a given placement id @param placementId @return
getFBAdsManager
java
callstack/react-native-fbads
android/app/src/main/java/suraj/tiwari/reactnativefbads/NativeAdManager.java
https://github.com/callstack/react-native-fbads/blob/master/android/app/src/main/java/suraj/tiwari/reactnativefbads/NativeAdManager.java
MIT
public static boolean isResource(String fileName) { LOGGER.fine("Checking if file is a resource: " + fileName); for (Pattern pattern : RESOURCE_PATTERNS) { if (pattern.matcher(fileName).matches()) { LOGGER.fine("File identified as resource: " + fileName); return true; } } return false; }
Checks if a file name matches any predefined resource pattern.
isResource
java
LaurieWired/Malimite
src/main/java/com/lauriewired/malimite/utils/ResourceParser.java
https://github.com/LaurieWired/Malimite/blob/master/src/main/java/com/lauriewired/malimite/utils/ResourceParser.java
Apache-2.0
public static boolean isRGBAColor(String color) { if (color == null) { return false; } if (!color.startsWith("#")) { return false; } if (color.length() != 9 && color.length() != 7) { return false; } for (int i = 1; i < color.length(); i++) { char c = color.charAt(i); if (!Character.isDigit(c) && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) { return false; } } return true; }
author : ywl5320 e-mail : ywl5320@163.com desc : wlmedia date : 2024/8/10
isRGBAColor
java
ywl5320/wlmedia
wlmedia_android/wlmedia/src/main/java/com/ywl5320/wlmedia/util/WlColorUtil.java
https://github.com/ywl5320/wlmedia/blob/master/wlmedia_android/wlmedia/src/main/java/com/ywl5320/wlmedia/util/WlColorUtil.java
Apache-2.0
@Override public CacheManager createCacheManager(Application application) throws CacheCreationException { CacheManager cacheManager = new CacheManager(); cacheManager.addPersister(new GsonObjectPersisterFactory(application)); return cacheManager; }
A {@link GoogleHttpClientSpiceService} dedicated to json web services via gson. Provides caching. @author sni
createCacheManager
java
stephanenicolas/robospice
extensions/robospice-google-http-client-parent/robospice-google-http-client/src/main/java/com/octo/android/robospice/GsonGoogleHttpClientSpiceService.java
https://github.com/stephanenicolas/robospice/blob/master/extensions/robospice-google-http-client-parent/robospice-google-http-client/src/main/java/com/octo/android/robospice/GsonGoogleHttpClientSpiceService.java
Apache-2.0
@Override public InputStream processStream(final int contentLength, final InputStream inputStream) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); readBytes(inputStream, new ProgressByteProcessor(this, bos, contentLength)); final byte[] bytes = bos.toByteArray(); return new ByteArrayInputStream(bytes); }
Downloads small images in size. All data is passed to the listener using memory. This class is meant to help download small images (like thumbnails). If you wish to download bigger documents (or if you don't know the size of your documents), you would be better using {@link OkHttpBigBinaryRequest}. @author sni & jva
processStream
java
stephanenicolas/robospice
extensions/robospice-okhttp-parent/robospice-okhttp/src/main/java/com/octo/android/robospice/request/okhttp/simple/OkHttpSmallBinaryRequest.java
https://github.com/stephanenicolas/robospice/blob/master/extensions/robospice-okhttp-parent/robospice-okhttp/src/main/java/com/octo/android/robospice/request/okhttp/simple/OkHttpSmallBinaryRequest.java
Apache-2.0
protected final Application getApplication() { return mApplication; }
Creates an {@link ObjectPersisterFactory} given an Android application and a list of handled classes. @param application the android context needed to access android file system or databases to store. @param listHandledClasses the list of classes that is handled by the factory. The factory will try to produce an {@link ObjectPersister} for each element of the list.
getApplication
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
Apache-2.0
@Override public boolean canHandleClass(Class<?> clazz) { if (listHandledClasses == null) { return true; } else { return listHandledClasses.contains(clazz); } }
Wether or not this bus element can persist/unpersist objects of the given class clazz. @param clazz the class of objets we are looking forward to persist. @return true if this bus element can persist/unpersist objects of the given class clazz. False otherwise.
canHandleClass
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
Apache-2.0
public void setAsyncSaveEnabled(boolean isAsyncSaveEnabled) { this.isAsyncSaveEnabled = isAsyncSaveEnabled; }
Set whether this {@link ObjectPersisterFactory} will set the {@link ObjectPersister} instances it produces to save data asynchronously or not. @param isAsyncSaveEnabled whether or not data will be saved asynchronously by {@link ObjectPersister} instances produced by this factory.
setAsyncSaveEnabled
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
Apache-2.0
public boolean isAsyncSaveEnabled() { return isAsyncSaveEnabled; }
Indicates whether this {@link ObjectPersisterFactory} will set the {@link ObjectPersister} instances it produces to save data asynchronously or not. @return true if the {@link ObjectPersister} instances it produces to save data asynchronously. False otherwise.
isAsyncSaveEnabled
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
Apache-2.0
protected List<Class<?>> getListHandledClasses() { return listHandledClasses; }
Return the list of classes persisted by this factory. @return the list of classes persisted by this factory.
getListHandledClasses
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/ObjectPersisterFactory.java
Apache-2.0
public boolean isUsingKeySanitizer() { return keySanitizer != null; }
@return Whether or not this {@link InFileObjectPersister} uses a {@link KeySanitizer}.
isUsingKeySanitizer
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersister.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersister.java
Apache-2.0
public void setKeySanitizer(KeySanitizer keySanitizer) { this.keySanitizer = keySanitizer; }
@param keySanitizer the new key sanitizer to be used by this {@link InFileObjectPersister}. May be null, in that case no key sanitation will be used default). If key sanitation fails on a given cache key (by throwing a {@link KeySanitationExcepion}, original (unsanitized) cache keys will be used directly.
setKeySanitizer
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersister.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersister.java
Apache-2.0
protected final String toKey(String cacheKey) { if (isUsingKeySanitizer()) { try { return (String) keySanitizer.sanitizeKey(cacheKey); } catch (KeySanitationExcepion e) { Ln.e(e, "Key could not be sanitized, falling back on original key."); return cacheKey; } } else { return cacheKey; } }
Get a key that may be sanitized if a {@link KeySanitizer} is used. @param cacheKey a non-sanitized cacheKey. @return a key that will be sanitized if a {@link KeySanitizer} is used.
toKey
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersister.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersister.java
Apache-2.0
public void setCacheFolder(File cacheFolder) throws CacheCreationException { if (cacheFolder == null) { cacheFolder = new File(getApplication().getCacheDir(), InFileObjectPersister.DEFAULT_ROOT_CACHE_DIR); } this.cacheFolder = cacheFolder; if (!cacheFolder.exists() && !cacheFolder.mkdirs()) { throw new CacheCreationException("The cache folder " + cacheFolder.getAbsolutePath() + " could not be created."); } }
Sets the folder used by object persisters of this factory. @param cacheFolder the new cache folder of this factory (and persisters it will create). Ca be null, it will then default to the sub folder {@link InFileObjectPersister#DEFAULT_ROOT_CACHE_DIR} in side the application cache folder. Will be created if doesn't exist yet. @throws CacheCreationException
setCacheFolder
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersisterFactory.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersisterFactory.java
Apache-2.0
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override protected int sizeOf(Object key, CacheItem<Bitmap> value) { Bitmap data = value.getData(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) { return data.getRowBytes() * data.getHeight(); } else { return data.getByteCount(); } }
{@link LruCache} for {@link Bitmap}s. @author David Stemmer @author Mike Jancola @author SNI
sizeOf
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/memory/BitmapLruCache.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/memory/BitmapLruCache.java
Apache-2.0
public void trimToSize(int maxSize) { while (true) { K key; V value; synchronized (this) { if (size < 0 || map.isEmpty() && size != 0) { throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } if (size <= maxSize || map.isEmpty()) { break; } Map.Entry<K, V> toEvict = map.entrySet().iterator().next(); key = toEvict.getKey(); value = toEvict.getValue(); map.remove(key); size -= safeSizeOf(key, value); evictionCount++; } entryRemoved(true, key, value, null); } }
Remove the eldest entries until the total of remaining entries is at or below the requested size. @param maxSize the maximum size of the cache before returning. May be -1 to evict even 0-sized elements.
trimToSize
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/memory/LruCache.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/memory/LruCache.java
Apache-2.0
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override protected int sizeOf(Object key, CacheItem<String> value) { String data = value.getData(); return data.length(); }
{@link LruCache} for {@link String}. @author David Stemmer @author Mike Jancola @author SNI
sizeOf
java
stephanenicolas/robospice
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/memory/StringLruCache.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/memory/StringLruCache.java
Apache-2.0
protected int getThreadCount() { return DEFAULT_THREAD_COUNT; }
Number of threads used internally by this spice manager to communicate commands to the SpiceService it is bound to @return the thread count. Defaults to {@link #DEFAULT_THREAD_COUNT}.
getThreadCount
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0
public synchronized void start(final Context context) { this.contextWeakReference = new WeakReference<Context>(context); if (isStarted()) { throw new IllegalStateException("Already started."); } else { executorService = Executors.newFixedThreadPool(getThreadCount(), new MinPriorityThreadFactory()); // start the binding to the service runner = new Thread(this, SPICE_MANAGER_THREAD_NAME_PREFIX + spiceManagerThreadIndex++); runner.setPriority(Thread.MIN_PRIORITY); isStopped = false; runner.start(); Ln.d("SpiceManager started."); } }
Start the {@link SpiceManager}. It will bind asynchronously to the {@link SpiceService}. @param context a context that will be used to bind to the service. Typically, the Activity or Fragment that needs to interact with the {@link SpiceService}.
start
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0
public synchronized boolean isStarted() { return !isStopped; }
Method is synchronized with {@link #start(Context)}. @return whether or not the {@link SpiceManager} is started.
isStarted
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0
public int getRequestToLaunchCount() { return mapRequestToLaunchToRequestListener.size(); }
@return the number of current requests that should be launched ASAP (when the spice service is bound).
getRequestToLaunchCount
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0
public synchronized void shouldStop() { try { shouldStopAndJoin(DELAY_WAIT_FOR_RUNNER_TO_STOP); } catch (InterruptedException e) { Ln.e(e, "Exception when joining the runner that was stopping."); } }
Stops the {@link SpiceManager}. It will unbind from {@link SpiceService}. All request listeners that had been registered to listen to {@link SpiceRequest}s sent from this {@link SpiceManager} will be unregistered. None of them will be notified with the results of their {@link SpiceRequest}s. Unbinding will occur asynchronously.
shouldStop
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0
public synchronized void shouldStopAndJoin(final long timeOut) throws InterruptedException { if (!isStarted()) { throw new IllegalStateException("Not started yet"); } Ln.d("SpiceManager stopping. Joining"); this.isStopped = true; dontNotifyAnyRequestListenersInternal(); if (requestQueue.isEmpty()) { this.runner.interrupt(); } long start = System.currentTimeMillis(); try { this.runner.join(timeOut); } catch (InterruptedException e) { throw e; } finally { long end = System.currentTimeMillis(); Ln.d("Runner join time (ms) when should stop %d", end - start); } unbindFromService(); this.runner = null; this.executorService.shutdown(); this.contextWeakReference.clear(); Ln.d("SpiceManager stopped."); }
This is mostly a testing method. Stops the {@link SpiceManager}. It will unbind from {@link SpiceService}. All request listeners that had been registered to listen to {@link SpiceRequest}s sent from this {@link SpiceManager} will be unregistered. None of them will be notified with the results of their {@link SpiceRequest}s. Unbinding will occur syncrhonously : the method returns when all events have been unregistered and when main processing thread stops.
shouldStopAndJoin
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0
public <T> void addListenerIfPending(final Class<T> clazz, final Object requestCacheKey, final PendingRequestListener<T> requestListener) { addListenerIfPending(clazz, requestCacheKey, (RequestListener<T>) requestListener); }
Add listener to a pending request if it exists. If no such request exists, this method calls onRequestNotFound on the listener. If a request identified by clazz and requestCacheKey, it will receive an additional listener. @param clazz the class of the result of the pending request to look for. @param requestCacheKey the key used to store and retrieve the result of the request in the cache @param requestListener the listener to notify when the request will finish.
addListenerIfPending
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0
public <T> void execute(final SpiceRequest<T> request, final RequestListener<T> requestListener) { final CachedSpiceRequest<T> cachedSpiceRequest = new CachedSpiceRequest<T>(request, null, DurationInMillis.ALWAYS_RETURNED); execute(cachedSpiceRequest, requestListener); }
Execute a request, without using cache. No result from cache will be returned. The method {@link SpiceRequest#loadDataFromNetwork()} will always be invoked. The result will not be stored in cache. @param request the request to execute. @param requestListener the listener to notify when the request will finish.
execute
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0
public <T> void execute(final SpiceRequest<T> request, final Object requestCacheKey, final long cacheExpiryDuration, final RequestListener<T> requestListener) { final CachedSpiceRequest<T> cachedSpiceRequest = new CachedSpiceRequest<T>(request, requestCacheKey, cacheExpiryDuration); execute(cachedSpiceRequest, requestListener); }
Execute a request. Before invoking the method {@link SpiceRequest#loadDataFromNetwork()}, the cache will be checked : if a result has been cached with the cache key <i>requestCacheKey</i>, RoboSpice will consider the parameter <i>cacheExpiryDuration</i> to determine whether the result in the cache is expired or not. If it is not expired, then listeners will receive the data in cache. Otherwise, the method {@link SpiceRequest#loadDataFromNetwork()} will be invoked and the result will be stored in cache using the cache key <i>requestCacheKey</i>. @param request the request to execute @param requestCacheKey the key used to store and retrieve the result of the request in the cache @param cacheExpiryDuration duration in milliseconds after which the content of the cache will be considered to be expired. {@link DurationInMillis#ALWAYS_RETURNED} means data in cache is always returned if it exists. {@link DurationInMillis#ALWAYS_EXPIRED} means data in cache is never returned.(see {@link DurationInMillis}) @param requestListener the listener to notify when the request will finish
execute
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0
public <T> void execute(final CachedSpiceRequest<T> cachedSpiceRequest, final RequestListener<T> requestListener) { addRequestListenerToListOfRequestListeners(cachedSpiceRequest, requestListener); Ln.d("adding request to request queue"); this.requestQueue.add(cachedSpiceRequest); }
Execute a request, put the result in cache and register listeners to notify when request is finished. @param cachedSpiceRequest the request to execute. {@link CachedSpiceRequest} is a wrapper of {@link SpiceRequest} that contains cache key and cache duration @param requestListener the listener to notify when the request will finish
execute
java
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
https://github.com/stephanenicolas/robospice/blob/master/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java
Apache-2.0