code
stringlengths
73
34.1k
label
stringclasses
1 value
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, 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
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 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
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
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
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 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 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 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
public void invokeNotification(String methodName, Object argument, OutputStream output) throws IOException { writeRequest(methodName, argument, output, null); output.flush(); }
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; }
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()); }
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(); }
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(); } }
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()); } }
java
protected void bindBlobLiteral(int index, byte[] value) { if (blobLiterals == null) { blobLiterals = new LinkedHashMap<>(); } blobLiterals.put(index, value); }
java
public void createIndexes(Connection connection, TableCreationMode mode) { ArrayList<Type<?>> sorted = sortTypes(); for (Type<?> type : sorted) { createIndexes(connection, mode, type); } }
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(); }
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); } }
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); } }
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(); }
java
@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 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 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
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
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
public static long parse(String configuredMemorySize) throws IllegalArgumentException { MemorySize size = parseIncludingUnit(configuredMemorySize); return size.calculateMemorySizeInBytes(); }
java
public boolean abandonLeadership(String entityIdentifier, boolean healthyConnection) { Hold hold = maintenanceHolds.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); }
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()); }); }
java
public ClusteringServiceConfigurationBuilder timeouts(Builder<? extends Timeouts> timeoutsBuilder) { return new ClusteringServiceConfigurationBuilder(this.connectionSource, timeoutsBuilder.build(), this.autoCreate); }
java
@Deprecated public ClusteringServiceConfigurationBuilder readOperationTimeout(long duration, TimeUnit unit) { Duration readTimeout = Duration.of(duration, toChronoUnit(unit)); return timeouts(TimeoutsBuilder.timeouts().read(readTimeout).build()); }
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); } }
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; }
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; } } }
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); } }
java
@Override public boolean containsKeyFailure(K key, StoreAccessException e) { cleanup(key, e); return false; }
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); } }
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); } }
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; }
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); } }
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); } }
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); } }
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); } }
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)); } }
java
protected void cleanup(StoreAccessException from) { try { store.obliterate(); } catch (StoreAccessException e) { inconsistent(from, e); return; } recovered(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); }
java
protected void recovered(Iterable<? extends K> keys, StoreAccessException from) { LOGGER.info("Ehcache keys {} recovered from", keys, from); }
java
protected void inconsistent(K key, StoreAccessException because, StoreAccessException... cleanup) { pacedErrorLog("Ehcache key {} in possible inconsistent state", key, because); }
java
protected void inconsistent(Iterable<? extends K> keys, StoreAccessException because, StoreAccessException... cleanup) { pacedErrorLog("Ehcache keys {} in possible inconsistent state", keys, because); }
java
public ServerSideConfigurationBuilder resourcePool(String name, long size, MemoryUnit unit, String serverResource) { return resourcePool(name, new Pool(unit.toBytes(size), serverResource)); }
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); } }
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; }
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); }
java
public boolean seen(long msgId) { boolean seen = nonContiguousMsgIds.contains(msgId) || msgId <= highestContiguousMsgId; tryReconcile(); return seen; }
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); } } }
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(); } }
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; } }
java
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 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
@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 V getFailure(K key, StoreAccessException e) { cleanup(key, e); return null; }
java
@Override public V putIfAbsentFailure(K key, V value, StoreAccessException e) { cleanup(key, e); return null; }
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; }
java
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 pool(String alias, int minSize, int maxSize) { PooledExecutionServiceConfigurationBuilder other = new PooledExecutionServiceConfigurationBuilder(this); other.pools.add(new Pool(alias, minSize, maxSize)); return other; }
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; } } }
java
public static boolean isAvailable(ServiceProvider<Service> serviceProvider) { return ENTITY_SERVICE_CLASS != null && serviceProvider.getService(ENTITY_SERVICE_CLASS) != null; }
java
public static int findBestCollectionSize(Iterable<?> iterable, int bestBet) { return (iterable instanceof Collection ? ((Collection<?>) iterable).size() : bestBet); }
java
public static DedicatedClusteredResourcePool clusteredDedicated(String fromResource, long size, MemoryUnit unit) { return new DedicatedClusteredResourcePoolImpl(fromResource, size, unit); }
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(); }
java
@Override public long getQueueSize() { Batch snapshot = openBatch; return executorQueue.size() * batchSize + (snapshot == null ? 0 : snapshot.size()); }
java
@Override public Result<K, V> apply(final Result<K, V> previousOperation) { if(previousOperation == null) { return this; } else { return previousOperation; } }
java
public void setClip(Rectangle2D clip) { xMin = clip.getX(); xMax = xMin + clip.getWidth(); yMin = clip.getY(); yMax = yMin + clip.getHeight(); }
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) }
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); } }
java
public Rectangle getTextBounds() { List<TextElement> texts = this.getText(); if (!texts.isEmpty()) { return Utils.bounds(texts); } else { return new Rectangle(); } }
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; }
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; }
java
public static <T extends Comparable<? super T>> void sort(List<T> list) { if (useQuickSort) QuickSort.sort(list); else Collections.sort(list); }
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() + ")"); // } }
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()))); } }
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"); } }
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; }
java
@Override public void smoothScrollToPosition(int position) { int transformedPosition = transformInnerPositionIfNeed(position); super.smoothScrollToPosition(transformedPosition); Log.e("test", "transformedPosition:" + transformedPosition); }
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); } }
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); }
java
@NonNull public final ItemBinding<T> bindExtra(int variableId, Object value) { if (extraBindings == null) { extraBindings = new SparseArray<>(1); } extraBindings.put(variableId, value); return this; }
java
@Nullable public final Object extraBinding(int variableId) { if (extraBindings == null) { return null; } return extraBindings.get(variableId); }
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()"); } } }
java
public MergeObservableList<T> insertItem(T object) { lists.add(Collections.singletonList(object)); modCount += 1; listeners.notifyInserted(this, size() - 1, 1); return this; }
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; }
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); }
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); } } }
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; }
java
@Nullable public Transition getTransitionAt(int index) { if (index < 0 || index >= mTransitions.size()) { return null; } return mTransitions.get(index); }
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; }
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(); }
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++; }
java