/** * Determines the read preference that should be used for the given command. * * @param command the {@link DBObject} representing the command * @param requestedPreference the preference requested by the client. * @return the read preference to use for the given command. It will never return {@code null}. * @see com.mongodb.ReadPreference */ ReadPreference getCommandReadPreference(DBObject command, ReadPreference requestedPreference) { String comString = command.keySet().iterator().next(); if (comString.equals("getnonce") || comString.equals("authenticate")) { return ReadPreference.primaryPreferred(); } boolean primaryRequired; // explicitly check mapreduce commands are inline if (comString.equals("mapreduce")) { Object out = command.get("out"); if (out instanceof BSONObject) { BSONObject outMap = (BSONObject) out; primaryRequired = outMap.get("inline") == null; } else primaryRequired = true; } else { primaryRequired = !_obedientCommands.contains(comString.toLowerCase()); } if (primaryRequired) { return ReadPreference.primary(); } else if (requestedPreference == null) { return ReadPreference.primary(); } else { return requestedPreference; } }
@Test public void testPrimaryPreferredWithNoPrimary() { for (int i = 0; i < 1000; i++) { nodeSet.add(ReadPreference.primaryPreferred().getNode(_setNoPrimary)); } expectedNodeSet.addAll(Arrays.asList(_secondary1, _secondary2)); assertEquals(expectedNodeSet, nodeSet); }
@Test public void testTaggedPrimaryPreferredWithNoPrimary() { final TaggableReadPreference readPreference = ReadPreference.primaryPreferred(new BasicDBObject("dc", "ny")); for (int i = 0; i < 1000; i++) { nodeSet.add(readPreference.getNode(_setNoPrimary)); } expectedNodeSet.addAll(Arrays.asList(_secondary1, _secondary2)); assertEquals(expectedNodeSet, nodeSet); }