code
stringlengths
73
34.1k
label
stringclasses
1 value
public <T> void addListenerIfPending(final Class<T> clazz, final Object requestCacheKey, final PendingRequestListener<T> requestListener) { addListenerIfPending(clazz, requestCacheKey, (RequestListener<T>) requestListener); }
java
public <T> void execute(final CachedSpiceRequest<T> cachedSpiceRequest, final RequestListener<T> requestListener) { addRequestListenerToListOfRequestListeners(cachedSpiceRequest, requestListener); Ln.d("adding request to request queue"); this.requestQueue.add(cachedSpiceRequest); }
java
public <U, T extends U> void putInCache(final Class<U> clazz, final Object requestCacheKey, final T data, RequestListener<U> listener) { @SuppressWarnings({ "unchecked", "rawtypes" }) final SpiceRequest<U> spiceRequest = new SpiceRequest(clazz) { @Override public U loadDataFromNe...
java
public <T> void cancel(final Class<T> clazz, final Object requestCacheKey) { final SpiceRequest<T> request = new SpiceRequest<T>(clazz) { @Override public T loadDataFromNetwork() throws Exception { return null; } }; final CachedSpiceRequest<T>...
java
protected void dontNotifyAnyRequestListenersInternal() { lockSendRequestsToService.lock(); try { if (spiceService == null) { return; } synchronized (mapRequestToLaunchToRequestListener) { if (!mapRequestToLaunchToRequestListener.isEmpty...
java
private void removeListenersOfAllPendingCachedRequests() throws InterruptedException { synchronized (mapPendingRequestToRequestListener) { if (!mapPendingRequestToRequestListener.isEmpty()) { for (final CachedSpiceRequest<?> cachedSpiceRequest : mapPendingRequestToRequestListener.key...
java
public Future<Boolean> isDataInCache(Class<?> clazz, final Object cacheKey, long cacheExpiryDuration) throws CacheCreationException { return executeCommand(new IsDataInCacheCommand(this, clazz, cacheKey, cacheExpiryDuration)); }
java
public Future<Date> getDateOfDataInCache(Class<?> clazz, final Object cacheKey) throws CacheCreationException { return executeCommand(new GetDateOfDataInCacheCommand(this, clazz, cacheKey)); }
java
public void dumpState() { executorService.execute(new Runnable() { @Override public void run() { lockSendRequestsToService.lock(); try { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(...
java
public void notifyObserversOfRequestFailure(CachedSpiceRequest<?> request) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext(); requestProcessingContext.setExecutionThread(Thread.currentThread()); post(new RequestFailedNotifier(request, spiceServiceListenerList, ...
java
public <T> void notifyObserversOfRequestSuccess(CachedSpiceRequest<T> request) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext(); requestProcessingContext.setExecutionThread(Thread.currentThread()); post(new RequestSucceededNotifier<T>(request, spiceServiceList...
java
public void notifyObserversOfRequestCancellation(CachedSpiceRequest<?> request) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext(); requestProcessingContext.setExecutionThread(Thread.currentThread()); post(new RequestCancelledNotifier(request, spiceServiceListen...
java
public void notifyObserversOfRequestProgress(CachedSpiceRequest<?> request, RequestProgress requestProgress) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext(); requestProcessingContext.setExecutionThread(Thread.currentThread()); requestProcessingContext.setRequ...
java
public void notifyObserversOfRequestProcessed(CachedSpiceRequest<?> request, Set<RequestListener<?>> requestListeners) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext(); requestProcessingContext.setExecutionThread(Thread.currentThread()); requestProcessingConte...
java
protected void post(Runnable runnable) { Ln.d("Message queue is " + messageQueue); if (messageQueue == null) { return; } messageQueue.postAtTime(runnable, SystemClock.uptimeMillis()); }
java
public void setCacheFolder(File cacheFolder) throws CacheCreationException { if (cacheFolder == null) { cacheFolder = new File(getApplication().getCacheDir(), DEFAULT_ROOT_CACHE_DIR); } synchronized (cacheFolder.getAbsolutePath().intern()) { if (!cacheFolder.exists() && !...
java
@Override public Future<?> submit(Runnable task) { if (task == null) { throw new NullPointerException(); } RunnableFuture<Object> ftask = newTaskFor(task, null); execute(ftask); return ftask; }
java
public KafkaProducer<String, String> createStringProducer(Properties overrideConfig) { return createProducer(new StringSerializer(), new StringSerializer(), overrideConfig); }
java
public <K, V> void produce(String topic, KafkaProducer<K, V> producer, Map<K, V> data) { data.forEach((k, v) -> producer.send(new ProducerRecord<>(topic, k, v))); producer.flush(); }
java
public void produceStrings(String topic, String... values) { try (KafkaProducer<String, String> producer = createStringProducer()) { Map<String, String> data = Arrays.stream(values) .collect(Collectors.toMap(k -> String.valueOf(k.hashCode()), Function.identity())); pr...
java
public KafkaConsumer<String, String> createStringConsumer(Properties overrideConfig) { return createConsumer(new StringDeserializer(), new StringDeserializer(), overrideConfig); }
java
public <K, V> ListenableFuture<List<ConsumerRecord<K, V>>> consume(String topic, KafkaConsumer<K, V> consumer, int numMessagesToConsume) { consumer.subscribe(Lists.newArrayList(topic)); ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); ret...
java
public ListenableFuture<List<String>> consumeStrings(String topic, int numMessagesToConsume) { KafkaConsumer<String, String> consumer = createStringConsumer(); ListenableFuture<List<ConsumerRecord<String, String>>> records = consume(topic, consumer, numMessagesToConsume); return Futures.transfor...
java
public static EphemeralKafkaBroker create(int kafkaPort, int zookeeperPort, Properties overrideBrokerProperties) { return new EphemeralKafkaBroker(kafkaPort, zookeeperPort, overrideBrokerProperties); }
java
public Optional<String> getLogDir() { return brokerStarted ? Optional.of(kafkaLogDir.toString()) : Optional.empty(); }
java
public Optional<String> getZookeeperConnectString() { return brokerStarted ? Optional.of(zookeeper.getConnectString()) : Optional.empty(); }
java
public Optional<String> getBrokerList() { return brokerStarted ? Optional.of(LOCALHOST + ":" + kafkaPort) : Optional.empty(); }
java
public static <E extends Exception, E2 extends Exception> void parse(final Connection conn, final String sql, final long offset, final long count, final int processThreadNum, final int queueSize, final Try.Consumer<Object[], E> rowParser, final Try.Runnable<E2> onComplete) throws UncheckedSQLE...
java
public static <E extends Exception, E2 extends Exception> void parse(final PreparedStatement stmt, final long offset, final long count, final int processThreadNum, final int queueSize, final Try.Consumer<Object[], E> rowParser, final Try.Runnable<E2> onComplete) throws UncheckedSQLException, E...
java
public static <E extends Exception, E2 extends Exception> void parse(final ResultSet rs, long offset, long count, final int processThreadNum, final int queueSize, final Try.Consumer<Object[], E> rowParser, final Try.Runnable<E2> onComplete) throws UncheckedSQLException, E, E2 { final Iterator<Ob...
java
@Override public void close() throws SQLException { if ((id == null) || (poolableConn == null)) { internalStmt.close(); } else { poolableConn.cachePreparedStatement(this); } }
java
@Override public boolean execute() throws SQLException { boolean isOk = false; try { boolean result = internalStmt.execute(); isOk = true; return result; } finally { poolableConn.updateLastSQLExecutionTime(isOk); } }
java
@Override public ResultSet executeQuery(String sql) throws SQLException { boolean isOk = false; try { final ResultSet result = wrap(internalStmt.executeQuery(sql)); isOk = true; return result; } finally { poolableConn.updateLastSQLExe...
java
@Override public void setArray(int parameterIndex, Array x) throws SQLException { internalStmt.setArray(parameterIndex, x); }
java
@Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { internalStmt.setAsciiStream(parameterIndex, x, length); }
java
@Override public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { internalStmt.setBigDecimal(parameterIndex, x); }
java
@Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { internalStmt.setBinaryStream(parameterIndex, x); }
java
@Override public void setDate(int parameterIndex, Date x) throws SQLException { internalStmt.setDate(parameterIndex, x); }
java
@Override public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { internalStmt.setNCharacterStream(parameterIndex, value); }
java
@Override public void setNString(int parameterIndex, String value) throws SQLException { internalStmt.setNString(parameterIndex, value); }
java
@Override public void setRef(int parameterIndex, Ref x) throws SQLException { internalStmt.setRef(parameterIndex, x); }
java
@Override public void setRowId(int parameterIndex, RowId x) throws SQLException { internalStmt.setRowId(parameterIndex, x); }
java
@Override public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { internalStmt.setSQLXML(parameterIndex, xmlObject); }
java
@Override public void setString(int parameterIndex, String x) throws SQLException { internalStmt.setString(parameterIndex, x); }
java
@Override public void setTime(int parameterIndex, Time x) throws SQLException { internalStmt.setTime(parameterIndex, x); }
java
@Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { internalStmt.setTimestamp(parameterIndex, x); }
java
@Override public void setURL(int parameterIndex, URL x) throws SQLException { internalStmt.setURL(parameterIndex, x); }
java
public boolean cancelAll(boolean mayInterruptIfRunning) { boolean res = true; if (N.notNullOrEmpty(upFutures)) { for (ContinuableFuture<?> preFuture : upFutures) { res = res & preFuture.cancelAll(mayInterruptIfRunning); } } return cancel...
java
public boolean isAllCancelled() { boolean res = true; if (N.notNullOrEmpty(upFutures)) { for (ContinuableFuture<?> preFuture : upFutures) { res = res & preFuture.isAllCancelled(); } } return isCancelled() && res; }
java
@Override public int read() throws IOException { int b = in.read(); if (b != -1) { hasher.put((byte) b); } return b; }
java
@Override public int read(byte[] bytes, int off, int len) throws IOException { int numOfBytesRead = in.read(bytes, off, len); if (numOfBytesRead != -1) { hasher.put(bytes, off, numOfBytesRead); } return numOfBytesRead; }
java
public static <T> SortedSet<HBaseColumn<T>> asSortedSet(T value, long version) { return asSortedSet(value, version, DESC_HBASE_COLUMN_COMPARATOR); }
java
public static <T> SortedMap<Long, HBaseColumn<T>> asSortedMap(T value) { return asSortedMap(value, DESC_HBASE_VERSION_COMPARATOR); }
java
@SafeVarargs @NullSafe public static <T> List<T> asList(T... a) { return N.isNullOrEmpty(a) ? N.<T> emptyList() : Arrays.asList(a); }
java
@SuppressWarnings("deprecation") public CQLBuilder set(final Object entity) { if (entity instanceof String) { return set(N.asArray((String) entity)); } else if (entity instanceof Map) { return set((Map<String, Object>) entity); } else { this.entityC...
java
public boolean remove(Object key, Object value) { final Object curValue = get(key); if (!Objects.equals(curValue, value) || (curValue == null && !containsKey(key))) { return false; } remove(key); return true; }
java
public boolean replace(K key, V oldValue, V newValue) { Object curValue = get(key); if (!Objects.equals(curValue, oldValue) || (curValue == null && !containsKey(key))) { return false; } put(key, newValue); return true; }
java
@Override public Stream<T> queued(int queueSize) { final Iterator<T> iter = iterator(); if (iter instanceof QueuedIterator && ((QueuedIterator<? extends T>) iter).max() >= queueSize) { return newStream(elements, sorted, cmp); } else { return newStream(Stream.p...
java
@SequentialOnly public BiIterator<K, V> iterator() { final ObjIterator<Entry<K, V>> iter = s.iterator(); final BooleanSupplier hasNext = new BooleanSupplier() { @Override public boolean getAsBoolean() { return iter.hasNext(); } };...
java
public static String removePattern(final String source, final String regex) { return replacePattern(source, regex, N.EMPTY_STRING); }
java
static long fingerprint(byte[] bytes, int offset, int length) { if (length <= 32) { if (length <= 16) { return hashLength0to16(bytes, offset, length); } else { return hashLength17to32(bytes, offset, length); } } else if (length <= 64) {...
java
public DBSequence getDBSequence(final String tableName, final String seqName, final long startVal, final int seqBufferSize) { return new DBSequence(this, tableName, seqName, startVal, seqBufferSize); }
java
@Override public void close() throws IOException { try { if (_ds != null && _ds.isClosed() == false) { _ds.close(); } } finally { if (_dsm != null && _dsm.isClosed() == false) { _dsm.close(); } } }
java
protected void evict() { lock.lock(); Map<K, E> removingObjects = null; try { for (Map.Entry<K, E> entry : pool.entrySet()) { if (entry.getValue().activityPrint().isExpired()) { if (removingObjects == null) { removi...
java
@SafeVarargs public static Map<String, AttributeValue> asItem(Object... a) { if (0 != (a.length % 2)) { throw new IllegalArgumentException( "The parameters must be the pairs of property name and value, or Map, or an entity class with getter/setter methods."); } ...
java
@SafeVarargs public static Map<String, AttributeValueUpdate> asUpdateItem(Object... a) { if (0 != (a.length % 2)) { throw new IllegalArgumentException( "The parameters must be the pairs of property name and value, or Map, or an entity class with getter/setter methods."); ...
java
public static Map<String, AttributeValueUpdate> toUpdateItem(final Object entity) { return toUpdateItem(entity, NamingPolicy.LOWER_CAMEL_CASE); }
java
public void moveRow(Object rowKey, int newRowIndex) { checkFrozen(); this.checkRowIndex(newRowIndex); final int rowIndex = this.getRowIndex(rowKey); final List<R> tmp = new ArrayList<>(rowLength()); tmp.addAll(_rowKeySet); tmp.add(newRowIndex, tmp.remove(rowInde...
java
public void swapRows(Object rowKeyA, Object rowKeyB) { checkFrozen(); final int rowIndexA = this.getRowIndex(rowKeyA); final int rowIndexB = this.getRowIndex(rowKeyB); final List<R> tmp = new ArrayList<>(rowLength()); tmp.addAll(_rowKeySet); final R tmpRowKeyA =...
java
public void moveColumn(Object columnKey, int newColumnIndex) { checkFrozen(); this.checkColumnIndex(newColumnIndex); final int columnIndex = this.getColumnIndex(columnKey); final List<C> tmp = new ArrayList<>(columnLength()); tmp.addAll(_columnKeySet); tmp.add(n...
java
public void swapColumns(Object columnKeyA, Object columnKeyB) { checkFrozen(); final int columnIndexA = this.getColumnIndex(columnKeyA); final int columnIndexB = this.getColumnIndex(columnKeyB); final List<C> tmp = new ArrayList<>(rowLength()); tmp.addAll(_columnKeySet);...
java
private static int mulPosAndCheck(final int x, final int y) { /* assert x>=0 && y>=0; */ final long m = (long) x * (long) y; if (m > Integer.MAX_VALUE) { throw new ArithmeticException("overflow: mulPos"); } return (int) m; }
java
private static int addAndCheck(final int x, final int y) { final long s = (long) x + (long) y; if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { throw new ArithmeticException("overflow: add"); } return (int) s; }
java
private static int subAndCheck(final int x, final int y) { final long s = (long) x - (long) y; if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { throw new ArithmeticException("overflow: add"); } return (int) s; }
java
public int binarySearch(final int fromIndex, final int toIndex, final int key) { checkFromToIndex(fromIndex, toIndex); return N.binarySearch(elementData, fromIndex, toIndex, key); }
java
public static <K, V> boolean remove(final Map<K, V> map, Map.Entry<?, ?> entry) { return remove(map, entry.getKey(), entry.getValue()); }
java
public static double asinh(double a) { boolean negative = false; if (a < 0) { negative = true; a = -a; } double absAsinh; if (a > 0.167) { absAsinh = Math.log(Math.sqrt(a * a + 1) + a); } else { final double a2 =...
java
public static double atanh(double a) { boolean negative = false; if (a < 0) { negative = true; a = -a; } double absAtanh; if (a > 0.15) { absAtanh = 0.5 * Math.log((1 + a) / (1 - a)); } else { final double a2 = a...
java
@Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { // return new // NativeStatement(internalConn.createStatement(resultSetType, // resultSetConcurrency), this); return internalConn.createStatement(resultSetType, resultSe...
java
@Override public boolean isClosed() throws SQLException { if (!isClosed) { try { if (internalConn.isClosed()) { destroy(); } } catch (SQLException e) { // ignore destroy(); ...
java
@Override public void setTypeMap(Map<String, Class<?>> arg0) throws SQLException { internalConn.setTypeMap(arg0); }
java
@Override public void setClientInfo(String name, String value) throws SQLClientInfoException { internalConn.setClientInfo(name, value); }
java
public AnyDelete addFamilyVersion(String family, final long timestamp) { delete.addFamilyVersion(toFamilyQualifierBytes(family), timestamp); return this; }
java
public AnyDelete addColumn(String family, String qualifier) { delete.addColumn(toFamilyQualifierBytes(family), toFamilyQualifierBytes(qualifier)); return this; }
java
public AnyDelete addColumns(String family, String qualifier) { delete.addColumns(toFamilyQualifierBytes(family), toFamilyQualifierBytes(qualifier)); return this; }
java
@Beta public Triple<R, M, L> reversed() { return new Triple<>(this.right, this.middle, this.left); }
java
long freeSpaceWindows(String path, final long timeout) throws IOException { path = FilenameUtil.normalize(path, false); if (path.length() > 0 && path.charAt(0) != '"') { path = "\"" + path + "\""; } // build and run the 'dir' command final String[] cmdAttribs ...
java
long parseDir(final String line, final String path) throws IOException { // read from the end of the line to find the last numeric // character on the line, then continue until we find the first // non-numeric character, and everything between that and the last // numeric character i...
java
long parseBytes(final String freeSpace, final String path) throws IOException { try { final long bytes = Long.parseLong(freeSpace); if (bytes < 0) { throw new IOException("Command line '" + DF + "' did not find free space in response " + "for path '" + path + "'- chec...
java
List<String> performCommand(final String[] cmdAttribs, final int max, final long timeout) throws IOException { // this method does what it can to avoid the 'Too many open files' error // based on trial and error and these links: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692 ...
java
@Override public Set<Map.Entry<K, V>> entrySet() { return new AbstractSet<Map.Entry<K, V>>() { @Override public Iterator<Map.Entry<K, V>> iterator() { return new ObjIterator<Map.Entry<K, V>>() { private final Iterator<Map.Entry<K, V>> keyValu...
java
public BiMap<V, K> inversed() { return (inverse == null) ? inverse = new BiMap<>(valueMap, keyMap) : inverse; }
java
protected void evict() { for (int i = 0, len = _segments.length; i < len; i++) { if (_segments[i].blockBitSet.isEmpty()) { final Deque<Segment> queue = _segmentQueueMap.get(i); if (queue != null) { synchronized (queue) { ...
java
private void log(String callerFQCN, Level level, String msg, Throwable t) { // millis and thread are filled by the constructor LogRecord record = new LogRecord(level, msg); record.setLoggerName(getName()); record.setThrown(t); // Note: parameters in record are not set becaus...
java
final private void fillCallerData(String callerFQCN, LogRecord record) { StackTraceElement[] steArray = new Throwable().getStackTrace(); int selfIndex = -1; for (int i = 0; i < steArray.length; i++) { final String className = steArray[i].getClassName(); if (classNa...
java
public boolean removeAll(final Collection<?> c, final long occurrences) { checkOccurrences(occurrences); if (N.isNullOrEmpty(c) || occurrences == 0) { return false; } boolean result = false; for (Object e : c) { if (result == false) { ...
java
public static <T> T newInstance(final Class<T> cls) { if (Modifier.isAbstract(cls.getModifiers())) { if (cls.equals(Map.class)) { return (T) new HashMap<>(); } else if (cls.equals(List.class)) { return (T) new ArrayList<>(); } else if (cl...
java
@SuppressWarnings("unchecked") public static <T> T newArray(final Class<?> componentType, final int length) { // if (length == 0) { // final Object result = CLASS_EMPTY_ARRAY.get(componentType); // // if (result != null) { // ...
java
public static <E> Set<E> newSetFromMap(final Map<E, Boolean> map) { return Collections.newSetFromMap(map); }
java
@SuppressWarnings("unchecked") public static Object[] toArray(final Collection<?> c) { if (N.isNullOrEmpty(c)) { return N.EMPTY_OBJECT_ARRAY; } return c.toArray(new Object[c.size()]); }
java