List of usage examples for java.util HashMap clear
public void clear()
From source file:mobisocial.musubi.service.AddressBookUpdateHandler.java
@Override public void onChange(boolean selfChange) { final DatabaseManager dbManager = new DatabaseManager(mContext); if (!dbManager.getIdentitiesManager().hasConnectedAccounts()) { Log.w(TAG, "no connected accounts, skipping friend import"); return;//from w w w .ja va 2 s . c om } //a new meta contact appears (and the previous ones disappear) if the user merges //or if a new entry is added, we can detect the ones that have changed by //this condition long highestContactIdAlreadySeen = dbManager.getContactDataVersionManager().getMaxContactIdSeen(); //a new data item corresponds with a new contact, but its possible //that a users just adds a new contact method to an existing contact //and we need to detect that long highestDataIdAlreadySeen = dbManager.getContactDataVersionManager().getMaxDataIdSeen(); // BJD -- this didn't end up being faster once all import features were added. /*if (highestContactIdAlreadySeen == -1) { importFullAddressBook(mContext); return; }*/ long now = System.currentTimeMillis(); if (mLastRun + ONCE_PER_PERIOD > now) { //wake up when the period expires if (!mScheduled) { new Handler(mThread.getLooper()).postDelayed(new Runnable() { @Override public void run() { mScheduled = false; dispatchChange(false); } }, ONCE_PER_PERIOD - (now - mLastRun) + 1); } mScheduled = true; //skip this update return; } Log.i(TAG, "waking up to handle contact changes..."); boolean identityAdded = false, profileDataChanged = false; Date start = new Date(); assert (SYNC_EMAIL); String account_type_selection = getAccountSelectionString(); Cursor c = mContext.getContentResolver().query( ContactsContract.Data.CONTENT_URI, new String[] { ContactsContract.Data._ID, ContactsContract.Data.DATA_VERSION, ContactsContract.Data.CONTACT_ID }, "(" + ContactsContract.Data.DATA_VERSION + ">0 OR " + //maybe updated ContactsContract.Data.CONTACT_ID + ">? OR " + //definitely new or merged ContactsContract.Data._ID + ">? " + //definitely added a data item ") AND (" + ContactsContract.RawContacts.ACCOUNT_TYPE + "<>'" + mAccountType + "'" + ") AND (" + NAME_OR_OTHER_SELECTION + account_type_selection + ")", // All known contacts. new String[] { String.valueOf(highestContactIdAlreadySeen), String.valueOf(highestDataIdAlreadySeen) }, null); if (c == null) { Log.e(TAG, "no valid cursor", new Throwable()); mContext.getContentResolver().notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, this); return; } HashMap<Pair<String, String>, MMyAccount> account_mapping = new HashMap<Pair<String, String>, MMyAccount>(); int max_changes = c.getCount(); TLongArrayList raw_data_ids = new TLongArrayList(max_changes); TLongArrayList versions = new TLongArrayList(max_changes); long new_max_data_id = highestDataIdAlreadySeen; long new_max_contact_id = highestContactIdAlreadySeen; TLongHashSet potentially_changed = new TLongHashSet(); try { //the cursor points to a list of raw contact data items that may have changed //the items will include a type specific field that we are interested in updating //it is possible that multiple data item entries mention the same identifier //so we build a list of contacts to update and then perform synchronization //by refreshing given that we know the top level contact id. if (DBG) Log.d(TAG, "Scanning " + c.getCount() + " contacts..."); while (c.moveToNext()) { if (DBG) Log.v(TAG, "check for updates of contact " + c.getLong(0)); long raw_data_id = c.getLong(0); long version = c.getLong(1); long contact_id = c.getLong(2); //if the contact was split or merged, then we get a higher contact id //so if we have a higher id, data version doesnt really matter if (contact_id <= highestContactIdAlreadySeen) { //the data associated with this contact may not be dirty //we just can't do the join against our table because thise //api is implmented over the content provider if (dbManager.getContactDataVersionManager().getVersion(raw_data_id) == version) continue; } else { new_max_contact_id = Math.max(new_max_contact_id, contact_id); } raw_data_ids.add(raw_data_id); versions.add(version); potentially_changed.add(contact_id); new_max_data_id = Math.max(new_max_data_id, raw_data_id); } if (DBG) Log.d(TAG, "Finished iterating over " + c.getCount() + " contacts for " + potentially_changed.size() + " candidates."); } finally { c.close(); } if (potentially_changed.size() == 0) { Log.w(TAG, "possible bug, woke up to update contacts, but no change was detected; there are extra wakes so it could be ok"); } final SQLiteDatabase db = dbManager.getDatabase(); Pattern emailPattern = getEmailPattern(); Pattern numberPattern = getNumberPattern(); //slice it up so we don't use too much system resource on keeping a lot of state in memory int total = potentially_changed.size(); sAddressBookTotal = total; sAddressBookPosition = 0; final TLongArrayList slice_of_changed = new TLongArrayList(BATCH_SIZE); final StringBuilder to_fetch = new StringBuilder(); final HashMap<Pair<String, String>, TLongHashSet> ids_for_account = new HashMap<Pair<String, String>, TLongHashSet>(); final TLongObjectHashMap<String> names = new TLongObjectHashMap<String>(); TLongIterator it = potentially_changed.iterator(); for (int i = 0; i < total && it.hasNext();) { sAddressBookPosition = i; if (BootstrapActivity.isBootstrapped()) { try { Thread.sleep(mSleepTime * SLEEP_SCALE); } catch (InterruptedException e) { } } slice_of_changed.clear(); ids_for_account.clear(); names.clear(); int max = i + BATCH_SIZE; for (; i < max && it.hasNext(); ++i) { slice_of_changed.add(it.next()); } if (DBG) Log.v(TAG, "looking up names "); to_fetch.setLength(0); to_fetch.append(ContactsContract.Contacts._ID + " IN "); SQLClauseHelper.appendArray(to_fetch, slice_of_changed.iterator()); //lookup the fields we care about from a user profile perspective c = mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, }, to_fetch.toString(), null, null); try { while (c.moveToNext()) { long id = c.getLong(0); String name = c.getString(1); if (name == null) continue; //reject names that are just the email address or are just a number //the default for android is just to propagate this as the name //if there is no name if (emailPattern.matcher(name).matches() || numberPattern.matcher(name).matches()) continue; names.put(id, name); } } finally { c.close(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { db.beginTransactionNonExclusive(); } else { db.beginTransaction(); } long before = SystemClock.elapsedRealtime(); SliceUpdater updater = new SliceUpdater(dbManager, slice_of_changed, ids_for_account, names, account_type_selection); long after = SystemClock.elapsedRealtime(); mSleepTime = (mSleepTime + after - before) / 2; slice_of_changed.forEach(updater); profileDataChanged |= updater.profileDataChanged; identityAdded |= updater.identityAdded; db.setTransactionSuccessful(); db.endTransaction(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { db.beginTransactionNonExclusive(); } else { db.beginTransaction(); } //add all detected members to account feed for (Entry<Pair<String, String>, TLongHashSet> e : ids_for_account.entrySet()) { Pair<String, String> k = e.getKey(); TLongHashSet v = e.getValue(); MMyAccount cached_account = account_mapping.get(k); if (cached_account == null) { cached_account = lookupOrCreateAccount(dbManager, k.getValue0(), k.getValue1()); prepareAccountWhitelistFeed(dbManager.getMyAccountManager(), dbManager.getFeedManager(), cached_account); account_mapping.put(k, cached_account); } final MMyAccount account = cached_account; v.forEach(new TLongProcedure() { @Override public boolean execute(long id) { dbManager.getFeedManager().ensureFeedMember(account.feedId_, id); db.yieldIfContendedSafely(75); return true; } }); } db.setTransactionSuccessful(); db.endTransaction(); } sAddressBookTotal = sAddressBookPosition = 0; //TODO: handle deleted //for all android data ids in our table, check if they still exist in the //contacts table, probably in batches of 100 or something. if they don't //null them out. this is annoyingly non-differential. //TODO: adding friend should update accepted feed status, however, //if a crashe happens for whatever reason, then its possible that this may need to //be run for identities which actually exist in the db. so this update code //needs to do the feed accepted status change for all users that were touched //by the profile update process //update the version ids so we can be faster on subsequent runs if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { db.beginTransactionNonExclusive(); } else { db.beginTransaction(); } int changed_data_rows = raw_data_ids.size(); for (int i = 0; i < changed_data_rows; ++i) { dbManager.getContactDataVersionManager().setVersion(raw_data_ids.get(i), versions.get(i)); } db.setTransactionSuccessful(); db.endTransaction(); dbManager.getContactDataVersionManager().setMaxDataIdSeen(new_max_data_id); dbManager.getContactDataVersionManager().setMaxContactIdSeen(new_max_contact_id); ContentResolver resolver = mContext.getContentResolver(); Date end = new Date(); double time = end.getTime() - start.getTime(); time /= 1000; Log.w(TAG, "update address book " + mChangeCount++ + " took " + time + " seconds"); if (identityAdded) { //wake up the profile push resolver.notifyChange(MusubiService.WHITELIST_APPENDED, this); } if (profileDataChanged) { //refresh the ui... resolver.notifyChange(MusubiService.PRIMARY_CONTENT_CHANGED, this); } if (identityAdded || profileDataChanged) { //update the our musubi address book as needed. String accountName = mContext.getString(R.string.account_name); String accountType = mContext.getString(R.string.account_type); Account account = new Account(accountName, accountType); ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); } dbManager.close(); mLastRun = new Date().getTime(); resolver.notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, this); }
From source file:org.dasein.cloud.aws.storage.S3.java
@Override public Blob getObject(@Nullable String bucketName, @Nonnull String objectName) throws InternalException, CloudException { APITrace.begin(provider, "Blob.getObject"); try {/*from w w w . j ava2 s . co m*/ if (bucketName == null) { return null; } ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new CloudException("No context was set for this request"); } String regionId = ctx.getRegionId(); if (regionId == null) { throw new CloudException("No region was set for this request"); } String myRegion = getRegion(bucketName, false); if (!myRegion.equals(regionId)) { return null; } HashMap<String, String> parameters = new HashMap<String, String>(); S3Response response; String marker = null; boolean done = false; S3Method method; while (!done) { NodeList blocks; parameters.clear(); if (marker != null) { parameters.put("marker", marker); } parameters.put("max-keys", String.valueOf(30)); method = new S3Method(provider, S3Action.LIST_CONTENTS, parameters, null); try { response = method.invoke(bucketName, null); } catch (S3Exception e) { String code = e.getCode(); if (code == null || !code.equals("SignatureDoesNotMatch")) { throw new CloudException(e); } logger.error(e.getSummary()); throw new CloudException(e); } blocks = response.document.getElementsByTagName("IsTruncated"); if (blocks.getLength() > 0) { done = blocks.item(0).getFirstChild().getNodeValue().trim().equalsIgnoreCase("false"); } blocks = response.document.getElementsByTagName("Contents"); for (int i = 0; i < blocks.getLength(); i++) { Node object = blocks.item(i); Storage<org.dasein.util.uom.storage.Byte> size = null; String name = null; long ts = -1L; if (object.hasChildNodes()) { NodeList attrs = object.getChildNodes(); for (int j = 0; j < attrs.getLength(); j++) { Node attr = attrs.item(j); if (attr.getNodeName().equalsIgnoreCase("Key")) { String key = attr.getFirstChild().getNodeValue().trim(); name = key; marker = key; } else if (attr.getNodeName().equalsIgnoreCase("Size")) { size = new Storage<org.dasein.util.uom.storage.Byte>( Long.parseLong(attr.getFirstChild().getNodeValue().trim()), Storage.BYTE); } else if (attr.getNodeName().equalsIgnoreCase("LastModified")) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); String dateString = attr.getFirstChild().getNodeValue().trim(); try { ts = fmt.parse(dateString).getTime(); } catch (ParseException e) { logger.error(e); e.printStackTrace(); throw new CloudException(e); } } } } if (!objectName.equals(name) || size == null) { continue; } return Blob.getInstance(regionId, getLocation(bucketName, name), bucketName, name, ts, size); } } return null; } finally { APITrace.end(); } }
From source file:de.hybris.platform.cronjob.jalo.CronJobTest.java
@Test public void testCompositeCronJob() throws Exception { // YTODO// w w w . ja v a 2s. co m // deactivated, because this test fails in an undeterministic way final TypeManager manager = TypeManager.getInstance(); final ComposedType compositeJobType = manager.getComposedType(CompositeJob.class); final Job compositeJob = (Job) compositeJobType .newInstance(Collections.singletonMap(Job.CODE, "MyCompositeJob")); final HashMap attributeValues = new HashMap(); attributeValues.put(CronJob.JOB, compositeJob); attributeValues.put(CronJob.CODE, "CompositeCronJob"); attributeValues.put(CronJob.ACTIVE, Boolean.TRUE); final CompositeCronJob compositeCronJob = CronJobManager.getInstance() .createCompositeCronJob(attributeValues); final List<CompositeEntry> entries = new ArrayList<CompositeEntry>(); // // TestJob generation // final ComposedType jobType = manager.createComposedType(manager.getComposedType(Job.class), "TestCompositeJob"); jobType.setJaloClass(TestJob.class); // Cron Job // Job 1 final Job testJob1 = (Job) jobType.newInstance(Collections.singletonMap(Job.CODE, "TestCompositeJob1")); ((TestJob) testJob1).setPerformable(new MyCompositeTestPerformable()); testJob1.createCronjob(); testJob1.setTransientObject("value", Long.valueOf(1)); attributeValues.clear(); attributeValues.put(CompositeEntry.CODE, "job1"); attributeValues.put(CompositeEntry.TRIGGERABLEJOB, testJob1); entries.add(CronJobManager.getInstance().createCompositeEntry(attributeValues)); // Job 2 final Job testJob2 = (Job) jobType.newInstance(Collections.singletonMap(Job.CODE, "TestCompositeJob2")); ((TestJob) testJob2).setPerformable(new MyCompositeTestPerformable()); testJob2.createCronjob(); testJob2.setTransientObject("value", Long.valueOf(10)); attributeValues.clear(); attributeValues.put(CompositeEntry.CODE, "job2"); attributeValues.put(CompositeEntry.TRIGGERABLEJOB, testJob2); entries.add(CronJobManager.getInstance().createCompositeEntry(attributeValues)); // Job 3 final Job testJob3 = (Job) jobType.newInstance(Collections.singletonMap(Job.CODE, "TestCompositeJob3")); ((TestJob) testJob3).setPerformable(new MyCompositeTestPerformable()); testJob3.createCronjob(); testJob3.setTransientObject("value", Long.valueOf(100)); attributeValues.clear(); attributeValues.put(CompositeEntry.CODE, "job3"); attributeValues.put(CompositeEntry.TRIGGERABLEJOB, testJob3); entries.add(CronJobManager.getInstance().createCompositeEntry(attributeValues)); // Cron Job / Job 4 final Job testJob4 = (Job) jobType.newInstance(Collections.singletonMap(Job.CODE, "TestCompositeJob4")); ((TestJob) testJob4).setPerformable(new MyCompositeTestPerformable()); testJob4.createCronjob(); testJob4.setTransientObject("value", Long.valueOf(1000)); final CronJob testCronJob = CronJobManager.getInstance().createCronJob(testJob4, "TestCompositeJob4", true); attributeValues.clear(); attributeValues.put(CompositeEntry.CODE, "job4"); attributeValues.put(CompositeEntry.EXECUTABLECRONJOB, testCronJob); entries.add(CronJobManager.getInstance().createCompositeEntry(attributeValues)); compositeCronJob.setCompositeEntries(entries); compositeJob.perform(compositeCronJob); Thread.sleep(1000); while (compositeCronJob.isRunning() || (!testJob1.getCronJobs().isEmpty() && testJob1.getCronJobs().iterator().next().isRunning()) || (!testJob2.getCronJobs().isEmpty() && testJob2.getCronJobs().iterator().next().isRunning()) || (!testJob3.getCronJobs().isEmpty() && testJob3.getCronJobs().iterator().next().isRunning()) || (!testJob4.getCronJobs().isEmpty() && testJob4.getCronJobs().iterator().next().isRunning()) || (testCronJob.isRunning())) { Thread.sleep(2000); } final long sum = ((Long) testJob1.getTransientObject("value")).longValue() + ((Long) testJob2.getTransientObject("value")).longValue() + ((Long) testJob3.getTransientObject("value")).longValue() + ((Long) testCronJob.getJob().getTransientObject("value")).longValue(); assertEquals(sum, 2222); }
From source file:de.dfki.km.perspecting.obie.model.Document.java
public List<TokenSequence<SemanticEntity>> getEntityTypes() { List<TokenSequence<SemanticEntity>> entities = new ArrayList<TokenSequence<SemanticEntity>>(); HashMap<Integer, TokenSequence<SemanticEntity>> map = new HashMap<Integer, TokenSequence<SemanticEntity>>(); for (int tokenIndex : this.data.getIntegerKeys(TokenSequence.TYPE)) { List<SemanticEntity> values = this.data.get(TokenSequence.TYPE, tokenIndex); if (values != null) { for (SemanticEntity value : values) { int property = value.getPropertyIndex(); if (value.getPosition().equals("B")) { TokenSequence<SemanticEntity> entity = map.get(property); if (entity != null) { entities.add(map.remove(property)); }/* www. ja v a 2 s . c o m*/ entity = new TokenSequence<SemanticEntity>(value); entity.addToken(new Token(tokenIndex, this)); map.put(property, entity); } else { map.get(property).addToken(new Token(tokenIndex, this)); } } } else { entities.addAll(map.values()); map.clear(); } } entities.addAll(map.values()); return entities; }
From source file:de.betterform.xml.xforms.model.submission.Submission.java
/** * Performs replace processing according to section 11.1, para 5. *//*from ww w. j a v a2 s. co m*/ protected void submitReplaceAll(Map response) throws XFormsException { // XForms 1.0, section 11.1, para 5 // - For a success response including a body, when the value of the // replace attribute on element submission is "all", the event // xforms-submit-done is dispatched, and submit processing concludes // with entire containing document being replaced with the returned // body. if (getLogger().isDebugEnabled()) { getLogger().debug(this + " submit: replacing all"); } // todo: refactor submission response // split copied response into header and body (keep original response // for backwards compat) Map header = new HashMap(); header.putAll(response); Object body = header.remove(XFormsProcessor.SUBMISSION_RESPONSE_STREAM); HashMap map = new HashMap(); map.put("header", header); map.put("body", body); // dispatch xforms-submit-done this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, constructEventInfo(response)); // dispatch internal betterform event // special case for URI redirection, resubmit as GET if (header.containsKey("Location")) { map.clear(); map.put("show", "replace"); map.put("uri", response.get("Location")); this.container.dispatch(this.target, BetterFormEventNames.LOAD_URI, map); return; } else { if (getMediatype().equals(BetterFORMConstants.XFORMS_MEDIATYPE)) { map.put(BetterFORMConstants.SUBMISSION_REDIRECT_XFORMS, this.action); this.container.dispatch(this.target, BetterFormEventNames.REPLACE_ALL_XFORMS, map); } else { this.container.dispatch(this.target, BetterFormEventNames.REPLACE_ALL, map); } this.container.dispatch(this.target, XFormsEventNames.MODEL_DESTRUCT, null); } // backwards compat forward(response); }
From source file:de.dfki.km.perspecting.obie.model.Document.java
public List<TokenSequence<SemanticEntity>> getRetrievedPropertyValues() { List<TokenSequence<SemanticEntity>> entities = new ArrayList<TokenSequence<SemanticEntity>>(); HashMap<String, TokenSequence<SemanticEntity>> map = new HashMap<String, TokenSequence<SemanticEntity>>(); for (int tokenIndex : this.data.getIntegerKeys(TokenSequence.PROPERTY)) { List<SemanticEntity> values = this.data.get(TokenSequence.PROPERTY, tokenIndex); if (values != null) { for (SemanticEntity value : values) { String key = Integer.toString(value.getPropertyIndex()) + Integer.toString(value.getLiteralValueIndex()); if (value.getPosition().equals("B")) { TokenSequence<SemanticEntity> entity = map.get(key); if (entity != null) { entities.add(map.remove(key)); }//ww w . j a v a 2 s. co m entity = new TokenSequence<SemanticEntity>(value); entity.addToken(new Token(tokenIndex, this)); map.put(key, entity); } else { map.get(key).addToken(new Token(tokenIndex, this)); } } } else { entities.addAll(map.values()); map.clear(); } } entities.addAll(map.values()); return entities; }
From source file:com.polyvi.xface.extension.contact.XContactsExt.java
/** * ????json.// w w w . j a va 2 s. c o m * * @param requiredField * ???? * @param c * * @param contactsMaxNum * ? * @return ? JSON */ private JSONArray populateContactArray(HashSet<String> requiredField, Cursor c, int contactsMaxNum) { String oldContactId = ""; boolean newContact = true; JSONArray contacts = new JSONArray(); JSONObject contact = new JSONObject(); HashMap<String, Object> contactMap = new HashMap<String, Object>(); // ?? mContactAccessor.initQuantityOfFields(contactMap); if (c.getCount() > 0) { while (c.moveToNext() && (contacts.length() <= (contactsMaxNum - 1))) { String contactId = mContactAccessor.getContactId(c); String rawId = mContactAccessor.getRawId(c); try { // oldContactId if (c.getPosition() == 0) { oldContactId = contactId; } // contact ID? // ?Contact object contacts // Contact object if (!oldContactId.equals(contactId)) { hashMapToJson(requiredField, contactMap, contact); contacts.put(contact); // contact = new JSONObject(); contactMap.clear(); // ?? mContactAccessor.initQuantityOfFields(contactMap); newContact = true; } // ? ID display name // ???? if (newContact) { newContact = false; contact.put(XContactAccessor.LOGIC_FIELD_ID, contactId); contact.put(XContactAccessor.LOGIC_FIELD_RAWID, rawId); } mContactAccessor.cursorToHashMap(contactMap, c); } catch (JSONException e) { XLog.e(CLASS_NAME, e.getMessage(), e); } oldContactId = contactId; } // Push?? contacts if (contacts.length() < contactsMaxNum) { hashMapToJson(requiredField, contactMap, contact); contacts.put(contact); } } return contacts; }
From source file:com.google.gwt.emultest.java.util.HashMapTest.java
/** * Test method for 'java.util.HashMap.size()'. */// w ww .j a v a 2s . co m public void testSize() { HashMap<String, String> hashMap = new HashMap<String, String>(); checkEmptyHashMapAssumptions(hashMap); // Test size behavior on put assertEquals(hashMap.size(), SIZE_ZERO); hashMap.put(KEY_1, VALUE_1); assertEquals(hashMap.size(), SIZE_ONE); hashMap.put(KEY_2, VALUE_2); assertEquals(hashMap.size(), SIZE_TWO); hashMap.put(KEY_3, VALUE_3); assertEquals(hashMap.size(), SIZE_THREE); // Test size behavior on remove hashMap.remove(KEY_1); assertEquals(hashMap.size(), SIZE_TWO); hashMap.remove(KEY_2); assertEquals(hashMap.size(), SIZE_ONE); hashMap.remove(KEY_3); assertEquals(hashMap.size(), SIZE_ZERO); // Test size behavior on putAll hashMap.put(KEY_1, VALUE_1); hashMap.put(KEY_2, VALUE_2); hashMap.put(KEY_3, VALUE_3); HashMap<String, String> srcMap = new HashMap<String, String>(hashMap); hashMap.putAll(srcMap); assertEquals(hashMap.size(), SIZE_THREE); // Test size behavior on clear hashMap.clear(); assertEquals(hashMap.size(), SIZE_ZERO); }
From source file:com.wizecommerce.hecuba.HecubaCassandraManagerTestBase.java
/** * testColumnNameBasedSecondaryIndexBasics * /* w ww .j a va 2s. co m*/ * @throws Exception */ @Test public void testUpdateRowScenario14() throws Exception { CassandraParamsBean bean = getDefaultCassandraParamsBean(); // create secondary index on all column names. bean.setSiByColumnsPattern(".*"); bean.setSiColumns("MySecondaryKey_1:MySecondaryKey_2"); HecubaClientManager<Long> cassandraManager = getHecubaClientManager(bean); HashMap<String, Object> row = new HashMap<String, Object>(); List<Long> listOfIds = Lists.newArrayList(123L, 124L, 126L, 127L, 3456L, 4567L); for (Long id : listOfIds) { row.clear(); row.put("column_1", "value_1"); if (id < 130) { row.put("column_2", "value_2"); } cassandraManager.updateRow(id, row); } // *************************************************************************************** // Scenario 1: Check with the first column name. // *************************************************************************************** // first retrieve by column 1 CassandraResultSet<Long, String> idsWithColumn1 = cassandraManager .retrieveByColumnNameBasedSecondaryIndex("column_1"); // has it got some results. assertNotNull(idsWithColumn1); assertTrue(idsWithColumn1.hasResults()); int count = 0; while (idsWithColumn1.hasResults()) { Long key = idsWithColumn1.getKey(); count++; // make sure this id is part of the original list assertTrue(listOfIds.indexOf(key) > -1); if (idsWithColumn1.hasNextResult()) { idsWithColumn1.nextResult(); } else { break; } } // make sure we retrieved all of the ids. assertEquals(count, listOfIds.size()); // *************************************************************************************** // Scenario 2: Check with the second column name. // *************************************************************************************** // retrieve by column 2 CassandraResultSet<Long, String> idsWithColumn2 = cassandraManager .retrieveByColumnNameBasedSecondaryIndex("column_2"); // has it got some results. assertTrue(idsWithColumn2.hasResults()); count = 0; while (idsWithColumn2.hasResults()) { Long key = idsWithColumn2.getKey(); count++; // make sure this id is part of the original list assertTrue(listOfIds.indexOf(key) > -1); assertTrue(key < 130); if (idsWithColumn2.hasNextResult()) { idsWithColumn2.nextResult(); } else { break; } } assertEquals(4, count); // *************************************************************************************** // Scenario 3: Delete the column 1 from 3456L and 123L // *************************************************************************************** cassandraManager.deleteColumn(123L, "column_1"); cassandraManager.deleteColumn(3456L, "column_1"); // retrieve by column 1 idsWithColumn1 = cassandraManager.retrieveByColumnNameBasedSecondaryIndex("column_1"); // has it got some results. assertTrue(idsWithColumn1.hasResults()); count = 0; while (idsWithColumn1.hasResults()) { Long key = idsWithColumn1.getKey(); count++; // make sure this id is part of the original list assertTrue(listOfIds.indexOf(key) > -1); assertTrue(key != 123L && key != 3456L); if (idsWithColumn1.hasNextResult()) { idsWithColumn1.nextResult(); } else { break; } } assertEquals(4, count); // *************************************************************************************** // Scenario 3: Retrieve by a secondary index that doesn't exist // *************************************************************************************** idsWithColumn1 = cassandraManager.retrieveByColumnNameBasedSecondaryIndex("column_33"); // it shouldn't have any results. assertNull(idsWithColumn1); }
From source file:org.dasein.cloud.nimbula.network.Vethernet.java
@Override public @Nonnull VLAN createVlan(@Nonnull String cidr, @Nonnull String name, @Nonnull String description, @Nonnull String domainName, @Nonnull String[] dnsServers, @Nonnull String[] ntpServers) throws CloudException, InternalException { ProviderContext ctx = cloud.getContext(); if (ctx == null) { throw new CloudException("No context was set for this request"); }/*from ww w .ja v a 2s . c o m*/ if (!"root".equals(ctx.getAccountNumber())) { throw new OperationNotSupportedException("VLAN creation is not yet supported for non-root"); } int id = findId(); int[] parts = new int[4]; int idx = cidr.indexOf('/'); int mask = 32; if (idx > -1) { mask = Integer.parseInt(cidr.substring(idx + 1)); cidr = cidr.substring(0, idx); } String[] dotted = cidr.split("\\."); if (dotted.length != 4) { throw new CloudException("Invalid IP address: " + cidr); } int i = 0; for (String dot : dotted) { try { parts[i++] = Integer.parseInt(dot); } catch (NumberFormatException e) { throw new CloudException("Invalid IP address: " + cidr); } } HashMap<String, Object> state = new HashMap<String, Object>(); state.put("id", id); state.put("description", description); state.put("type", "vlan"); state.put("uri", null); try { state.put("name", "/" + cloud.getContext().getAccountNumber() + "/" + new String(cloud.getContext().getAccessPublic(), "utf-8") + "/vnet" + id); } catch (UnsupportedEncodingException e) { if (logger.isDebugEnabled()) { logger.error("Failed UTF-8 encoding: " + e.getMessage()); e.printStackTrace(); } throw new InternalException(e); } NimbulaMethod method = new NimbulaMethod(cloud, "vethernet"); method.post(state); VLAN vlan; try { vlan = toVlan(method.getResponseBody()); } catch (JSONException e) { if (logger.isDebugEnabled()) { logger.error("Error parsing JSON: " + e.getMessage()); e.printStackTrace(); } throw new CloudException(e); } state.clear(); String ipStop; if (mask == 32 || mask == 31) { ipStop = cidr; } else { if (mask >= 24) { int count = ((int) Math.pow(2, (32 - mask)) - 1); if (count > 4) { count = count - 4; } parts[3] = parts[3] + count; } else if (mask >= 16) { int count = ((int) Math.pow(2, (24 - mask)) - 1); if (count > 4) { count = count - 4; } parts[2] = parts[2] + count; } else if (mask >= 8) { int count = ((int) Math.pow(2, (16 - mask)) - 1); if (count > 4) { count = count - 4; } parts[1] = parts[1] + count; } else { int count = ((int) Math.pow(2, (8 - mask)) - 1); if (count > 4) { count = count - 4; } parts[0] = parts[0] + count; } ipStop = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3]; } state.put("iprange_mask", mask); state.put("dns_server", dnsServers[0]); state.put("dns_server_standby", dnsServers[1]); state.put("iprange_start", cidr); state.put("iprange_stop", ipStop); state.put("uri", null); try { state.put("vethernet", "/" + cloud.getContext().getAccountNumber() + "/" + new String(cloud.getContext().getAccessPublic(), "utf-8") + "/vnet" + id); state.put("name", "/" + cloud.getContext().getAccountNumber() + "/" + new String(cloud.getContext().getAccessPublic(), "utf-8") + "/vdhcpd" + id); } catch (UnsupportedEncodingException e) { if (logger.isDebugEnabled()) { logger.error("Encoding error: " + e.getMessage()); e.printStackTrace(); } throw new InternalException(e); } int slash = cidr.indexOf('/'); state.put("iprouter", cidr.subSequence(0, slash)); method = new NimbulaMethod(cloud, VDHCPD); method.post(state); return vlan; }