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(ser...
java
private void registerJsonProxyBean(DefaultListableBeanFactory defaultListableBeanFactory, String className, String path) { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder .rootBeanDefinition(JsonProxyFactoryBean.class) .addPropertyValue("serviceUrl", appendBasePath(path)) .addPrope...
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(cac...
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, Objec...
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(jsonObjec...
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(reques...
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; } }...
java
private void registerServiceProxy(DefaultListableBeanFactory defaultListableBeanFactory, String servicePath, String serviceBeanName) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(JsonServiceExporter.class).addPropertyReference("service", serviceBeanName); BeanDefinition serviceBeanDef...
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())) ...
java
Optional<? extends AttributeDescriptor> referencingAttribute(AttributeDescriptor attribute, EntityDescriptor referenced) { String referencedColumn = attribute.referencedColumn(); if (Names.isEmpty(referencedColumn)) { // using ...
java
Set<AttributeDescriptor> mappedAttributes(EntityDescriptor entity, AttributeDescriptor attribute, EntityDescriptor referenced) { String mappedBy = attribute.mappedBy(); if (Names.isEmpty(mappedBy)) { ...
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"); }...
java
public void dropTables() { try (Connection connection = getConnection(); Statement statement = connection.createStatement()) { ArrayList<Type<?>> reversed = sortTypes(); Collections.reverse(reversed); executeDropStatements(statement, reversed); } catch (S...
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 TableModificatio...
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(...
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); ...
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 Ille...
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()) { ...
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...
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.Poo...
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); ...
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.getServiceConfigu...
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) { ...
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 Exception...
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) { re...
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) {...
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....
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 { cleanu...
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"); } ...
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() ...
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.isOrd...
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.reg...
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 ...
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 (nonContiguou...
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...
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 HashM...
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); } ret...
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 = requireNonNu...
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))))) ...
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()) { horizonta...
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 ...
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 ne...
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; ...
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()....
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 (Exceptio...
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 no...
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) ? (i...
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).r...
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 onTransi...
java
@NonNull public TransitionSet setOrdering(int ordering) { switch (ordering) { case ORDERING_SEQUENTIAL: mPlayTogether = false; break; case ORDERING_TOGETHER: mPlayTogether = true; break; default: ...
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 isExponentia...
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 (Anim...
java
protected void start() { if (mNumInstances == 0) { if (mListeners != null && mListeners.size() > 0) { ArrayList<TransitionListener> tmpListeners = (ArrayList<TransitionListener>) mListeners.clone(); int numListeners = tmpListeners.size(); ...
java