@Override public StatusDetail statusDetail() { String databaseStatusName = "MongoDB Status"; Document document = new Document().append("ping", 1); Document answer; try { answer = mongoDatabase.runCommand(document); } catch (MongoTimeoutException e) { return StatusDetail.statusDetail(databaseStatusName, ERROR, "Mongo database check ran into timeout (" + e.getMessage() + ")."); } catch (Exception other) { return StatusDetail.statusDetail(databaseStatusName, ERROR, "Exception during database check (" + other.getMessage() + ")."); } if (answer != null && answer.get("ok") != null && (Double)answer.get("ok") == 1.0d) { return StatusDetail.statusDetail(databaseStatusName, OK, "Mongo database is reachable."); } return StatusDetail.statusDetail(databaseStatusName, ERROR, "Mongo database unreachable or ping command failed."); }
private boolean testConnection(MongoDatabase database) { CountDownLatch waiter = new CountDownLatch(1); final AtomicReference<Throwable> error = new AtomicReference<>(); boolean erroneous = false; try { database.getCollection(RegionStorageAdapter.COLLECTION_NAME).count(new OperationResultCallback<Long>(error, waiter)); waiter.await(); Throwable realError = error.get(); if (realError != null) throw realError; } catch (MongoTimeoutException ignore) { getLogger().severe("Cannot connect to MongoDB server."); erroneous = true; } catch (Throwable throwable) { getLogger().log(Level.SEVERE, "An error occurred while connecting to database.", throwable); erroneous = true; } if (erroneous) { getLogger().severe("An error was encountered. Disabling plugin and NOT injecting into WorldGuard."); getServer().getPluginManager().disablePlugin(this); return false; } return true; }
public Boolean isValidCredentials(String userName, String db, String password) { try { client = createClient(MongoCredential.createCredential(userName, db, password.toCharArray())); // Simple command that needs authentication client.listDatabaseNames().first(); return Boolean.TRUE; } catch (MongoTimeoutException timeout) { if (MongoException.fromThrowable(timeout).toString().contains("Authentication failed.")) { System.out.println("ERROR: Authentication Failed."); } timeout.printStackTrace(); return Boolean.FALSE; } finally { client.close(); } }
@Override public boolean testConnection() { log.debug("---[ Testing connectivity to MongoDB ]------"); try { DBCursor cursor = config.mongoCollection.find().limit(1).maxTime(config.actionTimeout, MILLISECONDS);; if(cursor.hasNext()) { return true; } } catch(MongoTimeoutException ex) { log.debug("Caught MTE: " + ex.getMessage()); return false; } catch(Exception e) { log.debug("Caught exception: " + e.getMessage()); return false; } return false; }
@Override public List<String> getAvailableFields() { log.debug("---[ Retrieving Available Fields ]------"); List<String> availableFields = new ArrayList<String>(); try { DBCursor cursor = config.mongoCollection.find().limit(1).maxTime(config.actionTimeout, MILLISECONDS);; if(cursor.hasNext()) { DBObject schema = cursor.next(); for (String k : schema.keySet()) { availableFields.add(k); } } } catch(MongoTimeoutException ex) { log.error("ERROR: Timeout occurred - " + ex.getMessage()); } return sortList(availableFields); }
@Test public void testMongoDBConnect() throws UnknownHostException { MongoClient mongoClient = new MongoClient(new MongoClientURI(MONGO_URI)); DB database = mongoClient.getDB(DB_NAME); DBCollection events = database.getCollection(EVENT_COLLECTION_NAME); DBCollection readings = database.getCollection(READING_COLLECTION_NAME); try { assertFalse("MongoDB Events collection not accessible", events.isCapped()); assertFalse("MongoDB Readings collection not accessible", readings.isCapped()); } catch (MongoTimeoutException ex) { fail("Mongo DB not available. Check that Mongo DB has been started"); } }
public MongoTransporterConfig(Config config) { try { MongoClientOptions.Builder builder = MongoClientOptions.builder().connectTimeout(5000).socketTimeout(5000).serverSelectionTimeout(3000); client = new MongoClient(new ServerAddress(config.getConfigString("host"), config.getConfigInt("port")), builder.build()); client.getAddress(); database = client.getDatabase(config.getConfigString("database")); collection = database.getCollection(config.getConfigString("collection")); } catch (MongoTimeoutException e) { client.close(); log.error("MongoClient initial failed", e); throw new LogregatorException(); } }
@Test public void testException() throws Exception { MongoDatabase db = mock(MongoDatabase.class); when(db.runCommand(new Document("ping", 1))) .thenThrow(new MongoTimeoutException("Timeout")); MongoHealthCheck check = new MongoHealthCheck(db); HealthCheck.Result result = check.check(); assertFalse(result.isHealthy()); assertEquals("Timeout", result.getMessage()); }
@Test public void shouldReturnErrorStatusWhenDatabaseTimesOut() { //given when(mongoDatabase.runCommand(new Document().append("ping", 1))).thenThrow(new MongoTimeoutException("Timeout")); //when StatusDetail statusDetail = testee.statusDetail(); //then assertThat(statusDetail.getStatus(), is(ERROR)); assertThat(statusDetail.getMessage(), containsString("Mongo database check ran into timeout")); }
public void await() throws Throwable { if (!latch.await(10, SECONDS)) { throw new MongoTimeoutException("Publisher timed out"); } if (error != null) { throw error; } }
public ObservableSubscriber<T> await(final long timeout, final TimeUnit unit) throws Throwable { subscription.request(Integer.MAX_VALUE); if (!latch.await(timeout, unit)) { throw new MongoTimeoutException("Publisher onComplete timed out"); } if (!errors.isEmpty()) { throw errors.get(0); } return this; }
public CountingSubscriber<T> await(final long timeout, final TimeUnit unit) throws Throwable { if (!latch.await(timeout, unit)) { if (!isCompleted()) { subscription.cancel(); } throw new MongoTimeoutException("Publisher onComplete timed out"); } if (!isCompleted()) { subscription.cancel(); } if (error != null) { throw error; } return this; }
@BeforeClass public static void setUp() throws Exception { MongoClient client = new MongoClient(new ServerAddress("127.0.0.1", 27017), MongoClientOptions.builder().connectTimeout(2500).writeConcern(WriteConcern.ACKNOWLEDGED).build()); morphix = new Morphix(client, "morphix_testing"); try { List<String> names = client.getDatabaseNames(); System.out.println("Connected to DB: " + names); } catch (MongoTimeoutException ex) { assumeTrue("Could not connect to MongoDB server - ignoring tests which require DB connection", false); } }
@Override public Map<String, Object> retrieveValues(Collection<String> attributeNamesToFill, SimpleFieldList filterConfiguration) { log.debug("---[ Retrieving Values ]------"); Map<String, Object> returnMap = new HashMap<String, Object>(); BasicDBObject mongoDBQuery = buildMongoQueryFromFilter(filterConfiguration); try { DBCursor cursor = config.mongoCollection.find(mongoDBQuery).limit(1).maxTime(config.actionTimeout, MILLISECONDS); if(cursor.hasNext()) { DBObject entry = cursor.next(); for(String attribute : attributeNamesToFill) { log.debug("Checking for attribute: " + attribute); if (entry.containsField(attribute)) { log.debug(" - returning value: " + entry.get(attribute)); returnMap.put(attribute, entry.get(attribute)); } else { log.debug(" - returning value: null"); returnMap.put(attribute, null); } } } else { log.info("No object found"); } } catch(MongoTimeoutException ex) { log.error("ERROR: Timeout occurred - " + ex.getMessage()); } return returnMap; }
private Error analyzeException(Exception e, final String otherwise, final String msg, boolean specialHandling) { if (e instanceof Error) { return (Error) e; } if (e instanceof MongoException) { MongoException me = (MongoException) e; if (me.getCode() == 18) { return Error.get(CrudConstants.ERR_AUTH_FAILED, e.getMessage()); } else if (me instanceof MongoTimeoutException || me instanceof MongoExecutionTimeoutException) { LOGGER.error(CrudConstants.ERR_DATASOURCE_TIMEOUT, e); return Error.get(CrudConstants.ERR_DATASOURCE_TIMEOUT, e.getMessage()); } else if (me instanceof DuplicateKeyException) { return Error.get(MongoCrudConstants.ERR_DUPLICATE, e.getMessage()); } else if (me instanceof MongoSocketException) { LOGGER.error(MongoCrudConstants.ERR_CONNECTION_ERROR, e); return Error.get(MongoCrudConstants.ERR_CONNECTION_ERROR, e.getMessage()); } else { LOGGER.error(MongoCrudConstants.ERR_MONGO_ERROR, e); return Error.get(MongoCrudConstants.ERR_MONGO_ERROR, e.getMessage()); } } else if (msg == null) { return Error.get(otherwise, e.getMessage()); } else if (specialHandling) { return Error.get(otherwise, msg, e); } else { return Error.get(otherwise, msg); } }