code
stringlengths
73
34.1k
label
stringclasses
1 value
public String getAsString(String key) { Object value = mValues.get(key); return value != null ? value.toString() : null; }
java
public int getVersion() throws SQLException { try { return this.submit(new VersionCallable()).get(); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Failed to get database version", e); throw new SQLException(e); } catch (ExecutionException e) { ...
java
public <T> Future<T> submit(SQLCallable<T> callable){ return this.submitTaskToQueue(new SQLQueueCallable<T>(db, callable)); }
java
public <T> Future<T> submitTransaction(SQLCallable<T> callable){ return this.submitTaskToQueue(new SQLQueueCallable<T>(db, callable, true)); }
java
public void shutdown() { // If shutdown has already been called then we don't need to shutdown again if (acceptTasks.getAndSet(false)) { //pass straight to queue, tasks passed via submitTaskToQueue will now be blocked. Future<?> close = queue.submit(new Runnable() { ...
java
private <T> Future<T> submitTaskToQueue(SQLQueueCallable<T> callable){ if(acceptTasks.get()){ return queue.submit(callable); } else { throw new RejectedExecutionException("Database is closed"); } }
java
public synchronized String getSQLiteVersion() { if (this.sqliteVersion == null) { try { this.sqliteVersion = this.submit(new SQLiteVersionCallable()).get(); return sqliteVersion; } catch (InterruptedException e) { logger.log(Level.WARNING,...
java
private boolean validateEncryptionKeyData(KeyData data) { if (data.getIv().length != ENCRYPTIONKEYCHAINMANAGER_AES_IV_SIZE) { LOGGER.warning("IV does not have the expected size: " + ENCRYPTIONKEYCHAINMANAGER_AES_IV_SIZE + " bytes"); return false; } ret...
java
@SuppressWarnings("unchecked") private List<DBParameter> parametersToIndexRevision(DocumentRevision rev, String indexName, List<FieldSort> fieldNames) { Misc.checkNotNull...
java
private static SQLDatabase internalOpenSQLDatabase(File dbFile, KeyProvider provider) throws SQLException { boolean runningOnAndroid = Misc.isRunningOnAndroid(); boolean useSqlCipher = (provider.getEncryptionKey() != null); try { if (runningOnAndroid) { if (useSql...
java
public Task createDocument(Task task) { DocumentRevision rev = new DocumentRevision(); rev.setBody(DocumentBodyFactory.create(task.asMap())); try { DocumentRevision created = this.mDocumentStore.database().create(rev); return Task.fromRevision(created); } catch (D...
java
public Task updateDocument(Task task) throws ConflictException, DocumentStoreException { DocumentRevision rev = task.getDocumentRevision(); rev.setBody(DocumentBodyFactory.create(task.asMap())); try { DocumentRevision updated = this.mDocumentStore.database().update(rev); ...
java
public void deleteDocument(Task task) throws ConflictException, DocumentNotFoundException, DocumentStoreException { this.mDocumentStore.database().delete(task.getDocumentRevision()); }
java
protected static boolean validFieldName(String fieldName) { String[] parts = fieldName.split("\\."); for (String part: parts) { if (part.startsWith("$")) { String msg = String.format("Field names cannot start with a $ in field %s", part); logger.log(Level.SEVE...
java
public static String tokenizerToJson(Tokenizer tokenizer) { Map<String, String> settingsMap = new HashMap<String, String>(); if (tokenizer != null) { settingsMap.put(TOKENIZE, tokenizer.tokenizerName); // safe to store args even if they are null settingsMap.put(TOKENI...
java
public static UnindexedMatcher matcherWithSelector(Map<String, Object> selector) { ChildrenQueryNode root = buildExecutionTreeForSelector(selector); if (root == null) { return null; } UnindexedMatcher matcher = new UnindexedMatcher(); matcher.root = root; r...
java
protected static boolean compareLT(Object l, Object r) { if (l == null || r == null) { return false; // null fails all lt/gt/lte/gte tests } else if (!(l instanceof String || l instanceof Number)) { String msg = String.format("Value in document not a Number or String: %s", l); ...
java
public List<String> documentIds() { List<String> documentIds = new ArrayList<String>(); List<DocumentRevision> docs = CollectionUtils.newArrayList(iterator()); for (DocumentRevision doc : docs) { documentIds.add(doc.getId()); } return documentIds; }
java
public static List<String> createRevisionIdHistory(DocumentRevs documentRevs) { validateDocumentRevs(documentRevs); String latestRevision = documentRevs.getRev(); int generation = CouchUtils.generationFromRevId(latestRevision); assert generation == documentRevs.getRevisions().getStart()...
java
@Override public List<DocumentRevision> delete(final String id) throws DocumentNotFoundException, DocumentStoreException { Misc.checkNotNull(id, "ID"); try { if (id.startsWith(CouchConstants._local_prefix)) { String localId = id.substring(CouchConstants._local...
java
public static <T> T get(Future<T> future) throws ExecutionException { try { return future.get(); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Re-throwing InterruptedException as ExecutionException"); throw new ExecutionException(e); } }
java
public static String join(String separator, Collection<String> stringsToJoin) { StringBuilder builder = new StringBuilder(); // Check if there is at least 1 element then use do/while to avoid trailing separator int index = stringsToJoin.size(); for (String str : stringsToJoin) { ...
java
public static void checkNotNull(Object param, String errorMessagePrefix) throws IllegalArgumentException { checkArgument(param != null, (errorMessagePrefix != null ? errorMessagePrefix : "Parameter") + " must not be null."); }
java
public static void checkNotNullOrEmpty(String param, String errorMessagePrefix) throws IllegalArgumentException { checkNotNull(param, errorMessagePrefix); checkArgument(!param.isEmpty(), (errorMessagePrefix != null ? errorMessagePrefix : "Parameter") + " must not be empty.");...
java
private void setup() { try { this.partBoundary = ("--" + boundary).getBytes("UTF-8"); this.trailingBoundary = ("--" + boundary + "--").getBytes("UTF-8"); this.contentType = "content-type: application/json".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { ...
java
public static void updateAllIndexes(List<Index> indexes, Database database, SQLDatabaseQueue queue) throws QueryException { IndexUpdater updater = new IndexUpdater(database, queue); updater.updateAllIndexes(indexes); ...
java
public static void updateIndex(String indexName, List<FieldSort> fieldNames, Database database, SQLDatabaseQueue queue) throws QueryException { IndexUpdater updater = new IndexUpdater(database, queu...
java
@JsonAnySetter public void setOthers(String name, Object value) { if(name.startsWith("_")) { // Just be defensive throw new RuntimeException("This is a reserved field, and should not be treated as document content."); } this.others.put(name, value); }
java
@SuppressWarnings("unchecked") public static Map<String, Object> normaliseAndValidateQuery(Map<String, Object> query) throws QueryException{ boolean isWildCard = false; if (query.isEmpty()) { isWildCard = true; } // First expand the query to include a leading compound pr...
java
@SuppressWarnings("unchecked") private static void validateSelector(Map<String, Object> selector) throws QueryException { String topLevelOp = (String) selector.keySet().toArray()[0]; // top level op can only be $and or $or after normalisation if (topLevelOp.equals(AND) || topLevelOp.equals(...
java
@SuppressWarnings("unchecked") private static void validateCompoundOperatorClauses(List<Object> clauses, Boolean[] textClauseLimitReached) throws QueryException { for (Object obj : clauses) { if (!(obj instanceof Map)) { ...
java
public InputStream getInputStream(File file, Attachment.Encoding encoding) throws IOException { // First, open a stream to the raw bytes on disk. // Then, if we have a key assume the file is encrypted, so add a stream // to the chain which decrypts the data as we read from disk. // Fina...
java
public OutputStream getOutputStream(File file, Attachment.Encoding encoding) throws IOException { // First, open a stream to the raw bytes on disk. // Then, if we have a key assume the file should be encrypted before writing, // so wrap the file stream in a stream which encrypts dur...
java
public void addValueToKey(K key, V value) { this.addValuesToKey(key, Collections.singletonList(value)); }
java
public void addValuesToKey(K key, Collection<V> valueCollection) { if (!valueCollection.isEmpty()) { // Create a new collection to store the values (will be changed to internal type by call // to putIfAbsent anyway) List<V> collectionToAppendValuesOn = new ArrayList<V>(); ...
java
private String queryAsString(Map<String, Object> query) { ArrayList<String> queryParts = new ArrayList<String>(query.size()); for(Map.Entry<String, Object> entry : query.entrySet()) { String value = this.encodeQueryParameter(entry.getValue().toString()); String key = this.encodeQ...
java
void replicationComplete() { reloadTasksFromModel(); Toast.makeText(getApplicationContext(), R.string.replication_completed, Toast.LENGTH_LONG).show(); dismissDialog(DIALOG_PROGRESS); }
java
void replicationError() { Log.i(LOG_TAG, "error()"); reloadTasksFromModel(); Toast.makeText(getApplicationContext(), R.string.replication_error, Toast.LENGTH_LONG).show(); dismissDialog(DIALOG_PROGRESS); }
java
protected static PreparedAttachment prepareAttachment(String attachmentsDir, AttachmentStreamFactory attachmentStreamFactory, Attachment attachment, long length, long encodedLength) throws AttachmentException { PreparedAttachment pa = new PreparedAttachm...
java
public static Map<String, SavedAttachment> findExistingAttachments( Map<String, ? extends Attachment> attachments) { Map<String, SavedAttachment> existingAttachments = new HashMap<String, SavedAttachment>(); for (Map.Entry<String, ? extends Attachment> a : attachments.entrySet()) { ...
java
public static Map<String, Attachment> findNewAttachments(Map<String, ? extends Attachment> attachments) { Map<String, Attachment> newAttachments = new HashMap<String, Attachment>(); for (Map.Entry<String, ? extends Attachment> a : attachments.entrySet()) { if (!(a instanceof SavedAttachment)...
java
public static void copyAttachment(SQLDatabase db, long parentSequence, long newSequence, String filename) throws SQLException { Cursor c = null; try{ c = db.rawQuery(SQL_ATTACHMENTS_SELECT, new String[]{filename, String.valueOf(par...
java
public static void purgeAttachments(SQLDatabase db, String attachmentsDir) { // it's easier to deal with Strings since java doesn't know how to compare byte[]s Set<String> currentKeys = new HashSet<String>(); Cursor c = null; try { // delete attachment table entries for revs ...
java
static String generateFilenameForKey(SQLDatabase db, String keyString) throws NameGenerationException { String filename = null; long result = -1; // -1 is error for insert call int tries = 0; while (result == -1 && tries < 200) { byte[] randomBytes = new byte[2...
java
public void put(int index, long value) { if(desc.get(index) != Cursor.FIELD_TYPE_INTEGER) { throw new IllegalArgumentException("Inserting an integer, but expecting " + getTypeName(desc.get(index))); } this.values.add(index, value); }
java
private URI addAuthInterceptorIfRequired(URI uri) { String uriProtocol = uri.getScheme(); String uriHost = uri.getHost(); String uriPath = uri.getRawPath(); int uriPort = getDefaultPort(uri); setUserInfo(uri); setAuthInterceptor(uriHost, uriPath, uriProtocol, uriPort); ...
java
public E username(String username) { Misc.checkNotNull(username, "username"); this.username = username; //noinspection unchecked return (E) this; }
java
public E password(String password) { Misc.checkNotNull(password, "password"); this.password = password; //noinspection unchecked return (E) this; }
java
@Override public List<Index> listIndexes() throws QueryException { try { return DatabaseImpl.get(dbQueue.submit(new ListIndexesCallable())); } catch (ExecutionException e) { String msg = "Failed to list indexes"; logger.log(Level.SEVERE, msg, e); thro...
java
private Index ensureIndexed(List<FieldSort> fieldNames, String indexName, IndexType indexType, Tokenizer tokenizer) throws QueryException { // synchronized to prevent race conditions in IndexCreator when looking for ...
java
@Override public void deleteIndex(final String indexName) throws QueryException { Misc.checkNotNullOrEmpty(indexName, "indexName"); Future<Void> result = dbQueue.submitTransaction(new DeleteIndexCallable(indexName)); try { result.get(); } catch (ExecutionException e) { ...
java
@Override public void refreshAllIndexes() throws QueryException { List<Index> indexes = listIndexes(); IndexUpdater.updateAllIndexes(indexes, database, dbQueue); }
java
public QueryResult find(Map<String, Object> query, final List<Index> indexes, long skip, long limit, List<String> fields, final List<FieldSort> sortDocument) throws QueryException ...
java
private void validateFields(List<String> fields) { if (fields == null) { return; } List<String> badFields = new ArrayList<String>(); for (String field: fields) { if (field.contains(".")) { badFields.add(field); } } if (...
java
private List<String> sortIds(Set<String> docIdSet, List<FieldSort> sortDocument, List<Index> indexes, SQLDatabase db) throws QueryException { boolean smallResultSet = (docIdSet.size() < SMALL_RESULT_SET_SIZE_THRES...
java
protected static SqlParts sqlToSortIds(Set<String> docIdSet, List<FieldSort> sortDocument, List<Index> indexes) throws QueryException { String chosenIndex = chooseIndexForSort(sortDocument, indexes); if (chosenIndex == null) { ...
java
public static String generateNextRevisionId(String revisionId) { validateRevisionId(revisionId); int generation = generationFromRevId(revisionId); String digest = createUUID(); return Integer.toString(generation + 1) + "-" + digest; }
java
public static AndroidSQLCipherSQLite open(File path, KeyProvider provider) { //Call SQLCipher-based method for opening database, or creating if database not found SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, KeyUtils.sqlCipherKeyForKeyProvider(provider), null); ...
java
protected void upgradePreferences() { String alarmDueElapsed = "com.cloudant.sync.replication.PeriodicReplicationService.alarmDueElapsed"; if (mPrefs.contains(alarmDueElapsed)) { // These are old style preferences. We need to rewrite them in the new form that allows // multiple r...
java
public synchronized void startPeriodicReplication() { if (!isPeriodicReplicationEnabled()) { setPeriodicReplicationEnabled(true); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent alarmIntent = new Intent(this, clazz); alar...
java
public synchronized void stopPeriodicReplication() { if (isPeriodicReplicationEnabled()) { setPeriodicReplicationEnabled(false); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent alarmIntent = new Intent(this, clazz); alarm...
java
private void setPeriodicReplicationEnabled(boolean running) { SharedPreferences.Editor editor = mPrefs.edit(); editor.putBoolean(constructKey(PERIODIC_REPLICATION_ENABLED_SUFFIX), running); editor.apply(); }
java
private void setExplicitlyStopped(boolean explicitlyStopped) { SharedPreferences.Editor editor = mPrefs.edit(); editor.putBoolean(constructKey(EXPLICITLY_STOPPED_SUFFIX), explicitlyStopped); editor.apply(); }
java
private void resetAlarmDueTimesOnReboot() { // As the device has been rebooted, we use clock time rather than elapsed time since // booting to set check whether we missed any alarms while the device was off and to // make sure the next alarm time isn't too far in the future (indicating the syste...
java
public static void setReplicationsPending(Context context, Class<? extends PeriodicReplicationService> prsClass, boolean pending) { SharedPreferences prefs = context.getSharedPreferences(PREFERENCES_FILE_NAME, Context .MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); ...
java
public static boolean replicationsPending(Context context, Class<? extends PeriodicReplicationService> prsClass) { SharedPreferences prefs = context.getSharedPreferences(PREFERENCES_FILE_NAME, Context .MODE_PRIVATE); return prefs.getBoolean(constructKey(prsClass, REPLICATIONS_PENDING...
java
private <T> T executeWithRetry(final Callable<ExecuteResult> task, InputStreamProcessor<T> processor) throws CouchException { int attempts = 10; CouchException lastException = null; while (attempts-- > 0) { ExecuteResult result = null; ...
java
public Response update(String id, Object document) { Misc.checkNotNullOrEmpty(id, "id"); Misc.checkNotNull(document, "Document"); // Get the latest rev, will throw if doc doesn't exist getDocumentRev(id); return putUpdate(id, document); }
java
public List<Response> bulkCreateSerializedDocs(List<String> serializedDocs) { Misc.checkNotNull(serializedDocs, "Serialized doc list"); String payload = generateBulkSerializedDocsPayload(serializedDocs); return bulkCreateDocs(payload); }
java
@RenderMapping public String initializeView(Model model, RenderRequest renderRequest) { IUserInstance ui = userInstanceManager.getUserInstance(portalRequestUtils.getCurrentPortalRequest()); UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager(); IUs...
java
public String getAttributeValue(String name) { Attr att = node.getAttributeNode(name); if (att == null) return null; return att.getNodeValue(); }
java
public static Element getPLFNode( Element compViewNode, IPerson person, boolean create, boolean includeChildNodes) throws PortalException { Document plf = (Document) person.getAttribute(Constants.PLF); String ID = compViewNode.getAttribute(Constants.ATT_ID); Element plfNo...
java
public static Element createPlfNodeAndPath( Element compViewNode, boolean includeChildNodes, IPerson person) throws PortalException { // first attempt to get parent Element compViewParent = (Element) compViewNode.getParentNode(); Element plfParent = getPLFNode(compViewPar...
java
private static Element createILFCopy( Element compViewNode, Element compViewParent, boolean includeChildNodes, Document plf, Element plfParent, IPerson person) throws PortalException { Element plfNode = (Element) plf.importNode(...
java
static Element createOrMovePLFOwnedNode( Element compViewNode, Element compViewParent, boolean createIfNotFound, boolean createChildNodes, Document plf, Element plfParent, IPerson person) throws PortalException { Ele...
java
public static void mergeFragment( Document fragment, Document composite, IAuthorizationPrincipal ap) throws AuthorizationException { Element fragmentLayout = fragment.getDocumentElement(); Element fragmentRoot = (Element) fragmentLayout.getFirstChild(); Element compositeL...
java
private static boolean mergeAllowed(Element child, IAuthorizationPrincipal ap) throws AuthorizationException { if (!child.getTagName().equals("channel")) return true; String channelPublishId = child.getAttribute("chanID"); return ap.canRender(channelPublishId); }
java
private Object[] getPersonGroupMemberKeys(IGroupMember gm) { Object[] keys = null; EntityIdentifier ei = gm.getUnderlyingEntityIdentifier(); IPersonAttributes attr = personAttributeDao.getPerson(ei.getKey()); if (attr != null && attr.getAttributes() != null && !attr.getAttributes().isEmp...
java
@Override public IEntityGroup newInstance(Class entityType) throws GroupsException { log.warn("Unsupported method accessed: SmartLdapGroupStore.newInstance"); throw new UnsupportedOperationException(UNSUPPORTED_MESSAGE); }
java
@Override public EntityIdentifier[] searchForGroups(String query, SearchMethod method, Class leaftype) throws GroupsException { if (isTreeRefreshRequired()) { refreshTree(); } log.debug( "Invoking searchForGroups(): query={}, method={}, leaftype=", ...
java
@RequestMapping(method = RequestMethod.POST, params = "action=removeElement") public ModelAndView removeElement(HttpServletRequest request, HttpServletResponse response) throws IOException { IUserInstance ui = userInstanceManager.getUserInstance(request); IPerson per = getPerson(ui, res...
java
@RequestMapping(method = RequestMethod.POST, params = "action=removeByFName") public ModelAndView removeByFName( HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "fname") String fname) throws IOException { IUserInstance ui = use...
java
@RequestMapping(method = RequestMethod.POST, params = "action=addFolder") public ModelAndView addFolder( HttpServletRequest request, HttpServletResponse response, @RequestParam("targetId") String targetId, @RequestParam(value = "siblingId", required = false) String si...
java
@RequestMapping(method = RequestMethod.POST, params = "action=renameTab") public ModelAndView renameTab(HttpServletRequest request, HttpServletResponse response) throws IOException { IUserInstance ui = userInstanceManager.getUserInstance(request); UserPreferencesManager upm = (UserPrefe...
java
private void setObjectAttributes( IUserLayoutNodeDescription node, HttpServletRequest request, Map<String, Map<String, String>> attributes) { // Attempt to set the object attributes for (String name : attributes.get("attributes").keySet()) { try { ...
java
protected boolean isTab(IUserLayoutManager ulm, String folderId) throws PortalException { // we could be a bit more careful here and actually check the type return ulm.getRootFolderId().equals(ulm.getParentId(folderId)); }
java
protected String getMessage(String key, String defaultMessage, Locale locale) { try { return messageSource.getMessage(key, new Object[] {}, defaultMessage, locale); } catch (Exception e) { // sadly, messageSource.getMessage can throw e.g. when message is ill formatted. ...
java
private boolean moveElementInternal( HttpServletRequest request, String sourceId, String destinationId, String method) { logger.debug( "moveElementInternal invoked for sourceId={}, destinationId={}, method={}", sourceId, destinationId, ...
java
protected final void setReportFormGroups(final F report) { if (!report.getGroups().isEmpty()) { return; } final Set<AggregatedGroupMapping> groups = this.getGroups(); if (!groups.isEmpty()) { report.getGroups().add(groups.iterator().next().getId()); } ...
java
protected final boolean showFullColumnHeaderDescriptions(F form) { boolean showFullHeaderDescriptions = false; switch (form.getFormat()) { case csv: { showFullHeaderDescriptions = true; break; } case html: ...
java
private AggregatedGroupMapping[] extractGroupsArray(Set<D> columnGroups) { Set<AggregatedGroupMapping> groupMappings = new HashSet<AggregatedGroupMapping>(); for (D discriminator : columnGroups) { groupMappings.add(discriminator.getAggregatedGroup()); } return groupMappings.t...
java
public static Preference createSingleTextPreference(String name, String label) { return createSingleTextPreference( name, "attribute.displayName." + name, TextDisplay.TEXT, null); }
java
public static Preference createSingleTextPreference( String name, String label, TextDisplay displayType, String defaultValue) { SingleTextPreferenceInput input = new SingleTextPreferenceInput(); input.setDefault(defaultValue); input.setDisplay(displayType); Preference pref =...
java
public static Preference createSingleChoicePreference( String name, String label, SingleChoiceDisplay displayType, List<Option> options, String defaultValue) { SingleChoicePreferenceInput input = new SingleChoicePreferenceInput(); input.setDefa...
java
public static Preference createMultiTextPreference( String name, String label, TextDisplay displayType, List<String> defaultValues) { MultiTextPreferenceInput input = new MultiTextPreferenceInput(); input.getDefaults().addAll(defaultValues); input.setDisplay(displayType); Pr...
java
public static Preference createMultiChoicePreference( String name, String label, MultiChoiceDisplay displayType, List<Option> options, List<String> defaultValues) { MultiChoicePreferenceInput input = new MultiChoicePreferenceInput(); input.getD...
java
private void initRelatedPortlets() { final Set<MarketplacePortletDefinition> allRelatedPortlets = new HashSet<>(); for (PortletCategory parentCategory : this.portletCategoryRegistry.getParentCategories(this)) { final Set<IPortletDefinition> portletsInCategory = ...
java
public Set<MarketplacePortletDefinition> getRandomSamplingRelatedPortlets(final IPerson user) { Validate.notNull(user, "Cannot filter to BROWSEable by a null user"); final IAuthorizationPrincipal principal = AuthorizationPrincipalHelper.principalFromUser(user); // lazy init is...
java
public String getRenderUrl() { final String alternativeMaximizedUrl = getAlternativeMaximizedLink(); if (null != alternativeMaximizedUrl) { return alternativeMaximizedUrl; } final String contextPath = PortalWebUtils.currentRequestContextPath(); // TODO: stop abstra...
java
static void evaluateAndApply( List<NodeInfo> order, Element compViewParent, Element positionSet, IntegrationResult result) throws PortalException { adjustPositionSet(order, positionSet, result); if (hasAffectOnCVP(order, compViewParent)) { ...
java