code
stringlengths
73
34.1k
label
stringclasses
1 value
public static boolean isBlank(final String source) { if (isEmpty(source)) { return true; } int strLen = source.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(source.charAt(i))) { return false; } } return true; }
java
public static int indexOfIgnoreCase(final String source, final String target) { int targetIndex = source.indexOf(target); if (targetIndex == INDEX_OF_NOT_FOUND) { String sourceLowerCase = source.toLowerCase(); String targetLowerCase = target.toLowerCase(); targetIndex = sourceLowerCase.indexO...
java
public static boolean containsWord(final String text, final String word) { if (text == null || word == null) { return false; } if (text.contains(word)) { Matcher matcher = matchText(text); for (; matcher.find();) { String matchedWord = matcher.group(0); if (matchedWord.equ...
java
public static boolean containsWordIgnoreCase(final String text, final String word) { if (text == null || word == null) { return false; } return containsWord(text.toLowerCase(), word.toLowerCase()); }
java
public static boolean startsWithIgnoreCase(final String source, final String target) { if (source.startsWith(target)) { return true; } if (source.length() < target.length()) { return false; } return source.substring(0, target.length()).equalsIgnoreCase(target); }
java
public static boolean endsWithIgnoreCase(final String source, final String target) { if (source.endsWith(target)) { return true; } if (source.length() < target.length()) { return false; } return source.substring(source.length() - target.length()).equalsIgnoreCase(target); }
java
public static String getRandomString(final int stringLength) { StringBuilder stringBuilder = getStringBuild(); for (int i = 0; i < stringLength; i++) { stringBuilder.append(getRandomAlphabetic()); } return stringBuilder.toString(); }
java
public static String encoding(final String source, final String sourceCharset, final String encodingCharset) throws IllegalArgumentException { byte[] sourceBytes; String encodeString = null; try { sourceBytes = source.getBytes(sourceCharset); encodeString = new String(sourceBytes, encodingC...
java
public static double[] getBorders(int numberOfBins, List<Double> counts) { Collections.sort(counts); if (!counts.isEmpty()) { List<Integer> borderInds = findBordersNaive(numberOfBins, counts); if (borderInds == null) { borderInds = findBorderIndsByRepeatedDividing...
java
public Map<String,Set<String>> getDependencies() { Map<String,Set<String>> new_deps = new HashMap<String,Set<String>>(); if (explicitPackages == null) return new_deps; for (Name pkg : explicitPackages) { Set<Name> set = deps.get(pkg); if (set != null) { Se...
java
public void visitPubapi(Element e) { Name n = ((ClassSymbol)e).fullname; Name p = ((ClassSymbol)e).packge().fullname; StringBuffer sb = publicApiPerClass.get(n); assert(sb == null); sb = new StringBuffer(); PubapiVisitor v = new PubapiVisitor(sb); v.visit(e); ...
java
public void collect(Name currPkg, Name depPkg) { if (!currPkg.equals(depPkg)) { Set<Name> theset = deps.get(currPkg); if (theset==null) { theset = new HashSet<Name>(); deps.put(currPkg, theset); } theset.add(depPkg); } }
java
@SuppressWarnings("unchecked") public void preload(int quantity) { Object[] objects = new Object[quantity]; for (int i = 0; i < quantity; i++) { objects[i] = this.instantiate(); } for (int i = 0; i < quantity; i++) { this.release((T)objects[i]); } }
java
private void blockMe(int cyclesToBlock) { long unblock = cycles + cyclesToBlock; BlockedEntry newEntry = new BlockedEntry(unblock); blockedCollection.add(newEntry); while (unblock > cycles) { try { newEntry.getSync().acquire(); // blocks } catch (InterruptedException exc) { log.error("[temporaryBloc...
java
public void tick() { log.trace("Tick {}", cycles); cycles++; // check for robots up for unblocking for (BlockedEntry entry : blockedCollection) { if (entry.getTimeout() >= cycles) { entry.getSync().release(); } } }
java
public void waitFor(Integer clientId, int turns, String reason) { // for safety, check if we know the robot, otherwise fail if (!registered.contains(clientId)) { throw new IllegalArgumentException("Unknown robot. All robots must first register with clock"); } synchronized (waitingList) { if (waitingList...
java
public String produce(int size) { byte bytes[] = new byte[size]; _random.nextBytes(bytes); return Strings.toHexString(bytes); }
java
public String produce(String state, long time) { Nonce nonce = new Nonce(INSTANCE, time > 0 ? time : TTL, SIZE, _random); _map.put(state + ':' + nonce.value, nonce); return nonce.value; }
java
public boolean renew(String value, String state, long time) { Nonce nonce = _map.get(state + ':' + value); if (nonce != null && !nonce.hasExpired()) { nonce.renew(time > 0 ? time : TTL); return true; } else { return false; } }
java
public boolean prove(String value, String state) { Nonce nonce = _map.remove(state + ':' + value); return nonce != null && !nonce.hasExpired(); }
java
public boolean hasCategory(final String conceptURI) { return Iterables.any(getCategories(), new Predicate<TopicAnnotation>() { @Override public boolean apply(TopicAnnotation ta) { return ta.getTopicReference(). ...
java
public static SQLiteDatabase create(CursorFactory factory) { // This is a magic string with special meaning for SQLite. return openDatabase(com.couchbase.lite.internal.database.sqlite.SQLiteDatabaseConfiguration.MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY); }
java
public long replace(String table, String nullColumnHack, ContentValues initialValues) { try { return insertWithOnConflict(table, nullColumnHack, initialValues, CONFLICT_REPLACE); } catch (SQLException e) { DLog.e(TAG, "Error inserting " + initialValues, e); ...
java
private static byte[] decodeBase64Digest(String base64Digest) { String expectedPrefix = "sha1-"; if (!base64Digest.startsWith(expectedPrefix)) { throw new IllegalArgumentException(base64Digest + " did not start with " + expectedPrefix); } base64Digest = ba...
java
protected void fireTrigger(final ReplicationTrigger trigger) { Log.d(Log.TAG_SYNC, "%s [fireTrigger()] => " + trigger, this); // All state machine triggers need to happen on the replicator thread synchronized (executor) { if (!executor.isShutdown()) { executor.submit(...
java
protected void start() { try { if (!db.isOpen()) { String msg = String.format(Locale.ENGLISH, "Db: %s is not open, abort replication", db); parentReplication.setLastError(new Exception(msg)); fireTrigger(ReplicationTrigger.STOP_IMMEDIATE); ...
java
protected void close() { this.authenticating = false; // cancel pending futures for (Future future : pendingFutures) { future.cancel(false); CancellableRunnable runnable = cancellables.get(future); if (runnable != null) { runnable.cancel(); ...
java
@InterfaceAudience.Private protected void checkSession() { if (getAuthenticator() != null) { Authorizer auth = (Authorizer) getAuthenticator(); auth.setRemoteURL(remote); auth.setLocalUUID(db.publicUUID()); } if (getAuthenticator() != null && getAuthentica...
java
@InterfaceAudience.Private private void refreshRemoteCheckpointDoc() { Log.i(Log.TAG_SYNC, "%s: Refreshing remote checkpoint to get its _rev...", this); Future future = sendAsyncRequest("GET", "_local/" + remoteCheckpointDocID(), null, new RemoteRequestCompletion() { @Override ...
java
protected void stop() { this.authenticating = false; // clear batcher batcher.clear(); // set non-continuous setLifecycle(Replication.Lifecycle.ONESHOT); // cancel if middle of retry cancelRetryFuture(); // cancel all pending future tasks. while (!...
java
private void notifyChangeListeners(final Replication.ChangeEvent changeEvent) { if (changeListenerNotifyStyle == ChangeListenerNotifyStyle.SYNC) { for (ChangeListener changeListener : changeListeners) { try { changeListener.changed(changeEvent); } ...
java
private void scheduleRetryFuture() { Log.v(Log.TAG_SYNC, "%s: Failed to xfer; will retry in %d sec", this, RETRY_DELAY_SECONDS); synchronized (executor) { if (!executor.isShutdown()) { this.retryFuture = executor.schedule(new Runnable() { public void run()...
java
private void cancelRetryFuture() { if (retryFuture != null && !retryFuture.isDone()) { retryFuture.cancel(true); } retryFuture = null; }
java
protected void retryReplicationIfError() { Log.d(TAG, "retryReplicationIfError() state=" + stateMachine.getState() + ", error=" + this.error + ", isContinuous()=" + isContinuous() + ", isTransientError()=" + Utils.isTransientError(this.error)); // Make su...
java
void dumpUnsafe(Printer printer, boolean verbose) { printer.println("Connection #" + mConnectionId + ":"); if (verbose) { printer.println(" connectionPtr: 0x" + Long.toHexString(mConnectionPtr)); } printer.println(" isPrimaryConnection: " + mIsPrimaryConnection); pr...
java
void collectDbStatsUnsafe(ArrayList<com.couchbase.lite.internal.database.sqlite.SQLiteDebug.DbStats> dbStatsList) { dbStatsList.add(getMainDbStatsUnsafe(0, 0, 0)); }
java
protected void execute() { Log.v(Log.TAG_SYNC, "%s: RemoteRequest execute() called, url: %s", this, url); executeRequest(factory.getOkHttpClient(), request()); Log.v(Log.TAG_SYNC, "%s: RemoteRequest execute() finished, url: %s", this, url); }
java
protected RequestBody setCompressedBody(byte[] bodyBytes) { if (bodyBytes.length < MIN_JSON_LENGTH_TO_COMPRESS) return null; byte[] encodedBytes = Utils.compressByGzip(bodyBytes); if (encodedBytes == null || encodedBytes.length >= bodyBytes.length) return null; re...
java
int indexOf(byte[] data, int dataLength, byte[] pattern, int dataOffset) { int[] failure = computeFailure(pattern); int j = 0; if (data.length == 0) return -1; //final int dataLength = data.length; final int patternLength = pattern.length; for (int i = dataOff...
java
private static int[] computeFailure(byte[] pattern) { int[] failure = new int[pattern.length]; int j = 0; for (int i = 1; i < pattern.length; i++) { while (j > 0 && pattern[j] != pattern[i]) j = failure[j - 1]; if (pattern[j] == pattern[i]) ...
java
@InterfaceAudience.Public public List<String> getAllDatabaseNames() { String[] databaseFiles = directoryFile.list(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.endsWith(Manager.kDBExtension)) { re...
java
@InterfaceAudience.Public public void close() { synchronized (lockDatabases) { Log.d(Database.TAG, "Closing " + this); // Close all database: // Snapshot of the current open database to avoid concurrent modification as // the database will be forgotten (remov...
java
@InterfaceAudience.Public public boolean replaceDatabase(String databaseName, String databaseDir) { Database db = getDatabase(databaseName, false); if(db == null) return false; File dir = new File(databaseDir); if(!dir.exists()){ Log.w(Database.TAG, "Database...
java
@InterfaceAudience.Private public Future runAsync(String databaseName, final AsyncTask function) throws CouchbaseLiteException { final Database database = getDatabase(databaseName); return runAsync(new Runnable() { @Override public void run() { function.run(da...
java
@Override public void startedPart(Map headers) { if (_docReader != null) throw new IllegalStateException("_docReader is already defined"); Log.v(TAG, "%s: Starting new document; headers =%s", this, headers); _docReader = new MultipartDocumentReader(db); _docReader.setHead...
java
@Override public void finishedPart() { if (_docReader == null) throw new IllegalStateException("_docReader is not defined"); _docReader.finish(); _onDocument.onDocument(_docReader.getDocumentProperties(), _docReader.getDocumentSize()); _docReader = null; Log.v(TAG...
java
@InterfaceAudience.Public public Document getDocument() { if (getDocumentId() == null) { return null; } assert (database != null); Document document = database.getDocument(getDocumentId()); document.loadCurrentRevisionFrom(this); return document; }
java
@InterfaceAudience.Public public String getDocumentId() { // Get the doc id from either the embedded document contents, or the '_id' value key. // Failing that, there's no document linking, so use the regular old _sourceDocID String docID = null; if (documentRevision != null) ...
java
@InterfaceAudience.Public public String getDocumentRevisionId() { // Get the revision id from either the embedded document contents, // or the '_rev' or 'rev' value key: String rev = null; if (documentRevision != null) rev = documentRevision.getRevID(); if (rev ==...
java
public void add(final AtomicAction action) { if (action instanceof Action) { Action a = (Action)action; peforms.addAll(a.peforms); backouts.addAll(a.backouts); cleanUps.addAll(a.cleanUps); } else { add(new ActionBlock() { @Overr...
java
public void add(ActionBlock perform, ActionBlock backout, ActionBlock cleanup) { peforms.add(perform != null ? perform : nullAction); backouts.add(backout != null ? backout : nullAction); cleanUps.add(cleanup != null ? cleanup : nullAction); }
java
public void run() throws ActionException { try { perform(); try { cleanup(); // Ignore exception } catch (ActionException e) {} lastError = null; } catch (ActionException e) { // (perform: has already backed out whatever it did)...
java
private void doAction(List<ActionBlock> actions) throws ActionException { try { actions.get(nextStep).execute(); } catch (ActionException e) { throw e; } catch (Exception e) { throw new ActionException("Exception raised by step: " + nextStep, e); } ...
java
@Override public boolean setVersion(String version) { // Update the version column in the database. This is a little weird looking because we want // to avoid modifying the database if the version didn't change, and because the row might // not exist yet. SQLiteStorageEngine storage ...
java
@Override public long getLastSequenceIndexed() { String sql = "SELECT lastSequence FROM views WHERE name=?"; String[] args = {name}; Cursor cursor = null; long result = -1; try { cursor = store.getStorageEngine().rawQuery(sql, args); if (cursor.moveToN...
java
private static boolean groupTogether(Object key1, Object key2, int groupLevel) { if (groupLevel == 0 || !(key1 instanceof List) || !(key2 instanceof List)) { return key1.equals(key2); } @SuppressWarnings("unchecked") List<Object> key1List = (List<Object>) key1; @Suppr...
java
public static Object groupKey(Object key, int groupLevel) { if (groupLevel > 0 && (key instanceof List) && (((List<Object>) key).size() > groupLevel)) { return ((List<Object>) key).subList(0, groupLevel); } else { return key; } }
java
@InterfaceAudience.Public public int getTotalRows() { try { updateIndex(); } catch (CouchbaseLiteException e) { Log.e(Log.TAG_VIEW, "Update index failed when getting the total rows", e); } return getCurrentTotalRows(); }
java
@InterfaceAudience.Public public static double totalValues(List<Object> values) { double total = 0; for (Object object : values) { if (object instanceof Number) { Number number = (Number) object; total += number.doubleValue(); } else { ...
java
@InterfaceAudience.Private protected Status updateIndexes(List<View> views) throws CouchbaseLiteException { List<ViewStore> storages = new ArrayList<ViewStore>(); for (View view : views) { storages.add(view.viewStore); } return viewStore.updateIndexes(storages); }
java
@InterfaceAudience.Private public List<QueryRow> query(QueryOptions options) throws CouchbaseLiteException { if (options == null) options = new QueryOptions(); if (groupOrReduce(options)) return viewStore.reducedQuery(options); else return viewStore.regula...
java
public static Printer create(Printer printer, String prefix) { if (prefix == null || prefix.equals("")) { return printer; } return new PrefixPrinter(printer, prefix); }
java
public void deleteCookie(Cookie cookie) { cookies.remove(cookie.name()); deletePersistedCookie(cookie.name()); }
java
public static int getDefaultPageSize() { synchronized (sLock) { if (sDefaultPageSize == 0) { try { Class clazz = Class.forName("android.os.StatFs"); Method m = clazz.getMethod("getBlockSize"); Object statFsObj = clazz.getCon...
java
private static String byteArrayToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); for (byte element : bytes) { int v = element & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); ...
java
@InterfaceAudience.Public public SavedRevision createRevision(Map<String, Object> properties) throws CouchbaseLiteException { boolean allowConflict = false; return document.putProperties(properties, revisionInternal.getRevID(), allowConflict); }
java
@Override @InterfaceAudience.Public public Map<String, Object> getProperties() { Map<String, Object> properties = revisionInternal.getProperties(); if (!checkedProperties) { if (properties == null) { if (loadProperties() == true) { properties = rev...
java
public Object jsonObject() { if (json == null) { return null; } if (cached == null) { Object tmp = null; if (json[0] == '{') { tmp = new LazyJsonObject<String, Object>(json); } else if (json[0] == '[') { tmp = new...
java
public void queueObjects(List<T> objects) { if (objects == null || objects.size() == 0) return; boolean readyToProcess = false; synchronized (mutex) { Log.v(Log.TAG_BATCHER, "%s: queueObjects called with %d objects (current inbox size = %d)", this, ob...
java
public void flushAll(boolean waitForAllToFinish) { Log.v(Log.TAG_BATCHER, "%s: flushing all objects (wait=%b)", this, waitForAllToFinish); synchronized (mutex) { isFlushing = true; unschedule(); } while (true) { ScheduledFuture future = null; ...
java
private void scheduleBatchProcess(boolean immediate) { synchronized (mutex) { if (inbox.size() == 0) return; // Schedule the processing. To improve latency, if we haven't processed anything // in at least our delay time, rush these object(s) through a minimum...
java
private void scheduleWithDelay(long delay) { synchronized (mutex) { if (scheduled && delay < scheduledDelay) { if (isPendingFutureReadyOrInProcessing()) { // Ignore as there is one batch currently in processing or ready to be processed: Log.v(L...
java
private void unschedule() { synchronized (mutex) { if (pendingFuture != null && !pendingFuture.isDone() && !pendingFuture.isCancelled()) { Log.v(Log.TAG_BATCHER, "%s: cancelling the pending future ...", this); pendingFuture.cancel(false); } sch...
java
private boolean isPendingFutureReadyOrInProcessing() { synchronized (mutex) { if (pendingFuture != null && !pendingFuture.isDone() && !pendingFuture.isCancelled()) { return pendingFuture.getDelay(TimeUnit.MILLISECONDS) <= 0; } return false; } }
java
private void processNow() { List<T> toProcess; boolean scheduleNextBatchImmediately = false; synchronized (mutex) { int count = inbox.size(); Log.v(Log.TAG_BATCHER, "%s: processNow() called, inbox size: %d", this, count); if (count == 0) return...
java
private String getRequestHeaderContentType() { String contentType = getRequestHeaderValue("Content-Type"); if (contentType != null) { // remove parameter (Content-Type := type "/" subtype *[";" parameter] ) int index = contentType.indexOf(';'); if (index > 0) ...
java
private void setResponseLocation(URL url) { String location = url.getPath(); String query = url.getQuery(); if (query != null) { int startOfQuery = location.indexOf(query); if (startOfQuery > 0) { location = location.substring(0, startOfQuery); ...
java
private static void convertCBLQueryRowsToMaps(Map<String, Object> allDocsResult) { List<Map<String, Object>> rowsAsMaps = new ArrayList<Map<String, Object>>(); List<QueryRow> rows = (List<QueryRow>) allDocsResult.get("rows"); if (rows != null) { for (QueryRow row : rows) { ...
java
@Override public void changed(Database.ChangeEvent event) { synchronized (changesLock) { if (isTimeout) return; lastChangesTimestamp = System.currentTimeMillis(); // Stop timeout timer: stopTimeout(); // In race condition, new do...
java
public void cancel() { final OnCancelListener listener; synchronized (this) { if (mIsCanceled) { return; } mIsCanceled = true; mCancelInProgress = true; listener = mOnCancelListener; } try { if (list...
java
public void setOnCancelListener(OnCancelListener listener) { synchronized (this) { waitForCancelFinishedLocked(); if (mOnCancelListener == listener) { return; } mOnCancelListener = listener; if (!mIsCanceled || listener == null) { ...
java
@InterfaceAudience.Public public void waitForRows() throws CouchbaseLiteException { start(); while (true) { try { queryFuture.get(); break; } catch (InterruptedException e) { continue; } catch (Exception e) { ...
java
@InterfaceAudience.Public public QueryEnumerator getRows() { start(); if (rows == null) { return null; } else { // Have to return a copy because the enumeration has to start at item #0 every time return new QueryEnumerator(rows); } }
java
@InterfaceAudience.Public public SavedRevision getCurrentRevision() { if (currentRevision == null) currentRevision = getRevision(null); return currentRevision; }
java
@InterfaceAudience.Public public Map<String, Object> getProperties() { return getCurrentRevision() == null ? null : getCurrentRevision().getProperties(); }
java
@InterfaceAudience.Public public boolean delete() throws CouchbaseLiteException { return getCurrentRevision() == null ? false : getCurrentRevision().deleteDocument() != null; }
java
@InterfaceAudience.Public public void purge() throws CouchbaseLiteException { Map<String, List<String>> docsToRevs = new HashMap<String, List<String>>(); List<String> revs = new ArrayList<String>(); revs.add("*"); docsToRevs.put(documentId, revs); database.purgeRevisions(docs...
java
@InterfaceAudience.Public public SavedRevision getRevision(String revID) { if (revID != null && currentRevision != null && revID.equals(currentRevision.getId())) return currentRevision; RevisionInternal revisionInternal = database.getDocument(getId(), revID, true); return getRevi...
java
@InterfaceAudience.Public public long getLength() { Number length = (Number) metadata.get("length"); if (length != null) { return length.longValue(); } else { return 0; } }
java
@InterfaceAudience.Private protected static Map<String, Object> installAttachmentBodies(Map<String, Object> attachments, Database database) throws CouchbaseLiteException { Map<String, Object> updatedAttachments = new HashMap<String...
java
private void initSupportExecutor() { if (supportExecutor == null || supportExecutor.isShutdown()) { supportExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { String maskedRemote = URLU...
java
@InterfaceAudience.Public public List<String> getAttachmentNames() { Map<String, Object> attachmentMetadata = getAttachmentMetadata(); if (attachmentMetadata == null) { return new ArrayList<String>(); } return new ArrayList<String>(attachmentMetadata.keySet()); }
java
@InterfaceAudience.Public public List<Attachment> getAttachments() { Map<String, Object> attachmentMetadata = getAttachmentMetadata(); if (attachmentMetadata == null) { return new ArrayList<Attachment>(); } List<Attachment> result = new ArrayList<Attachment>(attachmentMet...
java
@InterfaceAudience.Public public void setUserProperties(Map<String, Object> userProperties) { Map<String, Object> newProps = new HashMap<String, Object>(); newProps.putAll(userProperties); for (String key : properties.keySet()) { if (key.startsWith("_")) { newProp...
java
@InterfaceAudience.Private protected void addAttachment(Attachment attachment, String name) { Map<String, Object> attachments = (Map<String, Object>) properties.get("_attachments"); if (attachments == null) { attachments = new HashMap<String, Object>(); } attachments.put(...
java
protected void beginReplicating() { Log.v(TAG, "submit startReplicating()"); executor.submit(new Runnable() { @Override public void run() { if (isRunning()) { Log.v(TAG, "start startReplicating()"); initPendingSequences(); ...
java
@Override @InterfaceAudience.Private protected void processInbox(RevisionList inbox) { Log.d(TAG, "processInbox called"); if (db == null || !db.isOpen()) { Log.w(Log.TAG_SYNC, "%s: Database is null or closed. Unable to continue. db name is %s.", this, db.getName()); retu...
java
protected void pullBulkRevisions(List<RevisionInternal> bulkRevs) { int nRevs = bulkRevs.size(); if (nRevs == 0) { return; } Log.d(TAG, "%s bulk-fetching %d remote revisions...", this, nRevs); Log.d(TAG, "%s bulk-fetching remote revisions: %s", this, bulkRevs); ...
java
private void queueDownloadedRevision(RevisionInternal rev) { if (revisionBodyTransformationBlock != null) { // Add 'file' properties to attachments pointing to their bodies: for (Map.Entry<String, Map<String, Object>> entry : ( (Map<String, Map<String, Object>>) rev...
java
protected void pullBulkWithAllDocs(final List<RevisionInternal> bulkRevs) { // http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API ++httpConnectionCount; final RevisionList remainingRevs = new RevisionList(bulkRevs); Collection<String> keys = CollectionUtils.transform(bulkRevs, ...
java