protected static void issueCommand(String[] commandArray, String errorMessage, Pair<String, Object>[] errorContextValues) { String commandStr = StringUtils.join(commandArray, ' '); logger.info("Docker command: {}", commandStr); try { Process docker = createProcess(commandArray); waitForThrowingException(docker, commandStr); } catch (Exception e) { ContextedRuntimeException cEx = new DockerProcessAPIException(errorMessage, e) .addContextValue("commandStr", commandStr); if (errorContextValues != null) { for (Pair<String, Object> pair : errorContextValues) { cEx.addContextValue(pair.getKey(), pair.getValue()); } } throw cEx; } }
@Test public void testCheckException() throws Exception { TestCassandraHealthCheck testCassandraHealthCheck = new TestCassandraHealthCheck(TEST_SERVER); testCassandraHealthCheck.cluster = testCluster; FieldUtils.writeField(testCassandraHealthCheck, "logger", loggerMock, true); Mockito.when(session.execute(Matchers.anyString())).thenThrow(new RuntimeException("crap")); Result result = testCassandraHealthCheck.check(); Assert.assertFalse(result.isHealthy()); Mockito.verify(session).close(); Mockito.verify(session).execute(Matchers.anyString()); Assert.assertEquals(1, testCluster.nbrTimesCloseCalled); ArgumentCaptor<ContextedRuntimeException> exCaptor = ArgumentCaptor.forClass(ContextedRuntimeException.class); Mockito.verify(loggerMock).error(Matchers.anyString(), exCaptor.capture()); Assert.assertEquals(3, exCaptor.getValue().getContextLabels().size()); Assert.assertEquals(result.getError(), exCaptor.getValue()); }
@Override protected Result check() throws Exception { Connection conn = null; Statement stmt = null; ResultSet rSet = null; try { conn = dataSource.getConnection(); stmt = conn.createStatement(); rSet = stmt.executeQuery(testSqlText); safeClose(rSet); } catch (Exception e) { Exception wrappedException = new ContextedRuntimeException(e).addContextValue("datasource", dataSource); logger.error("Healthcheck Failure", wrappedException); return Result.unhealthy(wrappedException); } finally { safeClose(stmt); safeClose(conn); } return Result.healthy(); }
@Test public void testCheckInvalidDatabase() throws Exception { TestMongoDbHealthCheck healthCheck = setTpcheckMocks(); Mockito.when(commandResult.get(Matchers.anyString())).thenReturn(Integer.valueOf(0)); Result result = healthCheck.check(); Mockito.verify(loggerMock).debug("connectionUrl={} databaseList={} stats={}", TEST_CONNECT_URL, "", "commandResult"); Mockito.verify(mongoClientMock).close(); Assert.assertFalse(result.isHealthy()); ArgumentCaptor<ContextedRuntimeException> exCaptor = ArgumentCaptor.forClass(ContextedRuntimeException.class); Mockito.verify(loggerMock).error(Matchers.anyString(), exCaptor.capture()); Assert.assertEquals(4, exCaptor.getValue().getContextLabels().size()); Assert.assertEquals("Database has nothing in it.", exCaptor.getValue().getCause().getMessage()); }
@Override protected Result check() throws Exception { Connection conn = null; Channel channel = null; try { conn = connectionFactory.newConnection(); channel = conn.createChannel(); channel.queueDeclarePassive(queueName); return Result.healthy(); } catch (Exception e) { Exception wrappedException = new ContextedRuntimeException(e).addContextValue("queueName", queueName) .addContextValue("connectionFactory", ToStringBuilder.reflectionToString(connectionFactory)); logger.error("Healthcheck Failure", wrappedException); return Result.unhealthy(wrappedException); } finally { closeChannel(channel); closeConnection(conn); } }
private void closeChannel(Channel channel) throws IOException, TimeoutException { try { if (channel != null && channel.isOpen()) { channel.close(); } } catch (Exception e) { logger.warn("RabbitMQ channel erred on close", new ContextedRuntimeException(e) .addContextValue("queueName", queueName) .addContextValue("connectionFactory", ToStringBuilder.reflectionToString(connectionFactory))); } }
/** * @throws RuntimeException if course does not exist or if the courseForm is null */ public void loadIntoForm(CourseConfigurationForm courseForm, long courseId) { Validate.notNull(courseForm, "courseForm must not be null"); List<AttendanceSection> sections = sectionRepository.findByCanvasCourseId(courseId); if(CollectionUtils.isEmpty(sections)){ RuntimeException e = new RuntimeException("Cannot load data into courseForm for non-existent sections for this course"); throw new ContextedRuntimeException(e).addContextValue("courseId", courseId); } AttendanceAssignment attendanceAssignment = assignmentRepository.findByAttendanceSection(sections.get(0)); if(attendanceAssignment == null) { attendanceAssignment = new AttendanceAssignment(); } courseForm.setAssignmentName(StringUtils.defaultIfEmpty(attendanceAssignment.getAssignmentName(), "Attendance")); courseForm.setAssignmentPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getAssignmentPoints(), "100")); //default to full points for present or excused courseForm.setPresentPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getPresentPoints(), courseForm.getAssignmentPoints())); courseForm.setExcusedPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getExcusedPoints(), courseForm.getAssignmentPoints())); courseForm.setTardyPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getTardyPoints(), "0")); courseForm.setAbsentPoints(StringUtils.defaultIfEmpty(attendanceAssignment.getAbsentPoints(), "0")); courseForm.setGradingOn(attendanceAssignment.getGradingOn()); }
/** * @throws RuntimeException if course does not exist or if the courseForm is null */ public void loadIntoForm(CourseConfigurationForm courseForm, long courseId) { Validate.notNull(courseForm, "courseForm must not be null"); AttendanceCourse attendanceCourse = attendanceCourseRepository.findByCanvasCourseId(courseId); if(attendanceCourse == null) { RuntimeException e = new IllegalArgumentException("Cannot load data into courseForm for non-existent course"); throw new ContextedRuntimeException(e).addContextValue("courseId", courseId); } courseForm.setTotalClassMinutes(attendanceCourse.getTotalMinutes()); courseForm.setDefaultMinutesPerSession(attendanceCourse.getDefaultMinutesPerSession()); courseForm.setSimpleAttendance(attendanceCourse.getAttendanceType().equals(AttendanceType.SIMPLE)); courseForm.setShowNotesToStudents(attendanceCourse.getShowNotesToStudents()); }
/** * @throws IllegalArgumentException when a student cannot be found in the database for the given studentId */ public MakeupForm createMakeupForm(long studentId, long sectionId, boolean addEmptyEntry) { AttendanceStudent student = attendanceStudentRepository.findByStudentId(new Long(studentId)); if(student == null) { RuntimeException e = new IllegalArgumentException("student does not exist in the database"); throw new ContextedRuntimeException(e).addContextValue("studentId", studentId); } List<Makeup> makeups = makeupRepository.findByAttendanceStudentOrderByDateOfClassAsc(student); if (addEmptyEntry) { makeups.add(new Makeup()); } MakeupForm makeupForm = new MakeupForm(); makeupForm.setEntriesFromMakeEntities(makeups); makeupForm.setSectionId(sectionId); makeupForm.setStudentId(studentId); return makeupForm; }
@Override protected Result check() throws Exception { try { return localCheck(); } catch (Exception e) { Exception wrappedException = new ContextedRuntimeException(e).addContextValue("checkUrl", checkUrl) .addContextValue("requestTimeoutMillis", requestTimeoutMillis).addContextValue("headerMap", (headerMap == null) ? headerMap : Arrays.toString(headerMap.entrySet().toArray())); logger.error("Healthcheck Failure", wrappedException); return Result.unhealthy(wrappedException); } }
@Test public void testCheckUrlNonExistent() throws Exception { makeCheck3Args(TEST_URL, TEST_TIMEOUT, TEST_HEADERS); FieldUtils.writeField(healthCheck3Args, "checkUrl", "invalidUrl", true); HealthCheck.Result result = healthCheck3Args.check(); // System.out.println(result.getMessage()); Mockito.verify(loggerMock).error(Matchers.anyString(), Matchers.any(ContextedRuntimeException.class)); Assert.assertTrue(result.getMessage().contains("invalidUrl")); Assert.assertTrue(result.getMessage().contains("10")); Assert.assertTrue(result.getMessage().contains("headerMap=[]")); Assert.assertFalse(result.isHealthy()); }
@Test public void testCloseClusterQuietlyClusterException() throws Exception { testCluster.exceptionToThrow = new RuntimeException("crap"); MethodUtils.invokeMethod(healthCheck, true, "closeClusterQuietly", testCluster); Assert.assertEquals(1, testCluster.nbrTimesCloseCalled); ArgumentCaptor<ContextedRuntimeException> exCaptor = ArgumentCaptor.forClass(ContextedRuntimeException.class); Mockito.verify(loggerMock).warn(Matchers.anyString(), exCaptor.capture()); Assert.assertEquals(3, exCaptor.getValue().getContextLabels().size()); }
@Test public void testCloseSessionQuietlyException() throws Exception { Mockito.doThrow(new RuntimeException("crap")).when(session).close(); MethodUtils.invokeMethod(healthCheck, true, "closeSessionQuietly", session); Mockito.verify(session).close(); ArgumentCaptor<ContextedRuntimeException> exCaptor = ArgumentCaptor.forClass(ContextedRuntimeException.class); Mockito.verify(loggerMock).warn(Matchers.anyString(), exCaptor.capture()); Assert.assertEquals(3, exCaptor.getValue().getContextLabels().size()); }
private void safeClose(AutoCloseable statement) { try { if (statement != null) { statement.close(); } } catch (Exception e) { logger.warn("JDBC Statement erred on close", new ContextedRuntimeException(e).addContextValue("datasource", dataSource)); } }
@Test public void checkQueryExecutionFailure() throws Exception { Mockito.when(dataSourceMock.getConnection()).thenReturn(connectionMock); Mockito.when(connectionMock.createStatement()).thenReturn(statementMock); Mockito.when(statementMock.executeQuery(TEST_QUERY)).thenThrow(TEST_EXCEPTION); Result result = healthCheck.check(); Assert.assertTrue(!result.isHealthy()); Assert.assertEquals(TEST_EXCEPTION, result.getError().getCause()); Mockito.verify(loggerMock).error(Matchers.anyString(), Matchers.any(ContextedRuntimeException.class)); Mockito.verify(connectionMock).close(); Mockito.verify(statementMock).close(); }
@Test public void checkCloseFailure() throws Exception { mockSetup(); Mockito.doThrow(TEST_EXCEPTION).when(connectionMock).close(); Result result = healthCheck.check(); Assert.assertTrue(result.isHealthy()); Mockito.verify(loggerMock).warn(Matchers.anyString(), Matchers.any(ContextedRuntimeException.class)); }
@Override protected Result check() throws Exception { MongoClient mongoClient = null; String databaseList = null; String databaseStats = null; try { mongoClient = createMongoClient(); MongoIterable<String> dbList = mongoClient.listDatabaseNames(); databaseList = StringUtils.join(dbList, ','); CommandResult resultSet = mongoClient.getDB(databaseName).getStats(); databaseStats = resultSet.toString(); logger.debug("connectionUrl={} databaseList={} stats={}", connectionUrl, databaseList, databaseStats); Integer nbrCollections = (Integer) resultSet.get("collections"); if (nbrCollections == 0) { throw new RuntimeException("Database has nothing in it."); } } catch (Exception e) { ContextedRuntimeException wrappedException = wrapException(e); wrappedException.addContextValue("databaseList", databaseList); wrappedException.addContextValue("databaseStats", databaseStats); logger.error("MongoDB Healthcheck Failure", wrappedException); return Result.unhealthy(wrappedException); } finally { closeQuietly(mongoClient); } return Result.healthy(); }
@Test public void testCloseQuietlyExcepting() throws Exception { TestMongoClient mongoClient = new TestMongoClient(); mongoClient.exceptionToThrow = TEST_EXCEPTION; MethodUtils.invokeMethod(healthCheck, true, "closeQuietly", mongoClient); ArgumentCaptor<ContextedRuntimeException> exCaptor = ArgumentCaptor.forClass(ContextedRuntimeException.class); Mockito.verify(loggerMock).warn(Matchers.anyString(), exCaptor.capture()); Assert.assertEquals(2, exCaptor.getValue().getContextLabels().size()); Assert.assertEquals(mongoClient.exceptionToThrow, exCaptor.getValue().getCause()); }
@Test public void testWrapException() throws Exception { ContextedRuntimeException wrapped = (ContextedRuntimeException) MethodUtils.invokeMethod(healthCheck, true, "wrapException", TEST_EXCEPTION); Assert.assertEquals(TEST_EXCEPTION, wrapped.getCause()); Assert.assertEquals(2, wrapped.getContextEntries().size()); Assert.assertEquals(TEST_CONNECT_URL, wrapped.getContextValues("connectionUrl").get(0)); Assert.assertEquals(TEST_DATABASE, wrapped.getContextValues("databaseName").get(0)); }
private void closeConnection(Connection conn) throws IOException { try { if (conn != null && conn.isOpen()) { conn.close(); } } catch (Exception e) { logger.warn("RabbitMQ connection erred on close", new ContextedRuntimeException(e) .addContextValue("connectionFactory", ToStringBuilder.reflectionToString(connectionFactory))); } }
@Test public void checkNonexistentQueue() throws Exception { mockSetup(); Mockito.when(channelMock.queueDeclarePassive(TEST_QUEUE)).thenThrow(TEST_EXCEPTION); Result result = healthCheck.check(); Assert.assertFalse(result.isHealthy()); Mockito.verify(loggerMock).error(Matchers.anyString(), Matchers.any(ContextedRuntimeException.class)); }
@Test public void checkChannelCloseError() throws Exception { mockSetup(); Mockito.doThrow(TEST_EXCEPTION).when(channelMock).close(); healthCheck.check(); Mockito.verify(loggerMock).warn(Matchers.anyString(), Matchers.any(ContextedRuntimeException.class)); }
@Test public void checkConnectionCloseError() throws Exception { mockSetup(); Mockito.doThrow(TEST_EXCEPTION).when(connectionMock).close(); healthCheck.check(); Mockito.verify(loggerMock).warn(Matchers.anyString(), Matchers.any(ContextedRuntimeException.class)); }
@Test(expected = ContextedRuntimeException.class) public void loadIntoForm_CourseDoesntExist() { long nonExistantCanvasCourseId = -1; CourseConfigurationForm courseForm = new CourseConfigurationForm(); when(mockCourseRepository.findByCanvasCourseId(nonExistantCanvasCourseId)).thenReturn(null); courseService.loadIntoForm(courseForm, nonExistantCanvasCourseId); }
@Test(expected = ContextedRuntimeException.class) public void createMakeupForm_NonExistantStudent() { long nonExistantStudentId = -1; long sectionId = 500; boolean addEmptyEntry = true; when(mockStudentRepository.findByStudentId(nonExistantStudentId)).thenReturn(null); makeupService.createMakeupForm(nonExistantStudentId, sectionId, addEmptyEntry); }
public static HttpResponse simpleRESTGet(String requestUri) { Validate.notEmpty(requestUri, "Null or blank requestUri not allowed."); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(requestUri); try { return httpclient.execute(httpGet); } catch (Exception e) { throw new ContextedRuntimeException(e) .addContextValue("requestUri", requestUri); } }
@Override public Object clone() throws CloneNotSupportedException { CallingRegistry.addCall("clone"); try { return BeanUtils.cloneBean(this); } catch (Exception e) { throw new ContextedRuntimeException("Error cloning value object", e) .addContextValue("class", this.getClass().getName()); } }
private Exception wrapException(Exception e) { return new ContextedRuntimeException(e) .addContextValue("serverName", serverName) .addContextValue("keySpace", keySpace) .addContextValue("query", query); }
private ContextedRuntimeException wrapException(Exception e) { return new ContextedRuntimeException(e) .addContextValue("connectionUrl", connectionUrl) .addContextValue("databaseName", databaseName); }