repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/ProxyUtil.java | ProxyUtil.createCompositeServiceProxy | public static Object createCompositeServiceProxy(ClassLoader classLoader, Object[] services, boolean allowMultipleInheritance) {
return createCompositeServiceProxy(classLoader, services, null, allowMultipleInheritance);
} | java | public static Object createCompositeServiceProxy(ClassLoader classLoader, Object[] services, boolean allowMultipleInheritance) {
return createCompositeServiceProxy(classLoader, services, null, allowMultipleInheritance);
} | [
"public",
"static",
"Object",
"createCompositeServiceProxy",
"(",
"ClassLoader",
"classLoader",
",",
"Object",
"[",
"]",
"services",
",",
"boolean",
"allowMultipleInheritance",
")",
"{",
"return",
"createCompositeServiceProxy",
"(",
"classLoader",
",",
"services",
",",
... | Creates a composite service using all of the given
services.
@param classLoader the {@link ClassLoader}
@param services the service objects
@param allowMultipleInheritance whether or not to allow multiple inheritance
@return the object | [
"Creates",
"a",
"composite",
"service",
"using",
"all",
"of",
"the",
"given",
"services",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/ProxyUtil.java#L37-L39 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/ProxyUtil.java | ProxyUtil.createCompositeServiceProxy | public static Object createCompositeServiceProxy(ClassLoader classLoader, Object[] services, Class<?>[] serviceInterfaces, boolean allowMultipleInheritance) {
Set<Class<?>> interfaces = collectInterfaces(services, serviceInterfaces);
final Map<Class<?>, Object> serviceClassToInstanceMapping = buildServiceMap(services, allowMultipleInheritance, interfaces);
// now create the proxy
return Proxy.newProxyInstance(classLoader, interfaces.toArray(new Class<?>[0]), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Class<?> clazz = method.getDeclaringClass();
if (clazz == Object.class) {
return proxyObjectMethods(method, proxy, args);
}
return method.invoke(serviceClassToInstanceMapping.get(clazz), args);
}
});
} | java | public static Object createCompositeServiceProxy(ClassLoader classLoader, Object[] services, Class<?>[] serviceInterfaces, boolean allowMultipleInheritance) {
Set<Class<?>> interfaces = collectInterfaces(services, serviceInterfaces);
final Map<Class<?>, Object> serviceClassToInstanceMapping = buildServiceMap(services, allowMultipleInheritance, interfaces);
// now create the proxy
return Proxy.newProxyInstance(classLoader, interfaces.toArray(new Class<?>[0]), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Class<?> clazz = method.getDeclaringClass();
if (clazz == Object.class) {
return proxyObjectMethods(method, proxy, args);
}
return method.invoke(serviceClassToInstanceMapping.get(clazz), args);
}
});
} | [
"public",
"static",
"Object",
"createCompositeServiceProxy",
"(",
"ClassLoader",
"classLoader",
",",
"Object",
"[",
"]",
"services",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"serviceInterfaces",
",",
"boolean",
"allowMultipleInheritance",
")",
"{",
"Set",
"<",
"Cl... | Creates a composite service using all of the given
services and implementing the given interfaces.
@param classLoader the {@link ClassLoader}
@param services the service objects
@param serviceInterfaces the service interfaces
@param allowMultipleInheritance whether or not to allow multiple inheritance
@return the object | [
"Creates",
"a",
"composite",
"service",
"using",
"all",
"of",
"the",
"given",
"services",
"and",
"implementing",
"the",
"given",
"interfaces",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/ProxyUtil.java#L51-L66 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/spring/AutoJsonRpcClientProxyCreator.java | AutoJsonRpcClientProxyCreator.registerJsonProxyBean | private void registerJsonProxyBean(DefaultListableBeanFactory defaultListableBeanFactory, String className, String path) {
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
.rootBeanDefinition(JsonProxyFactoryBean.class)
.addPropertyValue("serviceUrl", appendBasePath(path))
.addPropertyValue("serviceInterface", className);
if (objectMapper != null) {
beanDefinitionBuilder.addPropertyValue("objectMapper", objectMapper);
}
if (contentType != null) {
beanDefinitionBuilder.addPropertyValue("contentType", contentType);
}
defaultListableBeanFactory.registerBeanDefinition(className + "-clientProxy", beanDefinitionBuilder.getBeanDefinition());
} | java | private void registerJsonProxyBean(DefaultListableBeanFactory defaultListableBeanFactory, String className, String path) {
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
.rootBeanDefinition(JsonProxyFactoryBean.class)
.addPropertyValue("serviceUrl", appendBasePath(path))
.addPropertyValue("serviceInterface", className);
if (objectMapper != null) {
beanDefinitionBuilder.addPropertyValue("objectMapper", objectMapper);
}
if (contentType != null) {
beanDefinitionBuilder.addPropertyValue("contentType", contentType);
}
defaultListableBeanFactory.registerBeanDefinition(className + "-clientProxy", beanDefinitionBuilder.getBeanDefinition());
} | [
"private",
"void",
"registerJsonProxyBean",
"(",
"DefaultListableBeanFactory",
"defaultListableBeanFactory",
",",
"String",
"className",
",",
"String",
"path",
")",
"{",
"BeanDefinitionBuilder",
"beanDefinitionBuilder",
"=",
"BeanDefinitionBuilder",
".",
"rootBeanDefinition",
... | Registers a new proxy bean with the bean factory. | [
"Registers",
"a",
"new",
"proxy",
"bean",
"with",
"the",
"bean",
"factory",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/spring/AutoJsonRpcClientProxyCreator.java#L76-L91 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/spring/AutoJsonRpcClientProxyCreator.java | AutoJsonRpcClientProxyCreator.appendBasePath | private String appendBasePath(String path) {
try {
return new URL(baseUrl, path).toString();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(format("Cannot combine URLs '%s' and '%s' to valid URL.", baseUrl, path), e);
}
} | java | private String appendBasePath(String path) {
try {
return new URL(baseUrl, path).toString();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(format("Cannot combine URLs '%s' and '%s' to valid URL.", baseUrl, path), e);
}
} | [
"private",
"String",
"appendBasePath",
"(",
"String",
"path",
")",
"{",
"try",
"{",
"return",
"new",
"URL",
"(",
"baseUrl",
",",
"path",
")",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"e",
")",
"{",
"throw",
"new",
"Il... | Appends the base path to the path found in the interface. | [
"Appends",
"the",
"base",
"path",
"to",
"the",
"path",
"found",
"in",
"the",
"interface",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/spring/AutoJsonRpcClientProxyCreator.java#L96-L102 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/ReflectionUtil.java | ReflectionUtil.findCandidateMethods | static Set<Method> findCandidateMethods(Class<?>[] classes, String name) {
StringBuilder sb = new StringBuilder();
for (Class<?> clazz : classes) {
sb.append(clazz.getName()).append("::");
}
String cacheKey = sb.append(name).toString();
if (methodCache.containsKey(cacheKey)) {
return methodCache.get(cacheKey);
}
Set<Method> methods = new HashSet<>();
for (Class<?> clazz : classes) {
for (Method method : clazz.getMethods()) {
if (method.isAnnotationPresent(JsonRpcMethod.class)) {
JsonRpcMethod methodAnnotation = method.getAnnotation(JsonRpcMethod.class);
if (methodAnnotation.required()) {
if (methodAnnotation.value().equals(name)) {
methods.add(method);
}
} else if (methodAnnotation.value().equals(name) || method.getName().equals(name)) {
methods.add(method);
}
} else if (method.getName().equals(name)) {
methods.add(method);
}
}
}
methods = Collections.unmodifiableSet(methods);
methodCache.put(cacheKey, methods);
return methods;
} | java | static Set<Method> findCandidateMethods(Class<?>[] classes, String name) {
StringBuilder sb = new StringBuilder();
for (Class<?> clazz : classes) {
sb.append(clazz.getName()).append("::");
}
String cacheKey = sb.append(name).toString();
if (methodCache.containsKey(cacheKey)) {
return methodCache.get(cacheKey);
}
Set<Method> methods = new HashSet<>();
for (Class<?> clazz : classes) {
for (Method method : clazz.getMethods()) {
if (method.isAnnotationPresent(JsonRpcMethod.class)) {
JsonRpcMethod methodAnnotation = method.getAnnotation(JsonRpcMethod.class);
if (methodAnnotation.required()) {
if (methodAnnotation.value().equals(name)) {
methods.add(method);
}
} else if (methodAnnotation.value().equals(name) || method.getName().equals(name)) {
methods.add(method);
}
} else if (method.getName().equals(name)) {
methods.add(method);
}
}
}
methods = Collections.unmodifiableSet(methods);
methodCache.put(cacheKey, methods);
return methods;
} | [
"static",
"Set",
"<",
"Method",
">",
"findCandidateMethods",
"(",
"Class",
"<",
"?",
">",
"[",
"]",
"classes",
",",
"String",
"name",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"cl... | Finds methods with the given name on the given class.
@param classes the classes
@param name the method name
@return the methods | [
"Finds",
"methods",
"with",
"the",
"given",
"name",
"on",
"the",
"given",
"class",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/ReflectionUtil.java#L35-L65 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/ReflectionUtil.java | ReflectionUtil.parseArguments | public static Object parseArguments(Method method, Object[] arguments) {
JsonRpcParamsPassMode paramsPassMode = JsonRpcParamsPassMode.AUTO;
JsonRpcMethod jsonRpcMethod = getAnnotation(method, JsonRpcMethod.class);
if (jsonRpcMethod != null)
paramsPassMode = jsonRpcMethod.paramsPassMode();
Map<String, Object> namedParams = getNamedParameters(method, arguments);
switch (paramsPassMode) {
case ARRAY:
if (namedParams.size() > 0) {
Object[] parsed = new Object[namedParams.size()];
int i = 0;
for (Object value : namedParams.values()) {
parsed[i++] = value;
}
return parsed;
} else {
return arguments != null ? arguments : new Object[]{};
}
case OBJECT:
if (namedParams.size() > 0) {
return namedParams;
} else {
if (arguments == null) {
return new Object[]{};
}
throw new IllegalArgumentException(
"OBJECT parameters pass mode is impossible without declaring JsonRpcParam annotations for all parameters on method "
+ method.getName());
}
case AUTO:
default:
if (namedParams.size() > 0) {
return namedParams;
} else {
return arguments != null ? arguments : new Object[]{};
}
}
} | java | public static Object parseArguments(Method method, Object[] arguments) {
JsonRpcParamsPassMode paramsPassMode = JsonRpcParamsPassMode.AUTO;
JsonRpcMethod jsonRpcMethod = getAnnotation(method, JsonRpcMethod.class);
if (jsonRpcMethod != null)
paramsPassMode = jsonRpcMethod.paramsPassMode();
Map<String, Object> namedParams = getNamedParameters(method, arguments);
switch (paramsPassMode) {
case ARRAY:
if (namedParams.size() > 0) {
Object[] parsed = new Object[namedParams.size()];
int i = 0;
for (Object value : namedParams.values()) {
parsed[i++] = value;
}
return parsed;
} else {
return arguments != null ? arguments : new Object[]{};
}
case OBJECT:
if (namedParams.size() > 0) {
return namedParams;
} else {
if (arguments == null) {
return new Object[]{};
}
throw new IllegalArgumentException(
"OBJECT parameters pass mode is impossible without declaring JsonRpcParam annotations for all parameters on method "
+ method.getName());
}
case AUTO:
default:
if (namedParams.size() > 0) {
return namedParams;
} else {
return arguments != null ? arguments : new Object[]{};
}
}
} | [
"public",
"static",
"Object",
"parseArguments",
"(",
"Method",
"method",
",",
"Object",
"[",
"]",
"arguments",
")",
"{",
"JsonRpcParamsPassMode",
"paramsPassMode",
"=",
"JsonRpcParamsPassMode",
".",
"AUTO",
";",
"JsonRpcMethod",
"jsonRpcMethod",
"=",
"getAnnotation",
... | Parses the given arguments for the given method optionally
turning them into named parameters.
@param method the method
@param arguments the arguments
@return the parsed arguments | [
"Parses",
"the",
"given",
"arguments",
"for",
"the",
"given",
"method",
"optionally",
"turning",
"them",
"into",
"named",
"parameters",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/ReflectionUtil.java#L190-L230 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/JsonRpcHttpAsyncClient.java | JsonRpcHttpAsyncClient.addHeaders | private void addHeaders(HttpRequest request, Map<String, String> headers) {
for (Map.Entry<String, String> key : headers.entrySet()) {
request.addHeader(key.getKey(), key.getValue());
}
} | java | private void addHeaders(HttpRequest request, Map<String, String> headers) {
for (Map.Entry<String, String> key : headers.entrySet()) {
request.addHeader(key.getKey(), key.getValue());
}
} | [
"private",
"void",
"addHeaders",
"(",
"HttpRequest",
"request",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"key",
":",
"headers",
".",
"entrySet",
"(",
")",
... | Set the request headers.
@param request the request object
@param headers to be used | [
"Set",
"the",
"request",
"headers",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcHttpAsyncClient.java#L261-L265 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java | JsonRpcClient.invokeAndReadResponse | private Object invokeAndReadResponse(String methodName, Object argument, Type returnType, OutputStream output, InputStream input, String id) throws Throwable {
invoke(methodName, argument, output, id);
return readResponse(returnType, input, id);
} | java | private Object invokeAndReadResponse(String methodName, Object argument, Type returnType, OutputStream output, InputStream input, String id) throws Throwable {
invoke(methodName, argument, output, id);
return readResponse(returnType, input, id);
} | [
"private",
"Object",
"invokeAndReadResponse",
"(",
"String",
"methodName",
",",
"Object",
"argument",
",",
"Type",
"returnType",
",",
"OutputStream",
"output",
",",
"InputStream",
"input",
",",
"String",
"id",
")",
"throws",
"Throwable",
"{",
"invoke",
"(",
"met... | Invokes the given method on the remote service
passing the given arguments and reads a response.
@param methodName the method to invoke
@param argument the argument to pass to the method
@param returnType the expected return type
@param output the {@link OutputStream} to write to
@param input the {@link InputStream} to read from
@param id id to send with the JSON-RPC request
@return the returned Object
@throws Throwable if there is an error
while reading the response
@see #writeRequest(String, Object, OutputStream, String) | [
"Invokes",
"the",
"given",
"method",
"on",
"the",
"remote",
"service",
"passing",
"the",
"given",
"arguments",
"and",
"reads",
"a",
"response",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java#L157-L160 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java | JsonRpcClient.readResponse | private Object readResponse(Type returnType, InputStream input, String id) throws Throwable {
ReadContext context = ReadContext.getReadContext(input, mapper);
ObjectNode jsonObject = getValidResponse(id, context);
notifyAnswerListener(jsonObject);
handleErrorResponse(jsonObject);
if (hasResult(jsonObject)) {
if (isReturnTypeInvalid(returnType)) {
return null;
}
return constructResponseObject(returnType, jsonObject);
}
// no return type
return null;
} | java | private Object readResponse(Type returnType, InputStream input, String id) throws Throwable {
ReadContext context = ReadContext.getReadContext(input, mapper);
ObjectNode jsonObject = getValidResponse(id, context);
notifyAnswerListener(jsonObject);
handleErrorResponse(jsonObject);
if (hasResult(jsonObject)) {
if (isReturnTypeInvalid(returnType)) {
return null;
}
return constructResponseObject(returnType, jsonObject);
}
// no return type
return null;
} | [
"private",
"Object",
"readResponse",
"(",
"Type",
"returnType",
",",
"InputStream",
"input",
",",
"String",
"id",
")",
"throws",
"Throwable",
"{",
"ReadContext",
"context",
"=",
"ReadContext",
".",
"getReadContext",
"(",
"input",
",",
"mapper",
")",
";",
"Obje... | Reads a JSON-PRC response from the server. This blocks until
a response is received. If an id is given, responses that do
not correspond, are disregarded.
@param returnType the expected return type
@param input the {@link InputStream} to read from
@param id The id used to compare the response with.
@return the object returned by the JSON-RPC response
@throws Throwable on error | [
"Reads",
"a",
"JSON",
"-",
"PRC",
"response",
"from",
"the",
"server",
".",
"This",
"blocks",
"until",
"a",
"response",
"is",
"received",
".",
"If",
"an",
"id",
"is",
"given",
"responses",
"that",
"do",
"not",
"correspond",
"are",
"disregarded",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java#L191-L207 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java | JsonRpcClient.internalCreateRequest | private ObjectNode internalCreateRequest(String methodName, Object arguments, String id) {
final ObjectNode request = mapper.createObjectNode();
addId(id, request);
addProtocolAndMethod(methodName, request);
addParameters(arguments, request);
addAdditionalHeaders(request);
notifyBeforeRequestListener(request);
return request;
} | java | private ObjectNode internalCreateRequest(String methodName, Object arguments, String id) {
final ObjectNode request = mapper.createObjectNode();
addId(id, request);
addProtocolAndMethod(methodName, request);
addParameters(arguments, request);
addAdditionalHeaders(request);
notifyBeforeRequestListener(request);
return request;
} | [
"private",
"ObjectNode",
"internalCreateRequest",
"(",
"String",
"methodName",
",",
"Object",
"arguments",
",",
"String",
"id",
")",
"{",
"final",
"ObjectNode",
"request",
"=",
"mapper",
".",
"createObjectNode",
"(",
")",
";",
"addId",
"(",
"id",
",",
"request... | Creates RPC request.
@param methodName the method name
@param arguments the arguments
@param id the optional id
@return Jackson request object | [
"Creates",
"RPC",
"request",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java#L339-L347 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java | JsonRpcClient.invokeNotification | public void invokeNotification(String methodName, Object argument, OutputStream output) throws IOException {
writeRequest(methodName, argument, output, null);
output.flush();
} | java | public void invokeNotification(String methodName, Object argument, OutputStream output) throws IOException {
writeRequest(methodName, argument, output, null);
output.flush();
} | [
"public",
"void",
"invokeNotification",
"(",
"String",
"methodName",
",",
"Object",
"argument",
",",
"OutputStream",
"output",
")",
"throws",
"IOException",
"{",
"writeRequest",
"(",
"methodName",
",",
"argument",
",",
"output",
",",
"null",
")",
";",
"output",
... | Invokes the given method on the remote service passing
the given argument without reading or expecting a return
response.
@param methodName the method to invoke
@param argument the argument to pass to the method
@param output the {@link OutputStream} to write to
@throws IOException on error
@see #writeRequest(String, Object, OutputStream, String) | [
"Invokes",
"the",
"given",
"method",
"on",
"the",
"remote",
"service",
"passing",
"the",
"given",
"argument",
"without",
"reading",
"or",
"expecting",
"a",
"return",
"response",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java#L501-L504 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/spring/rest/MappingJacksonRPC2HttpMessageConverter.java | MappingJacksonRPC2HttpMessageConverter.getJsonEncoding | private JsonEncoding getJsonEncoding(MediaType contentType) {
if (contentType != null && contentType.getCharset() != null) {
Charset charset = contentType.getCharset();
for (JsonEncoding encoding : JsonEncoding.values()) {
if (charset.name().equals(encoding.getJavaName())) {
return encoding;
}
}
}
return JsonEncoding.UTF8;
} | java | private JsonEncoding getJsonEncoding(MediaType contentType) {
if (contentType != null && contentType.getCharset() != null) {
Charset charset = contentType.getCharset();
for (JsonEncoding encoding : JsonEncoding.values()) {
if (charset.name().equals(encoding.getJavaName())) {
return encoding;
}
}
}
return JsonEncoding.UTF8;
} | [
"private",
"JsonEncoding",
"getJsonEncoding",
"(",
"MediaType",
"contentType",
")",
"{",
"if",
"(",
"contentType",
"!=",
"null",
"&&",
"contentType",
".",
"getCharset",
"(",
")",
"!=",
"null",
")",
"{",
"Charset",
"charset",
"=",
"contentType",
".",
"getCharse... | Determine the JSON encoding to use for the given content type.
@param contentType the media type as requested by the caller
@return the JSON encoding to use (never <code>null</code>) | [
"Determine",
"the",
"JSON",
"encoding",
"to",
"use",
"for",
"the",
"given",
"content",
"type",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/spring/rest/MappingJacksonRPC2HttpMessageConverter.java#L173-L183 | train |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/spring/AutoJsonRpcServiceExporter.java | AutoJsonRpcServiceExporter.registerServiceProxy | private void registerServiceProxy(DefaultListableBeanFactory defaultListableBeanFactory, String servicePath, String serviceBeanName) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(JsonServiceExporter.class).addPropertyReference("service", serviceBeanName);
BeanDefinition serviceBeanDefinition = findBeanDefinition(defaultListableBeanFactory, serviceBeanName);
for (Class<?> currentInterface : getBeanInterfaces(serviceBeanDefinition, defaultListableBeanFactory.getBeanClassLoader())) {
if (currentInterface.isAnnotationPresent(JsonRpcService.class)) {
String serviceInterface = currentInterface.getName();
logger.debug("Registering interface '{}' for JSON-RPC bean [{}].", serviceInterface, serviceBeanName);
builder.addPropertyValue("serviceInterface", serviceInterface);
break;
}
}
if (objectMapper != null) {
builder.addPropertyValue("objectMapper", objectMapper);
}
if (errorResolver != null) {
builder.addPropertyValue("errorResolver", errorResolver);
}
if (invocationListener != null) {
builder.addPropertyValue("invocationListener", invocationListener);
}
if (registerTraceInterceptor != null) {
builder.addPropertyValue("registerTraceInterceptor", registerTraceInterceptor);
}
if (httpStatusCodeProvider != null) {
builder.addPropertyValue("httpStatusCodeProvider", httpStatusCodeProvider);
}
if (convertedParameterTransformer != null) {
builder.addPropertyValue("convertedParameterTransformer", convertedParameterTransformer);
}
builder.addPropertyValue("backwardsCompatible", backwardsCompatible);
builder.addPropertyValue("rethrowExceptions", rethrowExceptions);
builder.addPropertyValue("allowExtraParams", allowExtraParams);
builder.addPropertyValue("allowLessParams", allowLessParams);
defaultListableBeanFactory.registerBeanDefinition(servicePath, builder.getBeanDefinition());
} | java | private void registerServiceProxy(DefaultListableBeanFactory defaultListableBeanFactory, String servicePath, String serviceBeanName) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(JsonServiceExporter.class).addPropertyReference("service", serviceBeanName);
BeanDefinition serviceBeanDefinition = findBeanDefinition(defaultListableBeanFactory, serviceBeanName);
for (Class<?> currentInterface : getBeanInterfaces(serviceBeanDefinition, defaultListableBeanFactory.getBeanClassLoader())) {
if (currentInterface.isAnnotationPresent(JsonRpcService.class)) {
String serviceInterface = currentInterface.getName();
logger.debug("Registering interface '{}' for JSON-RPC bean [{}].", serviceInterface, serviceBeanName);
builder.addPropertyValue("serviceInterface", serviceInterface);
break;
}
}
if (objectMapper != null) {
builder.addPropertyValue("objectMapper", objectMapper);
}
if (errorResolver != null) {
builder.addPropertyValue("errorResolver", errorResolver);
}
if (invocationListener != null) {
builder.addPropertyValue("invocationListener", invocationListener);
}
if (registerTraceInterceptor != null) {
builder.addPropertyValue("registerTraceInterceptor", registerTraceInterceptor);
}
if (httpStatusCodeProvider != null) {
builder.addPropertyValue("httpStatusCodeProvider", httpStatusCodeProvider);
}
if (convertedParameterTransformer != null) {
builder.addPropertyValue("convertedParameterTransformer", convertedParameterTransformer);
}
builder.addPropertyValue("backwardsCompatible", backwardsCompatible);
builder.addPropertyValue("rethrowExceptions", rethrowExceptions);
builder.addPropertyValue("allowExtraParams", allowExtraParams);
builder.addPropertyValue("allowLessParams", allowLessParams);
defaultListableBeanFactory.registerBeanDefinition(servicePath, builder.getBeanDefinition());
} | [
"private",
"void",
"registerServiceProxy",
"(",
"DefaultListableBeanFactory",
"defaultListableBeanFactory",
",",
"String",
"servicePath",
",",
"String",
"serviceBeanName",
")",
"{",
"BeanDefinitionBuilder",
"builder",
"=",
"BeanDefinitionBuilder",
".",
"rootBeanDefinition",
"... | Registers the new beans with the bean factory. | [
"Registers",
"the",
"new",
"beans",
"with",
"the",
"bean",
"factory",
"."
] | d749762c9295b92d893677a8c7be2a14dd43b3bb | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/spring/AutoJsonRpcServiceExporter.java#L121-L162 | train |
requery/requery | requery-processor/src/main/java/io/requery/processor/EntityGraph.java | EntityGraph.referencingEntity | Optional<EntityDescriptor> referencingEntity(AttributeDescriptor attribute) {
if (!Names.isEmpty(attribute.referencedTable())) {
// match by table name
return entities.values().stream()
.filter(entity -> entity.tableName().equalsIgnoreCase(attribute.referencedTable()))
.findFirst();
} else if (!Names.isEmpty(attribute.referencedType())) {
// match by type name
Optional<TypeKind> primitiveType = Stream.of(TypeKind.values())
.filter(TypeKind::isPrimitive)
.filter(kind -> kind.toString().toLowerCase().equals(attribute.referencedType()))
.findFirst();
if (!primitiveType.isPresent()) {
QualifiedName referencedType = new QualifiedName(attribute.referencedType());
return entityByName(referencedType);
} // else attribute is basic foreign key and not referring to an entity
} else {
TypeMirror referencedType = attribute.typeMirror();
if (attribute.isIterable()) {
referencedType = collectionElementType(referencedType);
}
TypeElement referencedElement = (TypeElement) types.asElement(referencedType);
if (referencedElement != null) {
String referencedName = referencedElement.getSimpleName().toString();
return entities.values().stream()
.filter(entity -> match(entity, referencedName))
.findFirst();
}
}
return Optional.empty();
} | java | Optional<EntityDescriptor> referencingEntity(AttributeDescriptor attribute) {
if (!Names.isEmpty(attribute.referencedTable())) {
// match by table name
return entities.values().stream()
.filter(entity -> entity.tableName().equalsIgnoreCase(attribute.referencedTable()))
.findFirst();
} else if (!Names.isEmpty(attribute.referencedType())) {
// match by type name
Optional<TypeKind> primitiveType = Stream.of(TypeKind.values())
.filter(TypeKind::isPrimitive)
.filter(kind -> kind.toString().toLowerCase().equals(attribute.referencedType()))
.findFirst();
if (!primitiveType.isPresent()) {
QualifiedName referencedType = new QualifiedName(attribute.referencedType());
return entityByName(referencedType);
} // else attribute is basic foreign key and not referring to an entity
} else {
TypeMirror referencedType = attribute.typeMirror();
if (attribute.isIterable()) {
referencedType = collectionElementType(referencedType);
}
TypeElement referencedElement = (TypeElement) types.asElement(referencedType);
if (referencedElement != null) {
String referencedName = referencedElement.getSimpleName().toString();
return entities.values().stream()
.filter(entity -> match(entity, referencedName))
.findFirst();
}
}
return Optional.empty();
} | [
"Optional",
"<",
"EntityDescriptor",
">",
"referencingEntity",
"(",
"AttributeDescriptor",
"attribute",
")",
"{",
"if",
"(",
"!",
"Names",
".",
"isEmpty",
"(",
"attribute",
".",
"referencedTable",
"(",
")",
")",
")",
"{",
"// match by table name",
"return",
"ent... | Given a association attribute in an Entity find the Entity the attribute is referencing.
@param attribute association attribute
@return Optional Entity type being referenced. | [
"Given",
"a",
"association",
"attribute",
"in",
"an",
"Entity",
"find",
"the",
"Entity",
"the",
"attribute",
"is",
"referencing",
"."
] | 3070590c2ef76bb7062570bf9df03cd482db024a | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery-processor/src/main/java/io/requery/processor/EntityGraph.java#L94-L125 | train |
requery/requery | requery-processor/src/main/java/io/requery/processor/EntityGraph.java | EntityGraph.referencingAttribute | Optional<? extends AttributeDescriptor> referencingAttribute(AttributeDescriptor attribute,
EntityDescriptor referenced) {
String referencedColumn = attribute.referencedColumn();
if (Names.isEmpty(referencedColumn)) {
// using the id
List<AttributeDescriptor> keys = referenced.attributes().stream()
.filter(AttributeDescriptor::isKey).collect(Collectors.toList());
if (keys.size() == 1) {
return Optional.of(keys.get(0));
} else {
return keys.stream()
.filter(other -> other.typeMirror().equals(attribute.typeMirror()))
.findFirst();
}
} else {
return referenced.attributes().stream()
.filter(other -> other.name().equals(referencedColumn))
.findFirst();
}
} | java | Optional<? extends AttributeDescriptor> referencingAttribute(AttributeDescriptor attribute,
EntityDescriptor referenced) {
String referencedColumn = attribute.referencedColumn();
if (Names.isEmpty(referencedColumn)) {
// using the id
List<AttributeDescriptor> keys = referenced.attributes().stream()
.filter(AttributeDescriptor::isKey).collect(Collectors.toList());
if (keys.size() == 1) {
return Optional.of(keys.get(0));
} else {
return keys.stream()
.filter(other -> other.typeMirror().equals(attribute.typeMirror()))
.findFirst();
}
} else {
return referenced.attributes().stream()
.filter(other -> other.name().equals(referencedColumn))
.findFirst();
}
} | [
"Optional",
"<",
"?",
"extends",
"AttributeDescriptor",
">",
"referencingAttribute",
"(",
"AttributeDescriptor",
"attribute",
",",
"EntityDescriptor",
"referenced",
")",
"{",
"String",
"referencedColumn",
"=",
"attribute",
".",
"referencedColumn",
"(",
")",
";",
"if",... | Given an attribute in a given type finds the corresponding attribute that it is referencing
in that referencing type.
@param attribute attribute
@param referenced type being referenced
@return optional element it references | [
"Given",
"an",
"attribute",
"in",
"a",
"given",
"type",
"finds",
"the",
"corresponding",
"attribute",
"that",
"it",
"is",
"referencing",
"in",
"that",
"referencing",
"type",
"."
] | 3070590c2ef76bb7062570bf9df03cd482db024a | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery-processor/src/main/java/io/requery/processor/EntityGraph.java#L140-L160 | train |
requery/requery | requery-processor/src/main/java/io/requery/processor/EntityGraph.java | EntityGraph.mappedAttributes | Set<AttributeDescriptor> mappedAttributes(EntityDescriptor entity,
AttributeDescriptor attribute,
EntityDescriptor referenced) {
String mappedBy = attribute.mappedBy();
if (Names.isEmpty(mappedBy)) {
return referenced.attributes().stream()
.filter(other -> other.cardinality() != null)
.filter(other -> referencingEntity(other).isPresent())
.filter(other -> referencingEntity(other)
.orElseThrow(IllegalStateException::new) == entity)
.collect(Collectors.toSet());
} else {
return referenced.attributes().stream()
.filter(other -> other.name().equals(mappedBy))
.collect(Collectors.toSet());
}
} | java | Set<AttributeDescriptor> mappedAttributes(EntityDescriptor entity,
AttributeDescriptor attribute,
EntityDescriptor referenced) {
String mappedBy = attribute.mappedBy();
if (Names.isEmpty(mappedBy)) {
return referenced.attributes().stream()
.filter(other -> other.cardinality() != null)
.filter(other -> referencingEntity(other).isPresent())
.filter(other -> referencingEntity(other)
.orElseThrow(IllegalStateException::new) == entity)
.collect(Collectors.toSet());
} else {
return referenced.attributes().stream()
.filter(other -> other.name().equals(mappedBy))
.collect(Collectors.toSet());
}
} | [
"Set",
"<",
"AttributeDescriptor",
">",
"mappedAttributes",
"(",
"EntityDescriptor",
"entity",
",",
"AttributeDescriptor",
"attribute",
",",
"EntityDescriptor",
"referenced",
")",
"{",
"String",
"mappedBy",
"=",
"attribute",
".",
"mappedBy",
"(",
")",
";",
"if",
"... | Given an association in an entity find the attributes it maps onto in the referenced entity.
@param entity entity owning the attribute
@param attribute association attribute
@param referenced type being referenced
@return set of mapped attributes | [
"Given",
"an",
"association",
"in",
"an",
"entity",
"find",
"the",
"attributes",
"it",
"maps",
"onto",
"in",
"the",
"referenced",
"entity",
"."
] | 3070590c2ef76bb7062570bf9df03cd482db024a | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery-processor/src/main/java/io/requery/processor/EntityGraph.java#L170-L186 | train |
requery/requery | requery-android/src/main/java/io/requery/android/sqlite/BasePreparedStatement.java | BasePreparedStatement.bindBlobLiteral | protected void bindBlobLiteral(int index, byte[] value) {
if (blobLiterals == null) {
blobLiterals = new LinkedHashMap<>();
}
blobLiterals.put(index, value);
} | java | protected void bindBlobLiteral(int index, byte[] value) {
if (blobLiterals == null) {
blobLiterals = new LinkedHashMap<>();
}
blobLiterals.put(index, value);
} | [
"protected",
"void",
"bindBlobLiteral",
"(",
"int",
"index",
",",
"byte",
"[",
"]",
"value",
")",
"{",
"if",
"(",
"blobLiterals",
"==",
"null",
")",
"{",
"blobLiterals",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"}",
"blobLiterals",
".",
"put",
... | inlines a blob literal into the sql statement since it can't be used as bind parameter | [
"inlines",
"a",
"blob",
"literal",
"into",
"the",
"sql",
"statement",
"since",
"it",
"can",
"t",
"be",
"used",
"as",
"bind",
"parameter"
] | 3070590c2ef76bb7062570bf9df03cd482db024a | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery-android/src/main/java/io/requery/android/sqlite/BasePreparedStatement.java#L115-L120 | train |
requery/requery | requery/src/main/java/io/requery/sql/SchemaModifier.java | SchemaModifier.createIndexes | public void createIndexes(Connection connection, TableCreationMode mode) {
ArrayList<Type<?>> sorted = sortTypes();
for (Type<?> type : sorted) {
createIndexes(connection, mode, type);
}
} | java | public void createIndexes(Connection connection, TableCreationMode mode) {
ArrayList<Type<?>> sorted = sortTypes();
for (Type<?> type : sorted) {
createIndexes(connection, mode, type);
}
} | [
"public",
"void",
"createIndexes",
"(",
"Connection",
"connection",
",",
"TableCreationMode",
"mode",
")",
"{",
"ArrayList",
"<",
"Type",
"<",
"?",
">",
">",
"sorted",
"=",
"sortTypes",
"(",
")",
";",
"for",
"(",
"Type",
"<",
"?",
">",
"type",
":",
"so... | Creates all indexes in the model.
@param connection to use
@param mode creation mode.
@throws TableModificationException if the creation fails. | [
"Creates",
"all",
"indexes",
"in",
"the",
"model",
"."
] | 3070590c2ef76bb7062570bf9df03cd482db024a | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery/src/main/java/io/requery/sql/SchemaModifier.java#L173-L178 | train |
requery/requery | requery/src/main/java/io/requery/sql/SchemaModifier.java | SchemaModifier.createTablesString | public String createTablesString(TableCreationMode mode) {
ArrayList<Type<?>> sorted = sortTypes();
StringBuilder sb = new StringBuilder();
for (Type<?> type : sorted) {
String sql = tableCreateStatement(type, mode);
sb.append(sql);
sb.append(";\n");
}
return sb.toString();
} | java | public String createTablesString(TableCreationMode mode) {
ArrayList<Type<?>> sorted = sortTypes();
StringBuilder sb = new StringBuilder();
for (Type<?> type : sorted) {
String sql = tableCreateStatement(type, mode);
sb.append(sql);
sb.append(";\n");
}
return sb.toString();
} | [
"public",
"String",
"createTablesString",
"(",
"TableCreationMode",
"mode",
")",
"{",
"ArrayList",
"<",
"Type",
"<",
"?",
">",
">",
"sorted",
"=",
"sortTypes",
"(",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
... | Convenience method to generated the create table statements as a string.
@param mode table creation mode
@return DDL string | [
"Convenience",
"method",
"to",
"generated",
"the",
"create",
"table",
"statements",
"as",
"a",
"string",
"."
] | 3070590c2ef76bb7062570bf9df03cd482db024a | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery/src/main/java/io/requery/sql/SchemaModifier.java#L186-L195 | train |
requery/requery | requery/src/main/java/io/requery/sql/SchemaModifier.java | SchemaModifier.dropTables | public void dropTables() {
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
ArrayList<Type<?>> reversed = sortTypes();
Collections.reverse(reversed);
executeDropStatements(statement, reversed);
} catch (SQLException e) {
throw new TableModificationException(e);
}
} | java | public void dropTables() {
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
ArrayList<Type<?>> reversed = sortTypes();
Collections.reverse(reversed);
executeDropStatements(statement, reversed);
} catch (SQLException e) {
throw new TableModificationException(e);
}
} | [
"public",
"void",
"dropTables",
"(",
")",
"{",
"try",
"(",
"Connection",
"connection",
"=",
"getConnection",
"(",
")",
";",
"Statement",
"statement",
"=",
"connection",
".",
"createStatement",
"(",
")",
")",
"{",
"ArrayList",
"<",
"Type",
"<",
"?",
">",
... | Drop all tables in the schema. Note if the platform supports if exists that will be used in
the statement, if not and the table doesn't exist an exception will be thrown. | [
"Drop",
"all",
"tables",
"in",
"the",
"schema",
".",
"Note",
"if",
"the",
"platform",
"supports",
"if",
"exists",
"that",
"will",
"be",
"used",
"in",
"the",
"statement",
"if",
"not",
"and",
"the",
"table",
"doesn",
"t",
"exist",
"an",
"exception",
"will"... | 3070590c2ef76bb7062570bf9df03cd482db024a | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery/src/main/java/io/requery/sql/SchemaModifier.java#L201-L210 | train |
requery/requery | requery/src/main/java/io/requery/sql/SchemaModifier.java | SchemaModifier.dropTable | public void dropTable(Type<?> type) {
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
executeDropStatements(statement, Collections.<Type<?>>singletonList(type));
} catch (SQLException e) {
throw new TableModificationException(e);
}
} | java | public void dropTable(Type<?> type) {
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
executeDropStatements(statement, Collections.<Type<?>>singletonList(type));
} catch (SQLException e) {
throw new TableModificationException(e);
}
} | [
"public",
"void",
"dropTable",
"(",
"Type",
"<",
"?",
">",
"type",
")",
"{",
"try",
"(",
"Connection",
"connection",
"=",
"getConnection",
"(",
")",
";",
"Statement",
"statement",
"=",
"connection",
".",
"createStatement",
"(",
")",
")",
"{",
"executeDropS... | Drops a single table in the schema. | [
"Drops",
"a",
"single",
"table",
"in",
"the",
"schema",
"."
] | 3070590c2ef76bb7062570bf9df03cd482db024a | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery/src/main/java/io/requery/sql/SchemaModifier.java#L215-L222 | train |
requery/requery | requery/src/main/java/io/requery/sql/SchemaModifier.java | SchemaModifier.tableCreateStatement | public <T> String tableCreateStatement(Type<T> type, TableCreationMode mode) {
String tableName = type.getName();
QueryBuilder qb = createQueryBuilder();
qb.keyword(CREATE);
if (type.getTableCreateAttributes() != null) {
for (String attribute : type.getTableCreateAttributes()) {
qb.append(attribute, true);
}
}
qb.keyword(TABLE);
if (mode == TableCreationMode.CREATE_NOT_EXISTS) {
qb.keyword(IF, NOT, EXISTS);
}
qb.tableName(tableName);
qb.openParenthesis();
int index = 0;
// columns to define first
Predicate<Attribute> filter = new Predicate<Attribute>() {
@Override
public boolean test(Attribute value) {
if (value.isVersion() &&
!platform.versionColumnDefinition().createColumn()) {
return false;
}
if (platform.supportsInlineForeignKeyReference()) {
return !value.isForeignKey() && !value.isAssociation();
} else {
return value.isForeignKey() || !value.isAssociation();
}
}
};
Set<Attribute<T, ?>> attributes = type.getAttributes();
for (Attribute attribute : attributes) {
if (filter.test(attribute)) {
if (index > 0) {
qb.comma();
}
createColumn(qb, attribute);
index++;
}
}
// foreign keys
for (Attribute attribute : attributes) {
if (attribute.isForeignKey()) {
if (index > 0) {
qb.comma();
}
createForeignKeyColumn(qb, attribute, true, false);
index++;
}
}
// composite primary key
if(type.getKeyAttributes().size() > 1) {
if (index > 0) {
qb.comma();
}
qb.keyword(PRIMARY, KEY);
qb.openParenthesis();
qb.commaSeparated(type.getKeyAttributes(),
new QueryBuilder.Appender<Attribute<T, ?>>() {
@Override
public void append(QueryBuilder qb, Attribute<T, ?> value) {
qb.attribute(value);
}
});
qb.closeParenthesis();
}
qb.closeParenthesis();
return qb.toString();
} | java | public <T> String tableCreateStatement(Type<T> type, TableCreationMode mode) {
String tableName = type.getName();
QueryBuilder qb = createQueryBuilder();
qb.keyword(CREATE);
if (type.getTableCreateAttributes() != null) {
for (String attribute : type.getTableCreateAttributes()) {
qb.append(attribute, true);
}
}
qb.keyword(TABLE);
if (mode == TableCreationMode.CREATE_NOT_EXISTS) {
qb.keyword(IF, NOT, EXISTS);
}
qb.tableName(tableName);
qb.openParenthesis();
int index = 0;
// columns to define first
Predicate<Attribute> filter = new Predicate<Attribute>() {
@Override
public boolean test(Attribute value) {
if (value.isVersion() &&
!platform.versionColumnDefinition().createColumn()) {
return false;
}
if (platform.supportsInlineForeignKeyReference()) {
return !value.isForeignKey() && !value.isAssociation();
} else {
return value.isForeignKey() || !value.isAssociation();
}
}
};
Set<Attribute<T, ?>> attributes = type.getAttributes();
for (Attribute attribute : attributes) {
if (filter.test(attribute)) {
if (index > 0) {
qb.comma();
}
createColumn(qb, attribute);
index++;
}
}
// foreign keys
for (Attribute attribute : attributes) {
if (attribute.isForeignKey()) {
if (index > 0) {
qb.comma();
}
createForeignKeyColumn(qb, attribute, true, false);
index++;
}
}
// composite primary key
if(type.getKeyAttributes().size() > 1) {
if (index > 0) {
qb.comma();
}
qb.keyword(PRIMARY, KEY);
qb.openParenthesis();
qb.commaSeparated(type.getKeyAttributes(),
new QueryBuilder.Appender<Attribute<T, ?>>() {
@Override
public void append(QueryBuilder qb, Attribute<T, ?> value) {
qb.attribute(value);
}
});
qb.closeParenthesis();
}
qb.closeParenthesis();
return qb.toString();
} | [
"public",
"<",
"T",
">",
"String",
"tableCreateStatement",
"(",
"Type",
"<",
"T",
">",
"type",
",",
"TableCreationMode",
"mode",
")",
"{",
"String",
"tableName",
"=",
"type",
".",
"getName",
"(",
")",
";",
"QueryBuilder",
"qb",
"=",
"createQueryBuilder",
"... | Generates the create table for a specific type.
@param type to generate the table statement
@param mode creation mode
@param <T> Type
@return create table sql string | [
"Generates",
"the",
"create",
"table",
"for",
"a",
"specific",
"type",
"."
] | 3070590c2ef76bb7062570bf9df03cd482db024a | https://github.com/requery/requery/blob/3070590c2ef76bb7062570bf9df03cd482db024a/requery/src/main/java/io/requery/sql/SchemaModifier.java#L391-L463 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/copy/SerializingCopier.java | SerializingCopier.copy | @Override
public T copy(final T obj) {
try {
return serializer.read(serializer.serialize(obj));
} catch (ClassNotFoundException e) {
throw new SerializerException("Copying failed.", e);
}
} | java | @Override
public T copy(final T obj) {
try {
return serializer.read(serializer.serialize(obj));
} catch (ClassNotFoundException e) {
throw new SerializerException("Copying failed.", e);
}
} | [
"@",
"Override",
"public",
"T",
"copy",
"(",
"final",
"T",
"obj",
")",
"{",
"try",
"{",
"return",
"serializer",
".",
"read",
"(",
"serializer",
".",
"serialize",
"(",
"obj",
")",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"e",
")",
"{",
"... | Returns a copy of the passed in instance by serializing and deserializing it. | [
"Returns",
"a",
"copy",
"of",
"the",
"passed",
"in",
"instance",
"by",
"serializing",
"and",
"deserializing",
"it",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/copy/SerializingCopier.java#L57-L64 | train |
ehcache/ehcache3 | transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/BitronixXAResourceRegistry.java | BitronixXAResourceRegistry.registerXAResource | @Override
public void registerXAResource(String uniqueName, XAResource xaResource) {
Ehcache3XAResourceProducer xaResourceProducer = producers.get(uniqueName);
if (xaResourceProducer == null) {
xaResourceProducer = new Ehcache3XAResourceProducer();
xaResourceProducer.setUniqueName(uniqueName);
// the initial xaResource must be added before init() can be called
xaResourceProducer.addXAResource(xaResource);
Ehcache3XAResourceProducer previous = producers.putIfAbsent(uniqueName, xaResourceProducer);
if (previous == null) {
xaResourceProducer.init();
} else {
previous.addXAResource(xaResource);
}
} else {
xaResourceProducer.addXAResource(xaResource);
}
} | java | @Override
public void registerXAResource(String uniqueName, XAResource xaResource) {
Ehcache3XAResourceProducer xaResourceProducer = producers.get(uniqueName);
if (xaResourceProducer == null) {
xaResourceProducer = new Ehcache3XAResourceProducer();
xaResourceProducer.setUniqueName(uniqueName);
// the initial xaResource must be added before init() can be called
xaResourceProducer.addXAResource(xaResource);
Ehcache3XAResourceProducer previous = producers.putIfAbsent(uniqueName, xaResourceProducer);
if (previous == null) {
xaResourceProducer.init();
} else {
previous.addXAResource(xaResource);
}
} else {
xaResourceProducer.addXAResource(xaResource);
}
} | [
"@",
"Override",
"public",
"void",
"registerXAResource",
"(",
"String",
"uniqueName",
",",
"XAResource",
"xaResource",
")",
"{",
"Ehcache3XAResourceProducer",
"xaResourceProducer",
"=",
"producers",
".",
"get",
"(",
"uniqueName",
")",
";",
"if",
"(",
"xaResourceProd... | Register an XAResource of a cache with BTM. The first time a XAResource is registered a new
EhCacheXAResourceProducer is created to hold it.
@param uniqueName the uniqueName of this XAResourceProducer, usually the cache's name
@param xaResource the XAResource to be registered | [
"Register",
"an",
"XAResource",
"of",
"a",
"cache",
"with",
"BTM",
".",
"The",
"first",
"time",
"a",
"XAResource",
"is",
"registered",
"a",
"new",
"EhCacheXAResourceProducer",
"is",
"created",
"to",
"hold",
"it",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/BitronixXAResourceRegistry.java#L40-L59 | train |
ehcache/ehcache3 | transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/BitronixXAResourceRegistry.java | BitronixXAResourceRegistry.unregisterXAResource | @Override
public void unregisterXAResource(String uniqueName, XAResource xaResource) {
Ehcache3XAResourceProducer xaResourceProducer = producers.get(uniqueName);
if (xaResourceProducer != null) {
boolean found = xaResourceProducer.removeXAResource(xaResource);
if (!found) {
throw new IllegalStateException("no XAResource " + xaResource + " found in XAResourceProducer with name " + uniqueName);
}
if (xaResourceProducer.isEmpty()) {
xaResourceProducer.close();
producers.remove(uniqueName);
}
} else {
throw new IllegalStateException("no XAResourceProducer registered with name " + uniqueName);
}
} | java | @Override
public void unregisterXAResource(String uniqueName, XAResource xaResource) {
Ehcache3XAResourceProducer xaResourceProducer = producers.get(uniqueName);
if (xaResourceProducer != null) {
boolean found = xaResourceProducer.removeXAResource(xaResource);
if (!found) {
throw new IllegalStateException("no XAResource " + xaResource + " found in XAResourceProducer with name " + uniqueName);
}
if (xaResourceProducer.isEmpty()) {
xaResourceProducer.close();
producers.remove(uniqueName);
}
} else {
throw new IllegalStateException("no XAResourceProducer registered with name " + uniqueName);
}
} | [
"@",
"Override",
"public",
"void",
"unregisterXAResource",
"(",
"String",
"uniqueName",
",",
"XAResource",
"xaResource",
")",
"{",
"Ehcache3XAResourceProducer",
"xaResourceProducer",
"=",
"producers",
".",
"get",
"(",
"uniqueName",
")",
";",
"if",
"(",
"xaResourcePr... | Unregister an XAResource of a cache from BTM.
@param uniqueName the uniqueName of this XAResourceProducer, usually the cache's name
@param xaResource the XAResource to be registered | [
"Unregister",
"an",
"XAResource",
"of",
"a",
"cache",
"from",
"BTM",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/BitronixXAResourceRegistry.java#L66-L82 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ChainResolver.java | ChainResolver.compact | public void compact(ServerStoreProxy.ChainEntry entry) {
ChainBuilder builder = new ChainBuilder();
for (PutOperation<K, V> operation : resolveAll(entry).values()) {
builder = builder.add(codec.encode(operation));
}
Chain compacted = builder.build();
if (compacted.length() < entry.length()) {
entry.replaceAtHead(compacted);
}
} | java | public void compact(ServerStoreProxy.ChainEntry entry) {
ChainBuilder builder = new ChainBuilder();
for (PutOperation<K, V> operation : resolveAll(entry).values()) {
builder = builder.add(codec.encode(operation));
}
Chain compacted = builder.build();
if (compacted.length() < entry.length()) {
entry.replaceAtHead(compacted);
}
} | [
"public",
"void",
"compact",
"(",
"ServerStoreProxy",
".",
"ChainEntry",
"entry",
")",
"{",
"ChainBuilder",
"builder",
"=",
"new",
"ChainBuilder",
"(",
")",
";",
"for",
"(",
"PutOperation",
"<",
"K",
",",
"V",
">",
"operation",
":",
"resolveAll",
"(",
"ent... | Compacts the given chain entry by resolving every key within.
@param entry an uncompacted heterogenous {@link ServerStoreProxy.ChainEntry} | [
"Compacts",
"the",
"given",
"chain",
"entry",
"by",
"resolving",
"every",
"key",
"within",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ChainResolver.java#L93-L102 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ChainResolver.java | ChainResolver.resolveAll | protected Map<K, PutOperation<K, V>> resolveAll(Chain chain) {
//absent hash-collisions this should always be a 1 entry map
Map<K, PutOperation<K, V>> compacted = new HashMap<>(2);
for (Element element : chain) {
ByteBuffer payload = element.getPayload();
Operation<K, V> operation = codec.decode(payload);
compacted.compute(operation.getKey(), (k, v) -> applyOperation(k, v, operation));
}
return compacted;
} | java | protected Map<K, PutOperation<K, V>> resolveAll(Chain chain) {
//absent hash-collisions this should always be a 1 entry map
Map<K, PutOperation<K, V>> compacted = new HashMap<>(2);
for (Element element : chain) {
ByteBuffer payload = element.getPayload();
Operation<K, V> operation = codec.decode(payload);
compacted.compute(operation.getKey(), (k, v) -> applyOperation(k, v, operation));
}
return compacted;
} | [
"protected",
"Map",
"<",
"K",
",",
"PutOperation",
"<",
"K",
",",
"V",
">",
">",
"resolveAll",
"(",
"Chain",
"chain",
")",
"{",
"//absent hash-collisions this should always be a 1 entry map",
"Map",
"<",
"K",
",",
"PutOperation",
"<",
"K",
",",
"V",
">",
">"... | Resolves all keys within the given chain to their equivalent put operations.
@param chain target chain
@return a map of equivalent put operations | [
"Resolves",
"all",
"keys",
"within",
"the",
"given",
"chain",
"to",
"their",
"equivalent",
"put",
"operations",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ChainResolver.java#L145-L154 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/store/offheap/MemorySizeParser.java | MemorySizeParser.parse | public static long parse(String configuredMemorySize) throws IllegalArgumentException {
MemorySize size = parseIncludingUnit(configuredMemorySize);
return size.calculateMemorySizeInBytes();
} | java | public static long parse(String configuredMemorySize) throws IllegalArgumentException {
MemorySize size = parseIncludingUnit(configuredMemorySize);
return size.calculateMemorySizeInBytes();
} | [
"public",
"static",
"long",
"parse",
"(",
"String",
"configuredMemorySize",
")",
"throws",
"IllegalArgumentException",
"{",
"MemorySize",
"size",
"=",
"parseIncludingUnit",
"(",
"configuredMemorySize",
")",
";",
"return",
"size",
".",
"calculateMemorySizeInBytes",
"(",
... | Parse a String containing a human-readable memory size.
@param configuredMemorySize the String containing a human-readable memory size.
@return the memory size in bytes.
@throws IllegalArgumentException thrown when the configured memory size cannot be parsed. | [
"Parse",
"a",
"String",
"containing",
"a",
"human",
"-",
"readable",
"memory",
"size",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/store/offheap/MemorySizeParser.java#L37-L40 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/internal/ClusterTierManagerClientEntityFactory.java | ClusterTierManagerClientEntityFactory.abandonLeadership | public boolean abandonLeadership(String entityIdentifier, boolean healthyConnection) {
Hold hold = maintenanceHolds.remove(entityIdentifier);
return (hold != null) && healthyConnection && silentlyUnlock(hold, entityIdentifier);
} | java | public boolean abandonLeadership(String entityIdentifier, boolean healthyConnection) {
Hold hold = maintenanceHolds.remove(entityIdentifier);
return (hold != null) && healthyConnection && silentlyUnlock(hold, entityIdentifier);
} | [
"public",
"boolean",
"abandonLeadership",
"(",
"String",
"entityIdentifier",
",",
"boolean",
"healthyConnection",
")",
"{",
"Hold",
"hold",
"=",
"maintenanceHolds",
".",
"remove",
"(",
"entityIdentifier",
")",
";",
"return",
"(",
"hold",
"!=",
"null",
")",
"&&",... | Proactively abandon leadership before closing connection.
@param entityIdentifier the master entity identifier
@return true of abandoned false otherwise | [
"Proactively",
"abandon",
"leadership",
"before",
"closing",
"connection",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/internal/ClusterTierManagerClientEntityFactory.java#L94-L97 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/internal/ClusterTierManagerClientEntityFactory.java | ClusterTierManagerClientEntityFactory.abandonFetchHolds | private boolean abandonFetchHolds(String entityIdentifier, boolean healthyConnection) {
Hold hold = fetchHolds.remove(entityIdentifier);
return (hold != null) && healthyConnection && silentlyUnlock(hold, entityIdentifier);
} | java | private boolean abandonFetchHolds(String entityIdentifier, boolean healthyConnection) {
Hold hold = fetchHolds.remove(entityIdentifier);
return (hold != null) && healthyConnection && silentlyUnlock(hold, entityIdentifier);
} | [
"private",
"boolean",
"abandonFetchHolds",
"(",
"String",
"entityIdentifier",
",",
"boolean",
"healthyConnection",
")",
"{",
"Hold",
"hold",
"=",
"fetchHolds",
".",
"remove",
"(",
"entityIdentifier",
")",
";",
"return",
"(",
"hold",
"!=",
"null",
")",
"&&",
"h... | Proactively abandon any READ holds before closing connection.
@param entityIdentifier the master entity identifier
@return true of abandoned false otherwise | [
"Proactively",
"abandon",
"any",
"READ",
"holds",
"before",
"closing",
"connection",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/internal/ClusterTierManagerClientEntityFactory.java#L105-L108 | train |
ehcache/ehcache3 | clustered/server/src/main/java/org/ehcache/clustered/server/management/ClusterTierManagement.java | ClusterTierManagement.init | private void init() {
ServerSideServerStore serverStore = ehcacheStateService.getStore(storeIdentifier);
ServerStoreBinding serverStoreBinding = new ServerStoreBinding(storeIdentifier, serverStore);
CompletableFuture<Void> r1 = managementRegistry.register(serverStoreBinding);
ServerSideConfiguration.Pool pool = ehcacheStateService.getDedicatedResourcePool(storeIdentifier);
CompletableFuture<Void> allOf;
if (pool != null) {
allOf = CompletableFuture.allOf(r1, managementRegistry.register(new PoolBinding(storeIdentifier, pool, PoolBinding.AllocationType.DEDICATED)));
} else {
allOf = r1;
}
allOf.thenRun(() -> {
managementRegistry.refresh();
managementRegistry.pushServerEntityNotification(serverStoreBinding, EHCACHE_SERVER_STORE_CREATED.name());
});
} | java | private void init() {
ServerSideServerStore serverStore = ehcacheStateService.getStore(storeIdentifier);
ServerStoreBinding serverStoreBinding = new ServerStoreBinding(storeIdentifier, serverStore);
CompletableFuture<Void> r1 = managementRegistry.register(serverStoreBinding);
ServerSideConfiguration.Pool pool = ehcacheStateService.getDedicatedResourcePool(storeIdentifier);
CompletableFuture<Void> allOf;
if (pool != null) {
allOf = CompletableFuture.allOf(r1, managementRegistry.register(new PoolBinding(storeIdentifier, pool, PoolBinding.AllocationType.DEDICATED)));
} else {
allOf = r1;
}
allOf.thenRun(() -> {
managementRegistry.refresh();
managementRegistry.pushServerEntityNotification(serverStoreBinding, EHCACHE_SERVER_STORE_CREATED.name());
});
} | [
"private",
"void",
"init",
"(",
")",
"{",
"ServerSideServerStore",
"serverStore",
"=",
"ehcacheStateService",
".",
"getStore",
"(",
"storeIdentifier",
")",
";",
"ServerStoreBinding",
"serverStoreBinding",
"=",
"new",
"ServerStoreBinding",
"(",
"storeIdentifier",
",",
... | the goal of the following code is to send the management metadata from the entity into the monitoring tree AFTER the entity creation | [
"the",
"goal",
"of",
"the",
"following",
"code",
"is",
"to",
"send",
"the",
"management",
"metadata",
"from",
"the",
"entity",
"into",
"the",
"monitoring",
"tree",
"AFTER",
"the",
"entity",
"creation"
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/server/src/main/java/org/ehcache/clustered/server/management/ClusterTierManagement.java#L91-L106 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteringServiceConfigurationBuilder.java | ClusteringServiceConfigurationBuilder.timeouts | public ClusteringServiceConfigurationBuilder timeouts(Builder<? extends Timeouts> timeoutsBuilder) {
return new ClusteringServiceConfigurationBuilder(this.connectionSource, timeoutsBuilder.build(), this.autoCreate);
} | java | public ClusteringServiceConfigurationBuilder timeouts(Builder<? extends Timeouts> timeoutsBuilder) {
return new ClusteringServiceConfigurationBuilder(this.connectionSource, timeoutsBuilder.build(), this.autoCreate);
} | [
"public",
"ClusteringServiceConfigurationBuilder",
"timeouts",
"(",
"Builder",
"<",
"?",
"extends",
"Timeouts",
">",
"timeoutsBuilder",
")",
"{",
"return",
"new",
"ClusteringServiceConfigurationBuilder",
"(",
"this",
".",
"connectionSource",
",",
"timeoutsBuilder",
".",
... | Adds timeouts.
Read operations which time out return a result comparable to a cache miss.
Write operations which time out won't do anything.
Lifecycle operations which time out will fail with exception
@param timeoutsBuilder the builder for amount of time permitted for all operations
@return a clustering service configuration builder
@throws NullPointerException if {@code timeouts} is {@code null} | [
"Adds",
"timeouts",
".",
"Read",
"operations",
"which",
"time",
"out",
"return",
"a",
"result",
"comparable",
"to",
"a",
"cache",
"miss",
".",
"Write",
"operations",
"which",
"time",
"out",
"won",
"t",
"do",
"anything",
".",
"Lifecycle",
"operations",
"which... | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteringServiceConfigurationBuilder.java#L119-L121 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteringServiceConfigurationBuilder.java | ClusteringServiceConfigurationBuilder.readOperationTimeout | @Deprecated
public ClusteringServiceConfigurationBuilder readOperationTimeout(long duration, TimeUnit unit) {
Duration readTimeout = Duration.of(duration, toChronoUnit(unit));
return timeouts(TimeoutsBuilder.timeouts().read(readTimeout).build());
} | java | @Deprecated
public ClusteringServiceConfigurationBuilder readOperationTimeout(long duration, TimeUnit unit) {
Duration readTimeout = Duration.of(duration, toChronoUnit(unit));
return timeouts(TimeoutsBuilder.timeouts().read(readTimeout).build());
} | [
"@",
"Deprecated",
"public",
"ClusteringServiceConfigurationBuilder",
"readOperationTimeout",
"(",
"long",
"duration",
",",
"TimeUnit",
"unit",
")",
"{",
"Duration",
"readTimeout",
"=",
"Duration",
".",
"of",
"(",
"duration",
",",
"toChronoUnit",
"(",
"unit",
")",
... | Adds a read operation timeout. Read operations which time out return a result comparable to
a cache miss.
@param duration the amount of time permitted for read operations
@param unit the time units for {@code duration}
@return a clustering service configuration builder
@throws NullPointerException if {@code unit} is {@code null}
@throws IllegalArgumentException if {@code amount} is negative
@deprecated Use {@link #timeouts(Timeouts)}. Note that calling this method will override any timeouts previously set
by setting the read operation timeout to the specified value and everything else to its default. | [
"Adds",
"a",
"read",
"operation",
"timeout",
".",
"Read",
"operations",
"which",
"time",
"out",
"return",
"a",
"result",
"comparable",
"to",
"a",
"cache",
"miss",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteringServiceConfigurationBuilder.java#L138-L142 | train |
ehcache/ehcache3 | core/src/main/java/org/ehcache/core/EhcacheManager.java | EhcacheManager.removeCache | private void removeCache(final String alias, final boolean removeFromConfig) {
statusTransitioner.checkAvailable();
final CacheHolder cacheHolder = caches.remove(alias);
if(cacheHolder != null) {
final InternalCache<?, ?> ehcache = cacheHolder.retrieve(cacheHolder.keyType, cacheHolder.valueType);
if (ehcache != null) {
if (removeFromConfig) {
configuration.removeCacheConfiguration(alias);
}
if (!statusTransitioner.isTransitioning()) {
for (CacheManagerListener listener : listeners) {
listener.cacheRemoved(alias, ehcache);
}
}
ehcache.close();
closeEhcache(alias, ehcache);
}
LOGGER.info("Cache '{}' removed from {}.", alias, simpleName);
}
} | java | private void removeCache(final String alias, final boolean removeFromConfig) {
statusTransitioner.checkAvailable();
final CacheHolder cacheHolder = caches.remove(alias);
if(cacheHolder != null) {
final InternalCache<?, ?> ehcache = cacheHolder.retrieve(cacheHolder.keyType, cacheHolder.valueType);
if (ehcache != null) {
if (removeFromConfig) {
configuration.removeCacheConfiguration(alias);
}
if (!statusTransitioner.isTransitioning()) {
for (CacheManagerListener listener : listeners) {
listener.cacheRemoved(alias, ehcache);
}
}
ehcache.close();
closeEhcache(alias, ehcache);
}
LOGGER.info("Cache '{}' removed from {}.", alias, simpleName);
}
} | [
"private",
"void",
"removeCache",
"(",
"final",
"String",
"alias",
",",
"final",
"boolean",
"removeFromConfig",
")",
"{",
"statusTransitioner",
".",
"checkAvailable",
"(",
")",
";",
"final",
"CacheHolder",
"cacheHolder",
"=",
"caches",
".",
"remove",
"(",
"alias... | Closes and removes a cache, by alias, from this cache manager.
@param alias the alias of the cache to remove
@param removeFromConfig if {@code true}, the cache configuration is altered to remove the cache | [
"Closes",
"and",
"removes",
"a",
"cache",
"by",
"alias",
"from",
"this",
"cache",
"manager",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/core/src/main/java/org/ehcache/core/EhcacheManager.java#L199-L220 | train |
ehcache/ehcache3 | core/src/main/java/org/ehcache/core/EhcacheManager.java | EhcacheManager.adjustConfigurationWithCacheManagerDefaults | private <K, V> CacheConfiguration<K, V> adjustConfigurationWithCacheManagerDefaults(String alias, CacheConfiguration<K, V> config) {
ClassLoader cacheClassLoader = config.getClassLoader();
List<ServiceConfiguration<?>> configurationList = new ArrayList<>();
configurationList.addAll(config.getServiceConfigurations());
CacheLoaderWriterConfiguration loaderWriterConfiguration = findSingletonAmongst(CacheLoaderWriterConfiguration.class, config.getServiceConfigurations());
if (loaderWriterConfiguration == null) {
CacheLoaderWriterProvider loaderWriterProvider = serviceLocator.getService(CacheLoaderWriterProvider.class);
ServiceConfiguration<CacheLoaderWriterProvider> preConfiguredCacheLoaderWriterConfig = loaderWriterProvider.getPreConfiguredCacheLoaderWriterConfig(alias);
if (preConfiguredCacheLoaderWriterConfig != null) {
configurationList.add(preConfiguredCacheLoaderWriterConfig);
}
if (loaderWriterProvider.isLoaderJsrProvided(alias)) {
configurationList.add(new CacheLoaderWriterConfiguration() {
});
}
}
ServiceConfiguration<?>[] serviceConfigurations = new ServiceConfiguration<?>[configurationList.size()];
configurationList.toArray(serviceConfigurations);
if (cacheClassLoader == null) {
cacheClassLoader = cacheManagerClassLoader;
}
if (cacheClassLoader != config.getClassLoader() ) {
config = new BaseCacheConfiguration<>(config.getKeyType(), config.getValueType(),
config.getEvictionAdvisor(), cacheClassLoader, config.getExpiryPolicy(),
config.getResourcePools(), serviceConfigurations);
} else {
config = new BaseCacheConfiguration<>(config.getKeyType(), config.getValueType(),
config.getEvictionAdvisor(), config.getClassLoader(), config.getExpiryPolicy(),
config.getResourcePools(), serviceConfigurations);
}
return config;
} | java | private <K, V> CacheConfiguration<K, V> adjustConfigurationWithCacheManagerDefaults(String alias, CacheConfiguration<K, V> config) {
ClassLoader cacheClassLoader = config.getClassLoader();
List<ServiceConfiguration<?>> configurationList = new ArrayList<>();
configurationList.addAll(config.getServiceConfigurations());
CacheLoaderWriterConfiguration loaderWriterConfiguration = findSingletonAmongst(CacheLoaderWriterConfiguration.class, config.getServiceConfigurations());
if (loaderWriterConfiguration == null) {
CacheLoaderWriterProvider loaderWriterProvider = serviceLocator.getService(CacheLoaderWriterProvider.class);
ServiceConfiguration<CacheLoaderWriterProvider> preConfiguredCacheLoaderWriterConfig = loaderWriterProvider.getPreConfiguredCacheLoaderWriterConfig(alias);
if (preConfiguredCacheLoaderWriterConfig != null) {
configurationList.add(preConfiguredCacheLoaderWriterConfig);
}
if (loaderWriterProvider.isLoaderJsrProvided(alias)) {
configurationList.add(new CacheLoaderWriterConfiguration() {
});
}
}
ServiceConfiguration<?>[] serviceConfigurations = new ServiceConfiguration<?>[configurationList.size()];
configurationList.toArray(serviceConfigurations);
if (cacheClassLoader == null) {
cacheClassLoader = cacheManagerClassLoader;
}
if (cacheClassLoader != config.getClassLoader() ) {
config = new BaseCacheConfiguration<>(config.getKeyType(), config.getValueType(),
config.getEvictionAdvisor(), cacheClassLoader, config.getExpiryPolicy(),
config.getResourcePools(), serviceConfigurations);
} else {
config = new BaseCacheConfiguration<>(config.getKeyType(), config.getValueType(),
config.getEvictionAdvisor(), config.getClassLoader(), config.getExpiryPolicy(),
config.getResourcePools(), serviceConfigurations);
}
return config;
} | [
"private",
"<",
"K",
",",
"V",
">",
"CacheConfiguration",
"<",
"K",
",",
"V",
">",
"adjustConfigurationWithCacheManagerDefaults",
"(",
"String",
"alias",
",",
"CacheConfiguration",
"<",
"K",
",",
"V",
">",
"config",
")",
"{",
"ClassLoader",
"cacheClassLoader",
... | adjusts the config to reflect new classloader & serialization provider | [
"adjusts",
"the",
"config",
"to",
"reflect",
"new",
"classloader",
"&",
"serialization",
"provider"
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/core/src/main/java/org/ehcache/core/EhcacheManager.java#L534-L569 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java | OnHeapStore.evict | boolean evict(StoreEventSink<K, V> eventSink) {
evictionObserver.begin();
Random random = new Random();
@SuppressWarnings("unchecked")
Map.Entry<K, OnHeapValueHolder<V>> candidate = map.getEvictionCandidate(random, SAMPLE_SIZE, EVICTION_PRIORITIZER, EVICTION_ADVISOR);
if (candidate == null) {
// 2nd attempt without any advisor
candidate = map.getEvictionCandidate(random, SAMPLE_SIZE, EVICTION_PRIORITIZER, noAdvice());
}
if (candidate == null) {
return false;
} else {
Map.Entry<K, OnHeapValueHolder<V>> evictionCandidate = candidate;
AtomicBoolean removed = new AtomicBoolean(false);
map.computeIfPresent(evictionCandidate.getKey(), (mappedKey, mappedValue) -> {
if (mappedValue.equals(evictionCandidate.getValue())) {
removed.set(true);
if (!(evictionCandidate.getValue() instanceof Fault)) {
eventSink.evicted(evictionCandidate.getKey(), evictionCandidate.getValue());
invalidationListener.onInvalidation(mappedKey, evictionCandidate.getValue());
}
updateUsageInBytesIfRequired(-mappedValue.size());
return null;
}
return mappedValue;
});
if (removed.get()) {
evictionObserver.end(StoreOperationOutcomes.EvictionOutcome.SUCCESS);
return true;
} else {
evictionObserver.end(StoreOperationOutcomes.EvictionOutcome.FAILURE);
return false;
}
}
} | java | boolean evict(StoreEventSink<K, V> eventSink) {
evictionObserver.begin();
Random random = new Random();
@SuppressWarnings("unchecked")
Map.Entry<K, OnHeapValueHolder<V>> candidate = map.getEvictionCandidate(random, SAMPLE_SIZE, EVICTION_PRIORITIZER, EVICTION_ADVISOR);
if (candidate == null) {
// 2nd attempt without any advisor
candidate = map.getEvictionCandidate(random, SAMPLE_SIZE, EVICTION_PRIORITIZER, noAdvice());
}
if (candidate == null) {
return false;
} else {
Map.Entry<K, OnHeapValueHolder<V>> evictionCandidate = candidate;
AtomicBoolean removed = new AtomicBoolean(false);
map.computeIfPresent(evictionCandidate.getKey(), (mappedKey, mappedValue) -> {
if (mappedValue.equals(evictionCandidate.getValue())) {
removed.set(true);
if (!(evictionCandidate.getValue() instanceof Fault)) {
eventSink.evicted(evictionCandidate.getKey(), evictionCandidate.getValue());
invalidationListener.onInvalidation(mappedKey, evictionCandidate.getValue());
}
updateUsageInBytesIfRequired(-mappedValue.size());
return null;
}
return mappedValue;
});
if (removed.get()) {
evictionObserver.end(StoreOperationOutcomes.EvictionOutcome.SUCCESS);
return true;
} else {
evictionObserver.end(StoreOperationOutcomes.EvictionOutcome.FAILURE);
return false;
}
}
} | [
"boolean",
"evict",
"(",
"StoreEventSink",
"<",
"K",
",",
"V",
">",
"eventSink",
")",
"{",
"evictionObserver",
".",
"begin",
"(",
")",
";",
"Random",
"random",
"=",
"new",
"Random",
"(",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map"... | Try to evict a mapping.
@return true if a mapping was evicted, false otherwise.
@param eventSink target of eviction event | [
"Try",
"to",
"evict",
"a",
"mapping",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java#L1575-L1612 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.getFailure | @Override
public V getFailure(K key, StoreAccessException e) {
try {
return loaderWriter.load(key);
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
} finally {
cleanup(key, e);
}
} | java | @Override
public V getFailure(K key, StoreAccessException e) {
try {
return loaderWriter.load(key);
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
} finally {
cleanup(key, e);
}
} | [
"@",
"Override",
"public",
"V",
"getFailure",
"(",
"K",
"key",
",",
"StoreAccessException",
"e",
")",
"{",
"try",
"{",
"return",
"loaderWriter",
".",
"load",
"(",
"key",
")",
";",
"}",
"catch",
"(",
"Exception",
"e1",
")",
"{",
"throw",
"ExceptionFactory... | Get the value from the loader-writer.
@param key the key being retrieved
@param e the triggered failure
@return value as loaded from the loader-writer | [
"Get",
"the",
"value",
"from",
"the",
"loader",
"-",
"writer",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L55-L64 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.containsKeyFailure | @Override
public boolean containsKeyFailure(K key, StoreAccessException e) {
cleanup(key, e);
return false;
} | java | @Override
public boolean containsKeyFailure(K key, StoreAccessException e) {
cleanup(key, e);
return false;
} | [
"@",
"Override",
"public",
"boolean",
"containsKeyFailure",
"(",
"K",
"key",
",",
"StoreAccessException",
"e",
")",
"{",
"cleanup",
"(",
"key",
",",
"e",
")",
";",
"return",
"false",
";",
"}"
] | Return false. It doesn't matter if the key is present in the backend, we consider it's not in the cache.
@param key the key being queried
@param e the triggered failure
@return false | [
"Return",
"false",
".",
"It",
"doesn",
"t",
"matter",
"if",
"the",
"key",
"is",
"present",
"in",
"the",
"backend",
"we",
"consider",
"it",
"s",
"not",
"in",
"the",
"cache",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L73-L77 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.putFailure | @Override
public void putFailure(K key, V value, StoreAccessException e) {
try {
loaderWriter.write(key, value);
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(key, e);
}
} | java | @Override
public void putFailure(K key, V value, StoreAccessException e) {
try {
loaderWriter.write(key, value);
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(key, e);
}
} | [
"@",
"Override",
"public",
"void",
"putFailure",
"(",
"K",
"key",
",",
"V",
"value",
",",
"StoreAccessException",
"e",
")",
"{",
"try",
"{",
"loaderWriter",
".",
"write",
"(",
"key",
",",
"value",
")",
";",
"}",
"catch",
"(",
"Exception",
"e1",
")",
... | Write the value to the loader-write.
@param key the key being put
@param value the value being put
@param e the triggered failure | [
"Write",
"the",
"value",
"to",
"the",
"loader",
"-",
"write",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L86-L95 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.removeFailure | @Override
public void removeFailure(K key, StoreAccessException e) {
try {
loaderWriter.delete(key);
} catch(Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(key, e);
}
} | java | @Override
public void removeFailure(K key, StoreAccessException e) {
try {
loaderWriter.delete(key);
} catch(Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(key, e);
}
} | [
"@",
"Override",
"public",
"void",
"removeFailure",
"(",
"K",
"key",
",",
"StoreAccessException",
"e",
")",
"{",
"try",
"{",
"loaderWriter",
".",
"delete",
"(",
"key",
")",
";",
"}",
"catch",
"(",
"Exception",
"e1",
")",
"{",
"throw",
"ExceptionFactory",
... | Delete the key from the loader-writer.
@param key the key being removed
@param e the triggered failure | [
"Delete",
"the",
"key",
"from",
"the",
"loader",
"-",
"writer",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L103-L112 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.putIfAbsentFailure | @Override
public V putIfAbsentFailure(K key, V value, StoreAccessException e) {
// FIXME: Should I care about useLoaderInAtomics?
try {
try {
V loaded = loaderWriter.load(key);
if (loaded != null) {
return loaded;
}
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
}
try {
loaderWriter.write(key, value);
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
}
} finally {
cleanup(key, e);
}
return null;
} | java | @Override
public V putIfAbsentFailure(K key, V value, StoreAccessException e) {
// FIXME: Should I care about useLoaderInAtomics?
try {
try {
V loaded = loaderWriter.load(key);
if (loaded != null) {
return loaded;
}
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
}
try {
loaderWriter.write(key, value);
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
}
} finally {
cleanup(key, e);
}
return null;
} | [
"@",
"Override",
"public",
"V",
"putIfAbsentFailure",
"(",
"K",
"key",
",",
"V",
"value",
",",
"StoreAccessException",
"e",
")",
"{",
"// FIXME: Should I care about useLoaderInAtomics?",
"try",
"{",
"try",
"{",
"V",
"loaded",
"=",
"loaderWriter",
".",
"load",
"(... | Write the value to the loader-writer if it doesn't already exist in it. Note that the load and write pair
is not atomic. This atomicity, if needed, should be handled by the something else.
@param key the key being put
@param value the value being put
@param e the triggered failure
@return the existing value or null if the new was set | [
"Write",
"the",
"value",
"to",
"the",
"loader",
"-",
"writer",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"in",
"it",
".",
"Note",
"that",
"the",
"load",
"and",
"write",
"pair",
"is",
"not",
"atomic",
".",
"This",
"atomicity",
"if",
"needed",
"shoul... | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L133-L154 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.removeFailure | @Override
public boolean removeFailure(K key, V value, StoreAccessException e) {
try {
V loadedValue;
try {
loadedValue = loaderWriter.load(key);
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
}
if (loadedValue == null) {
return false;
}
if (!loadedValue.equals(value)) {
return false;
}
try {
loaderWriter.delete(key);
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
}
return true;
} finally {
cleanup(key, e);
}
} | java | @Override
public boolean removeFailure(K key, V value, StoreAccessException e) {
try {
V loadedValue;
try {
loadedValue = loaderWriter.load(key);
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
}
if (loadedValue == null) {
return false;
}
if (!loadedValue.equals(value)) {
return false;
}
try {
loaderWriter.delete(key);
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
}
return true;
} finally {
cleanup(key, e);
}
} | [
"@",
"Override",
"public",
"boolean",
"removeFailure",
"(",
"K",
"key",
",",
"V",
"value",
",",
"StoreAccessException",
"e",
")",
"{",
"try",
"{",
"V",
"loadedValue",
";",
"try",
"{",
"loadedValue",
"=",
"loaderWriter",
".",
"load",
"(",
"key",
")",
";",... | Delete the key from the loader-writer if it is found with a matching value. Note that the load and write pair
is not atomic. This atomicity, if needed, should be handled by the something else.
@param key the key being removed
@param value the value being removed
@param e the triggered failure
@return if the value was removed | [
"Delete",
"the",
"key",
"from",
"the",
"loader",
"-",
"writer",
"if",
"it",
"is",
"found",
"with",
"a",
"matching",
"value",
".",
"Note",
"that",
"the",
"load",
"and",
"write",
"pair",
"is",
"not",
"atomic",
".",
"This",
"atomicity",
"if",
"needed",
"s... | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L165-L192 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.getAllFailure | @SuppressWarnings("unchecked")
@Override
public Map<K, V> getAllFailure(Iterable<? extends K> keys, StoreAccessException e) {
try {
return loaderWriter.loadAll((Iterable) keys); // FIXME: bad typing that we should fix
} catch(BulkCacheLoadingException e1) {
throw e1;
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
} finally {
cleanup(keys, e);
}
} | java | @SuppressWarnings("unchecked")
@Override
public Map<K, V> getAllFailure(Iterable<? extends K> keys, StoreAccessException e) {
try {
return loaderWriter.loadAll((Iterable) keys); // FIXME: bad typing that we should fix
} catch(BulkCacheLoadingException e1) {
throw e1;
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
} finally {
cleanup(keys, e);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"@",
"Override",
"public",
"Map",
"<",
"K",
",",
"V",
">",
"getAllFailure",
"(",
"Iterable",
"<",
"?",
"extends",
"K",
">",
"keys",
",",
"StoreAccessException",
"e",
")",
"{",
"try",
"{",
"return",
"loa... | Get all entries for the provided keys. Entries not found by the loader-writer are expected to be an entry
with the key and a null value.
@param keys the keys being retrieved
@param e the triggered failure
@return a map of key-value pairs as loaded by the loader-writer | [
"Get",
"all",
"entries",
"for",
"the",
"provided",
"keys",
".",
"Entries",
"not",
"found",
"by",
"the",
"loader",
"-",
"writer",
"are",
"expected",
"to",
"be",
"an",
"entry",
"with",
"the",
"key",
"and",
"a",
"null",
"value",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L270-L282 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.putAllFailure | @Override
public void putAllFailure(Map<? extends K, ? extends V> entries, StoreAccessException e) {
try {
loaderWriter.writeAll(entries.entrySet()); // FIXME: bad typing that we should fix
} catch(BulkCacheWritingException e1) {
throw e1;
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(entries.keySet(), e);
}
} | java | @Override
public void putAllFailure(Map<? extends K, ? extends V> entries, StoreAccessException e) {
try {
loaderWriter.writeAll(entries.entrySet()); // FIXME: bad typing that we should fix
} catch(BulkCacheWritingException e1) {
throw e1;
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(entries.keySet(), e);
}
} | [
"@",
"Override",
"public",
"void",
"putAllFailure",
"(",
"Map",
"<",
"?",
"extends",
"K",
",",
"?",
"extends",
"V",
">",
"entries",
",",
"StoreAccessException",
"e",
")",
"{",
"try",
"{",
"loaderWriter",
".",
"writeAll",
"(",
"entries",
".",
"entrySet",
... | Write all entries to the loader-writer.
@param entries the entries being put
@param e the triggered failure | [
"Write",
"all",
"entries",
"to",
"the",
"loader",
"-",
"writer",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L290-L301 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.removeAllFailure | @Override
public void removeAllFailure(Iterable<? extends K> keys, StoreAccessException e) {
try {
loaderWriter.deleteAll(keys);
} catch(BulkCacheWritingException e1) {
throw e1;
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(keys, e);
}
} | java | @Override
public void removeAllFailure(Iterable<? extends K> keys, StoreAccessException e) {
try {
loaderWriter.deleteAll(keys);
} catch(BulkCacheWritingException e1) {
throw e1;
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(keys, e);
}
} | [
"@",
"Override",
"public",
"void",
"removeAllFailure",
"(",
"Iterable",
"<",
"?",
"extends",
"K",
">",
"keys",
",",
"StoreAccessException",
"e",
")",
"{",
"try",
"{",
"loaderWriter",
".",
"deleteAll",
"(",
"keys",
")",
";",
"}",
"catch",
"(",
"BulkCacheWri... | Delete all keys from the loader-writer.
@param keys the keys being removed
@param e the triggered failure | [
"Delete",
"all",
"keys",
"from",
"the",
"loader",
"-",
"writer",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L309-L320 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/config/executor/PooledExecutionServiceConfiguration.java | PooledExecutionServiceConfiguration.addPool | public void addPool(String alias, int minSize, int maxSize) {
if (alias == null) {
throw new NullPointerException("Pool alias cannot be null");
}
if (poolConfigurations.containsKey(alias)) {
throw new IllegalArgumentException("A pool with the alias '" + alias + "' is already configured");
} else {
poolConfigurations.put(alias, new PoolConfiguration(minSize, maxSize));
}
} | java | public void addPool(String alias, int minSize, int maxSize) {
if (alias == null) {
throw new NullPointerException("Pool alias cannot be null");
}
if (poolConfigurations.containsKey(alias)) {
throw new IllegalArgumentException("A pool with the alias '" + alias + "' is already configured");
} else {
poolConfigurations.put(alias, new PoolConfiguration(minSize, maxSize));
}
} | [
"public",
"void",
"addPool",
"(",
"String",
"alias",
",",
"int",
"minSize",
",",
"int",
"maxSize",
")",
"{",
"if",
"(",
"alias",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"Pool alias cannot be null\"",
")",
";",
"}",
"if",
"(",... | Adds a new pool with the provided minimum and maximum.
@param alias the pool alias
@param minSize the minimum size
@param maxSize the maximum size
@throws NullPointerException if alias is null
@throws IllegalArgumentException if another pool with the same alias was configured already | [
"Adds",
"a",
"new",
"pool",
"with",
"the",
"provided",
"minimum",
"and",
"maximum",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/config/executor/PooledExecutionServiceConfiguration.java#L82-L91 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java | AbstractResilienceStrategy.cleanup | protected void cleanup(StoreAccessException from) {
try {
store.obliterate();
} catch (StoreAccessException e) {
inconsistent(from, e);
return;
}
recovered(from);
} | java | protected void cleanup(StoreAccessException from) {
try {
store.obliterate();
} catch (StoreAccessException e) {
inconsistent(from, e);
return;
}
recovered(from);
} | [
"protected",
"void",
"cleanup",
"(",
"StoreAccessException",
"from",
")",
"{",
"try",
"{",
"store",
".",
"obliterate",
"(",
")",
";",
"}",
"catch",
"(",
"StoreAccessException",
"e",
")",
"{",
"inconsistent",
"(",
"from",
",",
"e",
")",
";",
"return",
";"... | Clear all entries from the store.
@param from original failure causing the cleanup | [
"Clear",
"all",
"entries",
"from",
"the",
"store",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java#L67-L75 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java | AbstractResilienceStrategy.cleanup | protected void cleanup(Iterable<? extends K> keys, StoreAccessException from) {
try {
store.obliterate(keys);
} catch (StoreAccessException e) {
inconsistent(keys, from, e);
return;
}
recovered(keys, from);
} | java | protected void cleanup(Iterable<? extends K> keys, StoreAccessException from) {
try {
store.obliterate(keys);
} catch (StoreAccessException e) {
inconsistent(keys, from, e);
return;
}
recovered(keys, from);
} | [
"protected",
"void",
"cleanup",
"(",
"Iterable",
"<",
"?",
"extends",
"K",
">",
"keys",
",",
"StoreAccessException",
"from",
")",
"{",
"try",
"{",
"store",
".",
"obliterate",
"(",
"keys",
")",
";",
"}",
"catch",
"(",
"StoreAccessException",
"e",
")",
"{"... | Clean all keys from the store.
@param keys keys to clean
@param from original failure causing the cleanup | [
"Clean",
"all",
"keys",
"from",
"the",
"store",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java#L83-L91 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java | AbstractResilienceStrategy.recovered | protected void recovered(Iterable<? extends K> keys, StoreAccessException from) {
LOGGER.info("Ehcache keys {} recovered from", keys, from);
} | java | protected void recovered(Iterable<? extends K> keys, StoreAccessException from) {
LOGGER.info("Ehcache keys {} recovered from", keys, from);
} | [
"protected",
"void",
"recovered",
"(",
"Iterable",
"<",
"?",
"extends",
"K",
">",
"keys",
",",
"StoreAccessException",
"from",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Ehcache keys {} recovered from\"",
",",
"keys",
",",
"from",
")",
";",
"}"
] | Called when the cache recovered from a failing store operation on a list of keys.
@param keys keys that failed
@param from exception thrown by the failing operation | [
"Called",
"when",
"the",
"cache",
"recovered",
"from",
"a",
"failing",
"store",
"operation",
"on",
"a",
"list",
"of",
"keys",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java#L125-L127 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java | AbstractResilienceStrategy.inconsistent | protected void inconsistent(K key, StoreAccessException because, StoreAccessException... cleanup) {
pacedErrorLog("Ehcache key {} in possible inconsistent state", key, because);
} | java | protected void inconsistent(K key, StoreAccessException because, StoreAccessException... cleanup) {
pacedErrorLog("Ehcache key {} in possible inconsistent state", key, because);
} | [
"protected",
"void",
"inconsistent",
"(",
"K",
"key",
",",
"StoreAccessException",
"because",
",",
"StoreAccessException",
"...",
"cleanup",
")",
"{",
"pacedErrorLog",
"(",
"\"Ehcache key {} in possible inconsistent state\"",
",",
"key",
",",
"because",
")",
";",
"}"
... | Called when the cache failed to recover from a failing store operation on a key.
@param key key now inconsistent
@param because exception thrown by the failing operation
@param cleanup all the exceptions that occurred during cleanup | [
"Called",
"when",
"the",
"cache",
"failed",
"to",
"recover",
"from",
"a",
"failing",
"store",
"operation",
"on",
"a",
"key",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java#L146-L148 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java | AbstractResilienceStrategy.inconsistent | protected void inconsistent(Iterable<? extends K> keys, StoreAccessException because, StoreAccessException... cleanup) {
pacedErrorLog("Ehcache keys {} in possible inconsistent state", keys, because);
} | java | protected void inconsistent(Iterable<? extends K> keys, StoreAccessException because, StoreAccessException... cleanup) {
pacedErrorLog("Ehcache keys {} in possible inconsistent state", keys, because);
} | [
"protected",
"void",
"inconsistent",
"(",
"Iterable",
"<",
"?",
"extends",
"K",
">",
"keys",
",",
"StoreAccessException",
"because",
",",
"StoreAccessException",
"...",
"cleanup",
")",
"{",
"pacedErrorLog",
"(",
"\"Ehcache keys {} in possible inconsistent state\"",
",",... | Called when the cache failed to recover from a failing store operation on a list of keys.
@param keys
@param because exception thrown by the failing operation
@param cleanup all the exceptions that occurred during cleanup | [
"Called",
"when",
"the",
"cache",
"failed",
"to",
"recover",
"from",
"a",
"failing",
"store",
"operation",
"on",
"a",
"list",
"of",
"keys",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java#L157-L159 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ServerSideConfigurationBuilder.java | ServerSideConfigurationBuilder.resourcePool | public ServerSideConfigurationBuilder resourcePool(String name, long size, MemoryUnit unit, String serverResource) {
return resourcePool(name, new Pool(unit.toBytes(size), serverResource));
} | java | public ServerSideConfigurationBuilder resourcePool(String name, long size, MemoryUnit unit, String serverResource) {
return resourcePool(name, new Pool(unit.toBytes(size), serverResource));
} | [
"public",
"ServerSideConfigurationBuilder",
"resourcePool",
"(",
"String",
"name",
",",
"long",
"size",
",",
"MemoryUnit",
"unit",
",",
"String",
"serverResource",
")",
"{",
"return",
"resourcePool",
"(",
"name",
",",
"new",
"Pool",
"(",
"unit",
".",
"toBytes",
... | Adds a resource pool with the given name and size and consuming the given server resource.
@param name pool name
@param size pool size
@param unit pool size unit
@param serverResource server resource to consume
@return a clustering service configuration builder | [
"Adds",
"a",
"resource",
"pool",
"with",
"the",
"given",
"name",
"and",
"size",
"and",
"consuming",
"the",
"given",
"server",
"resource",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ServerSideConfigurationBuilder.java#L88-L90 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/events/CacheEventDispatcherImpl.java | CacheEventDispatcherImpl.registerCacheEventListener | private synchronized void registerCacheEventListener(EventListenerWrapper<K, V> wrapper) {
if(aSyncListenersList.contains(wrapper) || syncListenersList.contains(wrapper)) {
throw new IllegalStateException("Cache Event Listener already registered: " + wrapper.getListener());
}
if (wrapper.isOrdered() && orderedListenerCount++ == 0) {
storeEventSource.setEventOrdering(true);
}
switch (wrapper.getFiringMode()) {
case ASYNCHRONOUS:
aSyncListenersList.add(wrapper);
break;
case SYNCHRONOUS:
syncListenersList.add(wrapper);
break;
default:
throw new AssertionError("Unhandled EventFiring value: " + wrapper.getFiringMode());
}
if (listenersCount++ == 0) {
storeEventSource.addEventListener(eventListener);
}
} | java | private synchronized void registerCacheEventListener(EventListenerWrapper<K, V> wrapper) {
if(aSyncListenersList.contains(wrapper) || syncListenersList.contains(wrapper)) {
throw new IllegalStateException("Cache Event Listener already registered: " + wrapper.getListener());
}
if (wrapper.isOrdered() && orderedListenerCount++ == 0) {
storeEventSource.setEventOrdering(true);
}
switch (wrapper.getFiringMode()) {
case ASYNCHRONOUS:
aSyncListenersList.add(wrapper);
break;
case SYNCHRONOUS:
syncListenersList.add(wrapper);
break;
default:
throw new AssertionError("Unhandled EventFiring value: " + wrapper.getFiringMode());
}
if (listenersCount++ == 0) {
storeEventSource.addEventListener(eventListener);
}
} | [
"private",
"synchronized",
"void",
"registerCacheEventListener",
"(",
"EventListenerWrapper",
"<",
"K",
",",
"V",
">",
"wrapper",
")",
"{",
"if",
"(",
"aSyncListenersList",
".",
"contains",
"(",
"wrapper",
")",
"||",
"syncListenersList",
".",
"contains",
"(",
"w... | Synchronized to make sure listener addition is atomic in order to prevent having the same listener registered
under multiple configurations
@param wrapper the listener wrapper to register | [
"Synchronized",
"to",
"make",
"sure",
"listener",
"addition",
"is",
"atomic",
"in",
"order",
"to",
"prevent",
"having",
"the",
"same",
"listener",
"registered",
"under",
"multiple",
"configurations"
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/events/CacheEventDispatcherImpl.java#L96-L119 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/events/CacheEventDispatcherImpl.java | CacheEventDispatcherImpl.removeWrapperFromList | private synchronized boolean removeWrapperFromList(EventListenerWrapper<K, V> wrapper, List<EventListenerWrapper<K, V>> listenersList) {
int index = listenersList.indexOf(wrapper);
if (index != -1) {
EventListenerWrapper<K, V> containedWrapper = listenersList.remove(index);
if(containedWrapper.isOrdered() && --orderedListenerCount == 0) {
storeEventSource.setEventOrdering(false);
}
if (--listenersCount == 0) {
storeEventSource.removeEventListener(eventListener);
}
return true;
}
return false;
} | java | private synchronized boolean removeWrapperFromList(EventListenerWrapper<K, V> wrapper, List<EventListenerWrapper<K, V>> listenersList) {
int index = listenersList.indexOf(wrapper);
if (index != -1) {
EventListenerWrapper<K, V> containedWrapper = listenersList.remove(index);
if(containedWrapper.isOrdered() && --orderedListenerCount == 0) {
storeEventSource.setEventOrdering(false);
}
if (--listenersCount == 0) {
storeEventSource.removeEventListener(eventListener);
}
return true;
}
return false;
} | [
"private",
"synchronized",
"boolean",
"removeWrapperFromList",
"(",
"EventListenerWrapper",
"<",
"K",
",",
"V",
">",
"wrapper",
",",
"List",
"<",
"EventListenerWrapper",
"<",
"K",
",",
"V",
">",
">",
"listenersList",
")",
"{",
"int",
"index",
"=",
"listenersLi... | Synchronized to make sure listener removal is atomic
@param wrapper the listener wrapper to unregister
@param listenersList the listener list to remove from | [
"Synchronized",
"to",
"make",
"sure",
"listener",
"removal",
"is",
"atomic"
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/events/CacheEventDispatcherImpl.java#L141-L154 | train |
ehcache/ehcache3 | clustered/server/src/main/java/org/ehcache/clustered/server/management/Management.java | Management.init | private void init() {
CompletableFuture.allOf(
managementRegistry.register(generateClusterTierManagerBinding()),
// PoolBinding.ALL_SHARED is a marker so that we can send events not specifically related to 1 pool
// this object is ignored from the stats and descriptors
managementRegistry.register(PoolBinding.ALL_SHARED)
).thenRun(managementRegistry::refresh);
} | java | private void init() {
CompletableFuture.allOf(
managementRegistry.register(generateClusterTierManagerBinding()),
// PoolBinding.ALL_SHARED is a marker so that we can send events not specifically related to 1 pool
// this object is ignored from the stats and descriptors
managementRegistry.register(PoolBinding.ALL_SHARED)
).thenRun(managementRegistry::refresh);
} | [
"private",
"void",
"init",
"(",
")",
"{",
"CompletableFuture",
".",
"allOf",
"(",
"managementRegistry",
".",
"register",
"(",
"generateClusterTierManagerBinding",
"(",
")",
")",
",",
"// PoolBinding.ALL_SHARED is a marker so that we can send events not specifically related to 1... | the goal of the following code is to send the management metadata from the entity into the monitoring tre AFTER the entity creation | [
"the",
"goal",
"of",
"the",
"following",
"code",
"is",
"to",
"send",
"the",
"management",
"metadata",
"from",
"the",
"entity",
"into",
"the",
"monitoring",
"tre",
"AFTER",
"the",
"entity",
"creation"
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/server/src/main/java/org/ehcache/clustered/server/management/Management.java#L117-L124 | train |
ehcache/ehcache3 | clustered/server/src/main/java/org/ehcache/clustered/server/state/MessageTracker.java | MessageTracker.seen | public boolean seen(long msgId) {
boolean seen = nonContiguousMsgIds.contains(msgId) || msgId <= highestContiguousMsgId;
tryReconcile();
return seen;
} | java | public boolean seen(long msgId) {
boolean seen = nonContiguousMsgIds.contains(msgId) || msgId <= highestContiguousMsgId;
tryReconcile();
return seen;
} | [
"public",
"boolean",
"seen",
"(",
"long",
"msgId",
")",
"{",
"boolean",
"seen",
"=",
"nonContiguousMsgIds",
".",
"contains",
"(",
"msgId",
")",
"||",
"msgId",
"<=",
"highestContiguousMsgId",
";",
"tryReconcile",
"(",
")",
";",
"return",
"seen",
";",
"}"
] | Check wheather the given message id is already seen by track call.
@param msgId Message Identifier to be checked.
@return true if the given msgId is already tracked otherwise false. | [
"Check",
"wheather",
"the",
"given",
"message",
"id",
"is",
"already",
"seen",
"by",
"track",
"call",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/server/src/main/java/org/ehcache/clustered/server/state/MessageTracker.java#L71-L75 | train |
ehcache/ehcache3 | clustered/server/src/main/java/org/ehcache/clustered/server/state/MessageTracker.java | MessageTracker.reconcile | private void reconcile() {
// If nonContiguousMsgIds is empty then nothing to reconcile.
if (nonContiguousMsgIds.isEmpty()) {
return;
}
// This happens when a passive is started after Active has moved on and
// passive starts to see msgIDs starting from a number > 0.
// Once the sync is completed, fast forward highestContiguousMsgId.
// Post sync completion assuming platform will send all msgIds beyond highestContiguousMsgId.
if (highestContiguousMsgId == -1L && isSyncCompleted) {
Long min = nonContiguousMsgIds.last();
LOGGER.info("Setting highestContiguousMsgId to {} from -1", min);
highestContiguousMsgId = min;
nonContiguousMsgIds.removeIf(msgId -> msgId <= min);
}
for (long msgId : nonContiguousMsgIds) {
if (msgId <= highestContiguousMsgId) {
nonContiguousMsgIds.remove(msgId);
} else if (msgId > highestContiguousMsgId + 1) {
break;
} else {
// the order is important..
highestContiguousMsgId = msgId;
nonContiguousMsgIds.remove(msgId);
}
}
} | java | private void reconcile() {
// If nonContiguousMsgIds is empty then nothing to reconcile.
if (nonContiguousMsgIds.isEmpty()) {
return;
}
// This happens when a passive is started after Active has moved on and
// passive starts to see msgIDs starting from a number > 0.
// Once the sync is completed, fast forward highestContiguousMsgId.
// Post sync completion assuming platform will send all msgIds beyond highestContiguousMsgId.
if (highestContiguousMsgId == -1L && isSyncCompleted) {
Long min = nonContiguousMsgIds.last();
LOGGER.info("Setting highestContiguousMsgId to {} from -1", min);
highestContiguousMsgId = min;
nonContiguousMsgIds.removeIf(msgId -> msgId <= min);
}
for (long msgId : nonContiguousMsgIds) {
if (msgId <= highestContiguousMsgId) {
nonContiguousMsgIds.remove(msgId);
} else if (msgId > highestContiguousMsgId + 1) {
break;
} else {
// the order is important..
highestContiguousMsgId = msgId;
nonContiguousMsgIds.remove(msgId);
}
}
} | [
"private",
"void",
"reconcile",
"(",
")",
"{",
"// If nonContiguousMsgIds is empty then nothing to reconcile.",
"if",
"(",
"nonContiguousMsgIds",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"// This happens when a passive is started after Active has moved on and",
... | Remove the contiguous seen msgIds from the nonContiguousMsgIds and update highestContiguousMsgId | [
"Remove",
"the",
"contiguous",
"seen",
"msgIds",
"from",
"the",
"nonContiguousMsgIds",
"and",
"update",
"highestContiguousMsgId"
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/server/src/main/java/org/ehcache/clustered/server/state/MessageTracker.java#L97-L127 | train |
ehcache/ehcache3 | clustered/server/src/main/java/org/ehcache/clustered/server/state/MessageTracker.java | MessageTracker.tryReconcile | private void tryReconcile() {
if (!this.reconciliationLock.tryLock()) {
return;
}
try {
reconcile();
// Keep on warning after every reconcile if nonContiguousMsgIds reaches 500 (kept it a bit higher so that we won't get unnecessary warning due to high concurrency).
if (nonContiguousMsgIds.size() > 500) {
LOGGER.warn("Non - Contiguous Message ID has size : {}, with highestContiguousMsgId as : {}", nonContiguousMsgIds.size(), highestContiguousMsgId);
}
} finally {
this.reconciliationLock.unlock();
}
} | java | private void tryReconcile() {
if (!this.reconciliationLock.tryLock()) {
return;
}
try {
reconcile();
// Keep on warning after every reconcile if nonContiguousMsgIds reaches 500 (kept it a bit higher so that we won't get unnecessary warning due to high concurrency).
if (nonContiguousMsgIds.size() > 500) {
LOGGER.warn("Non - Contiguous Message ID has size : {}, with highestContiguousMsgId as : {}", nonContiguousMsgIds.size(), highestContiguousMsgId);
}
} finally {
this.reconciliationLock.unlock();
}
} | [
"private",
"void",
"tryReconcile",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"reconciliationLock",
".",
"tryLock",
"(",
")",
")",
"{",
"return",
";",
"}",
"try",
"{",
"reconcile",
"(",
")",
";",
"// Keep on warning after every reconcile if nonContiguousMsgIds ... | Try to reconcile, if the lock is available otherwise just return as other thread would have hold the lock and performing reconcile. | [
"Try",
"to",
"reconcile",
"if",
"the",
"lock",
"is",
"available",
"otherwise",
"just",
"return",
"as",
"other",
"thread",
"would",
"have",
"hold",
"the",
"lock",
"and",
"performing",
"reconcile",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/server/src/main/java/org/ehcache/clustered/server/state/MessageTracker.java#L132-L147 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/config/resilience/DefaultResilienceStrategyConfiguration.java | DefaultResilienceStrategyConfiguration.bind | public DefaultResilienceStrategyConfiguration bind(RecoveryStore<?> store, CacheLoaderWriter<?, ?> loaderWriter) throws IllegalStateException {
if (getInstance() == null) {
Object[] arguments = getArguments();
Object[] boundArguments = Arrays.copyOf(arguments, arguments.length + 2);
boundArguments[arguments.length] = store;
boundArguments[arguments.length + 1] = loaderWriter;
return new BoundConfiguration(getClazz(), boundArguments);
} else {
return this;
}
} | java | public DefaultResilienceStrategyConfiguration bind(RecoveryStore<?> store, CacheLoaderWriter<?, ?> loaderWriter) throws IllegalStateException {
if (getInstance() == null) {
Object[] arguments = getArguments();
Object[] boundArguments = Arrays.copyOf(arguments, arguments.length + 2);
boundArguments[arguments.length] = store;
boundArguments[arguments.length + 1] = loaderWriter;
return new BoundConfiguration(getClazz(), boundArguments);
} else {
return this;
}
} | [
"public",
"DefaultResilienceStrategyConfiguration",
"bind",
"(",
"RecoveryStore",
"<",
"?",
">",
"store",
",",
"CacheLoaderWriter",
"<",
"?",
",",
"?",
">",
"loaderWriter",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"getInstance",
"(",
")",
"==",
"n... | Returns a configuration object bound to the given store and cache loader-writer.
@param store store to bind to
@param loaderWriter loader to bind to
@return a bound configuration
@throws IllegalStateException if the configuration is already bound | [
"Returns",
"a",
"configuration",
"object",
"bound",
"to",
"the",
"given",
"store",
"and",
"cache",
"loader",
"-",
"writer",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/config/resilience/DefaultResilienceStrategyConfiguration.java#L68-L78 | train |
ehcache/ehcache3 | core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java | AbstractValueHolder.setLastAccessTime | public void setLastAccessTime(long lastAccessTime) {
while (true) {
long current = this.lastAccessTime;
if (current >= lastAccessTime) {
break;
}
if (ACCESSTIME_UPDATER.compareAndSet(this, current, lastAccessTime)) {
break;
}
}
} | java | public void setLastAccessTime(long lastAccessTime) {
while (true) {
long current = this.lastAccessTime;
if (current >= lastAccessTime) {
break;
}
if (ACCESSTIME_UPDATER.compareAndSet(this, current, lastAccessTime)) {
break;
}
}
} | [
"public",
"void",
"setLastAccessTime",
"(",
"long",
"lastAccessTime",
")",
"{",
"while",
"(",
"true",
")",
"{",
"long",
"current",
"=",
"this",
".",
"lastAccessTime",
";",
"if",
"(",
"current",
">=",
"lastAccessTime",
")",
"{",
"break",
";",
"}",
"if",
"... | Set the last time this entry was accessed in milliseconds.
@param lastAccessTime last time the entry was accessed | [
"Set",
"the",
"last",
"time",
"this",
"entry",
"was",
"accessed",
"in",
"milliseconds",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java#L125-L135 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/EternalChainResolver.java | EternalChainResolver.applyOperation | public PutOperation<K, V> applyOperation(K key, PutOperation<K, V> existing, Operation<K, V> operation) {
final Result<K, V> newValue = operation.apply(existing);
if (newValue == null) {
return null;
} else {
return newValue.asOperationExpiringAt(Long.MAX_VALUE);
}
} | java | public PutOperation<K, V> applyOperation(K key, PutOperation<K, V> existing, Operation<K, V> operation) {
final Result<K, V> newValue = operation.apply(existing);
if (newValue == null) {
return null;
} else {
return newValue.asOperationExpiringAt(Long.MAX_VALUE);
}
} | [
"public",
"PutOperation",
"<",
"K",
",",
"V",
">",
"applyOperation",
"(",
"K",
"key",
",",
"PutOperation",
"<",
"K",
",",
"V",
">",
"existing",
",",
"Operation",
"<",
"K",
",",
"V",
">",
"operation",
")",
"{",
"final",
"Result",
"<",
"K",
",",
"V",... | Applies the given operation returning a result that never expires.
{@inheritDoc} | [
"Applies",
"the",
"given",
"operation",
"returning",
"a",
"result",
"that",
"never",
"expires",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/EternalChainResolver.java#L69-L76 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java | ClusteredStore.bulkCompute | @Override
public Map<K, ValueHolder<V>> bulkCompute(final Set<? extends K> keys, final Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>> remappingFunction)
throws StoreAccessException {
Map<K, ValueHolder<V>> valueHolderMap = new HashMap<>();
if(remappingFunction instanceof Ehcache.PutAllFunction) {
Ehcache.PutAllFunction<K, V> putAllFunction = (Ehcache.PutAllFunction<K, V>)remappingFunction;
Map<K, V> entriesToRemap = putAllFunction.getEntriesToRemap();
for(Map.Entry<K, V> entry: entriesToRemap.entrySet()) {
PutStatus putStatus = silentPut(entry.getKey(), entry.getValue());
if(putStatus == PutStatus.PUT) {
putAllFunction.getActualPutCount().incrementAndGet();
valueHolderMap.put(entry.getKey(), new ClusteredValueHolder<>(entry.getValue()));
}
}
} else if(remappingFunction instanceof Ehcache.RemoveAllFunction) {
Ehcache.RemoveAllFunction<K, V> removeAllFunction = (Ehcache.RemoveAllFunction<K, V>)remappingFunction;
for (K key : keys) {
boolean removed = silentRemove(key);
if(removed) {
removeAllFunction.getActualRemoveCount().incrementAndGet();
}
}
} else {
throw new UnsupportedOperationException("This bulkCompute method is not yet capable of handling generic computation functions");
}
return valueHolderMap;
} | java | @Override
public Map<K, ValueHolder<V>> bulkCompute(final Set<? extends K> keys, final Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>> remappingFunction)
throws StoreAccessException {
Map<K, ValueHolder<V>> valueHolderMap = new HashMap<>();
if(remappingFunction instanceof Ehcache.PutAllFunction) {
Ehcache.PutAllFunction<K, V> putAllFunction = (Ehcache.PutAllFunction<K, V>)remappingFunction;
Map<K, V> entriesToRemap = putAllFunction.getEntriesToRemap();
for(Map.Entry<K, V> entry: entriesToRemap.entrySet()) {
PutStatus putStatus = silentPut(entry.getKey(), entry.getValue());
if(putStatus == PutStatus.PUT) {
putAllFunction.getActualPutCount().incrementAndGet();
valueHolderMap.put(entry.getKey(), new ClusteredValueHolder<>(entry.getValue()));
}
}
} else if(remappingFunction instanceof Ehcache.RemoveAllFunction) {
Ehcache.RemoveAllFunction<K, V> removeAllFunction = (Ehcache.RemoveAllFunction<K, V>)remappingFunction;
for (K key : keys) {
boolean removed = silentRemove(key);
if(removed) {
removeAllFunction.getActualRemoveCount().incrementAndGet();
}
}
} else {
throw new UnsupportedOperationException("This bulkCompute method is not yet capable of handling generic computation functions");
}
return valueHolderMap;
} | [
"@",
"Override",
"public",
"Map",
"<",
"K",
",",
"ValueHolder",
"<",
"V",
">",
">",
"bulkCompute",
"(",
"final",
"Set",
"<",
"?",
"extends",
"K",
">",
"keys",
",",
"final",
"Function",
"<",
"Iterable",
"<",
"?",
"extends",
"Map",
".",
"Entry",
"<",
... | The assumption is that this method will be invoked only by cache.putAll and cache.removeAll methods. | [
"The",
"assumption",
"is",
"that",
"this",
"method",
"will",
"be",
"invoked",
"only",
"by",
"cache",
".",
"putAll",
"and",
"cache",
".",
"removeAll",
"methods",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java#L475-L501 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java | RobustResilienceStrategy.getFailure | @Override
public V getFailure(K key, StoreAccessException e) {
cleanup(key, e);
return null;
} | java | @Override
public V getFailure(K key, StoreAccessException e) {
cleanup(key, e);
return null;
} | [
"@",
"Override",
"public",
"V",
"getFailure",
"(",
"K",
"key",
",",
"StoreAccessException",
"e",
")",
"{",
"cleanup",
"(",
"key",
",",
"e",
")",
";",
"return",
"null",
";",
"}"
] | Return null.
@param key the key being retrieved
@param e the triggered failure
@return null | [
"Return",
"null",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java#L54-L58 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java | RobustResilienceStrategy.putIfAbsentFailure | @Override
public V putIfAbsentFailure(K key, V value, StoreAccessException e) {
cleanup(key, e);
return null;
} | java | @Override
public V putIfAbsentFailure(K key, V value, StoreAccessException e) {
cleanup(key, e);
return null;
} | [
"@",
"Override",
"public",
"V",
"putIfAbsentFailure",
"(",
"K",
"key",
",",
"V",
"value",
",",
"StoreAccessException",
"e",
")",
"{",
"cleanup",
"(",
"key",
",",
"e",
")",
";",
"return",
"null",
";",
"}"
] | Do nothing and return null.
@param key the key being put
@param value the value being put
@param e the triggered failure
@return null | [
"Do",
"nothing",
"and",
"return",
"null",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java#L114-L118 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java | RobustResilienceStrategy.getAllFailure | @Override
public Map<K, V> getAllFailure(Iterable<? extends K> keys, StoreAccessException e) {
cleanup(keys, e);
HashMap<K, V> result = keys instanceof Collection<?> ? new HashMap<>(((Collection<? extends K>) keys).size()) : new HashMap<>();
for (K key : keys) {
result.put(key, null);
}
return result;
} | java | @Override
public Map<K, V> getAllFailure(Iterable<? extends K> keys, StoreAccessException e) {
cleanup(keys, e);
HashMap<K, V> result = keys instanceof Collection<?> ? new HashMap<>(((Collection<? extends K>) keys).size()) : new HashMap<>();
for (K key : keys) {
result.put(key, null);
}
return result;
} | [
"@",
"Override",
"public",
"Map",
"<",
"K",
",",
"V",
">",
"getAllFailure",
"(",
"Iterable",
"<",
"?",
"extends",
"K",
">",
"keys",
",",
"StoreAccessException",
"e",
")",
"{",
"cleanup",
"(",
"keys",
",",
"e",
")",
";",
"HashMap",
"<",
"K",
",",
"V... | Do nothing and return a map of all the provided keys and null values.
@param keys the keys being retrieved
@param e the triggered failure
@return map of all provided keys and null values | [
"Do",
"nothing",
"and",
"return",
"a",
"map",
"of",
"all",
"the",
"provided",
"keys",
"and",
"null",
"values",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java#L170-L179 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/config/builders/PooledExecutionServiceConfigurationBuilder.java | PooledExecutionServiceConfigurationBuilder.defaultPool | public PooledExecutionServiceConfigurationBuilder defaultPool(String alias, int minSize, int maxSize) {
PooledExecutionServiceConfigurationBuilder other = new PooledExecutionServiceConfigurationBuilder(this);
other.defaultPool = new Pool(alias, minSize, maxSize);
return other;
} | java | public PooledExecutionServiceConfigurationBuilder defaultPool(String alias, int minSize, int maxSize) {
PooledExecutionServiceConfigurationBuilder other = new PooledExecutionServiceConfigurationBuilder(this);
other.defaultPool = new Pool(alias, minSize, maxSize);
return other;
} | [
"public",
"PooledExecutionServiceConfigurationBuilder",
"defaultPool",
"(",
"String",
"alias",
",",
"int",
"minSize",
",",
"int",
"maxSize",
")",
"{",
"PooledExecutionServiceConfigurationBuilder",
"other",
"=",
"new",
"PooledExecutionServiceConfigurationBuilder",
"(",
"this",... | Adds a default pool configuration to the returned builder.
@param alias the pool alias
@param minSize the minimum number of threads in the pool
@param maxSize the maximum number of threads in the pool
@return a new builder with the added default pool | [
"Adds",
"a",
"default",
"pool",
"configuration",
"to",
"the",
"returned",
"builder",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/PooledExecutionServiceConfigurationBuilder.java#L63-L67 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/config/builders/PooledExecutionServiceConfigurationBuilder.java | PooledExecutionServiceConfigurationBuilder.pool | public PooledExecutionServiceConfigurationBuilder pool(String alias, int minSize, int maxSize) {
PooledExecutionServiceConfigurationBuilder other = new PooledExecutionServiceConfigurationBuilder(this);
other.pools.add(new Pool(alias, minSize, maxSize));
return other;
} | java | public PooledExecutionServiceConfigurationBuilder pool(String alias, int minSize, int maxSize) {
PooledExecutionServiceConfigurationBuilder other = new PooledExecutionServiceConfigurationBuilder(this);
other.pools.add(new Pool(alias, minSize, maxSize));
return other;
} | [
"public",
"PooledExecutionServiceConfigurationBuilder",
"pool",
"(",
"String",
"alias",
",",
"int",
"minSize",
",",
"int",
"maxSize",
")",
"{",
"PooledExecutionServiceConfigurationBuilder",
"other",
"=",
"new",
"PooledExecutionServiceConfigurationBuilder",
"(",
"this",
")",... | Adds a pool configuration to the returned builder.
@param alias the pool alias
@param minSize the minimum number of threads in the pool
@param maxSize the maximum number of threads in the pool
@return a new builder with the added default pool | [
"Adds",
"a",
"pool",
"configuration",
"to",
"the",
"returned",
"builder",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/PooledExecutionServiceConfigurationBuilder.java#L77-L81 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java | ExpiryChainResolver.calculateExpiryTime | private long calculateExpiryTime(K key, PutOperation<K, V> existing, Operation<K, V> operation, Result<K, V> newValue) {
if (operation.isExpiryAvailable()) {
return operation.expirationTime();
} else {
try {
Duration duration;
if (existing == null) {
duration = requireNonNull(expiry.getExpiryForCreation(key, newValue.getValue()));
} else {
duration = expiry.getExpiryForUpdate(key, existing::getValue, newValue.getValue());
if (duration == null) {
return existing.expirationTime();
}
}
if (duration.isNegative()) {
duration = Duration.ZERO;
} else if (isExpiryDurationInfinite(duration)) {
return Long.MAX_VALUE;
}
return ExpiryUtils.getExpirationMillis(operation.timeStamp(), duration);
} catch (Exception ex) {
LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", ex);
return Long.MIN_VALUE;
}
}
} | java | private long calculateExpiryTime(K key, PutOperation<K, V> existing, Operation<K, V> operation, Result<K, V> newValue) {
if (operation.isExpiryAvailable()) {
return operation.expirationTime();
} else {
try {
Duration duration;
if (existing == null) {
duration = requireNonNull(expiry.getExpiryForCreation(key, newValue.getValue()));
} else {
duration = expiry.getExpiryForUpdate(key, existing::getValue, newValue.getValue());
if (duration == null) {
return existing.expirationTime();
}
}
if (duration.isNegative()) {
duration = Duration.ZERO;
} else if (isExpiryDurationInfinite(duration)) {
return Long.MAX_VALUE;
}
return ExpiryUtils.getExpirationMillis(operation.timeStamp(), duration);
} catch (Exception ex) {
LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", ex);
return Long.MIN_VALUE;
}
}
} | [
"private",
"long",
"calculateExpiryTime",
"(",
"K",
"key",
",",
"PutOperation",
"<",
"K",
",",
"V",
">",
"existing",
",",
"Operation",
"<",
"K",
",",
"V",
">",
"operation",
",",
"Result",
"<",
"K",
",",
"V",
">",
"newValue",
")",
"{",
"if",
"(",
"o... | Calculates the expiration time of the new state based on this resolvers expiry policy.
@param key cache key
@param existing current state
@param operation operation to apply
@param newValue new state
@return the calculated expiry time | [
"Calculates",
"the",
"expiration",
"time",
"of",
"the",
"new",
"state",
"based",
"on",
"this",
"resolvers",
"expiry",
"policy",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java#L130-L155 | train |
ehcache/ehcache3 | management/src/main/java/org/ehcache/management/cluster/Clustering.java | Clustering.isAvailable | public static boolean isAvailable(ServiceProvider<Service> serviceProvider) {
return ENTITY_SERVICE_CLASS != null && serviceProvider.getService(ENTITY_SERVICE_CLASS) != null;
} | java | public static boolean isAvailable(ServiceProvider<Service> serviceProvider) {
return ENTITY_SERVICE_CLASS != null && serviceProvider.getService(ENTITY_SERVICE_CLASS) != null;
} | [
"public",
"static",
"boolean",
"isAvailable",
"(",
"ServiceProvider",
"<",
"Service",
">",
"serviceProvider",
")",
"{",
"return",
"ENTITY_SERVICE_CLASS",
"!=",
"null",
"&&",
"serviceProvider",
".",
"getService",
"(",
"ENTITY_SERVICE_CLASS",
")",
"!=",
"null",
";",
... | Check if clustering is active for this cache manager | [
"Check",
"if",
"clustering",
"is",
"active",
"for",
"this",
"cache",
"manager"
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/management/src/main/java/org/ehcache/management/cluster/Clustering.java#L42-L44 | train |
ehcache/ehcache3 | core/src/main/java/org/ehcache/core/util/CollectionUtil.java | CollectionUtil.findBestCollectionSize | public static int findBestCollectionSize(Iterable<?> iterable, int bestBet) {
return (iterable instanceof Collection ? ((Collection<?>) iterable).size() : bestBet);
} | java | public static int findBestCollectionSize(Iterable<?> iterable, int bestBet) {
return (iterable instanceof Collection ? ((Collection<?>) iterable).size() : bestBet);
} | [
"public",
"static",
"int",
"findBestCollectionSize",
"(",
"Iterable",
"<",
"?",
">",
"iterable",
",",
"int",
"bestBet",
")",
"{",
"return",
"(",
"iterable",
"instanceof",
"Collection",
"?",
"(",
"(",
"Collection",
"<",
"?",
">",
")",
"iterable",
")",
".",
... | Used to create a new collection with the correct size. Given an iterable, will try to see it the iterable actually
have a size and will return it. If the iterable has no known size, we return the best bet.
@param iterable the iterable we will try to find the size of
@param bestBet our best bet for the size if the iterable is not sizeable
@return the size of the iterable if found or null | [
"Used",
"to",
"create",
"a",
"new",
"collection",
"with",
"the",
"correct",
"size",
".",
"Given",
"an",
"iterable",
"will",
"try",
"to",
"see",
"it",
"the",
"iterable",
"actually",
"have",
"a",
"size",
"and",
"will",
"return",
"it",
".",
"If",
"the",
"... | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/core/src/main/java/org/ehcache/core/util/CollectionUtil.java#L37-L39 | train |
ehcache/ehcache3 | clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteredResourcePoolBuilder.java | ClusteredResourcePoolBuilder.clusteredDedicated | public static DedicatedClusteredResourcePool clusteredDedicated(String fromResource, long size, MemoryUnit unit) {
return new DedicatedClusteredResourcePoolImpl(fromResource, size, unit);
} | java | public static DedicatedClusteredResourcePool clusteredDedicated(String fromResource, long size, MemoryUnit unit) {
return new DedicatedClusteredResourcePoolImpl(fromResource, size, unit);
} | [
"public",
"static",
"DedicatedClusteredResourcePool",
"clusteredDedicated",
"(",
"String",
"fromResource",
",",
"long",
"size",
",",
"MemoryUnit",
"unit",
")",
"{",
"return",
"new",
"DedicatedClusteredResourcePoolImpl",
"(",
"fromResource",
",",
"size",
",",
"unit",
"... | Creates a new clustered resource pool using dedicated clustered resources.
@param fromResource the name of the server-based resource from which this dedicated resource pool
is reserved; may be {@code null}
@param size the size
@param unit the unit for the size | [
"Creates",
"a",
"new",
"clustered",
"resource",
"pool",
"using",
"dedicated",
"clustered",
"resources",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteredResourcePoolBuilder.java#L54-L56 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java | StatsUtils.findStatisticOnDescendants | public static <T> Optional<T> findStatisticOnDescendants(Object context, String tag, String statName) {
@SuppressWarnings("unchecked")
Set<TreeNode> statResult = queryBuilder()
.descendants()
.filter(context(attributes(Matchers.allOf(
hasAttribute("name", statName),
hasTag(tag)))))
.build().execute(Collections.singleton(ContextManager.nodeFor(context)));
if (statResult.size() > 1) {
throw new RuntimeException("One stat expected for " + statName + " but found " + statResult.size());
}
if (statResult.size() == 1) {
@SuppressWarnings("unchecked")
T result = (T) statResult.iterator().next().getContext().attributes().get("this");
return Optional.ofNullable(result);
}
// No such stat in this context
return Optional.empty();
} | java | public static <T> Optional<T> findStatisticOnDescendants(Object context, String tag, String statName) {
@SuppressWarnings("unchecked")
Set<TreeNode> statResult = queryBuilder()
.descendants()
.filter(context(attributes(Matchers.allOf(
hasAttribute("name", statName),
hasTag(tag)))))
.build().execute(Collections.singleton(ContextManager.nodeFor(context)));
if (statResult.size() > 1) {
throw new RuntimeException("One stat expected for " + statName + " but found " + statResult.size());
}
if (statResult.size() == 1) {
@SuppressWarnings("unchecked")
T result = (T) statResult.iterator().next().getContext().attributes().get("this");
return Optional.ofNullable(result);
}
// No such stat in this context
return Optional.empty();
} | [
"public",
"static",
"<",
"T",
">",
"Optional",
"<",
"T",
">",
"findStatisticOnDescendants",
"(",
"Object",
"context",
",",
"String",
"tag",
",",
"String",
"statName",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Set",
"<",
"TreeNode",
">",
... | Search for a statistic on the descendant of the context that matches the tag and statistic name.
@param context the context of the query
@param tag the tag we are looking for
@param statName statistic name
@param <T> type of the statistic that will be returned
@return the wanted statistic or null if no such statistic is found
@throws RuntimeException when more than one matching statistic is found | [
"Search",
"for",
"a",
"statistic",
"on",
"the",
"descendant",
"of",
"the",
"context",
"that",
"matches",
"the",
"tag",
"and",
"statistic",
"name",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java#L108-L130 | train |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/BatchingLocalHeapWriteBehindQueue.java | BatchingLocalHeapWriteBehindQueue.getQueueSize | @Override
public long getQueueSize() {
Batch snapshot = openBatch;
return executorQueue.size() * batchSize + (snapshot == null ? 0 : snapshot.size());
} | java | @Override
public long getQueueSize() {
Batch snapshot = openBatch;
return executorQueue.size() * batchSize + (snapshot == null ? 0 : snapshot.size());
} | [
"@",
"Override",
"public",
"long",
"getQueueSize",
"(",
")",
"{",
"Batch",
"snapshot",
"=",
"openBatch",
";",
"return",
"executorQueue",
".",
"size",
"(",
")",
"*",
"batchSize",
"+",
"(",
"snapshot",
"==",
"null",
"?",
"0",
":",
"snapshot",
".",
"size",
... | Gets the best estimate for items in the queue still awaiting processing.
Since the value returned is a rough estimate, it can sometimes be more than
the number of items actually in the queue but not less.
@return the amount of elements still awaiting processing. | [
"Gets",
"the",
"best",
"estimate",
"for",
"items",
"in",
"the",
"queue",
"still",
"awaiting",
"processing",
".",
"Since",
"the",
"value",
"returned",
"is",
"a",
"rough",
"estimate",
"it",
"can",
"sometimes",
"be",
"more",
"than",
"the",
"number",
"of",
"it... | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/BatchingLocalHeapWriteBehindQueue.java#L162-L166 | train |
ehcache/ehcache3 | clustered/common/src/main/java/org/ehcache/clustered/common/internal/store/operations/PutIfAbsentOperation.java | PutIfAbsentOperation.apply | @Override
public Result<K, V> apply(final Result<K, V> previousOperation) {
if(previousOperation == null) {
return this;
} else {
return previousOperation;
}
} | java | @Override
public Result<K, V> apply(final Result<K, V> previousOperation) {
if(previousOperation == null) {
return this;
} else {
return previousOperation;
}
} | [
"@",
"Override",
"public",
"Result",
"<",
"K",
",",
"V",
">",
"apply",
"(",
"final",
"Result",
"<",
"K",
",",
"V",
">",
"previousOperation",
")",
"{",
"if",
"(",
"previousOperation",
"==",
"null",
")",
"{",
"return",
"this",
";",
"}",
"else",
"{",
... | PutIfAbsent operation succeeds only when there is no previous operation
for the same key. | [
"PutIfAbsent",
"operation",
"succeeds",
"only",
"when",
"there",
"is",
"no",
"previous",
"operation",
"for",
"the",
"same",
"key",
"."
] | 3cceda57185e522f8d241ddb75146d67ee2af898 | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/clustered/common/src/main/java/org/ehcache/clustered/common/internal/store/operations/PutIfAbsentOperation.java#L42-L49 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/CohenSutherlandClipping.java | CohenSutherlandClipping.setClip | public void setClip(Rectangle2D clip) {
xMin = clip.getX();
xMax = xMin + clip.getWidth();
yMin = clip.getY();
yMax = yMin + clip.getHeight();
} | java | public void setClip(Rectangle2D clip) {
xMin = clip.getX();
xMax = xMin + clip.getWidth();
yMin = clip.getY();
yMax = yMin + clip.getHeight();
} | [
"public",
"void",
"setClip",
"(",
"Rectangle2D",
"clip",
")",
"{",
"xMin",
"=",
"clip",
".",
"getX",
"(",
")",
";",
"xMax",
"=",
"xMin",
"+",
"clip",
".",
"getWidth",
"(",
")",
";",
"yMin",
"=",
"clip",
".",
"getY",
"(",
")",
";",
"yMax",
"=",
... | Sets the clip rectangle.
@param clip the clip rectangle | [
"Sets",
"the",
"clip",
"rectangle",
"."
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/CohenSutherlandClipping.java#L46-L51 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/QuickSort.java | QuickSort.sort | public static <T extends Comparable<? super T>> void sort(List<T> list) {
sort(list, QuickSort.<T>naturalOrder()); // JAVA_8 replace with Comparator.naturalOrder() (and cleanup)
} | java | public static <T extends Comparable<? super T>> void sort(List<T> list) {
sort(list, QuickSort.<T>naturalOrder()); // JAVA_8 replace with Comparator.naturalOrder() (and cleanup)
} | [
"public",
"static",
"<",
"T",
"extends",
"Comparable",
"<",
"?",
"super",
"T",
">",
">",
"void",
"sort",
"(",
"List",
"<",
"T",
">",
"list",
")",
"{",
"sort",
"(",
"list",
",",
"QuickSort",
".",
"<",
"T",
">",
"naturalOrder",
"(",
")",
")",
";",
... | Sorts the given list according to natural order. | [
"Sorts",
"the",
"given",
"list",
"according",
"to",
"natural",
"order",
"."
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/QuickSort.java#L41-L43 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/QuickSort.java | QuickSort.sort | public static <T> void sort(List<T> list, Comparator<? super T> comparator) {
if (list instanceof RandomAccess) {
quicksort(list, comparator);
} else {
List<T> copy = new ArrayList<>(list);
quicksort(copy, comparator);
list.clear();
list.addAll(copy);
}
} | java | public static <T> void sort(List<T> list, Comparator<? super T> comparator) {
if (list instanceof RandomAccess) {
quicksort(list, comparator);
} else {
List<T> copy = new ArrayList<>(list);
quicksort(copy, comparator);
list.clear();
list.addAll(copy);
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"sort",
"(",
"List",
"<",
"T",
">",
"list",
",",
"Comparator",
"<",
"?",
"super",
"T",
">",
"comparator",
")",
"{",
"if",
"(",
"list",
"instanceof",
"RandomAccess",
")",
"{",
"quicksort",
"(",
"list",
",",
... | Sorts the given list using the given comparator. | [
"Sorts",
"the",
"given",
"list",
"using",
"the",
"given",
"comparator",
"."
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/QuickSort.java#L48-L57 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/Page.java | Page.getTextBounds | public Rectangle getTextBounds() {
List<TextElement> texts = this.getText();
if (!texts.isEmpty()) {
return Utils.bounds(texts);
}
else {
return new Rectangle();
}
} | java | public Rectangle getTextBounds() {
List<TextElement> texts = this.getText();
if (!texts.isEmpty()) {
return Utils.bounds(texts);
}
else {
return new Rectangle();
}
} | [
"public",
"Rectangle",
"getTextBounds",
"(",
")",
"{",
"List",
"<",
"TextElement",
">",
"texts",
"=",
"this",
".",
"getText",
"(",
")",
";",
"if",
"(",
"!",
"texts",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"Utils",
".",
"bounds",
"(",
"texts",
... | Returns the minimum bounding box that contains all the TextElements on this Page | [
"Returns",
"the",
"minimum",
"bounding",
"box",
"that",
"contains",
"all",
"the",
"TextElements",
"on",
"this",
"Page"
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/Page.java#L139-L148 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/ProjectionProfile.java | ProjectionProfile.filter | public static float[] filter(float[] data, float alpha) {
float[] rv = new float[data.length];
rv[0] = data[0];
for (int i = 1; i < data.length; i++) {
rv[i] = rv[i-1] + alpha * (data[i] - rv[i-1]);
}
return rv;
} | java | public static float[] filter(float[] data, float alpha) {
float[] rv = new float[data.length];
rv[0] = data[0];
for (int i = 1; i < data.length; i++) {
rv[i] = rv[i-1] + alpha * (data[i] - rv[i-1]);
}
return rv;
} | [
"public",
"static",
"float",
"[",
"]",
"filter",
"(",
"float",
"[",
"]",
"data",
",",
"float",
"alpha",
")",
"{",
"float",
"[",
"]",
"rv",
"=",
"new",
"float",
"[",
"data",
".",
"length",
"]",
";",
"rv",
"[",
"0",
"]",
"=",
"data",
"[",
"0",
... | Simple Low pass filter | [
"Simple",
"Low",
"pass",
"filter"
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/ProjectionProfile.java#L180-L189 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/extractors/SpreadsheetExtractionAlgorithm.java | SpreadsheetExtractionAlgorithm.extract | public List<Table> extract(Page page, List<Ruling> rulings) {
// split rulings into horizontal and vertical
List<Ruling> horizontalR = new ArrayList<>(),
verticalR = new ArrayList<>();
for (Ruling r: rulings) {
if (r.horizontal()) {
horizontalR.add(r);
}
else if (r.vertical()) {
verticalR.add(r);
}
}
horizontalR = Ruling.collapseOrientedRulings(horizontalR);
verticalR = Ruling.collapseOrientedRulings(verticalR);
List<Cell> cells = findCells(horizontalR, verticalR);
List<Rectangle> spreadsheetAreas = findSpreadsheetsFromCells(cells);
List<Table> spreadsheets = new ArrayList<>();
for (Rectangle area: spreadsheetAreas) {
List<Cell> overlappingCells = new ArrayList<>();
for (Cell c: cells) {
if (c.intersects(area)) {
c.setTextElements(TextElement.mergeWords(page.getText(c)));
overlappingCells.add(c);
}
}
List<Ruling> horizontalOverlappingRulings = new ArrayList<>();
for (Ruling hr: horizontalR) {
if (area.intersectsLine(hr)) {
horizontalOverlappingRulings.add(hr);
}
}
List<Ruling> verticalOverlappingRulings = new ArrayList<>();
for (Ruling vr: verticalR) {
if (area.intersectsLine(vr)) {
verticalOverlappingRulings.add(vr);
}
}
TableWithRulingLines t = new TableWithRulingLines(area, overlappingCells, horizontalOverlappingRulings, verticalOverlappingRulings, this);
spreadsheets.add(t);
}
Utils.sort(spreadsheets, Rectangle.ILL_DEFINED_ORDER);
return spreadsheets;
} | java | public List<Table> extract(Page page, List<Ruling> rulings) {
// split rulings into horizontal and vertical
List<Ruling> horizontalR = new ArrayList<>(),
verticalR = new ArrayList<>();
for (Ruling r: rulings) {
if (r.horizontal()) {
horizontalR.add(r);
}
else if (r.vertical()) {
verticalR.add(r);
}
}
horizontalR = Ruling.collapseOrientedRulings(horizontalR);
verticalR = Ruling.collapseOrientedRulings(verticalR);
List<Cell> cells = findCells(horizontalR, verticalR);
List<Rectangle> spreadsheetAreas = findSpreadsheetsFromCells(cells);
List<Table> spreadsheets = new ArrayList<>();
for (Rectangle area: spreadsheetAreas) {
List<Cell> overlappingCells = new ArrayList<>();
for (Cell c: cells) {
if (c.intersects(area)) {
c.setTextElements(TextElement.mergeWords(page.getText(c)));
overlappingCells.add(c);
}
}
List<Ruling> horizontalOverlappingRulings = new ArrayList<>();
for (Ruling hr: horizontalR) {
if (area.intersectsLine(hr)) {
horizontalOverlappingRulings.add(hr);
}
}
List<Ruling> verticalOverlappingRulings = new ArrayList<>();
for (Ruling vr: verticalR) {
if (area.intersectsLine(vr)) {
verticalOverlappingRulings.add(vr);
}
}
TableWithRulingLines t = new TableWithRulingLines(area, overlappingCells, horizontalOverlappingRulings, verticalOverlappingRulings, this);
spreadsheets.add(t);
}
Utils.sort(spreadsheets, Rectangle.ILL_DEFINED_ORDER);
return spreadsheets;
} | [
"public",
"List",
"<",
"Table",
">",
"extract",
"(",
"Page",
"page",
",",
"List",
"<",
"Ruling",
">",
"rulings",
")",
"{",
"// split rulings into horizontal and vertical",
"List",
"<",
"Ruling",
">",
"horizontalR",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
",... | Extract a list of Table from page using rulings as separators | [
"Extract",
"a",
"list",
"of",
"Table",
"from",
"page",
"using",
"rulings",
"as",
"separators"
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/extractors/SpreadsheetExtractionAlgorithm.java#L90-L139 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/Utils.java | Utils.sort | public static <T extends Comparable<? super T>> void sort(List<T> list) {
if (useQuickSort) QuickSort.sort(list);
else Collections.sort(list);
} | java | public static <T extends Comparable<? super T>> void sort(List<T> list) {
if (useQuickSort) QuickSort.sort(list);
else Collections.sort(list);
} | [
"public",
"static",
"<",
"T",
"extends",
"Comparable",
"<",
"?",
"super",
"T",
">",
">",
"void",
"sort",
"(",
"List",
"<",
"T",
">",
"list",
")",
"{",
"if",
"(",
"useQuickSort",
")",
"QuickSort",
".",
"sort",
"(",
"list",
")",
";",
"else",
"Collect... | Wrap Collections.sort so we can fallback to a non-stable quicksort if we're
running on JDK7+ | [
"Wrap",
"Collections",
".",
"sort",
"so",
"we",
"can",
"fallback",
"to",
"a",
"non",
"-",
"stable",
"quicksort",
"if",
"we",
"re",
"running",
"on",
"JDK7",
"+"
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/Utils.java#L124-L127 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/Ruling.java | Ruling.normalize | public void normalize() {
double angle = this.getAngle();
if (Utils.within(angle, 0, 1) || Utils.within(angle, 180, 1)) { // almost horizontal
this.setLine(this.x1, this.y1, this.x2, this.y1);
}
else if (Utils.within(angle, 90, 1) || Utils.within(angle, 270, 1)) { // almost vertical
this.setLine(this.x1, this.y1, this.x1, this.y2);
}
// else {
// System.out.println("oblique: " + this + " ("+ this.getAngle() + ")");
// }
} | java | public void normalize() {
double angle = this.getAngle();
if (Utils.within(angle, 0, 1) || Utils.within(angle, 180, 1)) { // almost horizontal
this.setLine(this.x1, this.y1, this.x2, this.y1);
}
else if (Utils.within(angle, 90, 1) || Utils.within(angle, 270, 1)) { // almost vertical
this.setLine(this.x1, this.y1, this.x1, this.y2);
}
// else {
// System.out.println("oblique: " + this + " ("+ this.getAngle() + ")");
// }
} | [
"public",
"void",
"normalize",
"(",
")",
"{",
"double",
"angle",
"=",
"this",
".",
"getAngle",
"(",
")",
";",
"if",
"(",
"Utils",
".",
"within",
"(",
"angle",
",",
"0",
",",
"1",
")",
"||",
"Utils",
".",
"within",
"(",
"angle",
",",
"180",
",",
... | Normalize almost horizontal or almost vertical lines | [
"Normalize",
"almost",
"horizontal",
"or",
"almost",
"vertical",
"lines"
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/Ruling.java#L33-L45 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/CommandLineApp.java | CommandLineApp.whichOutputFormat | private static OutputFormat whichOutputFormat(CommandLine line) throws ParseException {
if (!line.hasOption('f')) {
return OutputFormat.CSV;
}
try {
return OutputFormat.valueOf(line.getOptionValue('f'));
} catch (IllegalArgumentException e) {
throw new ParseException(String.format(
"format %s is illegal. Available formats: %s",
line.getOptionValue('f'),
Utils.join(",", OutputFormat.formatNames())));
}
} | java | private static OutputFormat whichOutputFormat(CommandLine line) throws ParseException {
if (!line.hasOption('f')) {
return OutputFormat.CSV;
}
try {
return OutputFormat.valueOf(line.getOptionValue('f'));
} catch (IllegalArgumentException e) {
throw new ParseException(String.format(
"format %s is illegal. Available formats: %s",
line.getOptionValue('f'),
Utils.join(",", OutputFormat.formatNames())));
}
} | [
"private",
"static",
"OutputFormat",
"whichOutputFormat",
"(",
"CommandLine",
"line",
")",
"throws",
"ParseException",
"{",
"if",
"(",
"!",
"line",
".",
"hasOption",
"(",
"'",
"'",
")",
")",
"{",
"return",
"OutputFormat",
".",
"CSV",
";",
"}",
"try",
"{",
... | CommandLine parsing methods | [
"CommandLine",
"parsing",
"methods"
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/CommandLineApp.java#L204-L217 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/CommandLineApp.java | CommandLineApp.parseFloatList | public static List<Float> parseFloatList(String option) throws ParseException {
String[] f = option.split(",");
List<Float> rv = new ArrayList<>();
try {
for (int i = 0; i < f.length; i++) {
rv.add(Float.parseFloat(f[i]));
}
return rv;
} catch (NumberFormatException e) {
throw new ParseException("Wrong number syntax");
}
} | java | public static List<Float> parseFloatList(String option) throws ParseException {
String[] f = option.split(",");
List<Float> rv = new ArrayList<>();
try {
for (int i = 0; i < f.length; i++) {
rv.add(Float.parseFloat(f[i]));
}
return rv;
} catch (NumberFormatException e) {
throw new ParseException("Wrong number syntax");
}
} | [
"public",
"static",
"List",
"<",
"Float",
">",
"parseFloatList",
"(",
"String",
"option",
")",
"throws",
"ParseException",
"{",
"String",
"[",
"]",
"f",
"=",
"option",
".",
"split",
"(",
"\",\"",
")",
";",
"List",
"<",
"Float",
">",
"rv",
"=",
"new",
... | utilities, etc. | [
"utilities",
"etc",
"."
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/CommandLineApp.java#L275-L286 | train |
tabulapdf/tabula-java | src/main/java/technology/tabula/TextChunk.java | TextChunk.splitAt | public TextChunk[] splitAt(int i) {
if (i < 1 || i >= this.getTextElements().size()) {
throw new IllegalArgumentException();
}
TextChunk[] rv = new TextChunk[]{
new TextChunk(this.getTextElements().subList(0, i)),
new TextChunk(this.getTextElements().subList(i, this.getTextElements().size()))
};
return rv;
} | java | public TextChunk[] splitAt(int i) {
if (i < 1 || i >= this.getTextElements().size()) {
throw new IllegalArgumentException();
}
TextChunk[] rv = new TextChunk[]{
new TextChunk(this.getTextElements().subList(0, i)),
new TextChunk(this.getTextElements().subList(i, this.getTextElements().size()))
};
return rv;
} | [
"public",
"TextChunk",
"[",
"]",
"splitAt",
"(",
"int",
"i",
")",
"{",
"if",
"(",
"i",
"<",
"1",
"||",
"i",
">=",
"this",
".",
"getTextElements",
"(",
")",
".",
"size",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
... | Splits a TextChunk in two, at the position of the i-th TextElement | [
"Splits",
"a",
"TextChunk",
"in",
"two",
"at",
"the",
"position",
"of",
"the",
"i",
"-",
"th",
"TextElement"
] | a86b72aa81c0bcb4b8b4402dc94ca1211f152930 | https://github.com/tabulapdf/tabula-java/blob/a86b72aa81c0bcb4b8b4402dc94ca1211f152930/src/main/java/technology/tabula/TextChunk.java#L212-L222 | train |
lsjwzh/RecyclerViewPager | lib/src/main/java/com/lsjwzh/widget/recyclerviewpager/LoopRecyclerViewPager.java | LoopRecyclerViewPager.smoothScrollToPosition | @Override
public void smoothScrollToPosition(int position) {
int transformedPosition = transformInnerPositionIfNeed(position);
super.smoothScrollToPosition(transformedPosition);
Log.e("test", "transformedPosition:" + transformedPosition);
} | java | @Override
public void smoothScrollToPosition(int position) {
int transformedPosition = transformInnerPositionIfNeed(position);
super.smoothScrollToPosition(transformedPosition);
Log.e("test", "transformedPosition:" + transformedPosition);
} | [
"@",
"Override",
"public",
"void",
"smoothScrollToPosition",
"(",
"int",
"position",
")",
"{",
"int",
"transformedPosition",
"=",
"transformInnerPositionIfNeed",
"(",
"position",
")",
";",
"super",
".",
"smoothScrollToPosition",
"(",
"transformedPosition",
")",
";",
... | Starts a smooth scroll to an adapter position.
if position < adapter.getActualCount,
position will be transform to right position.
@param position target position | [
"Starts",
"a",
"smooth",
"scroll",
"to",
"an",
"adapter",
"position",
".",
"if",
"position",
"<",
"adapter",
".",
"getActualCount",
"position",
"will",
"be",
"transform",
"to",
"right",
"position",
"."
] | 28567e666b58ba710f52a02cff7a9961d26775fd | https://github.com/lsjwzh/RecyclerViewPager/blob/28567e666b58ba710f52a02cff7a9961d26775fd/lib/src/main/java/com/lsjwzh/widget/recyclerviewpager/LoopRecyclerViewPager.java#L49-L54 | train |
evant/binding-collection-adapter | bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/Utils.java | Utils.createClass | @SuppressWarnings("unchecked")
static <T, A extends BindingCollectionAdapter<T>> A createClass(Class<? extends BindingCollectionAdapter> adapterClass, ItemBinding<T> itemBinding) {
try {
return (A) adapterClass.getConstructor(ItemBinding.class).newInstance(itemBinding);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
} | java | @SuppressWarnings("unchecked")
static <T, A extends BindingCollectionAdapter<T>> A createClass(Class<? extends BindingCollectionAdapter> adapterClass, ItemBinding<T> itemBinding) {
try {
return (A) adapterClass.getConstructor(ItemBinding.class).newInstance(itemBinding);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"static",
"<",
"T",
",",
"A",
"extends",
"BindingCollectionAdapter",
"<",
"T",
">",
">",
"A",
"createClass",
"(",
"Class",
"<",
"?",
"extends",
"BindingCollectionAdapter",
">",
"adapterClass",
",",
"ItemBinding... | Constructs a binding adapter class from it's class name using reflection. | [
"Constructs",
"a",
"binding",
"adapter",
"class",
"from",
"it",
"s",
"class",
"name",
"using",
"reflection",
"."
] | f669eda0a7002128bb504dcba012c51531f1bedd | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/Utils.java#L99-L106 | train |
evant/binding-collection-adapter | bindingcollectionadapter-recyclerview/src/main/java/me/tatarka/bindingcollectionadapter2/collections/DiffObservableList.java | DiffObservableList.calculateDiff | @NonNull
public DiffUtil.DiffResult calculateDiff(@NonNull final List<T> newItems) {
final ArrayList<T> frozenList;
synchronized (LIST_LOCK) {
frozenList = new ArrayList<>(list);
}
return doCalculateDiff(frozenList, newItems);
} | java | @NonNull
public DiffUtil.DiffResult calculateDiff(@NonNull final List<T> newItems) {
final ArrayList<T> frozenList;
synchronized (LIST_LOCK) {
frozenList = new ArrayList<>(list);
}
return doCalculateDiff(frozenList, newItems);
} | [
"@",
"NonNull",
"public",
"DiffUtil",
".",
"DiffResult",
"calculateDiff",
"(",
"@",
"NonNull",
"final",
"List",
"<",
"T",
">",
"newItems",
")",
"{",
"final",
"ArrayList",
"<",
"T",
">",
"frozenList",
";",
"synchronized",
"(",
"LIST_LOCK",
")",
"{",
"frozen... | Calculates the list of update operations that can convert this list into the given one.
@param newItems The items that this list will be set to.
@return A DiffResult that contains the information about the edit sequence to covert this
list into the given one. | [
"Calculates",
"the",
"list",
"of",
"update",
"operations",
"that",
"can",
"convert",
"this",
"list",
"into",
"the",
"given",
"one",
"."
] | f669eda0a7002128bb504dcba012c51531f1bedd | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter-recyclerview/src/main/java/me/tatarka/bindingcollectionadapter2/collections/DiffObservableList.java#L82-L89 | train |
evant/binding-collection-adapter | bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/ItemBinding.java | ItemBinding.bindExtra | @NonNull
public final ItemBinding<T> bindExtra(int variableId, Object value) {
if (extraBindings == null) {
extraBindings = new SparseArray<>(1);
}
extraBindings.put(variableId, value);
return this;
} | java | @NonNull
public final ItemBinding<T> bindExtra(int variableId, Object value) {
if (extraBindings == null) {
extraBindings = new SparseArray<>(1);
}
extraBindings.put(variableId, value);
return this;
} | [
"@",
"NonNull",
"public",
"final",
"ItemBinding",
"<",
"T",
">",
"bindExtra",
"(",
"int",
"variableId",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"extraBindings",
"==",
"null",
")",
"{",
"extraBindings",
"=",
"new",
"SparseArray",
"<>",
"(",
"1",
")",... | Bind an extra variable to the view with the given variable id. The same instance will be
provided to all views the binding is bound to. | [
"Bind",
"an",
"extra",
"variable",
"to",
"the",
"view",
"with",
"the",
"given",
"variable",
"id",
".",
"The",
"same",
"instance",
"will",
"be",
"provided",
"to",
"all",
"views",
"the",
"binding",
"is",
"bound",
"to",
"."
] | f669eda0a7002128bb504dcba012c51531f1bedd | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/ItemBinding.java#L95-L102 | train |
evant/binding-collection-adapter | bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/ItemBinding.java | ItemBinding.extraBinding | @Nullable
public final Object extraBinding(int variableId) {
if (extraBindings == null) {
return null;
}
return extraBindings.get(variableId);
} | java | @Nullable
public final Object extraBinding(int variableId) {
if (extraBindings == null) {
return null;
}
return extraBindings.get(variableId);
} | [
"@",
"Nullable",
"public",
"final",
"Object",
"extraBinding",
"(",
"int",
"variableId",
")",
"{",
"if",
"(",
"extraBindings",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"extraBindings",
".",
"get",
"(",
"variableId",
")",
";",
"}"
] | Returns the current extra binding for the given variable id or null if one isn't present. | [
"Returns",
"the",
"current",
"extra",
"binding",
"for",
"the",
"given",
"variable",
"id",
"or",
"null",
"if",
"one",
"isn",
"t",
"present",
"."
] | f669eda0a7002128bb504dcba012c51531f1bedd | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/ItemBinding.java#L146-L152 | train |
evant/binding-collection-adapter | bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/ItemBinding.java | ItemBinding.onItemBind | public void onItemBind(int position, T item) {
if (onItemBind != null) {
variableId = VAR_INVALID;
layoutRes = LAYOUT_NONE;
onItemBind.onItemBind(this, position, item);
if (variableId == VAR_INVALID) {
throw new IllegalStateException("variableId not set in onItemBind()");
}
if (layoutRes == LAYOUT_NONE) {
throw new IllegalStateException("layoutRes not set in onItemBind()");
}
}
} | java | public void onItemBind(int position, T item) {
if (onItemBind != null) {
variableId = VAR_INVALID;
layoutRes = LAYOUT_NONE;
onItemBind.onItemBind(this, position, item);
if (variableId == VAR_INVALID) {
throw new IllegalStateException("variableId not set in onItemBind()");
}
if (layoutRes == LAYOUT_NONE) {
throw new IllegalStateException("layoutRes not set in onItemBind()");
}
}
} | [
"public",
"void",
"onItemBind",
"(",
"int",
"position",
",",
"T",
"item",
")",
"{",
"if",
"(",
"onItemBind",
"!=",
"null",
")",
"{",
"variableId",
"=",
"VAR_INVALID",
";",
"layoutRes",
"=",
"LAYOUT_NONE",
";",
"onItemBind",
".",
"onItemBind",
"(",
"this",
... | Updates the state of the binding for the given item and position. This is called internally
by the binding collection adapters. | [
"Updates",
"the",
"state",
"of",
"the",
"binding",
"for",
"the",
"given",
"item",
"and",
"position",
".",
"This",
"is",
"called",
"internally",
"by",
"the",
"binding",
"collection",
"adapters",
"."
] | f669eda0a7002128bb504dcba012c51531f1bedd | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/ItemBinding.java#L158-L170 | train |
evant/binding-collection-adapter | bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/collections/MergeObservableList.java | MergeObservableList.insertItem | public MergeObservableList<T> insertItem(T object) {
lists.add(Collections.singletonList(object));
modCount += 1;
listeners.notifyInserted(this, size() - 1, 1);
return this;
} | java | public MergeObservableList<T> insertItem(T object) {
lists.add(Collections.singletonList(object));
modCount += 1;
listeners.notifyInserted(this, size() - 1, 1);
return this;
} | [
"public",
"MergeObservableList",
"<",
"T",
">",
"insertItem",
"(",
"T",
"object",
")",
"{",
"lists",
".",
"add",
"(",
"Collections",
".",
"singletonList",
"(",
"object",
")",
")",
";",
"modCount",
"+=",
"1",
";",
"listeners",
".",
"notifyInserted",
"(",
... | Inserts the given item into the merge list. | [
"Inserts",
"the",
"given",
"item",
"into",
"the",
"merge",
"list",
"."
] | f669eda0a7002128bb504dcba012c51531f1bedd | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/collections/MergeObservableList.java#L37-L42 | train |
evant/binding-collection-adapter | bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/collections/MergeObservableList.java | MergeObservableList.removeItem | public boolean removeItem(T object) {
int size = 0;
for (int i = 0, listsSize = lists.size(); i < listsSize; i++) {
List<? extends T> list = lists.get(i);
if (!(list instanceof ObservableList)) {
Object item = list.get(0);
if ((object == null) ? (item == null) : object.equals(item)) {
lists.remove(i);
modCount += 1;
listeners.notifyRemoved(this, size, 1);
return true;
}
}
size += list.size();
}
return false;
} | java | public boolean removeItem(T object) {
int size = 0;
for (int i = 0, listsSize = lists.size(); i < listsSize; i++) {
List<? extends T> list = lists.get(i);
if (!(list instanceof ObservableList)) {
Object item = list.get(0);
if ((object == null) ? (item == null) : object.equals(item)) {
lists.remove(i);
modCount += 1;
listeners.notifyRemoved(this, size, 1);
return true;
}
}
size += list.size();
}
return false;
} | [
"public",
"boolean",
"removeItem",
"(",
"T",
"object",
")",
"{",
"int",
"size",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"listsSize",
"=",
"lists",
".",
"size",
"(",
")",
";",
"i",
"<",
"listsSize",
";",
"i",
"++",
")",
"{",
"List"... | Removes the given item from the merge list. | [
"Removes",
"the",
"given",
"item",
"from",
"the",
"merge",
"list",
"."
] | f669eda0a7002128bb504dcba012c51531f1bedd | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/collections/MergeObservableList.java#L63-L79 | train |
evant/binding-collection-adapter | bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/collections/MergeObservableList.java | MergeObservableList.removeAll | public void removeAll() {
int size = size();
if (size == 0) {
return;
}
for (int i = 0, listSize = lists.size(); i < listSize; i++) {
List<? extends T> list = lists.get(i);
if (list instanceof ObservableList) {
((ObservableList) list).removeOnListChangedCallback(callback);
}
}
lists.clear();
modCount += 1;
listeners.notifyRemoved(this, 0, size);
} | java | public void removeAll() {
int size = size();
if (size == 0) {
return;
}
for (int i = 0, listSize = lists.size(); i < listSize; i++) {
List<? extends T> list = lists.get(i);
if (list instanceof ObservableList) {
((ObservableList) list).removeOnListChangedCallback(callback);
}
}
lists.clear();
modCount += 1;
listeners.notifyRemoved(this, 0, size);
} | [
"public",
"void",
"removeAll",
"(",
")",
"{",
"int",
"size",
"=",
"size",
"(",
")",
";",
"if",
"(",
"size",
"==",
"0",
")",
"{",
"return",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"listSize",
"=",
"lists",
".",
"size",
"(",
")",
";",
... | Removes all items and lists from the merge list. | [
"Removes",
"all",
"items",
"and",
"lists",
"from",
"the",
"merge",
"list",
"."
] | f669eda0a7002128bb504dcba012c51531f1bedd | https://github.com/evant/binding-collection-adapter/blob/f669eda0a7002128bb504dcba012c51531f1bedd/bindingcollectionadapter/src/main/java/me/tatarka/bindingcollectionadapter2/collections/MergeObservableList.java#L104-L118 | train |
andkulikov/Transitions-Everywhere | library(1.x)/src/main/java/com/transitionseverywhere/TransitionManager.java | TransitionManager.endTransitions | public static void endTransitions(final @NonNull ViewGroup sceneRoot) {
sPendingTransitions.remove(sceneRoot);
final ArrayList<Transition> runningTransitions = getRunningTransitions(sceneRoot);
if (!runningTransitions.isEmpty()) {
// Make a copy in case this is called by an onTransitionEnd listener
ArrayList<Transition> copy = new ArrayList(runningTransitions);
for (int i = copy.size() - 1; i >= 0; i--) {
final Transition transition = copy.get(i);
transition.forceToEnd(sceneRoot);
}
}
} | java | public static void endTransitions(final @NonNull ViewGroup sceneRoot) {
sPendingTransitions.remove(sceneRoot);
final ArrayList<Transition> runningTransitions = getRunningTransitions(sceneRoot);
if (!runningTransitions.isEmpty()) {
// Make a copy in case this is called by an onTransitionEnd listener
ArrayList<Transition> copy = new ArrayList(runningTransitions);
for (int i = copy.size() - 1; i >= 0; i--) {
final Transition transition = copy.get(i);
transition.forceToEnd(sceneRoot);
}
}
} | [
"public",
"static",
"void",
"endTransitions",
"(",
"final",
"@",
"NonNull",
"ViewGroup",
"sceneRoot",
")",
"{",
"sPendingTransitions",
".",
"remove",
"(",
"sceneRoot",
")",
";",
"final",
"ArrayList",
"<",
"Transition",
">",
"runningTransitions",
"=",
"getRunningTr... | Ends all pending and ongoing transitions on the specified scene root.
@param sceneRoot The root of the View hierarchy to end transitions on. | [
"Ends",
"all",
"pending",
"and",
"ongoing",
"transitions",
"on",
"the",
"specified",
"scene",
"root",
"."
] | 828efe5f152a2f05e2bfeee6254b74ad2269d4f1 | https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/TransitionManager.java#L453-L465 | train |
andkulikov/Transitions-Everywhere | library(1.x)/src/main/java/com/transitionseverywhere/TransitionSet.java | TransitionSet.setOrdering | @NonNull
public TransitionSet setOrdering(int ordering) {
switch (ordering) {
case ORDERING_SEQUENTIAL:
mPlayTogether = false;
break;
case ORDERING_TOGETHER:
mPlayTogether = true;
break;
default:
throw new AndroidRuntimeException("Invalid parameter for TransitionSet " +
"ordering: " + ordering);
}
return this;
} | java | @NonNull
public TransitionSet setOrdering(int ordering) {
switch (ordering) {
case ORDERING_SEQUENTIAL:
mPlayTogether = false;
break;
case ORDERING_TOGETHER:
mPlayTogether = true;
break;
default:
throw new AndroidRuntimeException("Invalid parameter for TransitionSet " +
"ordering: " + ordering);
}
return this;
} | [
"@",
"NonNull",
"public",
"TransitionSet",
"setOrdering",
"(",
"int",
"ordering",
")",
"{",
"switch",
"(",
"ordering",
")",
"{",
"case",
"ORDERING_SEQUENTIAL",
":",
"mPlayTogether",
"=",
"false",
";",
"break",
";",
"case",
"ORDERING_TOGETHER",
":",
"mPlayTogethe... | Sets the play order of this set's child transitions.
@param ordering {@link #ORDERING_TOGETHER} to play this set's child
transitions together, {@link #ORDERING_SEQUENTIAL} to play the child
transitions in sequence.
@return This transitionSet object. | [
"Sets",
"the",
"play",
"order",
"of",
"this",
"set",
"s",
"child",
"transitions",
"."
] | 828efe5f152a2f05e2bfeee6254b74ad2269d4f1 | https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/TransitionSet.java#L101-L115 | train |
andkulikov/Transitions-Everywhere | library(1.x)/src/main/java/com/transitionseverywhere/TransitionSet.java | TransitionSet.getTransitionAt | @Nullable
public Transition getTransitionAt(int index) {
if (index < 0 || index >= mTransitions.size()) {
return null;
}
return mTransitions.get(index);
} | java | @Nullable
public Transition getTransitionAt(int index) {
if (index < 0 || index >= mTransitions.size()) {
return null;
}
return mTransitions.get(index);
} | [
"@",
"Nullable",
"public",
"Transition",
"getTransitionAt",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"index",
"<",
"0",
"||",
"index",
">=",
"mTransitions",
".",
"size",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"mTransitions",
".",
"g... | Returns the child Transition at the specified position in the TransitionSet.
@param index The position of the Transition to retrieve.
@see #addTransition(Transition)
@see #getTransitionCount() | [
"Returns",
"the",
"child",
"Transition",
"at",
"the",
"specified",
"position",
"in",
"the",
"TransitionSet",
"."
] | 828efe5f152a2f05e2bfeee6254b74ad2269d4f1 | https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/TransitionSet.java#L183-L189 | train |
andkulikov/Transitions-Everywhere | library(1.x)/src/main/java/com/transitionseverywhere/PathParser.java | PathParser.extract | private static void extract(String s, int start, ExtractFloatResult result) {
// Now looking for ' ', ',', '.' or '-' from the start.
int currentIndex = start;
boolean foundSeparator = false;
result.mEndWithNegOrDot = false;
boolean secondDot = false;
boolean isExponential = false;
for (; currentIndex < s.length(); currentIndex++) {
boolean isPrevExponential = isExponential;
isExponential = false;
char currentChar = s.charAt(currentIndex);
switch (currentChar) {
case ' ':
case ',':
foundSeparator = true;
break;
case '-':
// The negative sign following a 'e' or 'E' is not a separator.
if (currentIndex != start && !isPrevExponential) {
foundSeparator = true;
result.mEndWithNegOrDot = true;
}
break;
case '.':
if (!secondDot) {
secondDot = true;
} else {
// This is the second dot, and it is considered as a separator.
foundSeparator = true;
result.mEndWithNegOrDot = true;
}
break;
case 'e':
case 'E':
isExponential = true;
break;
}
if (foundSeparator) {
break;
}
}
// When there is nothing found, then we put the end position to the end
// of the string.
result.mEndPosition = currentIndex;
} | java | private static void extract(String s, int start, ExtractFloatResult result) {
// Now looking for ' ', ',', '.' or '-' from the start.
int currentIndex = start;
boolean foundSeparator = false;
result.mEndWithNegOrDot = false;
boolean secondDot = false;
boolean isExponential = false;
for (; currentIndex < s.length(); currentIndex++) {
boolean isPrevExponential = isExponential;
isExponential = false;
char currentChar = s.charAt(currentIndex);
switch (currentChar) {
case ' ':
case ',':
foundSeparator = true;
break;
case '-':
// The negative sign following a 'e' or 'E' is not a separator.
if (currentIndex != start && !isPrevExponential) {
foundSeparator = true;
result.mEndWithNegOrDot = true;
}
break;
case '.':
if (!secondDot) {
secondDot = true;
} else {
// This is the second dot, and it is considered as a separator.
foundSeparator = true;
result.mEndWithNegOrDot = true;
}
break;
case 'e':
case 'E':
isExponential = true;
break;
}
if (foundSeparator) {
break;
}
}
// When there is nothing found, then we put the end position to the end
// of the string.
result.mEndPosition = currentIndex;
} | [
"private",
"static",
"void",
"extract",
"(",
"String",
"s",
",",
"int",
"start",
",",
"ExtractFloatResult",
"result",
")",
"{",
"// Now looking for ' ', ',', '.' or '-' from the start.",
"int",
"currentIndex",
"=",
"start",
";",
"boolean",
"foundSeparator",
"=",
"fals... | Calculate the position of the next comma or space or negative sign
@param s the string to search
@param start the position to start searching
@param result the result of the extraction, including the position of the
the starting position of next number, whether it is ending with a '-'. | [
"Calculate",
"the",
"position",
"of",
"the",
"next",
"comma",
"or",
"space",
"or",
"negative",
"sign"
] | 828efe5f152a2f05e2bfeee6254b74ad2269d4f1 | https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/PathParser.java#L200-L244 | train |
andkulikov/Transitions-Everywhere | library(1.x)/src/main/java/com/transitionseverywhere/Transition.java | Transition.runAnimators | protected void runAnimators() {
if (DBG) {
Log.d(LOG_TAG, "runAnimators() on " + this);
}
start();
ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators();
// Now start every Animator that was previously created for this transition
for (Animator anim : mAnimators) {
if (DBG) {
Log.d(LOG_TAG, " anim: " + anim);
}
if (runningAnimators.containsKey(anim)) {
start();
runAnimator(anim, runningAnimators);
}
}
mAnimators.clear();
end();
} | java | protected void runAnimators() {
if (DBG) {
Log.d(LOG_TAG, "runAnimators() on " + this);
}
start();
ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators();
// Now start every Animator that was previously created for this transition
for (Animator anim : mAnimators) {
if (DBG) {
Log.d(LOG_TAG, " anim: " + anim);
}
if (runningAnimators.containsKey(anim)) {
start();
runAnimator(anim, runningAnimators);
}
}
mAnimators.clear();
end();
} | [
"protected",
"void",
"runAnimators",
"(",
")",
"{",
"if",
"(",
"DBG",
")",
"{",
"Log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"runAnimators() on \"",
"+",
"this",
")",
";",
"}",
"start",
"(",
")",
";",
"ArrayMap",
"<",
"Animator",
",",
"AnimationInfo",
">",
... | This is called internally once all animations have been set up by the
transition hierarchy.
@hide | [
"This",
"is",
"called",
"internally",
"once",
"all",
"animations",
"have",
"been",
"set",
"up",
"by",
"the",
"transition",
"hierarchy",
"."
] | 828efe5f152a2f05e2bfeee6254b74ad2269d4f1 | https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/Transition.java#L899-L917 | train |
andkulikov/Transitions-Everywhere | library(1.x)/src/main/java/com/transitionseverywhere/Transition.java | Transition.start | protected void start() {
if (mNumInstances == 0) {
if (mListeners != null && mListeners.size() > 0) {
ArrayList<TransitionListener> tmpListeners =
(ArrayList<TransitionListener>) mListeners.clone();
int numListeners = tmpListeners.size();
for (int i = 0; i < numListeners; ++i) {
tmpListeners.get(i).onTransitionStart(this);
}
}
mEnded = false;
}
mNumInstances++;
} | java | protected void start() {
if (mNumInstances == 0) {
if (mListeners != null && mListeners.size() > 0) {
ArrayList<TransitionListener> tmpListeners =
(ArrayList<TransitionListener>) mListeners.clone();
int numListeners = tmpListeners.size();
for (int i = 0; i < numListeners; ++i) {
tmpListeners.get(i).onTransitionStart(this);
}
}
mEnded = false;
}
mNumInstances++;
} | [
"protected",
"void",
"start",
"(",
")",
"{",
"if",
"(",
"mNumInstances",
"==",
"0",
")",
"{",
"if",
"(",
"mListeners",
"!=",
"null",
"&&",
"mListeners",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"ArrayList",
"<",
"TransitionListener",
">",
"tmpListene... | This method is called automatically by the transition and
TransitionSet classes prior to a Transition subclass starting;
subclasses should not need to call it directly.
@hide | [
"This",
"method",
"is",
"called",
"automatically",
"by",
"the",
"transition",
"and",
"TransitionSet",
"classes",
"prior",
"to",
"a",
"Transition",
"subclass",
"starting",
";",
"subclasses",
"should",
"not",
"need",
"to",
"call",
"it",
"directly",
"."
] | 828efe5f152a2f05e2bfeee6254b74ad2269d4f1 | https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/Transition.java#L1932-L1945 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.