repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/model/patient/PatientDataTest.java
package edu.ncsu.csc.itrust.unit.model.patient; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Assert; import org.junit.Test; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.DataBean; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.user.patient.Patient; import edu.ncsu.csc.itrust.model.user.patient.PatientMySQLConverter; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import junit.framework.TestCase; public class PatientDataTest extends TestCase { private DataBean<Patient> patientData; private TestDataGenerator gen; private DataSource ds; @Override protected void setUp() throws Exception { ds = ConverterDAO.getDataSource(); patientData = new PatientMySQLConverter(ds); gen = new TestDataGenerator(); } @Test public void testGetHCPInstead() throws FileNotFoundException, SQLException, IOException{ gen.hcp1(); gen.patient1(); Patient retVal; try { retVal = patientData.getByID(9900000000L); Assert.assertNull(retVal); } catch (DBException e) { Assert.assertTrue("error thrown",true); } } public void testGetPatient1() throws FileNotFoundException, SQLException, IOException{ gen.patient1(); Patient retVal; try { retVal = patientData.getByID(1L); Assert.assertEquals("Random", retVal.getFirstName()); Assert.assertEquals("Person", retVal.getLastName()); Assert.assertEquals(1L, retVal.getMID()); Assert.assertEquals(Role.PATIENT, retVal.getRole()); } catch (DBException e) { Assert.fail(); } } }
1,727
26.428571
89
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/model/prescription/PrescriptionMySQLTest.java
package edu.ncsu.csc.itrust.unit.model.prescription; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.time.LocalDate; import java.util.List; import javax.sql.DataSource; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import org.mockito.Spy; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisit; import edu.ncsu.csc.itrust.model.officeVisit.OfficeVisitMySQL; import edu.ncsu.csc.itrust.model.prescription.Prescription; import edu.ncsu.csc.itrust.model.prescription.PrescriptionMySQL; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import junit.framework.TestCase; public class PrescriptionMySQLTest extends TestCase { PrescriptionMySQL sql; @Spy PrescriptionMySQL mockSql; private DataSource ds; @Override public void setUp() throws DBException, FileNotFoundException, SQLException, IOException{ ds = ConverterDAO.getDataSource(); sql = new PrescriptionMySQL(ds); mockSql = Mockito.spy(new PrescriptionMySQL(ds)); TestDataGenerator gen = new TestDataGenerator(); gen.clearAllTables(); gen.ndCodes(); gen.ndCodes1(); gen.ndCodes100(); gen.ndCodes2(); gen.ndCodes3(); gen.ndCodes4(); gen.uc21(); } @Test public void testGetPrescriptionsForPatientEndingAfter() throws SQLException{ List<Prescription> pList = sql.getPrescriptionsForPatientEndingAfter(201, LocalDate.now().minusDays(91)); Assert.assertEquals(2, pList.size()); Assert.assertEquals("63739-291", pList.get(0).getCode()); Assert.assertEquals("48301-3420", pList.get(1).getCode()); } @Test public void testNoDataSource(){ try { new PrescriptionMySQL(); Assert.fail(); } catch (DBException e){ // yay, we passed } } class TestPrescriptionMySQL extends PrescriptionMySQL { public TestPrescriptionMySQL() throws DBException { super(); } @Override public DataSource getDataSource() { return ds; } } @Test public void testMockDataSource() throws Exception { TestPrescriptionMySQL mysql = new TestPrescriptionMySQL(); Assert.assertNotNull(mysql); } @Test public void testMockGetPrescriptionsForPatientEndingAfter() throws Exception { Mockito.doThrow(SQLException.class).when(mockSql).loadRecords(Mockito.any()); try { mockSql.getPrescriptionsForPatientEndingAfter(1L, LocalDate.now()); fail(); } catch (SQLException e) { // Do nothing } } @Test public void testGetPrescriptionsForOfficeVisit() throws DBException, SQLException{ OfficeVisitMySQL ovSQL = new OfficeVisitMySQL(ds); List<OfficeVisit> ovList = ovSQL.getVisitsForPatient(201L); Assert.assertEquals(3, ovList.size()); long ovId = ovList.get(0).getVisitID(); Assert.assertEquals(0, sql.getPrescriptionsForOfficeVisit(ovId).size()); ovId = ovList.get(1).getVisitID(); Assert.assertEquals(2, sql.getPrescriptionsForOfficeVisit(ovId).size()); ovId = ovList.get(2).getVisitID(); Assert.assertEquals(1, sql.getPrescriptionsForOfficeVisit(ovId).size()); ovId = -1; Assert.assertEquals(0, sql.getPrescriptionsForOfficeVisit(ovId).size()); } @Test public void testGetPrescriptionsForMID() throws Exception { { List<Prescription> plist = sql.getPrescriptionsByMID(201L); Assert.assertEquals(3, plist.size()); } { List<Prescription> plist = sql.getPrescriptionsByMID(202L); Assert.assertEquals(1, plist.size()); } { List<Prescription> plist = sql.getPrescriptionsByMID(203L); Assert.assertEquals(0, plist.size()); } } @Test public void testGetCodeName() throws Exception { String codeName = "Midichlomaxene"; String codeID = "48301-3420"; assertEquals( codeName, sql.getCodeName(codeID) ); } @Test public void testGetPrescriptionByID() throws Exception { List<Prescription> plist = sql.getPrescriptionsByMID(202L); Prescription expected = plist.get(0); Assert.assertNotNull(expected); long actualId = expected.getId(); Prescription actual = sql.get(actualId); Assert.assertNotNull(actual); Assert.assertEquals(expected.getDrugCode().getNDCode(), actual.getDrugCode().getNDCode()); } @Test public void testAddUpdateAndDelete() throws DBException, SQLException{ OfficeVisitMySQL ovSQL = new OfficeVisitMySQL(ds); List<OfficeVisit> ovList = ovSQL.getVisitsForPatient(201L); Assert.assertEquals(3, ovList.size()); long ovId = ovList.get(1).getVisitID(); List<Prescription> pList = sql.getPrescriptionsForOfficeVisit(ovId); Assert.assertEquals(2, pList.size()); Prescription toRemove = pList.get(0); Assert.assertTrue(sql.remove(toRemove.getId())); pList = sql.getPrescriptionsForOfficeVisit(ovId); Assert.assertEquals(1, pList.size()); Assert.assertTrue(sql.add(toRemove)); pList = sql.getPrescriptionsForOfficeVisit(ovId); Assert.assertEquals(2, pList.size()); Assert.assertTrue(toRemove.getCode().equals(pList.get(0).getCode()) || toRemove.getCode().equals(pList.get(1).getCode())); Assert.assertTrue(toRemove.getEndDate().equals(pList.get(0).getEndDate()) || toRemove.getEndDate().equals(pList.get(1).getEndDate())); Assert.assertTrue(toRemove.getStartDate().equals(pList.get(0).getStartDate()) || toRemove.getStartDate().equals(pList.get(1).getStartDate())); Assert.assertTrue(toRemove.getOfficeVisitId() == pList.get(0).getOfficeVisitId() || toRemove.getOfficeVisitId() == pList.get(1).getOfficeVisitId()); Assert.assertTrue(toRemove.getPatientMID() == pList.get(0).getPatientMID() || toRemove.getPatientMID() == pList.get(1).getPatientMID()); toRemove = pList.get(0); LocalDate oldDate = toRemove.getStartDate(); toRemove.setStartDate(oldDate.minusDays(20)); Assert.assertTrue(sql.update(toRemove)); pList = sql.getPrescriptionsForOfficeVisit(ovId); Assert.assertEquals(2, pList.size()); Assert.assertTrue(toRemove.getCode().equals(pList.get(0).getCode()) || toRemove.getCode().equals(pList.get(1).getCode())); Assert.assertTrue(toRemove.getEndDate().equals(pList.get(0).getEndDate()) || toRemove.getEndDate().equals(pList.get(1).getEndDate())); Assert.assertTrue(toRemove.getStartDate().equals(pList.get(0).getStartDate()) || toRemove.getStartDate().equals(pList.get(1).getStartDate())); Assert.assertTrue(toRemove.getOfficeVisitId() == pList.get(0).getOfficeVisitId() || toRemove.getOfficeVisitId() == pList.get(1).getOfficeVisitId()); Assert.assertTrue(toRemove.getPatientMID() == pList.get(0).getPatientMID() || toRemove.getPatientMID() == pList.get(1).getPatientMID()); toRemove.setStartDate(oldDate); Assert.assertTrue(sql.update(toRemove)); pList = sql.getPrescriptionsForOfficeVisit(ovId); Assert.assertEquals(2, pList.size()); Assert.assertTrue(toRemove.getCode().equals(pList.get(0).getCode()) || toRemove.getCode().equals(pList.get(1).getCode())); Assert.assertTrue(toRemove.getEndDate().equals(pList.get(0).getEndDate()) || toRemove.getEndDate().equals(pList.get(1).getEndDate())); Assert.assertTrue(toRemove.getStartDate().equals(pList.get(0).getStartDate()) || toRemove.getStartDate().equals(pList.get(1).getStartDate())); Assert.assertTrue(toRemove.getOfficeVisitId() == pList.get(0).getOfficeVisitId() || toRemove.getOfficeVisitId() == pList.get(1).getOfficeVisitId()); Assert.assertTrue(toRemove.getPatientMID() == pList.get(0).getPatientMID() || toRemove.getPatientMID() == pList.get(1).getPatientMID()); } }
8,013
39.271357
156
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/model/prescription/PrescriptionTest.java
package edu.ncsu.csc.itrust.unit.model.prescription; import java.time.LocalDate; import org.junit.Assert; import org.junit.Test; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.beans.MedicationBean; import edu.ncsu.csc.itrust.model.prescription.Prescription; public class PrescriptionTest extends TestCase { @Test public void testEverything(){ Prescription p = new Prescription(); p.setDrugCode(new MedicationBean("code","name")); Assert.assertEquals("code", p.getCode()); Assert.assertEquals("name", p.getName()); LocalDate now = LocalDate.now(); p.setEndDate(now); Assert.assertEquals(now, p.getEndDate()); now = LocalDate.of(2012, 12, 12); p.setStartDate(now); Assert.assertEquals(now, p.getStartDate()); p.setOfficeVisitId(155); Assert.assertEquals(155, p.getOfficeVisitId()); p.setPatientMID(100); Assert.assertEquals(100, p.getPatientMID()); p.setId(109); Assert.assertEquals(109, p.getId()); } }
1,128
27.225
59
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/model/user/UserDataTest.java
package edu.ncsu.csc.itrust.unit.model.user; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Assert; import org.junit.Test; import junit.framework.TestCase; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.ConverterDAO; import edu.ncsu.csc.itrust.model.DataBean; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.user.User; import edu.ncsu.csc.itrust.model.user.UserMySQLConverter; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; public class UserDataTest extends TestCase { //private User test; private DataBean<User> testData; private DataSource ds; TestDataGenerator gen; @Override protected void setUp() throws Exception { ds = ConverterDAO.getDataSource(); testData = new UserMySQLConverter(ds); gen = new TestDataGenerator(); } @Test public void testGetPatientUser() throws FileNotFoundException, IOException, SQLException, DBException{ gen.patient1(); User testUser = testData.getByID(1L); Assert.assertEquals(testUser.getFirstName(), "Random"); Assert.assertEquals(testUser.getLastName(), "Person"); Assert.assertEquals(testUser.getMID(), 1L); Assert.assertEquals(testUser.getRole(), Role.PATIENT); } @Test public void testGetHCPUser() throws FileNotFoundException, SQLException, IOException, DBException{ gen.hcp1(); User hcpTest = testData.getByID(9900000000L); Assert.assertEquals("Arehart",hcpTest.getLastName()); Assert.assertEquals("Tester",hcpTest.getFirstName()); Assert.assertEquals(9900000000L,hcpTest.getMID()); Assert.assertEquals(Role.HCP, hcpTest.getRole()); } }
1,716
30.796296
103
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/model/user/UserTest.java
package edu.ncsu.csc.itrust.unit.model.user; import org.junit.Assert; import org.junit.Test; import junit.framework.TestCase; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.user.User; public class UserTest extends TestCase { private User test; @Override protected void setUp() throws Exception { test = new User(); } /* * updated to reflect the new way addAllergy updates allergyDAO. */ @Test public void testMID() throws Exception { test.setMID(9000000001L); Assert.assertEquals(9000000001L, test.getMID()); } @Test public void testBigMID() throws Exception { try{ test.setMID(90000000000L); Assert.fail("No error thrown"); } catch(ITrustException ie){ Assert.assertTrue("Exception Thrown", true); } Assert.assertNotEquals(90000000000L, test.getMID()); } @Test public void testSmallMID() throws Exception { try{ test.setMID(-90000000L); Assert.fail("No error thrown"); } catch(ITrustException ie){ Assert.assertTrue("Exception Thrown", true); } Assert.assertNotEquals(-90000000L, test.getMID()); } @Test public void testRole(){ test.setRole(Role.HCP); Assert.assertEquals(Role.HCP, test.getRole()); } @Test public void testLastName(){ test.setLastName("testLN"); Assert.assertEquals("testLN", test.getLastName()); } @Test public void testFirstName(){ test.setFirstName("testFN"); Assert.assertEquals("testFN",test.getFirstName()); } }
1,534
20.319444
65
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/report/DemographicReportFilterTest.java
package edu.ncsu.csc.itrust.unit.report; import java.util.HashSet; import java.util.List; import java.util.Set; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.report.DemographicReportFilter; import edu.ncsu.csc.itrust.report.DemographicReportFilter.DemographicReportFilterType; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import junit.framework.TestCase; public class DemographicReportFilterTest extends TestCase { private DAOFactory factory = TestDAOFactory.getTestInstance(); private PatientDAO pDAO = factory.getPatientDAO(); private List<PatientBean> allPatients; private DemographicReportFilter filter; private TestDataGenerator gen = new TestDataGenerator(); @Override protected void setUp() throws Exception { gen.clearAllTables(); gen.standardData(); allPatients = pDAO.getAllPatients(); } public void testFilterByLastName() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.LAST_NAME, "Programmer", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(2, res.size()); assertTrue(res.get(0).getMID() == 2L); // Andy Programmer assertTrue(res.get(1).getMID() == 5L); // Baby Programmer } public void testFilterByLastNameNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.LAST_NAME, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByFirstName() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.FIRST_NAME, "Baby", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(4, res.size()); assertTrue(res.get(0).getMID() == 5L); // Baby Programmer assertTrue(res.get(1).getMID() == 6L); // Baby A assertTrue(res.get(2).getMID() == 7L); // Baby B assertTrue(res.get(3).getMID() == 8L); // Baby C } public void testFilterByFirstNameNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.FIRST_NAME, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByContactEmail() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.CONTACT_EMAIL, "fake@email.com", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(6, res.size()); assertTrue(res.get(0).getMID() == 3L); // Care Needs assertTrue(res.get(1).getMID() == 4L); // NoRecords Has assertTrue(res.get(2).getMID() == 5L); // Baby Programmer assertTrue(res.get(3).getMID() == 6L); // Baby A assertTrue(res.get(4).getMID() == 7L); // Baby B assertTrue(res.get(5).getMID() == 8L); // Baby C } public void testFilterByContactEmailNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.CONTACT_EMAIL, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByStreetAddr1() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.STREET_ADDR, "1247 Noname Dr", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(11, res.size()); Set<Long> retVals = new HashSet<Long>(); for(int i=0; i<res.size(); i++){ retVals.add(res.get(i).getMID()); } assertTrue(retVals.contains(1L)); // random person assertTrue(retVals.contains(3L)); // care needs assertTrue(retVals.contains(4L)); // norecords has assertTrue(retVals.contains(5L)); // baby programmer assertTrue(retVals.contains(6L)); // baby a assertTrue(retVals.contains(7L)); // baby b assertTrue(retVals.contains(8L)); // baby c assertTrue(retVals.contains(42L)); // bad horse } public void testFilterByStreetAddr2() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.STREET_ADDR, "Suite 106", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(12, res.size()); Set<Long> retVals = new HashSet<Long>(); for(int i=0; i<res.size(); i++){ retVals.add(res.get(i).getMID()); } assertTrue(retVals.contains(1L)); // random person assertTrue(retVals.contains(3L)); // care needs assertTrue(retVals.contains(4L)); // norecords has assertTrue(retVals.contains(5L)); // baby programmer assertTrue(retVals.contains(6L)); // baby a assertTrue(retVals.contains(7L)); // baby b assertTrue(retVals.contains(8L)); // baby c assertTrue(retVals.contains(42L)); // bad horse } public void testFilterByStreetAddr3() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.STREET_ADDR, "1247 Noname Dr Suite 106", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(11, res.size()); Set<Long> retVals = new HashSet<Long>(); for(int i=0; i<res.size(); i++){ retVals.add(res.get(i).getMID()); } assertTrue(retVals.contains(1L)); // random person assertTrue(retVals.contains(3L)); // care needs assertTrue(retVals.contains(4L)); // norecords has assertTrue(retVals.contains(5L)); // baby programmer assertTrue(retVals.contains(6L)); // baby a assertTrue(retVals.contains(7L)); // baby b assertTrue(retVals.contains(8L)); // baby c assertTrue(retVals.contains(42L)); // bad horse } public void testFilterByStreetAddrNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.STREET_ADDR, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByCity1() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.CITY, "", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(0, res.size()); } public void testFilterByCity2() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.CITY, "New YORK", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(3, res.size()); assertTrue(res.get(0).getMID() == 22L); // Fozzie Bear assertTrue(res.get(1).getMID() == 23L); // Dare Devil assertTrue(res.get(2).getMID() == 24L); // Devils Advocate } public void testFilterByCityNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.CITY, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByState() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.STATE, "NY", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(4, res.size()); assertTrue(res.get(0).getMID() == 22L); // Fozzie Bear assertTrue(res.get(1).getMID() == 23L); // Dare Devil assertTrue(res.get(2).getMID() == 24L); // Devils Advocate assertTrue(res.get(3).getMID() == 103L); // Fulton Gray } public void testFilterByStateNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.STATE, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByZip() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.ZIP, "10001", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(3, res.size()); assertTrue(res.get(0).getMID() == 22L); // Fozzie Bear assertTrue(res.get(1).getMID() == 23L); // Dare Devil assertTrue(res.get(2).getMID() == 24L); // Devils Advocate } public void testFilterByZip2() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.ZIP, "27606-1234", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(17, res.size()); assertTrue(res.get(0).getMID() == 1L); // random person assertTrue(res.get(1).getMID() == 3L); // care needs assertTrue(res.get(2).getMID() == 4L); // norecords has assertTrue(res.get(3).getMID() == 5L); // baby programmer assertTrue(res.get(4).getMID() == 6L); // baby a assertTrue(res.get(5).getMID() == 7L); // baby b assertTrue(res.get(6).getMID() == 8L); // baby c assertTrue(res.get(7).getMID() == 42L); // bad horse } public void testFilterByZipNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.ZIP, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByPhone() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.PHONE, "555-555-5554", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(1, res.size()); assertTrue(res.get(0).getMID() == 25L); // Trend Setter } public void testFilterByPhoneNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.PHONE, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByEmerContactName() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.EMER_CONTACT_NAME, "Mum", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(6, res.size()); assertTrue(res.get(0).getMID() == 3L); assertTrue(res.get(1).getMID() == 4L); assertTrue(res.get(2).getMID() == 5L); assertTrue(res.get(3).getMID() == 6L); assertTrue(res.get(4).getMID() == 7L); assertTrue(res.get(5).getMID() == 8L); } public void testFilterByEmerContactNameNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.EMER_CONTACT_NAME, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByContactPhoneNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.EMER_CONTACT_PHONE, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByGender() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.GENDER, "Female", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(21, res.size()); Set<Long> retVals = new HashSet<Long>(); for (int i =0; i<res.size(); i++){ retVals.add(res.get(i).getMID()); } assertTrue(retVals.contains(1L)); assertTrue(retVals.contains(5L)); assertTrue(retVals.contains(6L)); assertTrue(retVals.contains(21L)); assertTrue(retVals.contains(101L)); assertTrue(retVals.contains(104L)); } public void testFilterByGenderNoResult() { filter = new DemographicReportFilter(DemographicReportFilterType.GENDER, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByParentFirstName() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.PARENT_FIRST_NAME, "Random", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(5, res.size()); assertTrue(res.get(0).getMID() == 2L); assertTrue(res.get(1).getMID() == 3L); assertTrue(res.get(2).getMID() == 4L); assertTrue(res.get(3).getMID() == 20L); assertTrue(res.get(4).getMID() == 21L); } public void testFilterByParentFirstName2() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.PARENT_FIRST_NAME, "Andy", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(4, res.size()); assertTrue(res.get(0).getMID() == 5L); assertTrue(res.get(1).getMID() == 6L); assertTrue(res.get(2).getMID() == 7L); assertTrue(res.get(3).getMID() == 8L); } public void testFilterByParentFirstNameNoResult() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.PARENT_FIRST_NAME, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByParentLastName() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.PARENT_LAST_NAME, "Person", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(5, res.size()); assertTrue(res.get(0).getMID() == 2L); assertTrue(res.get(1).getMID() == 3L); assertTrue(res.get(2).getMID() == 4L); assertTrue(res.get(3).getMID() == 20L); assertTrue(res.get(4).getMID() == 21L); } public void testFilterByParentLastName2() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.PARENT_LAST_NAME, "Programmer", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(4, res.size()); assertTrue(res.get(0).getMID() == 5L); assertTrue(res.get(1).getMID() == 6L); assertTrue(res.get(2).getMID() == 7L); assertTrue(res.get(3).getMID() == 8L); } public void testFilterByParentLastNameNoResult() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.PARENT_LAST_NAME, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByChildFirstName() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.CHILD_FIRST_NAME, "Care", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(1, res.size()); assertTrue(res.get(0).getMID() == 1L); } public void testFilterByChildFirstNameNoResult() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.CHILD_FIRST_NAME, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByChildLastName() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.CHILD_LAST_NAME, "A", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(1, res.size()); assertTrue(res.get(0).getMID() == 2L); } public void testFilterByChildLastNameNoResult() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.CHILD_LAST_NAME, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterBySiblingFirstName() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.SIBLING_FIRST_NAME, "Baby", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(4, res.size()); assertTrue(res.get(0).getMID() == 5L); assertTrue(res.get(1).getMID() == 6L); assertTrue(res.get(2).getMID() == 7L); assertTrue(res.get(3).getMID() == 8L); } public void testFilterBySiblingFirstNameNoResult() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.SIBLING_FIRST_NAME, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterBySiblingLastName() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.SIBLING_LAST_NAME, "A", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(3, res.size()); assertTrue(res.get(0).getMID() == 5L); assertTrue(res.get(1).getMID() == 7L); assertTrue(res.get(2).getMID() == 8L); } public void testFilterBySiblingLastNameNoResult() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.SIBLING_LAST_NAME, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByInsuranceZip() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_ZIP, "19003-2715", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(5, res.size()); Set<Long> mids = new HashSet<Long>(); for(int i=0; i<res.size(); i++){ mids.add(res.get(i).getMID()); } assertTrue(mids.contains(2L)); assertTrue(mids.contains(22L)); assertTrue(mids.contains(25L)); assertTrue(mids.contains(23L)); assertTrue(mids.contains(24L)); } public void testFilterByInsuranceZipNoResult() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_ZIP, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testFilterByLowerAge() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.LOWER_AGE_LIMIT, "60", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(7, res.size()); Set<Long> retVals = new HashSet<Long>(); for(int i=0; i<res.size(); i++){ retVals.add(res.get(i).getMID()); } assertTrue(retVals.contains(1L)); assertTrue(retVals.contains(3L)); assertTrue(retVals.contains(4L)); assertTrue(retVals.contains(42L)); } public void testFilterByLowerAgeNoResult() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.LOWER_AGE_LIMIT, "Dalpe", factory); try { @SuppressWarnings("unused") List<PatientBean> res = filter.filter(allPatients); } catch (NumberFormatException e) { // exception is good. return; } assertTrue(false); } public void testFilterByUpperAgeNoResult() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.UPPER_AGE_LIMIT, "Dalpe", factory); try { @SuppressWarnings("unused") List<PatientBean> res = filter.filter(allPatients); } catch (NumberFormatException e) { // exception is good. return; } assertTrue(false); } public void testToString() { filter = new DemographicReportFilter(DemographicReportFilterType.LAST_NAME, "val", factory); String expected = "Filter by LAST NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.CHILD_FIRST_NAME, "val", factory); expected = "Filter by CHILD'S FIRST NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.CHILD_LAST_NAME, "val", factory); expected = "Filter by CHILD'S LAST NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.CITY, "val", factory); expected = "Filter by CITY with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.CONTACT_EMAIL, "val", factory); expected = "Filter by CONTACT EMAIL with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.EMER_CONTACT_NAME, "val", factory); expected = "Filter by EMERGENCY CONTACT NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.EMER_CONTACT_PHONE, "val", factory); expected = "Filter by EMERGENCY CONTACT PHONE # with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.FIRST_NAME, "val", factory); expected = "Filter by FIRST NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_ADDR, "val", factory); expected = "Filter by INSURANCE COMPANY ADDRESS with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_CITY, "val", factory); expected = "Filter by INSURANCE COMPANY CITY with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_ID, "val", factory); expected = "Filter by INSURANCE COMPANY ID with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_NAME, "val", factory); expected = "Filter by INSURANCE COMPANY NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_PHONE, "val", factory); expected = "Filter by INSURANCE COMPANY PHONE # with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_STATE, "val", factory); expected = "Filter by INSURANCE COMPANY STATE with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_ZIP, "val", factory); expected = "Filter by INSURANCE COMPANY ZIPCODE with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.PARENT_FIRST_NAME, "val", factory); expected = "Filter by PARENT'S FIRST NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.PARENT_LAST_NAME, "val", factory); expected = "Filter by PARENT'S LAST NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.PHONE, "val", factory); expected = "Filter by PHONE # with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.SIBLING_FIRST_NAME, "val", factory); expected = "Filter by SIBLING'S FIRST NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.SIBLING_LAST_NAME, "val", factory); expected = "Filter by SIBLING'S LAST NAME with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.STATE, "val", factory); expected = "Filter by STATE with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.STREET_ADDR, "val", factory); expected = "Filter by STREET ADDRESS with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.ZIP, "val", factory); expected = "Filter by ZIPCODE with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.GENDER, "val", factory); expected = "Filter by GENDER with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.LOWER_AGE_LIMIT, "val", factory); expected = "Filter by LOWER AGE LIMIT with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.UPPER_AGE_LIMIT, "val", factory); expected = "Filter by UPPER AGE LIMIT with value val"; assertEquals(expected, filter.toString()); filter = new DemographicReportFilter(DemographicReportFilterType.MID, "val", factory); expected = "Filter by MID with value val"; assertEquals(expected, filter.toString()); } public void testFilterTypeFromString() { DemographicReportFilterType expected = DemographicReportFilterType.EMER_CONTACT_NAME; DemographicReportFilterType actual = DemographicReportFilter.filterTypeFromString("emer_contACT_naME"); assertEquals(expected, actual); } public void testGetFilterType() { filter = new DemographicReportFilter(DemographicReportFilterType.CITY, "city!", factory); DemographicReportFilterType expected = DemographicReportFilterType.CITY; assertEquals(expected, filter.getFilterType()); } public void testGetFilterValue() { filter = new DemographicReportFilter(DemographicReportFilterType.CITY, "city!", factory); String expected = "city!"; assertEquals(expected, filter.getFilterValue()); } public void testFilterByInvalidLowerAge() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.LOWER_AGE_LIMIT, "-1", factory); try { @SuppressWarnings("unused") List<PatientBean> res = filter.filter(allPatients); } catch (NumberFormatException e) { // exception is good return; } assertTrue(false); } public void testFilterByInvalidUpperAge() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.UPPER_AGE_LIMIT, "-1", factory); try { @SuppressWarnings("unused") List<PatientBean> res = filter.filter(allPatients); } catch (NumberFormatException e) { // exception is good return; } assertTrue(false); } public void testFilterByMID() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.MID, "101", factory); List<PatientBean> filteredList = filter.filter(allPatients); assertEquals(1, filteredList.size()); PatientBean patient = filteredList.get(0); assertEquals(101L, patient.getMID()); } public void testFilterByICName() throws Exception { PatientBean testPat = pDAO.getPatient(1L); testPat.setIcName("FilterTest"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_NAME, "FilterTest", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); assertEquals(1, filteredList.size()); PatientBean patient = filteredList.get(0); assertEquals(1L, patient.getMID()); } public void testFilterByICID() throws Exception { PatientBean testPat = pDAO.getPatient(1L); testPat.setIcID("FilterTest"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_ID, "FilterTest", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); assertEquals(1, filteredList.size()); PatientBean patient = filteredList.get(0); assertEquals(1L, patient.getMID()); } public void testFilterByICCity() throws Exception { PatientBean testPat = pDAO.getPatient(1L); testPat.setIcCity("FilterTest"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_CITY, "FilterTest", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); assertEquals(1, filteredList.size()); PatientBean patient = filteredList.get(0); assertEquals(1L, patient.getMID()); } public void testFilterByICState() throws Exception { PatientBean testPat = pDAO.getPatient(1L); testPat.setIcState("MO"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_STATE, "MO", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); int originalFromMOSize = 0; for (PatientBean p : allPatients) { if (p.getIcState().equals("MO")) originalFromMOSize++; } assertEquals(originalFromMOSize + 1, filteredList.size()); PatientBean patient = filteredList.get(0); assertEquals(1L, patient.getMID()); } public void testFilterByICPhone() throws Exception { PatientBean testPat = pDAO.getPatient(1L); testPat.setIcPhone("FilterTest"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_PHONE, "FilterTest", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); assertEquals(1, filteredList.size()); PatientBean patient = filteredList.get(0); assertEquals(1L, patient.getMID()); } public void testFilterByICAddress1() throws Exception { PatientBean testPat = pDAO.getPatient(1L); testPat.setIcAddress1("FilterTest"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_ADDR, "FilterTest", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); assertEquals(1, filteredList.size()); PatientBean patient = filteredList.get(0); assertEquals(1L, patient.getMID()); } public void testFilterByICAddress2() throws Exception { PatientBean testPat = pDAO.getPatient(1L); testPat.setIcAddress2("FilterTest"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_ADDR, "FilterTest", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); assertEquals(1, filteredList.size()); PatientBean patient = filteredList.get(0); assertEquals(1L, patient.getMID()); } public void testFilterByICAddress3() throws Exception { PatientBean testPat = pDAO.getPatient(1L); testPat.setIcAddress1("Filter"); testPat.setIcAddress2("Test"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.INSURE_ADDR, "Filter Test", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); assertEquals(1, filteredList.size()); PatientBean patient = filteredList.get(0); assertEquals(1L, patient.getMID()); } public void testFilterByExcludeDeactivated() throws Exception { PatientBean testPat = pDAO.getPatient(1L); testPat.setDateOfDeactivationStr("09/25/2013"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.DEACTIVATED, "exclude", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); int originalNotDeactivatedSize = 0; for (PatientBean p : allPatients) { if (p.getDateOfDeactivationStr().equals("")) originalNotDeactivatedSize++; } assertEquals(originalNotDeactivatedSize - 1, filteredList.size()); } public void testFilterByOnlyDeactivated() throws Exception { int originalDeactivatedSize = 0; for (PatientBean p : allPatients) { if (!p.getDateOfDeactivationStr().equals("")) originalDeactivatedSize++; } PatientBean testPat = pDAO.getPatient(1L); testPat.setDateOfDeactivationStr("09/25/2013"); pDAO.editPatient(testPat, 9000000000L); filter = new DemographicReportFilter(DemographicReportFilterType.DEACTIVATED, "only", factory); List<PatientBean> filteredList = filter.filter(pDAO.getAllPatients()); assertEquals(originalDeactivatedSize + 1, filteredList.size()); Set<Long> mids = new HashSet<Long>(); for(int i=0; i<filteredList.size(); i++){ mids.add(filteredList.get(i).getMID()); } assertTrue(mids.contains(314159L)); } public void testGetFilterTypeString() throws Exception { filter = new DemographicReportFilter(DemographicReportFilterType.DEACTIVATED, "only", factory); assertEquals("DEACTIVATED", filter.getFilterTypeString()); filter = new DemographicReportFilter(DemographicReportFilterType.STATE, "only", factory); assertEquals("STATE", filter.getFilterTypeString()); } }
30,668
40.001337
109
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/report/MedicalReportFilterTest.java
package edu.ncsu.csc.itrust.unit.report; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.report.MedicalReportFilter; import edu.ncsu.csc.itrust.report.MedicalReportFilter.MedicalReportFilterType; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import junit.framework.TestCase; public class MedicalReportFilterTest extends TestCase { private DAOFactory factory = TestDAOFactory.getTestInstance(); private PatientDAO pDAO = factory.getPatientDAO(); private List<PatientBean> allPatients; private MedicalReportFilter filter; private TestDataGenerator gen = new TestDataGenerator(); @Override protected void setUp() throws Exception { gen.clearAllTables(); gen.standardData(); allPatients = pDAO.getAllPatients(); } public void testFilterByAllergy() throws Exception { filter = new MedicalReportFilter(MedicalReportFilterType.ALLERGY, "00882219", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(1, res.size()); assertTrue(res.get(0).getMID() == 100L); } public void testFilterByAllergyNoResult() { filter = new MedicalReportFilter(MedicalReportFilterType.ALLERGY, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testToString() { String expected = ""; filter = new MedicalReportFilter(MedicalReportFilterType.ALLERGY, "val", factory); expected = "Filter by ALLERGY with value val"; assertEquals(expected, filter.toString()); } public void testFilterTypeFromString() { MedicalReportFilterType expected = MedicalReportFilterType.CURRENT_PRESCRIPTIONS; MedicalReportFilterType actual = MedicalReportFilter.filterTypeFromString("CurrENt_PREscriptions"); assertEquals(expected, actual); } public void testGetFilterType() { filter = new MedicalReportFilter(MedicalReportFilterType.PROCEDURE, "city!", factory); MedicalReportFilterType expected = MedicalReportFilterType.PROCEDURE; assertEquals(expected, filter.getFilterType()); } public void testGetFilterValue() { filter = new MedicalReportFilter(MedicalReportFilterType.PROCEDURE, "city!", factory); String expected = "city!"; assertEquals(expected, filter.getFilterValue()); } public void testGetFilterTypeString() { filter = new MedicalReportFilter(MedicalReportFilterType.PROCEDURE, "city!", factory); assertEquals("PROCEDURE", filter.getFilterTypeString()); filter = new MedicalReportFilter(MedicalReportFilterType.CURRENT_PRESCRIPTIONS, "city!", factory); assertEquals("CURRENT PRESCRIPTIONS", filter.getFilterTypeString()); } }
2,802
36.373333
101
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/report/PersonnelReportFilterTest.java
package edu.ncsu.csc.itrust.unit.report; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.report.PersonnelReportFilter; import edu.ncsu.csc.itrust.report.PersonnelReportFilter.PersonnelReportFilterType; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import junit.framework.TestCase; public class PersonnelReportFilterTest extends TestCase { private DAOFactory factory = TestDAOFactory.getTestInstance(); private PatientDAO pDAO = factory.getPatientDAO(); private List<PatientBean> allPatients; private PersonnelReportFilter filter; private TestDataGenerator gen = new TestDataGenerator(); @Override protected void setUp() throws Exception { gen.clearAllTables(); gen.standardData(); allPatients = pDAO.getAllPatients(); } public void testFilterByProcedure() throws Exception { filter = new PersonnelReportFilter(PersonnelReportFilterType.DLHCP, "Beaker Beaker", factory); List<PatientBean> res = filter.filter(allPatients); assertEquals(2, res.size()); assertTrue(res.get(0).getMID() == 22L); assertTrue(res.get(1).getMID() == 23L); } public void testFilterByProcedureNoResult() { filter = new PersonnelReportFilter(PersonnelReportFilterType.DLHCP, "Dalpe", factory); List<PatientBean> res = filter.filter(allPatients); assertTrue(res.isEmpty()); } public void testToString() { String expected = ""; filter = new PersonnelReportFilter(PersonnelReportFilterType.DLHCP, "val", factory); expected = "Filter by DECLARED HCP with value val"; assertEquals(expected, filter.toString()); } public void testFilterTypeFromString() { PersonnelReportFilterType expected = PersonnelReportFilterType.DLHCP; PersonnelReportFilterType actual = PersonnelReportFilter.filterTypeFromString("dLhCP"); assertEquals(expected, actual); } public void testGetFilterType() { filter = new PersonnelReportFilter(PersonnelReportFilterType.DLHCP, "city!", factory); PersonnelReportFilterType expected = PersonnelReportFilterType.DLHCP; assertEquals(expected, filter.getFilterType()); } public void testGetFilterValue() { filter = new PersonnelReportFilter(PersonnelReportFilterType.DLHCP, "city!", factory); String expected = "city!"; assertEquals(expected, filter.getFilterValue()); } }
2,485
34.514286
96
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/CustomJSPTagsTest.java
package edu.ncsu.csc.itrust.unit.serverutils; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.classextension.EasyMock.createControl; import java.io.IOException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; import junit.framework.TestCase; import org.easymock.classextension.IMocksControl; import edu.ncsu.csc.itrust.tags.PatientNavigation; import edu.ncsu.csc.itrust.tags.StateSelect; /** * * * */ public class CustomJSPTagsTest extends TestCase { // This class uses an advanced concept not taught in CSC326 at NCSU called // Mock Objects. // Feel free to take a look at how this works, but know that you will not // need to know mock objects // to do nearly everything in iTrust. Unless your assignment mentions mock // objects somewhere, you should // not need them. // // But, if you are interested in a cool unit testing concept, feel free to // look at this code as an // example. // // This class uses the EasyMock library to manage the mock objects. // http://easymock.org/ private PageContext mockContext; private IMocksControl ctrl; private JspWriter mockWriter; private Tag mockParent; @Override protected void setUp() throws Exception { ctrl = createControl(); mockContext = ctrl.createMock(PageContext.class); mockWriter = ctrl.createMock(JspWriter.class); mockParent = ctrl.createMock(Tag.class); expect(mockContext.getOut()).andReturn(mockWriter).anyTimes(); } public void testPatientNavHappy() throws Exception { PatientNavigation nav = new PatientNavigation(); nav.setPageContext(mockContext); // we're okay with any strings written here - normally you want to be // more specific mockWriter.write((String) anyObject()); expectLastCall().anyTimes(); ctrl.replay(); String str = "Health Records"; nav.setThisTitle(str); assertSame(str, nav.getThisTitle()); assertEquals(Tag.SKIP_BODY, nav.doStartTag()); assertEquals(Tag.SKIP_BODY, nav.doEndTag()); nav.setParent(mockParent); assertSame(mockParent, nav.getParent()); nav.release(); ctrl.verify(); } public void testPatientNavException() throws Exception { PatientNavigation nav = new PatientNavigation(); nav.setPageContext(mockContext); // we're okay with any strings written here - normally you want to be // more specific mockWriter.write((String) anyObject()); expectLastCall().andThrow(new IOException()); // nothing done but // stacktrace ctrl.replay(); assertEquals(Tag.SKIP_BODY, nav.doStartTag()); ctrl.verify(); } public void testStateSelect() throws Exception { StateSelect tag = new StateSelect(); tag.setPageContext(mockContext); // we're okay with any strings written here - normally you want to be // more specific mockWriter.write((String) anyObject()); expectLastCall().anyTimes(); ctrl.replay(); assertEquals(Tag.SKIP_BODY, tag.doStartTag()); assertEquals(Tag.SKIP_BODY, tag.doEndTag()); tag.setParent(mockParent); assertSame(mockParent, tag.getParent()); String name = "Something!"; tag.setName(name); assertSame(name, tag.getName()); String value = "Something!!"; tag.setValue(value); assertSame(value, tag.getValue()); tag.setName(""); assertEquals(Tag.SKIP_BODY, tag.doStartTag()); tag.setValue("NC"); assertEquals(Tag.SKIP_BODY, tag.doStartTag()); tag.release(); ctrl.verify(); } public void testStateSelectException() throws Exception { StateSelect tag = new StateSelect(); tag.setPageContext(mockContext); // we're okay with any strings written here - normally you want to be // more specific mockWriter.write((String) anyObject()); expectLastCall().andThrow(new IOException()); // nothing done but // stacktrace ctrl.replay(); assertEquals(Tag.SKIP_BODY, tag.doStartTag()); ctrl.verify(); } }
3,978
29.374046
75
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/FindExpertServletTest.java
package edu.ncsu.csc.itrust.unit.serverutils; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import edu.ncsu.csc.itrust.server.FindExpertServlet; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; public class FindExpertServletTest { private HttpServletRequest request; private HttpServletResponse response; private TestDataGenerator gen; private Delegator test; @Before public void setUp() throws Exception { gen = new TestDataGenerator(); gen.clearAllTables(); gen.standardData(); request = mock(HttpServletRequest.class); response = mock(HttpServletResponse.class); test = new Delegator(); } @Test public void testDoGetHttpServletRequestHttpServletResponse() throws Exception { Writer t = new StringWriter(); PrintWriter temp = new PrintWriter(t); when(request.getParameter("query")).thenReturn("Kelly Doctor"); when(response.getWriter()).thenReturn(temp); test.testDoGet(response, request); assertTrue(t.toString().contains("fTable")); assertTrue(t.toString().contains("Kelly Doctor")); } private class Delegator extends FindExpertServlet { private static final long serialVersionUID = 1L; public Delegator() { super(TestDAOFactory.getTestInstance()); } public void testDoGet(HttpServletResponse r, HttpServletRequest req) throws ServletException, IOException { super.doGet(req, r); } } }
1,789
26.538462
109
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/GroupReportGeneratorTest.java
package edu.ncsu.csc.itrust.unit.serverutils; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.classextension.EasyMock.createControl; import java.util.ArrayList; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.easymock.EasyMock; import org.easymock.classextension.IMocksControl; import edu.ncsu.csc.itrust.XmlGenerator; import edu.ncsu.csc.itrust.action.GroupReportGeneratorAction; import edu.ncsu.csc.itrust.server.GroupReportGeneratorServlet; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import org.w3c.dom.Document; import junit.framework.TestCase; @SuppressWarnings("unused") public class GroupReportGeneratorTest extends TestCase { protected GroupReportGeneratorAction grga; private IMocksControl ctrl; private HttpServletRequest req; private HttpServletResponse resp; private Document doc; private XmlGenerator xmlgen; private ArrayList<String> headers = new ArrayList<String>(); private ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>(); @Override protected void setUp() throws Exception { ctrl = createControl(); req = ctrl.createMock(HttpServletRequest.class); resp = ctrl.createMock(HttpServletResponse.class); grga = ctrl.createMock(GroupReportGeneratorAction.class); xmlgen = ctrl.createMock(XmlGenerator.class); } public void testGroupReportGeneratorServletPost() throws Exception { String demo = new String(); String med = new String(); String pers = new String(); LittleDelegatorServlet servlet = new LittleDelegatorServlet(); expect(grga.getReportHeaders()).andReturn(headers); expect(grga.getReportData()).andReturn(data); expect(req.getParameter("demoparams")).andReturn(demo).anyTimes(); expect(req.getParameter("medparams")).andReturn(med).anyTimes(); expect(req.getParameter("persparams")).andReturn(pers).anyTimes(); resp.sendRedirect(""); expectLastCall(); resp.setContentType("application/x-download"); expectLastCall(); resp.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject()); expectLastCall(); ServletOutputStream sos = ctrl.createMock(ServletOutputStream.class); sos.write((byte[]) EasyMock.anyObject(), EasyMock.anyInt(), EasyMock.anyInt()); expectLastCall().anyTimes(); sos.flush(); expectLastCall().anyTimes(); expect(resp.getOutputStream()).andReturn(sos); ctrl.replay(); servlet.setUp(); servlet.doPost(req, resp); } private class LittleDelegatorServlet extends GroupReportGeneratorServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { super.doPost(req, resp); } public void setUp() { factory = TestDAOFactory.getTestInstance(); } } }
2,893
30.802198
81
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/MockHttpSession.java
package edu.ncsu.csc.itrust.unit.serverutils; import java.util.Enumeration; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionContext; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @SuppressWarnings("all") public class MockHttpSession implements HttpSession { static int mins = 0; @Override @SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") public void setMaxInactiveInterval(int arg0) { mins = arg0; } @Override public Object getAttribute(String arg0) { throw new IllegalStateException("should not be hit!"); } @Override public Enumeration getAttributeNames() { throw new IllegalStateException("should not be hit!"); } @Override public long getCreationTime() { throw new IllegalStateException("should not be hit!"); } @Override public String getId() { throw new IllegalStateException("should not be hit!"); } @Override public long getLastAccessedTime() { throw new IllegalStateException("should not be hit!"); } @Override public int getMaxInactiveInterval() { throw new IllegalStateException("should not be hit!"); } @Override public ServletContext getServletContext() { throw new IllegalStateException("should not be hit!"); } @Override @Deprecated public HttpSessionContext getSessionContext() { throw new IllegalStateException("should not be hit!"); } @Override public Object getValue(String arg0) { throw new IllegalStateException("should not be hit!"); } @Override public String[] getValueNames() { throw new IllegalStateException("should not be hit!"); } @Override public void invalidate() { throw new IllegalStateException("should not be hit!"); } @Override public boolean isNew() { throw new IllegalStateException("should not be hit!"); } @Override public void putValue(String arg0, Object arg1) { throw new IllegalStateException("should not be hit!"); } @Override public void removeAttribute(String arg0) { throw new IllegalStateException("should not be hit!"); } @Override public void removeValue(String arg0) { throw new IllegalStateException("should not be hit!"); } @Override public void setAttribute(String arg0, Object arg1) { throw new IllegalStateException("should not be hit!"); } }
2,308
21.637255
71
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/MockHttpSessionEvent.java
package edu.ncsu.csc.itrust.unit.serverutils; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; @SuppressWarnings("serial") public class MockHttpSessionEvent extends HttpSessionEvent { public MockHttpSessionEvent() { super(new MockHttpSession()); } @Override public HttpSession getSession() { return new MockHttpSession(); } }
372
20.941176
60
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/PateintSearchServletTest.java
package edu.ncsu.csc.itrust.unit.serverutils; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import edu.ncsu.csc.itrust.server.PatientSearchServlet; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; public class PateintSearchServletTest { private LittleDelegatorServlet subject; private HttpServletRequest request; private HttpServletResponse response; private TestDataGenerator gen = new TestDataGenerator(); @Before public void setUp() throws Exception { gen.clearAllTables(); gen.standardData(); subject = new LittleDelegatorServlet(); request = mock(HttpServletRequest.class); response = mock(HttpServletResponse.class); } @Test public void testDoGetAuditHttpServletRequestHttpServletResponse() { StringWriter s = new StringWriter(); PrintWriter p = new PrintWriter(s); when(request.getParameter("q")).thenReturn("Julia Roberts"); when(request.getParameter("isAudit")).thenReturn("true"); when(request.getParameter("forward")).thenReturn("hcp/auditPage.jsp"); try { when(response.getWriter()).thenReturn(p); } catch (IOException e1) { } try { subject.testDoGet(request, response); } catch (Exception e) { fail(); } assertTrue(s.toString().contains("Julia")); assertTrue(s.toString().contains("Roberts")); assertTrue(s.toString().contains("Action")); } @Test public void testEmptyAuditSearch() { StringWriter s = new StringWriter(); PrintWriter p = new PrintWriter(s); when(request.getParameter("q")).thenReturn(""); when(request.getParameter("isAudit")).thenReturn("true"); when(request.getParameter("allowDeactivated")).thenReturn("checked"); when(request.getParameter("forward")).thenReturn("hcp/auditPage.jsp"); try { when(response.getWriter()).thenReturn(p); } catch (IOException e1) { } try { subject.testDoGet(request, response); } catch (Exception e) { fail(); } assertTrue(s.toString().contains("Fake")); assertTrue(s.toString().contains("Baby")); } @Test public void testNonAuditSearch() { StringWriter s = new StringWriter(); PrintWriter p = new PrintWriter(s); when(request.getParameter("q")).thenReturn("Julia Roberts"); when(request.getParameter("isAudit")).thenReturn("false"); when(request.getParameter("allowDeactivated")).thenReturn(null); when(request.getParameter("forward")).thenReturn("hcp-uap/editPatient.jsp"); try { when(response.getWriter()).thenReturn(p); } catch (IOException e1) { } try { subject.testDoGet(request, response); } catch (Exception e) { fail(); } assertTrue(s.toString().contains("Julia")); assertTrue(s.toString().contains("Roberts")); assertTrue(!s.toString().contains("Action")); } private class LittleDelegatorServlet extends PatientSearchServlet { private static final long serialVersionUID = 1L; public LittleDelegatorServlet() { super(TestDAOFactory.getTestInstance()); } public void testDoGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } } }
3,446
28.461538
112
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/ProductionConnectionDriverTest.java
package edu.ncsu.csc.itrust.unit.serverutils; import static org.easymock.classextension.EasyMock.*; import java.sql.Connection; import javax.naming.InitialContext; import javax.sql.DataSource; import junit.framework.TestCase; import org.easymock.classextension.IMocksControl; import edu.ncsu.csc.itrust.model.old.dao.ProductionConnectionDriver; /** * * * */ public class ProductionConnectionDriverTest extends TestCase { // This class uses an advanced concept not taught in CSC326 at NCSU called // Mock Objects. // Feel free to take a look at how this works, but know that you will not // need to know mock objects // to do nearly everything in iTrust. Unless your assignment mentions mock // objects somewhere, you should // not need them. // // But, if you are interested in a cool unit testing concept, feel free to // look at this code as an // example. // // This class uses the EasyMock library to manage the mock objects. // http://easymock.org/ private IMocksControl ctrl; private InitialContext mockContext; private Connection mockConnection; private DataSource mockDataSource; @Override protected void setUp() throws Exception { ctrl = createControl(); mockContext = ctrl.createMock(InitialContext.class); mockConnection = ctrl.createMock(Connection.class); mockDataSource = ctrl.createMock(DataSource.class); } public void testProductionConnnectionDriver() throws Exception { ProductionConnectionDriver pcd = new ProductionConnectionDriver(mockContext); expect(mockContext.lookup("java:comp/env")).andReturn(mockContext).once(); expect(mockContext.lookup("jdbc/itrust")).andReturn(mockDataSource).once(); expect(mockDataSource.getConnection()).andReturn(mockConnection).once(); ctrl.replay(); assertSame(mockConnection, pcd.getConnection()); ctrl.verify(); } }
1,836
29.616667
79
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/SessionTimeoutListenerTest.java
package edu.ncsu.csc.itrust.unit.serverutils; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.verify; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import edu.ncsu.csc.itrust.server.SessionTimeoutListener; import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import junit.framework.TestCase; public class SessionTimeoutListenerTest extends TestCase { private TestDataGenerator gen; HttpSessionEvent mockSessionEvent; HttpSession mockSession; @Override protected void setUp() throws Exception { gen = new TestDataGenerator(); gen.timeout(); mockSessionEvent = mock(HttpSessionEvent.class); mockSession = mock(HttpSession.class); } // This uses a rudimentary mock object system - where we create these // objects that are // essentially stubs, except for keeping track of info passed to them. public void testListenerWorked() throws Exception { SessionTimeoutListener listener = new SessionTimeoutListener(TestDAOFactory.getTestInstance()); HttpSessionEvent event = new MockHttpSessionEvent(); listener.sessionCreated(event); assertEquals(1200, MockHttpSession.mins); } public void testSessionDestroyed() throws Exception { SessionTimeoutListener listener = new SessionTimeoutListener(TestDAOFactory.getTestInstance()); when(mockSessionEvent.getSession()).thenReturn(mockSession); when(mockSession.getAttribute("loggedInMID")).thenReturn(1L); listener.sessionDestroyed(mockSessionEvent); verify(mockSession).getAttribute("loggedInMID"); } public void testDBException() throws Exception { SessionTimeoutListener listener = new SessionTimeoutListener(); listener.sessionCreated(new MockHttpSessionEvent()); assertEquals(1200, MockHttpSession.mins); } }
1,882
33.87037
97
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/WardCRUDServletTest.java
package edu.ncsu.csc.itrust.unit.serverutils; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.classextension.EasyMock.createControl; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.easymock.classextension.IMocksControl; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.WardDAO; import edu.ncsu.csc.itrust.server.WardCRUDServlet; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; import junit.framework.TestCase; public class WardCRUDServletTest extends TestCase { protected WardDAO wardDAO = new WardDAO(DAOFactory.getProductionInstance()); private IMocksControl ctrl; private HttpServletRequest req; private HttpServletResponse resp; @Override protected void setUp() throws Exception { ctrl = createControl(); req = ctrl.createMock(HttpServletRequest.class); resp = ctrl.createMock(HttpServletResponse.class); } public void testWardCRUDServletPost() throws Exception, RuntimeException { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("requiredSpecialty")).andReturn("").once(); expect(req.getParameter("inHospital")).andReturn("1").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doPost(req, resp); } public void testWardCRUDServletPostFail() throws Exception, RuntimeException { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("requiredSpecialty")).andReturn("1").once(); expect(req.getParameter("inHospital")).andReturn("").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doPost(req, resp); } public void testWardCRUDServletPut() throws Exception, RuntimeException { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("wardID")).andReturn("1").once(); expect(req.getParameter("requiredSpecialty")).andReturn("").once(); expect(req.getParameter("inHospital")).andReturn("1").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doPut(req, resp); } public void testWardCRUDServletPutFail() throws Exception { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("wardID")).andReturn("").once(); expect(req.getParameter("requiredSpecialty")).andReturn("").once(); expect(req.getParameter("inHospital")).andReturn("1").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doPut(req, resp); } public void testWardCRUDServletDelete() throws Exception { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("wardID")).andReturn("1").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doDelete(req, resp); } public void testWardCRUDServletDeleteFail() throws Exception { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("wardID")).andReturn("").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doDelete(req, resp); } private class LittleDelegatorServlet extends WardCRUDServlet { private static final long serialVersionUID = -1256537436505857390L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { super.doPost(req, resp); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { super.doPut(req, resp); } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { super.doDelete(req, resp); } public void setUp() { wardDAO = new WardDAO(TestDAOFactory.getTestInstance()); } } }
3,979
28.924812
96
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/serverutils/WardRoomCRUDServletTest.java
package edu.ncsu.csc.itrust.unit.serverutils; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.classextension.EasyMock.createControl; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; import org.easymock.classextension.IMocksControl; import edu.ncsu.csc.itrust.model.old.dao.mysql.WardDAO; import edu.ncsu.csc.itrust.server.WardRoomCRUDServlet; import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory; /** * * */ public class WardRoomCRUDServletTest extends TestCase { private IMocksControl ctrl; private HttpServletRequest req; private HttpServletResponse resp; @Override protected void setUp() throws Exception { ctrl = createControl(); req = ctrl.createMock(HttpServletRequest.class); resp = ctrl.createMock(HttpServletResponse.class); } public void testWardRoomCRUDServletPost() throws Exception { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("inWard")).andReturn("1").once(); expect(req.getParameter("roomName")).andReturn("").once(); expect(req.getParameter("status")).andReturn("clean").once(); expect(req.getParameter("occupiedBy")).andReturn("1").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doPost(req, resp); } public void testWardRoomCRUDServletPut() throws Exception { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("inWard")).andReturn("1").once(); expect(req.getParameter("roomName")).andReturn("").once(); expect(req.getParameter("status")).andReturn("clean").once(); expect(req.getParameter("occupiedBy")).andReturn("1").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doPut(req, resp); } public void testWardRoomCRUDServletPutFail() throws Exception { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("inWard")).andReturn("").once(); expect(req.getParameter("roomName")).andReturn("").once(); expect(req.getParameter("status")).andReturn("clean").once(); expect(req.getParameter("occupiedBy")).andReturn("1").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doPut(req, resp); } public void testWardRoomCRUDServletDelete() throws Exception { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("roomID")).andReturn("1").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doDelete(req, resp); } public void testWardRoomCRUDServletDeleteFail() throws Exception { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("roomID")).andReturn("").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doDelete(req, resp); } public void testWardRoomCRUDServletFail() throws Exception { LittleDelegatorServlet servlet = new LittleDelegatorServlet(); servlet.setUp(); expect(req.getParameter("inWard")).andReturn("").once(); expect(req.getParameter("roomName")).andReturn("").once(); resp.sendRedirect(""); expectLastCall(); ctrl.replay(); servlet.doPost(req, resp); } private class LittleDelegatorServlet extends WardRoomCRUDServlet { private static final long serialVersionUID = -1256537436505857390L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { super.doPost(req, resp); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { super.doPut(req, resp); } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { super.doDelete(req, resp); } public void setUp() { wardDAO = new WardDAO(TestDAOFactory.getTestInstance()); } } }
4,057
27.377622
96
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/testutils/ActionTestWithMocks.java
package edu.ncsu.csc.itrust.unit.testutils; import static org.easymock.EasyMock.expect; import junit.framework.TestCase; import org.easymock.classextension.EasyMock; import org.easymock.classextension.IMocksControl; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AccessDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.AllergyDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.FakeEmailDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.FamilyDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.HospitalsDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.MessageDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.NDCodesDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.ReportRequestDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.TransactionDAO; /** * This class is used to create some of the basic mock objects for iTrust. This * keeps one control for all unit tests, then resets it for each usage. * * To use this class: * <ol> * <li>Extend this class instead of TestCase</li> * <li>Run initMocks in the setUp method</li> * <li>Use the mock objects as you wish. You don't need to worry about * factory.getDAO-type methods - those are set up to be expected a call any * number of times</li> * </ol> * * By default, control is set up to a "nice" control. * * Yes, everything in this class is protected static - which is not typically * desirable. However, this is a special test utility that takes advantage of * re-using mocks. Mock objects are created once and then reset every time * initMocks is used. This has a HUGE performance advantage as creating all of * these new Mocks takes 500ms, but resetting them takes 5ms. * * Meneely * */ abstract public class ActionTestWithMocks extends TestCase { protected static IMocksControl control; protected static DAOFactory factory; protected static AccessDAO accessDAO; protected static AllergyDAO allergyDAO; protected static AuthDAO authDAO; protected static FakeEmailDAO emailDAO; protected static FamilyDAO familyDAO; protected static HospitalsDAO hospitalDAO; protected static MessageDAO messageDAO; protected static NDCodesDAO ndDAO; protected static PatientDAO patientDAO; protected static PersonnelDAO personnelDAO; protected static ReportRequestDAO reportRequestDAO; protected static TransactionDAO transDAO; protected static void initMocks() { if (control == null) control = EasyMock.createNiceControl(); else control.reset(); createMocks(); createFactoryExpectations(); } private static void createMocks() { factory = control.createMock(DAOFactory.class); accessDAO = control.createMock(AccessDAO.class); allergyDAO = control.createMock(AllergyDAO.class); authDAO = control.createMock(AuthDAO.class); emailDAO = control.createMock(FakeEmailDAO.class); familyDAO = control.createMock(FamilyDAO.class); hospitalDAO = control.createMock(HospitalsDAO.class); messageDAO = control.createMock(MessageDAO.class); ndDAO = control.createMock(NDCodesDAO.class); patientDAO = control.createMock(PatientDAO.class); personnelDAO = control.createMock(PersonnelDAO.class); reportRequestDAO = control.createMock(ReportRequestDAO.class); transDAO = control.createMock(TransactionDAO.class); } private static void createFactoryExpectations() { expect(factory.getAccessDAO()).andReturn(accessDAO).anyTimes(); expect(factory.getAllergyDAO()).andReturn(allergyDAO).anyTimes(); expect(factory.getAuthDAO()).andReturn(authDAO).anyTimes(); expect(factory.getFakeEmailDAO()).andReturn(emailDAO).anyTimes(); expect(factory.getFamilyDAO()).andReturn(familyDAO).anyTimes(); expect(factory.getHospitalsDAO()).andReturn(hospitalDAO).anyTimes(); expect(factory.getMessageDAO()).andReturn(messageDAO).anyTimes(); expect(factory.getNDCodesDAO()).andReturn(ndDAO).anyTimes(); expect(factory.getPatientDAO()).andReturn(patientDAO).anyTimes(); expect(factory.getPersonnelDAO()).andReturn(personnelDAO).anyTimes(); expect(factory.getReportRequestDAO()).andReturn(reportRequestDAO).anyTimes(); expect(factory.getTransactionDAO()).andReturn(transDAO).anyTimes(); } }
4,347
41.213592
79
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/testutils/BadBean.java
package edu.ncsu.csc.itrust.unit.testutils; public class BadBean { // To make the coverage work... public BadBean() { setThing(5); setThing(""); } public void setThing(String str) { } public void setThing(Integer str) { } }
238
13.9375
43
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/testutils/EvilDAOFactory.java
package edu.ncsu.csc.itrust.unit.testutils; import java.sql.Connection; import java.sql.SQLException; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.IConnectionDriver; /** * This class is an "evil" (or Diabolical) test connection driver that will not * give you a connection, but instead will throw a special SQLException every * time. Unit tests need to test this catch block and assert the SQLException * message. <br /> * <br /> * It's implemented as a singleton to make unit tests easier (just a pointer * comparison) * * * */ public class EvilDAOFactory extends DAOFactory implements IConnectionDriver { public static final String MESSAGE = "Exception thrown from Evil Test Connection Driver"; private static DAOFactory evilTestInstance; public static DAOFactory getEvilInstance() { if (evilTestInstance == null) evilTestInstance = new EvilDAOFactory(); return evilTestInstance; } private DAOFactory driver = null; private int numCorrect = 0; public EvilDAOFactory() { } // Here's how this behavior works: you can set EvilDAOFactory to count down // to 0, giving correct // connections the whole way. Then, when you want it to, it starts throwing // exceptions public EvilDAOFactory(int numCorrect) { this.driver = TestDAOFactory.getTestInstance(); this.numCorrect = numCorrect; } @Override public Connection getConnection() throws SQLException { if (numCorrect-- > 0) // check THEN decrement return driver.getConnection(); else throw new SQLException(MESSAGE); } }
1,578
28.240741
90
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/testutils/JUnitiTrustUtils.java
package edu.ncsu.csc.itrust.unit.testutils; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.TransactionBean; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.selenium.iTrustSeleniumTest; public class JUnitiTrustUtils extends iTrustSeleniumTest { public static void assertTransactionOnly(TransactionType transType, long loggedInMID, long secondaryMID, String addedInfo) throws DBException { List<TransactionBean> transList = TestDAOFactory.getTestInstance().getTransactionDAO().getAllTransactions(); assertEquals("Only one transaction should have been logged", 1, transList.size()); assertTransaction(transType, loggedInMID, secondaryMID, addedInfo, transList.get(0)); } public static void assertLogged(TransactionType code, long loggedInMID, long secondaryMID, String addedInfo) throws DBException { List<TransactionBean> transList = TestDAOFactory.getTestInstance().getTransactionDAO().getAllTransactions(); TransactionBean lastRecordedAction = transList.get(0); assertTrue(lastRecordedAction.getTransactionType() == code); assertTrue(lastRecordedAction.getLoggedInMID() == loggedInMID); assertTrue(lastRecordedAction.getSecondaryMID() == secondaryMID); assertTrue(lastRecordedAction.getAddedInfo().equals(addedInfo)); } public static void assertTransactionsNone() throws DBException { assertEquals("No transactions should have been logged", 0, TestDAOFactory.getTestInstance().getTransactionDAO().getAllTransactions().size()); } private static void assertTransaction(TransactionType transType, long loggedInMID, long secondaryMID, String addedInfo, TransactionBean trans) { assertEquals(transType, trans.getTransactionType()); assertEquals(loggedInMID, trans.getLoggedInMID()); assertEquals(secondaryMID, trans.getSecondaryMID()); assertEquals(addedInfo, trans.getAddedInfo()); } public void testNull() { assert (true); } }
1,994
41.446809
110
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/testutils/OkayBean.java
package edu.ncsu.csc.itrust.unit.testutils; public class OkayBean { private String thing; public OkayBean() { setThing(""); } public String getThing() { return thing; } public void setThing(String thing) { this.thing = thing; } @Override public boolean equals(Object obj) { return obj != null && obj.getClass().equals(this.getClass()) && this.equals((OkayBean) obj); } @Override public int hashCode() { return 42; // any arbitrary constant will do } private boolean equals(OkayBean other) { return true; } }
543
15.484848
94
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/testutils/SQLFileCache.java
package edu.ncsu.csc.itrust.unit.testutils; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class SQLFileCache { private static SQLFileCache instance; public static SQLFileCache getInstance() { if (instance == null) instance = new SQLFileCache(); return instance; } private HashMap<String, List<String>> cache = new HashMap<String, List<String>>(100); private SQLFileCache() { } public List<String> getQueries(String fileName) throws FileNotFoundException, IOException { List<String> queries = cache.get(fileName); if (queries != null) return queries; else return parseAndCache(fileName); } private List<String> parseAndCache(String fileName) throws FileNotFoundException, IOException { List<String> queries = parseSQLFile(fileName); cache.put(fileName, queries); return queries; } private List<String> parseSQLFile(String filepath) throws FileNotFoundException, IOException { List<String> queries = new ArrayList<String>(); BufferedReader reader = null; FileReader fileReader = null; try{ fileReader = new FileReader(new File(filepath)); reader =new BufferedReader(fileReader); String line = ""; String currentQuery = ""; // ToDo either add functionality to accomodate triggers, or remove it // char delimiter = ';'; while ((line = reader.readLine()) != null) { for (int i = 0; i < line.length(); i++) { // if(currentQuery.isEmpty()){ // if(line.split(" ",2)[0].toLowerCase().equals("delimiter")){ // } // } if (line.charAt(i) == ';') { queries.add(currentQuery); currentQuery = ""; } else currentQuery += line.charAt(i); } } } finally{ try{ if(!(fileReader == null)) fileReader.close(); } finally{ if(!(reader==null)) reader.close(); } } return queries; } }
2,004
24.379747
96
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/testutils/TestBean.java
package edu.ncsu.csc.itrust.unit.testutils; public class TestBean { // Empty class isn't used at all - this is just used as a test hook into // testing BeanValidator. public TestBean() { } }
196
20.888889
73
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/testutils/TestDAOFactory.java
package edu.ncsu.csc.itrust.unit.testutils; import java.io.BufferedReader; import java.io.FileReader; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.w3c.dom.Document; import org.xml.sax.InputSource; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.IConnectionDriver; /** * This class pulls the JDBC driver information from Tomcat's context.xml file * in WebRoot/META-INF/context.xml. This is done only for convenience - so that * you only have to pull your JDBC info from one place (context.xml)<br /> * <br /> * The tangled mess you see here is SAX, the XML-parser and XPath, an XML * querying language. Note that this class is only ever constructed once since * DAOFactory only constructs up to 2 instances of itself.<br /> * <br /> * Also, you'll notice that we're using a "BasicDataSource" to obtain * connections instead of the usual DriverManager. That's because we're using * Tomcat's built-in database pooling mechanism. It's purely for performance in * this case. */ public class TestDAOFactory extends DAOFactory implements IConnectionDriver { private static DAOFactory testInstance; public static DAOFactory getTestInstance() { if (testInstance == null) testInstance = new TestDAOFactory(); return testInstance; } private BasicDataSource dataSource; private TestDAOFactory() { try { Document document = parseXML(new BufferedReader(new FileReader("WebRoot/META-INF/context.xml"))); dataSource = new BasicDataSource(); dataSource.setDriverClassName(getAttribute(document, "@driverClassName")); dataSource.setUsername(getAttribute(document, "@username")); dataSource.setPassword(getAttribute(document, "@password")); dataSource.setUrl(getAttribute(document, "@url")); dataSource.setMaxTotal(3); // only allow three connections open at // a time dataSource.setMaxWaitMillis(250); // wait 250ms until throwing an // exception dataSource.setPoolPreparedStatements(true); } catch (Exception e) { e.printStackTrace(); } } private String getAttribute(Document document, String attribute) throws XPathExpressionException { return (String) XPathFactory.newInstance().newXPath().compile("/Context/Resource/" + attribute) .evaluate(document.getDocumentElement(), XPathConstants.STRING); } private Document parseXML(BufferedReader reader) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(reader)); } @Override public Connection getConnection() throws SQLException { return dataSource.getConnection(); } public DataSource getDataSource() { return dataSource; } }
3,110
35.174419
100
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/testutils/ValidatorProxy.java
package edu.ncsu.csc.itrust.unit.testutils; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.enums.Gender; import edu.ncsu.csc.itrust.model.old.validate.BeanValidator; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; public class ValidatorProxy extends BeanValidator<TestBean> { @Override public String checkFormat(String name, Long value, ValidationFormat format, boolean isNullable) { return super.checkFormat(name, value, format, isNullable); } @Override public String checkFormat(String name, String value, ValidationFormat format, boolean isNullable) { return super.checkFormat(name, value, format, isNullable); } @Override public String checkGender(String name, Gender gen, ValidationFormat format, boolean isNullable) { return super.checkGender(name, gen, format, isNullable); } @Override public String checkInt(String name, String value, int lower, int upper, boolean isNullable) { return super.checkInt(name, value, lower, upper, isNullable); } @Override public String checkDouble(String name, String value, double lower, double upper) { return super.checkDouble(name, value, lower, upper); } @Override public void validate(TestBean bean) throws FormValidationException { throw new IllegalStateException( "Mock object acts as a proxy to protected BeanValidator classes. Do not call this method"); } }
1,417
33.585366
100
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/BeanValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.enums.Gender; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class BeanValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); public void testCheckIsNullable() throws Exception { String value = null; String errorMessage = ""; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.NAME, true)); } public void testCheckIsNullableEmpty() throws Exception { String value = ""; String errorMessage = ""; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.NAME, true)); } public void testCheckLongValues() throws Exception { Long value = 80L; String errorMessage = ""; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.MID, true)); } public void testProxyIsOnlyProxy() throws Exception { try { validatorProxy.validate(null); fail("exception should have been thrown"); } catch (IllegalStateException e) { assertEquals("Mock object acts as a proxy to protected BeanValidator classes. Do not call this method", e.getMessage()); } } public void testCheckGender() { assertEquals("", validatorProxy.checkGender("Gender", Gender.Male, ValidationFormat.GENDERCOD, true)); } public void testCheckGenderNull() { assertEquals("", validatorProxy.checkGender("Gender", null, ValidationFormat.GENDERCOD, true)); } /** * Test method to see if colon is accepted in notes. */ public void testCheckFormatStringStringValidationFormatBoolean() { assertEquals("", validatorProxy.checkFormat("Notes", "Updated Notes:", ValidationFormat.NOTES, true)); } public void testDoubleValues() throws Exception { assertEquals("Test must be a decimal in [1.0,2.0)", validatorProxy.checkDouble("Test", "0", 1L, 2L)); } public void testCheckInt() { assertEquals("", validatorProxy.checkInt("null", null, 0, 1, true)); } public void testCheckDouble() { assertEquals("", validatorProxy.checkDouble("double", "1.5", 1, 2)); assertEquals("double must be a decimal in [1.0,2.0)", validatorProxy.checkDouble("double", "bad", 1, 2)); } }
2,318
33.61194
107
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/TestMailValidator.java
package edu.ncsu.csc.itrust.unit.validate; import edu.ncsu.csc.itrust.model.old.validate.MailValidator; import junit.framework.TestCase; public class TestMailValidator extends TestCase { private MailValidator val = new MailValidator(); @Override public void setUp() throws Exception { } public void testValidateEmail() throws Exception { String value = "google@google.com"; assertEquals(true, val.validateEmail(value)); String value2 = "google google"; assertEquals(false, val.validateEmail(value2)); String value3 = "google?google.com"; assertEquals(false, val.validateEmail(value3)); String value4 = "googlegooglegooglegoogle@google.com"; assertEquals(true, val.validateEmail(value4)); } @Override public void tearDown() throws Exception { } }
780
25.033333
60
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/bean/AddPatientValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.bean; import junit.framework.TestCase; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.validate.AddPatientValidator; import edu.ncsu.csc.itrust.model.old.validate.MailValidator; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; public class AddPatientValidatorTest extends TestCase { public void testPatientAllCorrect() throws Exception { PatientBean p = new PatientBean(); p.setFirstName("Person'a"); p.setLastName("LastName"); p.setEmail("andy.programmer@gmail.com"); new AddPatientValidator().validate(p); } public void testPatientAllErrors() throws Exception { MailValidator val = new MailValidator(); PatientBean p = new PatientBean(); p.setFirstName("Person5"); p.setLastName("LastName5"); p.setEmail("andy.programmer?gmail.com"); try { new AddPatientValidator().validate(p); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals("First name: " + ValidationFormat.NAME.getDescription(), e.getErrorList().get(0)); assertEquals("Last name: " + ValidationFormat.NAME.getDescription(), e.getErrorList().get(1)); assertEquals(false, val.validateEmail("andy.programmer?gmail.com")); assertEquals("number of errors", 3, e.getErrorList().size()); } } }
1,406
37.027027
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/bean/AddPersonnelValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.bean; import junit.framework.TestCase; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.validate.AddPersonnelValidator; import edu.ncsu.csc.itrust.model.old.validate.MailValidator; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; public class AddPersonnelValidatorTest extends TestCase { public void testPatientAllCorrect() throws Exception { PersonnelBean p = new PersonnelBean(); p.setFirstName("Person'a"); p.setLastName("LastName"); p.setEmail("andy.programmer@gmail.com"); new AddPersonnelValidator().validate(p); } public void testPatientAllErrors() throws Exception { MailValidator val = new MailValidator(); PersonnelBean p = new PersonnelBean(); p.setFirstName("Person5"); p.setLastName("LastName5"); p.setEmail("andy.programmer?gmail.com"); try { new AddPersonnelValidator().validate(p); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals("First name: " + ValidationFormat.NAME.getDescription(), e.getErrorList().get(0)); assertEquals("Last name: " + ValidationFormat.NAME.getDescription(), e.getErrorList().get(1)); assertEquals(false, val.validateEmail("andy.programmer?gmail.com")); assertEquals("number of errors", 3, e.getErrorList().size()); } } }
1,423
38.555556
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/bean/AllergyBeanValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.bean; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.AllergyBean; import edu.ncsu.csc.itrust.model.old.validate.AllergyBeanValidator; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import junit.framework.TestCase; public class AllergyBeanValidatorTest extends TestCase { public void testCorrectFormat() throws Exception { AllergyBean ab = new AllergyBean(); ab.setDescription("Correct format"); new AllergyBeanValidator().validate(ab); } public void testWrongFormat() throws Exception { AllergyBean ab = new AllergyBean(); ab.setDescription(">"); try { new AllergyBeanValidator().validate(ab); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals(1, e.getErrorList().size()); assertEquals("Allergy Description: " + ValidationFormat.ALLERGY_DESCRIPTION.getDescription(), e.getErrorList().get(0)); } } }
1,001
32.4
96
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/bean/HospitalBeanValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.bean; import junit.framework.TestCase; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.validate.BeanValidator; import edu.ncsu.csc.itrust.model.old.validate.HospitalBeanValidator; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; public class HospitalBeanValidatorTest extends TestCase { private BeanValidator<HospitalBean> validator = new HospitalBeanValidator(); public void testAllCorrect() throws Exception { HospitalBean h = new HospitalBean(); h.setHospitalName("Sta. Maria's Children Hospital"); h.setHospitalID("1234567890"); validator.validate(h); } public void testHospitalAllErrors() throws Exception { HospitalBean h = new HospitalBean(); h.setHospitalName("A Hospital!"); h.setHospitalID("-1"); h.setHospitalAddress( "1000 Toooooooooooooooooo Manyyyyyyyyyyyyyyyyyy Charsssssssssssssssss Streetttttttttttttttt"); h.setHospitalCity("Longggggggggggggggggggggggg Nameeeeeeeeeeeeeeeeeeeeeeeee Cityyyyyyyyyyyyyyyyy"); h.setHospitalState("Zx"); h.setHospitalZip("2-304-22-"); try { validator.validate(h); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals("Hospital ID: " + ValidationFormat.HOSPITAL_ID.getDescription(), e.getErrorList().get(0)); assertEquals("Hospital Name: " + ValidationFormat.HOSPITAL_NAME.getDescription(), e.getErrorList().get(1)); assertEquals("Hospital Address: " + ValidationFormat.ADDRESS.getDescription(), e.getErrorList().get(2)); assertEquals("Hospital City: " + ValidationFormat.CITY.getDescription(), e.getErrorList().get(3)); assertEquals("Hospital State: " + ValidationFormat.STATE.getDescription(), e.getErrorList().get(4)); assertEquals("Hospital Zip: " + ValidationFormat.ZIPCODE.getDescription(), e.getErrorList().get(5)); assertEquals("number of errors", 6, e.getErrorList().size()); } } }
2,010
45.767442
110
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/bean/MedicationBeanValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.bean; import junit.framework.TestCase; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.MedicationBean; import edu.ncsu.csc.itrust.model.old.validate.BeanValidator; import edu.ncsu.csc.itrust.model.old.validate.MedicationBeanValidator; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; public class MedicationBeanValidatorTest extends TestCase { private BeanValidator<MedicationBean> validator = new MedicationBeanValidator(); public void testAllCorrect() throws Exception { MedicationBean d = new MedicationBean(); d.setDescription("A description"); d.setNDCode("52563"); validator.validate(d); } public void testPatientAllErrors() throws Exception { MedicationBean d = new MedicationBean(); d.setDescription("An description!"); d.setNDCode("-1"); try { validator.validate(d); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals("ND Code: " + ValidationFormat.ND.getDescription(), e.getErrorList().get(0)); assertEquals("Description: " + ValidationFormat.ND_CODE_DESCRIPTION.getDescription(), e.getErrorList().get(1)); assertEquals("number of errors", 2, e.getErrorList().size()); } } }
1,291
35.914286
93
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/bean/PatientValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.bean; import junit.framework.TestCase; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.validate.MailValidator; import edu.ncsu.csc.itrust.model.old.validate.PatientValidator; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; /** * PatientValidatorTest */ public class PatientValidatorTest extends TestCase { MailValidator val = new MailValidator(); /** * testPatientAllCorrect * * @throws Exception */ public void testPatientAllCorrect() throws Exception { PatientBean p = new PatientBean(); p.setFirstName("Person'a"); p.setLastName("LastName"); p.setDateOfBirthStr("10/10/2005"); p.setDateOfDeathStr(""); p.setCauseOfDeath(""); p.setEmail("andy.programmer@gmail.com"); p.setSecurityQuestion("'What is your quest?'-"); p.setSecurityAnswer("I s33k the holy grail"); p.setStreetAddress1("344 East Random Ave."); p.setStreetAddress2(""); p.setCity("Intercourse"); p.setState("PA"); p.setZip("17534"); p.setPhone("555-542-9023"); p.setEmergencyName("Tow Mater"); p.setEmergencyPhone("809-940-1943"); p.setIcName("Dewie Cheatum n Howe"); p.setIcAddress1("458 Ripoff Blvd."); p.setIcAddress2("Greedy Suite"); p.setIcCity("Hell"); p.setIcState("MI"); p.setIcZip("48169-0000"); p.setIcPhone("666-059-4023"); p.setIcID("Money"); p.setMotherMID("58"); p.setFatherMID("0"); p.setBloodTypeStr("O-"); p.setEthnicityStr("Caucasian"); p.setGenderStr("Male"); p.setTopicalNotes("Here are some random topical notes. Isn't there more? Yes.\n There is."); p.setPassword("testpass1"); p.setConfirmPassword("testpass1"); new PatientValidator().validate(p); } /** * testPatientAllErrors * * @throws Exception */ public void testPatientAllErrors() throws Exception { PatientBean p = new PatientBean(); p.setFirstName("Person5"); p.setLastName("LastName5"); p.setDateOfBirthStr("10/ 10/2005"); p.setDateOfDeathStr("05-19-1984"); p.setCauseOfDeath("Q150"); p.setEmail("andy.programmer?gmail.com"); p.setStreetAddress1("344 East < Ave."); p.setStreetAddress2("?"); p.setCity("Wr0ng"); p.setState("Pa"); p.setZip("17534-"); p.setPhone("555"); p.setEmergencyName("Tow #ater"); p.setEmergencyPhone("(809)"); p.setIcName("Dewie Che@tum and Howe the 2nd"); p.setIcAddress1("458 Ripoff Blvd?"); p.setIcAddress2("Greedy Suite "); p.setIcCity("%"); p.setIcState("mI"); p.setIcZip("48169-0000 "); p.setIcPhone(" 666-059-4023 "); p.setIcID("$$"); p.setMotherMID("-1"); p.setFatherMID("-2"); p.setBloodTypeStr("AB"); p.setEthnicityStr("Caucasion"); p.setGenderStr("female"); p.setTopicalNotes("<script>alert('hello');</script>"); p.setPassword("toooooooooooooooooooooooooo long password"); p.setPassword("toooooooooooooooooooooooooo long password"); try { new PatientValidator().validate(p); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals("First name: " + ValidationFormat.NAME.getDescription(), e.getErrorList().get(0)); assertEquals("Last name: " + ValidationFormat.NAME.getDescription(), e.getErrorList().get(1)); assertEquals("Date of Birth: MM/DD/YYYY", e.getErrorList().get(3)); assertEquals("Date of Death: MM/DD/YYYY", e.getErrorList().get(4)); assertEquals("Cause of Death cannot be specified without Date of Death!", e.getErrorList().get(5)); assertEquals("Cause of Death: xxx.xx", e.getErrorList().get(6)); assertEquals(false, val.validateEmail("andy.programmer?gmail.com")); assertEquals("Street Address 1: " + ValidationFormat.ADDRESS.getDescription(), e.getErrorList().get(7)); assertEquals("Street Address 2: " + ValidationFormat.ADDRESS.getDescription(), e.getErrorList().get(8)); assertEquals("City: " + ValidationFormat.CITY.getDescription(), e.getErrorList().get(9)); assertEquals("State: " + ValidationFormat.STATE.getDescription(), e.getErrorList().get(10)); assertEquals("Zip Code: " + ValidationFormat.ZIPCODE.getDescription(), e.getErrorList().get(11)); assertEquals("Phone Number: " + ValidationFormat.PHONE_NUMBER.getDescription(), e.getErrorList().get(12)); assertEquals("Emergency Contact Name: " + ValidationFormat.NAME.getDescription(), e.getErrorList().get(13)); assertEquals("Emergency Contact Phone: " + ValidationFormat.PHONE_NUMBER.getDescription(), e.getErrorList().get(14)); assertEquals("Insurance Company Name: " + ValidationFormat.NAME.getDescription(), e.getErrorList().get(15)); assertEquals("Insurance Company Address 1: " + ValidationFormat.ADDRESS.getDescription(), e.getErrorList().get(16)); assertEquals("Insurance Company Address 2: " + ValidationFormat.ADDRESS.getDescription(), e.getErrorList().get(17)); assertEquals("Insurance Company City: " + ValidationFormat.CITY.getDescription(), e.getErrorList().get(18)); assertEquals("Insurance Company State: " + ValidationFormat.STATE.getDescription(), e.getErrorList().get(19)); assertEquals("Insurance Company Zip: " + ValidationFormat.ZIPCODE.getDescription(), e.getErrorList().get(20)); assertEquals("Insurance Company Phone: " + ValidationFormat.PHONE_NUMBER.getDescription(), e.getErrorList().get(21)); assertEquals("Insurance Company ID: " + ValidationFormat.INSURANCE_ID.getDescription(), e.getErrorList().get(22)); assertEquals("Mother MID: " + ValidationFormat.NPMID.getDescription(), e.getErrorList().get(23)); assertEquals("Father MID: " + ValidationFormat.NPMID.getDescription(), e.getErrorList().get(24)); assertEquals("Topical Notes: " + ValidationFormat.NOTES.getDescription(), e.getErrorList().get(25)); assertEquals("number of errors", 26, e.getErrorList().size()); } } /** * testFutureBirthError */ public void testFutureBirthError() { PatientBean p = new PatientBean(); p.setFirstName("Person5"); p.setLastName("LastName5"); p.setDateOfBirthStr("10/10/3000"); p.setDateOfDeathStr(""); p.setCauseOfDeath(""); p.setEmail("andy.programmer?gmail.com"); p.setStreetAddress1("344 East < Ave."); p.setStreetAddress2("?"); p.setCity("Wr0ng"); p.setState("Pa"); p.setZip("17534-"); p.setPhone("555"); p.setEmergencyName("Tow #ater"); p.setEmergencyPhone("(809)"); p.setIcName("Dewie Che@tum and Howe the 2nd"); p.setIcAddress1("458 Ripoff Blvd?"); p.setIcAddress2("Greedy Suite "); p.setIcCity("%"); p.setIcState("mI"); p.setIcZip("48169-0000 "); p.setIcPhone(" 666-059-4023 "); p.setIcID("$$"); p.setMotherMID("-1"); p.setFatherMID("-2"); p.setBloodTypeStr("AB"); p.setEthnicityStr("Caucasion"); p.setGenderStr("female"); p.setTopicalNotes("<script>alert('hello');</script>"); p.setPassword("toooooooooooooooooooooooooo long password"); p.setPassword("toooooooooooooooooooooooooo long password"); try { new PatientValidator().validate(p); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals("Birth date cannot be in the future!", e.getErrorList().get(3)); } } /** * testCauseOfDeathValidation */ public void testCauseOfDeathValidation() { PatientBean p = new PatientBean(); p.setFirstName("Person5"); p.setLastName("LastName5"); p.setDateOfBirthStr("10/10/2000"); p.setDateOfDeathStr(""); p.setCauseOfDeath("Q150"); p.setEmail("andy.programmer?gmail.com"); p.setStreetAddress1("344 East < Ave."); p.setStreetAddress2("?"); p.setCity("Wr0ng"); p.setState("Pa"); p.setZip("17534-"); p.setPhone("555"); p.setEmergencyName("Tow #ater"); p.setEmergencyPhone("(809)"); p.setIcName("Dewie Che@tum and Howe the 2nd"); p.setIcAddress1("458 Ripoff Blvd?"); p.setIcAddress2("Greedy Suite "); p.setIcCity("%"); p.setIcState("mI"); p.setIcZip("48169-0000 "); p.setIcPhone(" 666-059-4023 "); p.setIcID("$$"); p.setMotherMID("-1"); p.setFatherMID("-2"); p.setBloodTypeStr("AB"); p.setEthnicityStr("Caucasion"); p.setGenderStr("female"); p.setTopicalNotes("<script>alert('hello');</script>"); p.setPassword("toooooooooooooooooooooooooo long password"); p.setPassword("toooooooooooooooooooooooooo long password"); try { new PatientValidator().validate(p); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals("Cause of Death cannot be specified without Date of Death!", e.getErrorList().get(3)); } } /* * JUnit test for bug #2 on the bug list */ /** * testPatientTopicalNoteWithQUotationMark * * @throws Exception */ public void testPatientTopicalNoteWithQuotationMark() throws Exception { PatientBean p = new PatientBean(); p.setFirstName("Person'a"); p.setLastName("LastName"); p.setDateOfBirthStr("10/10/2005"); p.setDateOfDeathStr(""); p.setCauseOfDeath(""); p.setEmail("andy.programmer@gmail.com"); p.setSecurityQuestion("'What is your quest?'-"); p.setSecurityAnswer("I s33k the holy grail"); p.setStreetAddress1("344 East Random Ave."); p.setStreetAddress2(""); p.setCity("Intercourse"); p.setState("PA"); p.setZip("17534"); p.setPhone("555-542-9023"); p.setEmergencyName("Tow Mater"); p.setEmergencyPhone("809-940-1943"); p.setIcName("Dewie Cheatum n Howe"); p.setIcAddress1("458 Ripoff Blvd."); p.setIcAddress2("Greedy Suite"); p.setIcCity("Hell"); p.setIcState("MI"); p.setIcZip("48169-0000"); p.setIcPhone("666-059-4023"); p.setIcID("Money"); p.setMotherMID("58"); p.setFatherMID("0"); p.setBloodTypeStr("O-"); p.setEthnicityStr("Caucasian"); p.setGenderStr("Male"); p.setTopicalNotes("Here are some random topical notes. \" Isn't there more? Yes.\n There is."); p.setPassword("testpass1"); p.setConfirmPassword("testpass1"); new PatientValidator().validate(p); } /* * Test for threat model - Last name too long. */ /** * testPatientWithLongLastName * * @throws Exception */ public void testPatientWithLongLastName() throws Exception { PatientBean p = new PatientBean(); p.setFirstName("Person'a"); p.setLastName("MyLastNameIsReallySuperDuperLoooooooong"); p.setDateOfBirthStr("10/10/2005"); p.setDateOfDeathStr(""); p.setCauseOfDeath(""); p.setEmail("andy.programmer@gmail.com"); p.setSecurityQuestion("'What is your quest?'-"); p.setSecurityAnswer("I s33k the holy grail"); p.setStreetAddress1("344 East Random Ave."); p.setStreetAddress2(""); p.setCity("Intercourse"); p.setState("PA"); p.setZip("17534"); p.setPhone("555-542-9023"); p.setEmergencyName("Tow Mater"); p.setEmergencyPhone("809-940-1943"); p.setIcName("Dewie Cheatum n Howe"); p.setIcAddress1("458 Ripoff Blvd."); p.setIcAddress2("Greedy Suite"); p.setIcCity("Hell"); p.setIcState("MI"); p.setIcZip("48169-0000"); p.setIcPhone("666-059-4023"); p.setIcID("Money"); p.setMotherMID("58"); p.setFatherMID("0"); p.setBloodTypeStr("O-"); p.setEthnicityStr("Caucasian"); p.setGenderStr("Male"); p.setTopicalNotes("Here are some random topical notes. \" Isn't there more? Yes.\n There is."); p.setPassword("testpass1"); p.setConfirmPassword("testpass1"); try { new PatientValidator().validate(p); fail(); } catch (FormValidationException e) { assertEquals("This form has not been validated correctly. The following field are not " + "properly filled in: [Last name: Up to 20 Letters, space, ' and -]", e.getMessage()); } } /** * testPatientWithValidCardNumbers * * @throws Exception */ public void testPatientWithValidCardNumbers() throws Exception { PatientBean p = new PatientBean(); p.setFirstName("Person'a"); p.setLastName("MyLastNameIsOK"); p.setDateOfBirthStr("10/10/2005"); p.setDateOfDeathStr(""); p.setCauseOfDeath(""); p.setEmail("andy.programmer@gmail.com"); p.setSecurityQuestion("'What is your quest?'-"); p.setSecurityAnswer("I s33k the holy grail"); p.setStreetAddress1("344 East Random Ave."); p.setStreetAddress2(""); p.setCity("Intercourse"); p.setState("PA"); p.setZip("17534"); p.setPhone("555-542-9023"); p.setEmergencyName("Tow Mater"); p.setEmergencyPhone("809-940-1943"); p.setIcName("Dewie Cheatum n Howe"); p.setIcAddress1("458 Ripoff Blvd."); p.setIcAddress2("Greedy Suite"); p.setIcCity("Hell"); p.setIcState("MI"); p.setIcZip("48169-0000"); p.setIcPhone("666-059-4023"); p.setIcID("Money"); p.setMotherMID("58"); p.setFatherMID("0"); p.setBloodTypeStr("O-"); p.setEthnicityStr("Caucasian"); p.setGenderStr("Male"); p.setTopicalNotes("Here are some random topical notes. \" Isn't there more? Yes.\n There is."); p.setPassword("testpass1"); p.setConfirmPassword("testpass1"); PatientValidator pv = new PatientValidator(); p.setCreditCardType("MASTERCARD"); p.setCreditCardNumber("5593090746812380"); pv.validate(p); p.setCreditCardType("VISA"); p.setCreditCardNumber("4539592576502361"); pv.validate(p); p.setCreditCardType("AMEX"); p.setCreditCardNumber("344558915054011"); pv.validate(p); p.setCreditCardType("DISCOVER"); p.setCreditCardNumber("6011953266156193"); pv.validate(p); } /** * testPatientWithBadCardNumbers * * @throws Exception */ public void testPatientWithBadCardNumbers() throws Exception { PatientBean p = new PatientBean(); p.setFirstName("Person'a"); p.setLastName("MyLastNameIsOK"); p.setDateOfBirthStr("10/10/2005"); p.setDateOfDeathStr(""); p.setCauseOfDeath(""); p.setEmail("andy.programmer@gmail.com"); p.setSecurityQuestion("'What is your quest?'-"); p.setSecurityAnswer("I s33k the holy grail"); p.setStreetAddress1("344 East Random Ave."); p.setStreetAddress2(""); p.setCity("Intercourse"); p.setState("PA"); p.setZip("17534"); p.setPhone("555-542-9023"); p.setEmergencyName("Tow Mater"); p.setEmergencyPhone("809-940-1943"); p.setIcName("Dewie Cheatum n Howe"); p.setIcAddress1("458 Ripoff Blvd."); p.setIcAddress2("Greedy Suite"); p.setIcCity("Hell"); p.setIcState("MI"); p.setIcZip("48169-0000"); p.setIcPhone("666-059-4023"); p.setIcID("Money"); p.setMotherMID("58"); p.setFatherMID("0"); p.setBloodTypeStr("O-"); p.setEthnicityStr("Caucasian"); p.setGenderStr("Male"); p.setTopicalNotes("Here are some random topical notes. \" Isn't there more? Yes.\n There is."); p.setPassword("testpass1"); p.setConfirmPassword("testpass1"); PatientValidator pv = new PatientValidator(); try { p.setCreditCardType("VISA"); p.setCreditCardNumber("5593090746812380"); pv.validate(p); fail("Invalid card number should have thrown exception"); } catch (Exception e) { // TODO } try { p.setCreditCardType("MASTERCARD"); p.setCreditCardNumber("4539592576502361"); pv.validate(p); fail("Invalid card number should have thrown exception"); } catch (Exception e) { // TODO } try { p.setCreditCardType("DISCOVER"); p.setCreditCardNumber("344558915054011"); pv.validate(p); fail("Invalid card number should have thrown exception"); } catch (Exception e) { // TODO } try { p.setCreditCardType("AMEX"); p.setCreditCardNumber("6011953266156193"); pv.validate(p); fail("Invalid card number should have thrown exception"); } catch (Exception e) { // TODO } } /** * testMFWithPersonnelMID * * @throws Exception */ public void testMFWithPersonnelMID() throws Exception { PatientBean p = new PatientBean(); p.setFirstName("Person'a"); p.setLastName("LastName"); p.setDateOfBirthStr("10/10/2005"); p.setDateOfDeathStr(""); p.setCauseOfDeath(""); p.setEmail("andy.programmer@gmail.com"); p.setSecurityQuestion("'What is your quest?'-"); p.setSecurityAnswer("I s33k the holy grail"); p.setStreetAddress1("344 East Random Ave."); p.setStreetAddress2(""); p.setCity("Intercourse"); p.setState("PA"); p.setZip("17534"); p.setPhone("555-542-9023"); p.setEmergencyName("Tow Mater"); p.setEmergencyPhone("809-940-1943"); p.setIcName("Dewie Cheatum n Howe"); p.setIcAddress1("458 Ripoff Blvd."); p.setIcAddress2("Greedy Suite"); p.setIcCity("Hell"); p.setIcState("MI"); p.setIcZip("48169-0000"); p.setIcPhone("666-059-4023"); p.setIcID("Money"); p.setMotherMID("9"); p.setFatherMID("98"); p.setBloodTypeStr("O-"); p.setEthnicityStr("Caucasian"); p.setGenderStr("Male"); p.setTopicalNotes("Here are some random topical notes. Isn't there more? Yes.\n There is."); p.setPassword("testpass1"); p.setConfirmPassword("testpass1"); try { new PatientValidator().validate(p); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals("Mother MID: " + ValidationFormat.NPMID.getDescription(), e.getErrorList().get(0)); assertEquals("Father MID: " + ValidationFormat.NPMID.getDescription(), e.getErrorList().get(1)); } } }
16,984
32.435039
111
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/bean/SecurityQuestionValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.bean; import junit.framework.TestCase; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.SecurityQA; import edu.ncsu.csc.itrust.model.old.validate.SecurityQAValidator; public class SecurityQuestionValidatorTest extends TestCase { private SecurityQA qa = new SecurityQA(); private SecurityQAValidator qav = new SecurityQAValidator(); public void testCorrectFormat() throws Exception { qa.setAnswer("12345678"); qa.setConfirmAnswer("12345678"); qa.setQuestion("12345678"); qav.validate(qa); } public void testNoMatch() throws Exception { qa.setAnswer("12345678"); qa.setConfirmAnswer("123456789"); qa.setQuestion("12345678"); try { qav.validate(qa); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals(1, e.getErrorList().size()); assertEquals("Security answers do not match", e.getErrorList().get(0)); } } public void testMatchWrongFormat() throws Exception { qa.setAnswer(">"); qa.setConfirmAnswer(">"); qa.setQuestion("12345678"); try { qav.validate(qa); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals(1, e.getErrorList().size()); assertEquals("Security Answer: Up to 30 alphanumeric characters", e.getErrorList().get(0)); } } public void testNullConfirm() throws Exception { qa.setAnswer("12345678"); qa.setConfirmAnswer(null); qa.setQuestion("12345678"); try { qav.validate(qa); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals(1, e.getErrorList().size()); assertEquals("Confirm answer cannot be empty", e.getErrorList().get(0)); } } public void testNullForm() throws Exception { try { qav.validate(null); fail("exception should have been thrown"); } catch (FormValidationException e) { assertEquals(1, e.getErrorList().size()); assertEquals("Null form", e.getErrorList().get(0)); } } }
2,039
28.565217
94
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/AnswerValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class AnswerValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.ANSWER; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testGoodAnswer() throws Exception { String value = "this is my answer5"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLength() throws Exception { String value = "abcabcabcabcabcabcabcabcabcabca"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLetters() throws Exception { String value = "bob%"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,201
37.774194
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/BloodTypeValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class BloodTypeValidatorTest extends TestCase { private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.BLOODTYPE; private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); private static final String PASSED = ""; public void testO() throws Exception { String value = "O-"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testAB() throws Exception { String value = "AB-"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testA() throws Exception { String value = "A+"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testB() throws Exception { String value = "B+"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLetter() throws Exception { String value = "a"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testNoNegative() throws Exception { String value = "O"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,746
33.94
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/CPTCodeValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class CPTCodeValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.CPT; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testGood() throws Exception { String value = "12345"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testNotInt() throws Exception { String value = "123a4"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testTooLong() throws Exception { String value = "123456"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,150
36.129032
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/CityValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class CityValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.CITY; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testGoodAnswer() throws Exception { String value = "City Name"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLength() throws Exception { String value = "aaaabbbbccccdddd"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLetters() throws Exception { String value = "bob%"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,173
36.870968
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/CodeDescriptionValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class CodeDescriptionValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.ICD_CODE_DESCRIPTION; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testNotesGood() throws Exception { String value = "A description"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testNotesTooLong() throws Exception { String value = "1234567890123456789012345678901"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,012
39.52
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/DateValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class DateValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final String PASSED = ""; private static final String FAILED = "Name: " + ValidationFormat.DATE.getDescription(); public void testDateGood() throws Exception { String value = "05/19/1984"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.DATE, false)); } public void testDateWithSpace() throws Exception { String value = "05/19/1984 "; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.DATE, false)); } }
892
36.208333
102
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/EmailValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class EmailValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.EMAIL; private static final String PASSED = ""; private static final String FAILED = "Name: " + ValidationFormat.EMAIL.getDescription(); public void testGoodEmail() throws Exception { String value = "bob.person1@nc.rr.A.com"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testGoodEmailWithPlus() throws Exception { String value = "disposable.style.email.with+symbol@example.com"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLength() throws Exception { String value = "1234567890123456789012345678901"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLetters() throws Exception { String value = "bob%"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } // Now legal according to http://tools.ietf.org/html/rfc2822 public void testGoodFormat() throws Exception { String value = "---@---.com"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, true)); } // This is now legal should validate see above link public void testGoodFormatMultipleAtSymbol() throws Exception { String value = "A@b@c@example.com"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, true)); } }
2,034
38.134615
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/GenderValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class GenderValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.ADDRESS; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testGoodAnswer() throws Exception { String value = "356 Some place blvd"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLength() throws Exception { String value = "abcabcabcabcabcabcabcabcabcabca"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLetters() throws Exception { String value = "bob%"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,203
37.83871
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/HospitalIDValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class HospitalIDValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final String FAILED = "Hospital ID: " + ValidationFormat.HOSPITAL_ID.getDescription(); private static final String PASSED = ""; public void testHospitalIDGood() throws Exception { String value = "0000000000"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Hospital ID", value, ValidationFormat.HOSPITAL_ID, false)); } public void testHospitalIDLetter() throws Exception { String value = "a"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Hospital ID", value, ValidationFormat.HOSPITAL_ID, false)); } public void testHospitalIDPunct() throws Exception { String value = "."; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Hospital ID", value, ValidationFormat.HOSPITAL_ID, false)); } public void testHospitalIDLength() throws Exception { String value = "12345678901"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Hospital ID", value, ValidationFormat.HOSPITAL_ID, false)); } public void testHospitalIDNegative() throws Exception { Long value = -1L; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Hospital ID", value, ValidationFormat.HOSPITAL_ID, false)); } }
1,658
34.297872
102
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/HospitalNameValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; /** * HospitalNameValidator */ public class HospitalNameValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.HOSPITAL_NAME; private static final String PASSED = ""; private static final String FAILED = "Hospital Name: " + VALIDATION_FORMAT.getDescription(); /** * testHospitalNameGood * * @throws Exception */ public void testHospitalNameGood() throws Exception { String value = "90A very long Hospital Name's."; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Hospital Name", value, VALIDATION_FORMAT, false)); } /** * testHospitalNameTooLong * * @throws Exception */ public void testHospitalNameTooLong() throws Exception { String chunkOfTen = "1234567890"; String value = "a"; for (int i = 0; i < 3; i++) { value += chunkOfTen; // shamelessly borrowed from Notes Test } String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Hospital Name", value, VALIDATION_FORMAT, false)); } /** * testHospitalNameBadChars */ public void testHospitalNameBadChars() { String hName = "9 A very long Hospital Name's!"; assertEquals(FAILED, validatorProxy.checkFormat("Hospital Name", hName, VALIDATION_FORMAT, false)); } /** * testHospitalNameTooShort */ public void testHospitalNameTooShort() { String hName = ""; assertEquals(FAILED, validatorProxy.checkFormat("Hospital Name", hName, VALIDATION_FORMAT, false)); } }
1,772
29.568966
107
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/ICD9CMValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class ICD9CMValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.ICD9CM; private static final String PASSED = ""; private static final String FAILED = "Name: " + ValidationFormat.ICD9CM.getDescription(); public void testGoodICD() throws Exception { String value = "1.0"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testGoodICDMore() throws Exception { String value = "159.02"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testGoodICDInt() throws Exception { String value = "159"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testGoodICDAnotherInt() throws Exception { String value = "159."; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadICDLengthFirst() throws Exception { String value = "0159.02"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadICDLengthSecond() throws Exception { String value = "159.022"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadICDLetters() throws Exception { String value = "159@022"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
2,035
36.018182
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/InsuranceIDValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class InsuranceIDValidatorTest extends TestCase { private static final String PASSED = ""; private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final String FAILED = "Name: " + ValidationFormat.INSURANCE_ID.getDescription(); public void testNameCheckTooLong() throws Exception { String value = "This-Name-Is-Too-Long "; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.INSURANCE_ID, false)); } public void testNameGood() throws Exception { String value = "NameIsGood-'"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.INSURANCE_ID, false)); } public void testIDWithNumber() throws Exception { String value = "NameIs1337"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.INSURANCE_ID, false)); } public void testNameLotsOfBadStuff() throws Exception { String value = "Bad!@#$%^&*()?.:;"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.INSURANCE_ID, false)); } }
1,410
38.194444
110
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/MIDValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class MIDValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final String FAILED = "Name: " + ValidationFormat.MID.getDescription(); private static final String PASSED = ""; public void testMIDGood() throws Exception { String value = "9000000000"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.MID, false)); } public void testMIDLetter() throws Exception { String value = "a"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.MID, false)); } public void testMIDLength() throws Exception { String value = "12345678901"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.MID, false)); } public void testMIDNegative() throws Exception { Long value = -1L; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.MID, false)); } }
1,299
35.111111
101
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/NDCodeValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class NDCodeValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.ND; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testGood() throws Exception { String value = "123456789"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testNotInt() throws Exception { String value = "1234a"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testTooLong() throws Exception { String value = "1234567890"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,156
36.322581
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/NameValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class NameValidatorTest extends TestCase { private static final String PASSED = ""; private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final String FAILED = "Name: " + ValidationFormat.NAME.getDescription(); public void testNameCheckTooLong() throws Exception { String value = "This-Name-Is-Too-Long "; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.NAME, false)); } public void testNameGood() throws Exception { String value = "NameIsGood-'"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.NAME, false)); } public void testNameNoLetters() throws Exception { String value = "----'"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.NAME, false)); } public void testNameLotsOfBadStuff() throws Exception { String value = "Bad!@#$%^&*()?.:;"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.NAME, false)); } }
1,359
36.777778
102
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/NotesValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; /** * NotesValidatorTest */ public class NotesValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.NOTES; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); /** * testNotesGood * * @throws Exception */ public void testNotesGood() throws Exception { String value = "This is a very long set of notes?!_."; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } /** * testNotesTooLong * * @throws Exception */ public void testNotesTooLong() throws Exception { String chunkOfTen = "1234567890"; String value = "a"; for (int i = 0; i < 30; i++) { value += chunkOfTen; // make 301 - BVA baby! } String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,244
28.642857
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/PasswordValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class PasswordValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.PASSWORD; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testGood() throws Exception { String value = "12345678901234567890"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testTooLong() throws Exception { String value = "123456789012345678901"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testWithSpace() throws Exception { String value = "12345678 "; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,193
37.516129
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/PhoneValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class PhoneValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final String FAILED = "Name: " + ValidationFormat.PHONE_NUMBER.getDescription(); private static final String PASSED = ""; public void testPhoneGood() throws Exception { String value = "012-345-6789"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.PHONE_NUMBER, false)); } public void testPhoneWithLetter() throws Exception { String value = "O12-345-6789"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.PHONE_NUMBER, false)); } public void testPhoneBadLength() throws Exception { String value = "012-345-67890"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, ValidationFormat.PHONE_NUMBER, false)); } }
1,158
36.387097
110
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/QuestionValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class QuestionValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.QUESTION; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testGoodQuestion() throws Exception { String value = "what is your name?-."; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLength() throws Exception { String value = "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLetters() throws Exception { String value = "bob%"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,230
38.709677
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/StateValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class StateValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.STATE; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testGoodAnswer() throws Exception { String value = "MI"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLength() throws Exception { String value = "MI "; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLetters() throws Exception { String value = "Mi"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadCapital() throws Exception { String value = "mI"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,360
35.783784
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/validate/regex/ZipcodeValidatorTest.java
package edu.ncsu.csc.itrust.unit.validate.regex; import junit.framework.TestCase; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; import edu.ncsu.csc.itrust.unit.testutils.ValidatorProxy; public class ZipcodeValidatorTest extends TestCase { private ValidatorProxy validatorProxy = new ValidatorProxy(); private static final ValidationFormat VALIDATION_FORMAT = ValidationFormat.ZIPCODE; private static final String PASSED = ""; private static final String FAILED = "Name: " + VALIDATION_FORMAT.getDescription(); public void testGoodAnswer() throws Exception { String value = "27607"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testGoodAnswerTwoParts() throws Exception { String value = "27607-0901"; String errorMessage = PASSED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLength() throws Exception { String value = "27607-"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } public void testBadLetters() throws Exception { String value = "xxxxx-xxxx"; String errorMessage = FAILED; assertEquals(errorMessage, validatorProxy.checkFormat("Name", value, VALIDATION_FORMAT, false)); } }
1,394
36.702703
98
java
iTrust
iTrust-master/iTrust/src/test/java/edu/ncsu/csc/itrust/unit/webutils/SessionUtilsTest.java
package edu.ncsu.csc.itrust.unit.webutils; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.webutils.SessionUtils; public class SessionUtilsTest { private SessionUtils utils; private List<PatientBean> list; private PatientBean a; private PatientBean b; @Before public void setUp() throws Exception { utils = spy(SessionUtils.getInstance()); list = new ArrayList<PatientBean>(2); a = new PatientBean(); a.setFirstName("Foo"); a.setLastName("Bar"); b = new PatientBean(); b.setFirstName("Baz"); b.setLastName("Quack"); list.add(a); list.add(b); } @Test public void testParseString() { Object foo = "foo"; String out = utils.parseString(foo); assertEquals(foo, out); } @Test public void testParseLong() { Object num = new Long(3L); Long out = utils.parseLong(num); assertEquals(num, out); } @Test public void testGetSessionUserRole() { when(utils.getSessionVariable("userRole")).thenReturn("some role"); String role = utils.getSessionUserRole(); assertEquals("some role", role); } @Test public void testGetSessionPID() { when(utils.getSessionVariable("pid")).thenReturn("some pid"); String pid = utils.getSessionPID(); assertEquals("some pid", pid); } @Test public void testGetSessionLoggedInMID() { when(utils.getSessionVariable("loggedInMID")).thenReturn("123"); String mid = utils.getSessionLoggedInMID(); assertEquals("123", mid); } @Test public void testGetSessionLoggedInMIDLong() { when(utils.getSessionVariable("loggedInMID")).thenReturn(34L); Long mid = utils.getSessionLoggedInMIDLong(); assertEquals(new Long(34L), mid); } @Test public void testGetCurrentPatientMID() { when(utils.getSessionVariable("pid")).thenReturn("123"); when(utils.getSessionVariable("userRole")).thenReturn("patient"); when(utils.getSessionVariable("loggedInMID")).thenReturn("456"); String mid = utils.getCurrentPatientMID(); assertEquals("456", mid); when(utils.getSessionVariable("userRole")).thenReturn("not a patient"); mid = utils.getCurrentPatientMID(); assertEquals("123", mid); } @Test public void testGetCurrentPatientMIDLong() { when(utils.getSessionVariable("pid")).thenReturn("123"); when(utils.getSessionVariable("userRole")).thenReturn("patient"); when(utils.getSessionVariable("loggedInMID")).thenReturn("456"); Long mid = utils.getCurrentPatientMIDLong(); assertEquals(new Long(456), mid); when(utils.getSessionVariable("userRole")).thenReturn("not a patient"); mid = utils.getCurrentPatientMIDLong(); assertEquals(new Long(123), mid); } @Test public void testGetCurrentOfficeVisitId() { when(utils.getSessionVariable("officeVisitId")).thenReturn(new Long(3)); Long id = utils.getCurrentOfficeVisitId(); assertEquals(new Long(3), id); } @Test public void testGetRepresenteeList() { when(utils.getSessionVariable("representees")).thenReturn(list); List<PatientBean> actual = utils.getRepresenteeList(); assertEquals(2, actual.size()); assertEquals(a, actual.get(0)); assertEquals(b, actual.get(1)); } @Test public void testSetRepresenteeList() { PatientBean a = new PatientBean(); a.setFirstName("Foo"); a.setLastName("Bar"); PatientBean b = new PatientBean(); b.setFirstName("Baz"); b.setLastName("Quack"); list.add(a); list.add(b); doNothing().when(utils).setSessionVariable(anyString(), any()); utils.setRepresenteeList(list); verify(utils).setSessionVariable("representees", list); } @Test public void testGetInstance() { SessionUtils first = SessionUtils.getInstance(); SessionUtils second = SessionUtils.getInstance(); assertEquals(first, second); // since it's a singleton } }
4,109
26.959184
74
java
acmeair
acmeair-master/acmeair-common/src/main/java/com/acmeair/AcmeAirConstants.java
package com.acmeair; public interface AcmeAirConstants { }
63
8.142857
35
java
acmeair
acmeair-master/acmeair-common/src/main/java/com/acmeair/entities/AirportCodeMapping.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.entities; public interface AirportCodeMapping{ public String getAirportCode(); public void setAirportCode(String airportCode); public String getAirportName(); public void setAirportName(String airportName); }
983
31.8
80
java
acmeair
acmeair-master/acmeair-common/src/main/java/com/acmeair/entities/Booking.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.entities; import java.util.Date; public interface Booking { public String getBookingId(); public String getFlightId(); public String getCustomerId(); public Date getDateOfBooking(); }
967
25.162162
80
java
acmeair
acmeair-master/acmeair-common/src/main/java/com/acmeair/entities/Customer.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.entities; public interface Customer { public enum MemberShipStatus { NONE, SILVER, GOLD, PLATINUM, EXEC_PLATINUM, GRAPHITE }; public enum PhoneType { UNKNOWN, HOME, BUSINESS, MOBILE }; public String getCustomerId(); public String getUsername(); public void setUsername(String username); public String getPassword(); public void setPassword(String password); public MemberShipStatus getStatus(); public void setStatus(MemberShipStatus status); public int getTotal_miles(); public int getMiles_ytd(); public String getPhoneNumber(); public void setPhoneNumber(String phoneNumber); public PhoneType getPhoneNumberType(); public void setPhoneNumberType(PhoneType phoneNumberType); public CustomerAddress getAddress(); public void setAddress(CustomerAddress address); }
1,572
26.596491
88
java
acmeair
acmeair-master/acmeair-common/src/main/java/com/acmeair/entities/CustomerAddress.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.entities; public interface CustomerAddress { public String getStreetAddress1(); public void setStreetAddress1(String streetAddress1); public String getStreetAddress2(); public void setStreetAddress2(String streetAddress2); public String getCity(); public void setCity(String city); public String getStateProvince(); public void setStateProvince(String stateProvince); public String getCountry(); public void setCountry(String country); public String getPostalCode(); public void setPostalCode(String postalCode); }
1,293
34.944444
80
java
acmeair
acmeair-master/acmeair-common/src/main/java/com/acmeair/entities/CustomerSession.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.entities; import java.util.Date; public interface CustomerSession { public String getId(); public String getCustomerid(); public Date getLastAccessedTime(); public Date getTimeoutTime(); }
966
25.861111
80
java
acmeair
acmeair-master/acmeair-common/src/main/java/com/acmeair/entities/Flight.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.entities; import java.math.BigDecimal; import java.util.Date; public interface Flight{ String getFlightId(); void setFlightId(String id); String getFlightSegmentId(); FlightSegment getFlightSegment(); void setFlightSegment(FlightSegment flightSegment); Date getScheduledDepartureTime(); Date getScheduledArrivalTime(); BigDecimal getFirstClassBaseCost(); BigDecimal getEconomyClassBaseCost(); int getNumFirstClassSeats(); int getNumEconomyClassSeats(); String getAirplaneTypeId(); }
1,286
22.4
80
java
acmeair
acmeair-master/acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.entities; public interface FlightSegment { public String getFlightName(); public String getOriginPort(); public String getDestPort(); public int getMiles(); }
930
31.103448
80
java
acmeair
acmeair-master/acmeair-loader/src/main/java/com/acmeair/loader/CustomerLoader.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.loader; import com.acmeair.entities.Customer; import com.acmeair.entities.CustomerAddress; import com.acmeair.entities.Customer.PhoneType; import com.acmeair.service.CustomerService; import com.acmeair.service.ServiceLocator; public class CustomerLoader { private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); public void loadCustomers(long numCustomers) { CustomerAddress address = customerService.createAddress("123 Main St.", null, "Anytown", "NC", "USA", "27617"); for (long ii = 0; ii < numCustomers; ii++) { customerService.createCustomer("uid"+ii+"@email.com", "password", Customer.MemberShipStatus.GOLD, 1000000, 1000, "919-123-4567", PhoneType.BUSINESS, address); } } }
1,505
39.702703
161
java
acmeair
acmeair-master/acmeair-loader/src/main/java/com/acmeair/loader/FlightLoader.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.loader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.*; import java.math.*; import com.acmeair.entities.AirportCodeMapping; import com.acmeair.service.FlightService; import com.acmeair.service.ServiceLocator; public class FlightLoader { private static final int MAX_FLIGHTS_PER_SEGMENT = 30; private FlightService flightService = ServiceLocator.instance().getService(FlightService.class); public void loadFlights() throws Exception { InputStream csvInputStream = FlightLoader.class.getResourceAsStream("/mileage.csv"); LineNumberReader lnr = new LineNumberReader(new InputStreamReader(csvInputStream)); String line1 = lnr.readLine(); StringTokenizer st = new StringTokenizer(line1, ","); ArrayList<AirportCodeMapping> airports = new ArrayList<AirportCodeMapping>(); // read the first line which are airport names while (st.hasMoreTokens()) { AirportCodeMapping acm = flightService.createAirportCodeMapping(null, st.nextToken()); // acm.setAirportName(st.nextToken()); airports.add(acm); } // read the second line which contains matching airport codes for the first line String line2 = lnr.readLine(); st = new StringTokenizer(line2, ","); int ii = 0; while (st.hasMoreTokens()) { String airportCode = st.nextToken(); airports.get(ii).setAirportCode(airportCode); ii++; } // read the other lines which are of format: // airport name, aiport code, distance from this airport to whatever airport is in the column from lines one and two String line; int flightNumber = 0; while (true) { line = lnr.readLine(); if (line == null || line.trim().equals("")) { break; } st = new StringTokenizer(line, ","); String airportName = st.nextToken(); String airportCode = st.nextToken(); if (!alreadyInCollection(airportCode, airports)) { AirportCodeMapping acm = flightService.createAirportCodeMapping(airportCode, airportName); airports.add(acm); } int indexIntoTopLine = 0; while (st.hasMoreTokens()) { String milesString = st.nextToken(); if (milesString.equals("NA")) { indexIntoTopLine++; continue; } int miles = Integer.parseInt(milesString); String toAirport = airports.get(indexIntoTopLine).getAirportCode(); String flightId = "AA" + flightNumber; flightService.storeFlightSegment(flightId, airportCode, toAirport, miles); Date now = new Date(); for (int daysFromNow = 0; daysFromNow < MAX_FLIGHTS_PER_SEGMENT; daysFromNow++) { Calendar c = Calendar.getInstance(); c.setTime(now); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); c.add(Calendar.DATE, daysFromNow); Date departureTime = c.getTime(); Date arrivalTime = getArrivalTime(departureTime, miles); flightService.createNewFlight(flightId, departureTime, arrivalTime, new BigDecimal(500), new BigDecimal(200), 10, 200, "B747"); } flightNumber++; indexIntoTopLine++; } } for (int jj = 0; jj < airports.size(); jj++) { flightService.storeAirportMapping(airports.get(jj)); } lnr.close(); } private static Date getArrivalTime(Date departureTime, int mileage) { double averageSpeed = 600.0; // 600 miles/hours double hours = (double) mileage / averageSpeed; // miles / miles/hour = hours double partsOfHour = hours % 1.0; int minutes = (int)(60.0 * partsOfHour); Calendar c = Calendar.getInstance(); c.setTime(departureTime); c.add(Calendar.HOUR, (int)hours); c.add(Calendar.MINUTE, minutes); return c.getTime(); } static private boolean alreadyInCollection(String airportCode, ArrayList<AirportCodeMapping> airports) { for (int ii = 0; ii < airports.size(); ii++) { if (airports.get(ii).getAirportCode().equals(airportCode)) { return true; } } return false; } }
4,705
34.119403
132
java
acmeair
acmeair-master/acmeair-loader/src/main/java/com/acmeair/loader/Loader.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.loader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Logger; public class Loader { public static String REPOSITORY_LOOKUP_KEY = "com.acmeair.repository.type"; private static Logger logger = Logger.getLogger(Loader.class.getName()); public String queryLoader() { String message = System.getProperty("loader.numCustomers"); if (message == null){ logger.info("The system property 'loader.numCustomers' has not been set yet. Looking up the default properties."); lookupDefaults(); message = System.getProperty("loader.numCustomers"); } return message; } public String loadDB(long numCustomers) { String message = ""; if(numCustomers == -1) message = execute(); else { System.setProperty("loader.numCustomers", Long.toString(numCustomers)); message = execute(numCustomers); } return message; } public static void main(String args[]) throws Exception { Loader loader = new Loader(); loader.execute(); } private String execute() { String numCustomers = System.getProperty("loader.numCustomers"); if (numCustomers == null){ logger.info("The system property 'loader.numCustomers' has not been set yet. Looking up the default properties."); lookupDefaults(); numCustomers = System.getProperty("loader.numCustomers"); } return execute(Long.parseLong(numCustomers)); } private String execute(long numCustomers) { FlightLoader flightLoader = new FlightLoader(); CustomerLoader customerLoader = new CustomerLoader(); double length = 0; try { long start = System.currentTimeMillis(); logger.info("Start loading flights"); flightLoader.loadFlights(); logger.info("Start loading " + numCustomers + " customers"); customerLoader.loadCustomers(numCustomers); long stop = System.currentTimeMillis(); logger.info("Finished loading in " + (stop - start)/1000.0 + " seconds"); length = (stop - start)/1000.0; } catch (Exception e) { e.printStackTrace(); } return "Loaded flights and " + numCustomers + " customers in " + length + " seconds"; } private void lookupDefaults (){ Properties props = getProperties(); String numCustomers = props.getProperty("loader.numCustomers","100"); System.setProperty("loader.numCustomers", numCustomers); } private Properties getProperties(){ /* * Get Properties from loader.properties file. * If the file does not exist, use default values */ Properties props = new Properties(); String propFileName = "/loader.properties"; try{ InputStream propFileStream = Loader.class.getResourceAsStream(propFileName); props.load(propFileStream); // props.load(new FileInputStream(propFileName)); }catch(FileNotFoundException e){ logger.info("Property file " + propFileName + " not found."); }catch(IOException e){ logger.info("IOException - Property file " + propFileName + " not found."); } return props; } /* private void execute(String args[]) { ApplicationContext ctx = null; // // Get Properties from loader.properties file. // If the file does not exist, use default values // Properties props = new Properties(); String propFileName = "/loader.properties"; try{ InputStream propFileStream = Loader.class.getResourceAsStream(propFileName); props.load(propFileStream); // props.load(new FileInputStream(propFileName)); }catch(FileNotFoundException e){ logger.info("Property file " + propFileName + " not found."); }catch(IOException e){ logger.info("IOException - Property file " + propFileName + " not found."); } String numCustomers = props.getProperty("loader.numCustomers","100"); System.setProperty("loader.numCustomers", numCustomers); String type = null; String lookup = REPOSITORY_LOOKUP_KEY.replace('.', '/'); javax.naming.Context context = null; javax.naming.Context envContext; try { context = new javax.naming.InitialContext(); envContext = (javax.naming.Context) context.lookup("java:comp/env"); if (envContext != null) type = (String) envContext.lookup(lookup); } catch (NamingException e) { // e.printStackTrace(); } if (type != null) { logger.info("Found repository in web.xml:" + type); } else if (context != null) { try { type = (String) context.lookup(lookup); if (type != null) logger.info("Found repository in server.xml:" + type); } catch (NamingException e) { // e.printStackTrace(); } } if (type == null) { type = System.getProperty(REPOSITORY_LOOKUP_KEY); if (type != null) logger.info("Found repository in jvm property:" + type); else { type = System.getenv(REPOSITORY_LOOKUP_KEY); if (type != null) logger.info("Found repository in environment property:" + type); } } if (type ==null) // Default to wxsdirect { type = "wxsdirect"; logger.info("Using default repository :" + type); } if (type.equals("wxsdirect")) ctx = new AnnotationConfigApplicationContext(WXSDirectAppConfig.class); else if (type.equals("mongodirect")) ctx = new AnnotationConfigApplicationContext(MongoDirectAppConfig.class); else { logger.info("Did not find a matching config. Using default repository wxsdirect instead"); ctx = new AnnotationConfigApplicationContext(WXSDirectAppConfig.class); } FlightLoader flightLoader = ctx.getBean(FlightLoader.class); CustomerLoader customerLoader = ctx.getBean(CustomerLoader.class); try { long start = System.currentTimeMillis(); logger.info("Start loading flights"); flightLoader.loadFlights(); logger.info("Start loading " + numCustomers + " customers"); customerLoader.loadCustomers(Long.parseLong(numCustomers)); long stop = System.currentTimeMillis(); logger.info("Finished loading in " + (stop - start)/1000.0 + " seconds"); } catch (Exception e) { e.printStackTrace(); } } */ }
6,820
31.793269
117
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/ReportGenerator.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import org.apache.velocity.tools.generic.ComparisonDateTool; import org.apache.velocity.tools.generic.MathTool; import org.apache.velocity.tools.generic.NumberTool; import com.acmeair.reporter.util.Messages; import com.acmeair.reporter.util.StatResult; import com.acmeair.reporter.parser.IndividualChartResults; import com.acmeair.reporter.parser.ResultParser; import com.acmeair.reporter.parser.ResultParserHelper; import com.acmeair.reporter.parser.component.JmeterJTLParser; import com.acmeair.reporter.parser.component.JmeterSummariserParser; import com.acmeair.reporter.parser.component.JtlTotals; import com.acmeair.reporter.parser.component.NmonParser; //import freemarker.cache.ClassTemplateLoader; //import freemarker.template.Configuration; //import freemarker.template.Template; public class ReportGenerator { private static final int max_lines = 15; private static final String RESULTS_FILE = Messages.getString("ReportGenerator.RESULT_FILE_NAME"); private static String searchingLocation = Messages.getString("inputDirectory"); private static String jmeterFileName = Messages.getString("ReportGenerator.DEFAULT_JMETER_FILENAME"); private static String nmonFileName = Messages.getString("ReportGenerator.DEFAULT_NMON_FILE_NAME"); private static final String BOOK_FLIGHT = "BookFlight"; private static final String CANCEL_BOOKING = "Cancel Booking"; private static final String LOGIN = "Login"; private static final String LOGOUT = "logout"; private static final String LIST_BOOKINGS = "List Bookings"; private static final String QUERY_FLIGHT = "QueryFlight"; private static final String UPDATE_CUSTOMER = "Update Customer"; private static final String VIEW_PROFILE = "View Profile Information"; private LinkedHashMap<String,ArrayList<String>> charMap = new LinkedHashMap<String,ArrayList<String>>(); public static void main(String[] args) { if (args.length == 1) { searchingLocation = (args[0]); } if (!new File(searchingLocation).isDirectory()) { System.out.println("\"" + searchingLocation + "\" is not a valid directory"); return; } System.out.println("Parsing acme air test results in the location \"" + searchingLocation + "\""); ReportGenerator generator = new ReportGenerator(); long start, stop; start = System.currentTimeMillis(); generator.process(); stop = System.currentTimeMillis(); System.out.println("Results generated in " + (stop - start)/1000.0 + " seconds"); } public void process() { long start, stop; String overallChartTitle = Messages.getString("ReportGenerator.THROUGHPUT_TOTAL_LABEL"); String throughputChartTitle = Messages.getString("ReportGenerator.THROUGHPUT_TITLE"); String yAxisLabel = Messages.getString("ReportGenerator.THROUGHPUT_YAXIS_LABEL"); Map<String, Object> input = new HashMap<String, Object>(); start = System.currentTimeMillis(); JmeterSummariserParser jmeterParser = new JmeterSummariserParser(); jmeterParser.setFileName(jmeterFileName); jmeterParser.setMultipleChartTitle(throughputChartTitle); jmeterParser.setMultipleYAxisLabel(yAxisLabel); jmeterParser.processDirectory(searchingLocation); //always call it before call generating multiple chart string String url = jmeterParser.generateChartStrings(overallChartTitle, yAxisLabel, "", jmeterParser.processData(jmeterParser.getAllInputList(), true), ResultParserHelper.scaleDown(jmeterParser.getAllTimeList(), 3), false); ArrayList<String> list = new ArrayList<String>(); list.add(url); charMap.put(overallChartTitle, list); generateMulitpleLinesChart(jmeterParser); charMap.put(throughputChartTitle, jmeterParser.getCharStrings()); StatResult jmeterStats = StatResult.getStatistics(jmeterParser.getAllInputList()); input.put("jmeterStats", jmeterStats); if(!jmeterParser.getAllTimeList().isEmpty()){ input.put("testStart", jmeterParser.getTestDate() + " " + jmeterParser.getAllTimeList().get(0)); input.put("testEnd", jmeterParser.getTestDate() + " " + jmeterParser.getAllTimeList().get(jmeterParser.getAllTimeList().size()-1)); } input.put("charUrlMap", charMap); stop = System.currentTimeMillis(); System.out.println("Parsed jmeter in " + (stop - start)/1000.0 + " seconds"); start = System.currentTimeMillis(); JmeterJTLParser jtlParser = new JmeterJTLParser(); jtlParser.processResultsDirectory(searchingLocation); input.put("totals", jtlParser.getResults()); String urls[] = {BOOK_FLIGHT,CANCEL_BOOKING,LOGIN,LOGOUT,LIST_BOOKINGS,QUERY_FLIGHT,UPDATE_CUSTOMER,VIEW_PROFILE,"Authorization"}; input.put("totalUrlMap" ,reorderTestcases(jtlParser.getResultsByUrl(), urls)); input.put("queryTotals", getTotals(QUERY_FLIGHT, jtlParser.getResultsByUrl())); input.put("bookingTotals", getTotals(BOOK_FLIGHT, jtlParser.getResultsByUrl())); input.put("loginTotals", getTotals(LOGIN, jtlParser.getResultsByUrl())); stop = System.currentTimeMillis(); System.out.println("Parsed jmeter jtl files in " + (stop - start)/1000.0 + " seconds"); List<Object> nmonParsers = Messages.getConfiguration().getList("parsers.nmonParser.directory"); if (nmonParsers != null){ LinkedHashMap<String,StatResult> cpuList = new LinkedHashMap<String,StatResult>(); start = System.currentTimeMillis(); for(int i = 0;i < nmonParsers.size(); i++) { String enabled = Messages.getString("parsers.nmonParser("+i+")[@enabled]"); if (enabled == null || !enabled.equalsIgnoreCase("false")) { String directory = Messages.getString("parsers.nmonParser("+i+").directory"); String chartTitle = Messages.getString("parsers.nmonParser("+i+").chartTitle"); String label = Messages.getString("parsers.nmonParser("+i+").label"); String fileName = Messages.getString("parsers.nmonParser("+i+").fileName"); String relativePath = Messages.getString("parsers.nmonParser("+i+").directory[@relative]"); if (relativePath == null || !relativePath.equalsIgnoreCase("false")) { directory = searchingLocation +"/" + directory; } if (fileName == null){ fileName = nmonFileName; } NmonParser nmon = parseNmonDirectory(directory, fileName, chartTitle); cpuList = addCpuStats(nmon, label, cpuList); } } input.put("cpuList", cpuList); stop = System.currentTimeMillis(); System.out.println("Parsed nmon files in " + (stop - start)/1000.0 + " seconds"); } if (charMap.size() > 0) { start = System.currentTimeMillis(); generateHtmlfile(input); stop = System.currentTimeMillis(); System.out.println("Generated html file in " + (stop - start)/1000.0 + " seconds"); System.out.println("Done, charts were saved to \"" + searchingLocation + System.getProperty("file.separator") + RESULTS_FILE + "\""); } else { System.out.println("Failed, cannot find valid \"" + jmeterFileName + "\" or \"" + nmonFileName + "\" files in location " + searchingLocation); } } private void generateMulitpleLinesChart(ResultParser parser) { if (parser.getResults().size()<=max_lines){ parser.generateMultipleLinesCharString(parser.getMultipleChartTitle(), parser.getMultipleYAxisLabel(), "", parser.getResults()); }else { System.out.println("More than "+max_lines+" throughput files found, will break them to "+max_lines+" each"); ArrayList<IndividualChartResults> results= parser.getResults(); int size = results.size(); for (int i=0;i<size;i=i+max_lines){ int endLocation = i+max_lines; if (endLocation >size) { endLocation=size; } parser.generateMultipleLinesCharString(parser.getMultipleChartTitle(), parser.getMultipleYAxisLabel(), "", results.subList(i,endLocation)); } } } private ArrayList<Double> getCombinedResultsList (NmonParser parser){ Iterator<IndividualChartResults> itr = parser.getMultipleChartResults().getResults().iterator(); ArrayList<Double> resultList = new ArrayList<Double>(); while(itr.hasNext()){ //trim trailing idle times from each of the individual results, //then combine the results together to get the final tallies. ArrayList<Double> curList = itr.next().getInputList(); for(int j = curList.size() - 1; j >= 0; j--){ if (curList.get(j).doubleValue() < 1){ curList.remove(j); } } resultList.addAll(curList); } return resultList; } /* private void generateHtmlfile(Map<String, Object> input) { try{ Configuration cfg = new Configuration(); ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "/templates"); cfg.setTemplateLoader(ctl); Template template = cfg.getTemplate("acmeair-report.ftl"); Writer file = new FileWriter(new File(searchingLocation + System.getProperty("file.separator") + RESULTS_FILE)); template.process(input, file); file.flush(); file.close(); }catch(Exception e){ e.printStackTrace(); } } */ private void generateHtmlfile(Map<String, Object> input) { try{ VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName()); ve.init(); Template template = ve.getTemplate("templates/acmeair-report.vtl"); VelocityContext context = new VelocityContext(); for(Map.Entry<String, Object> entry: input.entrySet()){ context.put(entry.getKey(), entry.getValue()); } context.put("math", new MathTool()); context.put("number", new NumberTool()); context.put("date", new ComparisonDateTool()); Writer file = new FileWriter(new File(searchingLocation + System.getProperty("file.separator") + RESULTS_FILE)); template.merge( context, file ); file.flush(); file.close(); }catch(Exception e){ e.printStackTrace(); } } private LinkedHashMap<String,StatResult> addCpuStats(NmonParser parser, String label, LinkedHashMap<String,StatResult> toAdd){ if (parser != null) { StatResult cpuStats = StatResult.getStatistics(getCombinedResultsList(parser)); cpuStats.setNumberOfResults(parser.getMultipleChartResults().getResults().size()); toAdd.put(label, cpuStats); }else { System.out.println("no "+label+" cpu data found"); } return toAdd; } /** * Re-orders a given map to using an array of Strings. * Any remaining items in the map that was passed in will be appended to the end of * the map to be returned. * @param totalUrlMap the map to be re-ordered. * @param urls An array of Strings with the desired order for the map keys. * @return A LinkedHashMap with the keys in the order requested. * @see LinkedHashMap */ private Map<String,JtlTotals> reorderTestcases(Map<String,JtlTotals> totalUrlMap, String urls[]){ LinkedHashMap<String,JtlTotals> newMap = new LinkedHashMap<String,JtlTotals>(); Iterator<String> keys; for(int i=0; i< urls.length;i++){ keys = totalUrlMap.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); if(key.toLowerCase().contains(urls[i].toLowerCase())){ newMap.put(key, totalUrlMap.get(key)); } } } //loop 2nd time to get the remaining items keys = totalUrlMap.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); boolean found = false; for(int i=0; i< urls.length;i++){ if(key.toLowerCase().contains(urls[i].toLowerCase())){ found = true; } } if(!found){ newMap.put(key, totalUrlMap.get(key)); } } return newMap; } /** * Searches the map for the given jmeter testcase url key. * The passed in string is expected to contain all or part of the desired key. * for example "QueryFlight" could match both "Mobile QueryFlight" and "Desktop QueryFlight" or just "QueryFlight". * If multiple results are found, their totals are added togehter in the JtlTotals Object returned. * * @param url String, jMeter Testcase URL string to search for. * @param totalUrlMap Map containing Strings and JtlTotals results. * @return JtlTotals object. * @see JtlTotals */ private JtlTotals getTotals(String url, Map<String,JtlTotals> totalUrlMap){ JtlTotals urlTotals = null; Iterator<String> keys = totalUrlMap.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); if(key.toLowerCase().contains(url.toLowerCase())){ if(urlTotals == null){ urlTotals = totalUrlMap.get(key); }else { urlTotals.add(totalUrlMap.get(key)); } } } return urlTotals; } /** * Sets up a new NmonParser Object for parsing a given directory. * @param directory directory to search for nmon files. * @param chartTitle Name of the title for the chart to be generated. * @return NmonParser object */ private NmonParser parseNmonDirectory (String directory, String fileName, String chartTitle ){ if (!new File(directory).isDirectory()) { return null; } NmonParser parser = new NmonParser(); parser.setFileName(fileName); parser.setMultipleChartTitle(chartTitle); parser.processDirectory(directory); generateMulitpleLinesChart(parser); charMap.put(chartTitle, parser.getCharStrings()); return parser; } }
15,148
39.289894
137
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter.parser; import java.util.ArrayList; public class IndividualChartResults { private ArrayList<Double> inputList = new ArrayList<Double>(); private String title; private ArrayList<String> timeList = new ArrayList<String>(); private int files = 0; public void setTitle(String title) { this.title = title; } public ArrayList<Double> getInputList() { return inputList; } public void setInputList(ArrayList<Double> inputList) { this.inputList = inputList; } public ArrayList<String> getTimeList() { return timeList; } public void setTimeList(ArrayList<String> timeList) { this.timeList = timeList; } public String getTitle() { return title; } public void incrementFiles(){ files++; } public int getFilesCount(){ return files; } }
1,559
27.363636
80
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/MultipleChartResults.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter.parser; import java.util.ArrayList; public class MultipleChartResults { private String multipleChartTitle; private String multipleChartYAxisLabel; private ArrayList<IndividualChartResults> results = new ArrayList<IndividualChartResults> (); private ArrayList<String> charStrings= new ArrayList<String>(); public String getMultipleChartTitle() { return multipleChartTitle; } public void setMultipleChartTitle(String multipleChartTitle) { this.multipleChartTitle = multipleChartTitle; } public String getMultipleChartYAxisLabel() { return multipleChartYAxisLabel; } public void setMultipleChartYAxisLabel(String multipleChartYAxisLabel) { this.multipleChartYAxisLabel = multipleChartYAxisLabel; } public ArrayList<IndividualChartResults> getResults() { return results; } public void setResults(ArrayList<IndividualChartResults> results) { this.results = results; } public ArrayList<String> getCharStrings() { return charStrings; } public void setCharStrings(ArrayList<String> charStrings) { this.charStrings = charStrings; } }
1,839
33.074074
95
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/OverallResults.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter.parser; import java.util.ArrayList; public class OverallResults { private ArrayList<Double> allInputList = new ArrayList<Double>(); private ArrayList<String> allTimeList = new ArrayList<String>(); private double scale_max; private double overallScale_max; public ArrayList<Double> getAllInputList() { return allInputList; } public void setAllInputList(ArrayList<Double> allInputList) { this.allInputList = new ArrayList<Double> (allInputList); } public ArrayList<String> getAllTimeList() { return allTimeList; } public void setAllTimeList(ArrayList<String> allTimeList) { this.allTimeList = new ArrayList<String> (allTimeList); } public double getOverallScale_max() { return overallScale_max; } public void setOverallScale_max(double overallScale_max) { this.overallScale_max = overallScale_max; } public double getScale_max() { return scale_max; } public void setScale_max(double scale_max) { this.scale_max = scale_max; } }
1,739
29
80
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParser.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter.parser; import static com.googlecode.charts4j.Color.ALICEBLUE; import static com.googlecode.charts4j.Color.BLACK; import static com.googlecode.charts4j.Color.LAVENDER; import static com.googlecode.charts4j.Color.WHITE; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.RegexFileFilter; import com.acmeair.reporter.parser.component.NmonParser; import com.googlecode.charts4j.AxisLabels; import com.googlecode.charts4j.AxisLabelsFactory; import com.googlecode.charts4j.AxisStyle; import com.googlecode.charts4j.AxisTextAlignment; import com.googlecode.charts4j.Color; import com.googlecode.charts4j.Data; import com.googlecode.charts4j.DataEncoding; import com.googlecode.charts4j.Fills; import com.googlecode.charts4j.GCharts; import com.googlecode.charts4j.Line; import com.googlecode.charts4j.LineChart; import com.googlecode.charts4j.LineStyle; import com.googlecode.charts4j.LinearGradientFill; import com.googlecode.charts4j.Plots; import com.googlecode.charts4j.Shape; public abstract class ResultParser { protected MultipleChartResults multipleChartResults = new MultipleChartResults(); protected OverallResults overallResults = new OverallResults(); public MultipleChartResults getMultipleChartResults() { return multipleChartResults; } protected void addUp(ArrayList<Double> list) { //if empty, don't need to add up if (overallResults.getAllInputList().isEmpty()) { overallResults.setAllInputList(list); return; } int size = overallResults.getAllInputList().size(); if (size > list.size()) { size = list.size(); } for (int i = 0; i < size; i++) { overallResults.getAllInputList().set(i, overallResults.getAllInputList().get(i) + list.get(i)); } } public void processDirectory(String dirName) { File root = new File(dirName); try { Collection<File> files = FileUtils.listFiles(root, new RegexFileFilter(getFileName()), DirectoryFileFilter.DIRECTORY); for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) { File file = (File) iterator.next(); processFile(file); } } catch (Exception e) { e.printStackTrace(); } } public String generateChartStrings(String titileLabel, String ylabel, String xlable, double[] inputs, ArrayList<String> timeList, boolean addToList) { if (inputs == null || inputs.length == 0) return null; Line line1 = Plots.newLine(Data.newData(inputs), Color.newColor("CA3D05"), ""); line1.setLineStyle(LineStyle.newLineStyle(2, 1, 0)); line1.addShapeMarkers(Shape.DIAMOND, Color.newColor("CA3D05"), 6); LineChart chart = GCharts.newLineChart(line1); // Defining axis info and styles chart.addYAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(0, overallResults.getScale_max() / 0.9)); if (timeList != null && timeList.size() > 0) { chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels(timeList)); } String url = generateDefaultChartSettings(titileLabel, ylabel, xlable, chart, addToList); return url; } public String generateDefaultChartSettings(String titileLabel, String ylabel, String xlable, LineChart chart, boolean addToList) { AxisStyle axisStyle = AxisStyle.newAxisStyle(BLACK, 13, AxisTextAlignment.CENTER); AxisLabels yAxisLabel = AxisLabelsFactory.newAxisLabels(ylabel, 50.0); yAxisLabel.setAxisStyle(axisStyle); AxisLabels time = AxisLabelsFactory.newAxisLabels(xlable, 50.0); time.setAxisStyle(axisStyle); chart.addYAxisLabels(yAxisLabel); chart.addXAxisLabels(time); chart.setDataEncoding(DataEncoding.SIMPLE); chart.setSize(1000, 300); chart.setTitle(titileLabel, BLACK, 16); chart.setGrid(100, 10, 3, 2); chart.setBackgroundFill(Fills.newSolidFill(ALICEBLUE)); LinearGradientFill fill = Fills.newLinearGradientFill(0, LAVENDER, 100); fill.addColorAndOffset(WHITE, 0); chart.setAreaFill(fill); String url = chart.toURLString(); if(addToList) { getCharStrings().add(url); } return url; } public String generateMultipleLinesCharString(String titileLabel, String ylabel, String xlabel, List<IndividualChartResults> list) { if (list ==null || list.size()==0) { return null; } Line[] lines = new Line[list.size()]; for (int i = 0; i < list.size(); i++) { double[] multiLineData = processMultiLineData(list.get(i).getInputList()); if (multiLineData!=null) { lines[i] = Plots.newLine(Data.newData(multiLineData), ResultParserHelper.getColor(i), list.get(i).getTitle()); lines[i].setLineStyle(LineStyle.newLineStyle(2, 1, 0)); } else { System.out.println("found jmeter log file that doesn't have data:\" " + list.get(i).getTitle() +"\" skipping!"); return null; } } LineChart chart = GCharts.newLineChart(lines); chart.addYAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(0, overallResults.getOverallScale_max() / 0.9)); chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels(list.get(0) .getTimeList())); // Defining axis info and styles String url = generateDefaultChartSettings(titileLabel, ylabel, xlabel, chart, true); return url; } public ArrayList<Double> getAllInputList() { return overallResults.getAllInputList(); } public ArrayList<String> getAllTimeList() { return overallResults.getAllTimeList(); } public ArrayList<String> getCharStrings() { return getMultipleChartResults().getCharStrings(); } protected <E> IndividualChartResults getData(String fileName) { IndividualChartResults results = new IndividualChartResults(); try { FileInputStream fstream = new FileInputStream(fileName); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { processLine(results, strLine); } in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } addUp(results.getInputList()); overallResults.setAllTimeList(results.getTimeList()); return results; } public abstract String getFileName(); public abstract void setFileName(String fileName); public ArrayList<IndividualChartResults> getResults() { return getMultipleChartResults().getResults(); } public double[] processData(ArrayList<Double> inputList, boolean isTotalThroughput) { if (inputList != null && inputList.size() > 0) { if (this instanceof NmonParser) { overallResults.setScale_max(90.0); } else { overallResults.setScale_max(Collections.max(inputList)); } if (overallResults.getOverallScale_max() < overallResults.getScale_max() && !isTotalThroughput) { overallResults.setOverallScale_max( overallResults.getScale_max()); } double scale_factor = 90 / overallResults.getScale_max(); return ResultParserHelper.scaleInputsData(inputList, scale_factor); } return null; } protected abstract void processFile(File file); protected abstract void processLine(IndividualChartResults result, String strLine); public double[] processMultiLineData(ArrayList<Double> inputList) { if (inputList != null && inputList.size() > 0) { double scale_factor = 90 / overallResults.getOverallScale_max(); return ResultParserHelper.scaleInputsData(inputList, scale_factor); } return null; } public String getMultipleChartTitle() { return multipleChartResults.getMultipleChartTitle(); } public void setMultipleYAxisLabel(String label){ multipleChartResults.setMultipleChartYAxisLabel(label); } public void setMultipleChartTitle(String label){ multipleChartResults.setMultipleChartTitle(label); } public String getMultipleYAxisLabel() { return multipleChartResults.getMultipleChartYAxisLabel(); } }
8,863
32.832061
116
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter.parser; import java.util.ArrayList; import com.googlecode.charts4j.Color; public class ResultParserHelper { public static Color getColor(int i) { Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW, Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER, Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY }; return colors[i % 15]; } public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) { if (testList==null) { return null; } if (testList.size() <= 7) return testList; if (scaleDownFactor > 10 || scaleDownFactor < 0) { throw new RuntimeException( "currently only support factor from 0-10"); } int listLastItemIndex = testList.size() - 1; int a = (int) java.lang.Math.pow(2, scaleDownFactor); if (a > listLastItemIndex) { return testList; } ArrayList<E> newList = new ArrayList<E>(); newList.add(testList.get(0)); if (scaleDownFactor == 0) { newList.add(testList.get(listLastItemIndex)); } else { for (int m = 1; m <= a; m++) { newList.add(testList.get(listLastItemIndex * m / a)); } } return newList; } public static double[] scaleInputsData(ArrayList<Double> inputList, double scale_factor) { double[] inputs = new double[inputList.size()]; for (int i = 0; i <= inputList.size() - 1; i++) { inputs[i] = inputList.get(i) * scale_factor; } return inputs; } }
2,213
30.628571
93
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterJTLParser.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter.parser.component; import java.io.File; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.RegexFileFilter; import com.acmeair.reporter.util.Messages; public class JmeterJTLParser { private String jmeterJTLFileName = "AcmeAir[1-9].jtl"; private String regEx = "<httpSample\\s*" + "t=\"([^\"]*)\"\\s*" + "lt=\"([^\"]*)\"\\s*" + "ts=\"([^\"]*)\"\\s*" + "s=\"([^\"]*)\"\\s*" + "lb=\"([^\"]*)\"\\s*" + "rc=\"([^\"]*)\"\\s*" + "rm=\"([^\"]*)\"\\s*" + "tn=\"([^\"]*)\"\\s*" + "dt=\"([^\"]*)\"\\s*" + "by=\"([^\"]*)\"\\s*" + "FLIGHTTOCOUNT=\"([^\"]*)\"\\s*" + "FLIGHTRETCOUNT=\"([^\"]*)\"\\s*"+ "ONEWAY\\s*=\"([^\"]*)\"\\s*"; // NOTE: The regular expression depends on user.properties in jmeter having the sample_variables property added. // sample_variables=FLIGHTTOCOUNT,FLIGHTRETCOUNT,ONEWAY private int GROUP_T = 1; private int GROUP_TS = 3; private int GROUP_S = 4; private int GROUP_LB = 5; private int GROUP_RC = 6; private int GROUP_TN = 8; private int GROUP_FLIGHTTOCOUNT = 11; private int GROUP_FLIGHTRETCOUNT = 12; private int GROUP_ONEWAY = 13; private JtlTotals totalAll; private Map<String, JtlTotals> totalUrlMap; public JmeterJTLParser() { totalAll = new JtlTotals(); totalUrlMap = new HashMap<String, JtlTotals>(); String jtlRegularExpression = Messages.getString("parsers.JmeterJTLParser.jtlRegularExpression"); if (jtlRegularExpression != null){ System.out.println("set regex string to be '" + jtlRegularExpression+ "'"); regEx = jtlRegularExpression; } String matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.t"); if (matcherGroup != null){ GROUP_T = new Integer(matcherGroup).intValue(); } matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.ts"); if (matcherGroup != null){ GROUP_TS = new Integer(matcherGroup).intValue(); } matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.s"); if (matcherGroup != null){ GROUP_S = new Integer(matcherGroup).intValue(); } matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.lb"); if (matcherGroup != null){ GROUP_LB = new Integer(matcherGroup).intValue(); } matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.rc"); if (matcherGroup != null){ GROUP_RC = new Integer(matcherGroup).intValue(); } matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.tn"); if (matcherGroup != null){ GROUP_TN = new Integer(matcherGroup).intValue(); } matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.FLIGHTTOCOUNT"); if (matcherGroup != null){ GROUP_FLIGHTTOCOUNT = new Integer(matcherGroup).intValue(); } matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.FLIGHTRETCOUNT"); if (matcherGroup != null){ GROUP_FLIGHTRETCOUNT = new Integer(matcherGroup).intValue(); } matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.ONEWAY"); if (matcherGroup != null){ GROUP_ONEWAY = new Integer(matcherGroup).intValue(); } String responseTimeStepping = Messages.getString("parsers.JmeterJTLParser.responseTimeStepping"); if (responseTimeStepping != null){ JtlTotals.setResponseTimeStepping(new Integer(responseTimeStepping).intValue()); } } public void setLogFileName (String logFileName) { this.jmeterJTLFileName = logFileName; } public void processResultsDirectory(String dirName) { File root = new File(dirName); try { Collection<File> files = FileUtils.listFiles(root, new RegexFileFilter(jmeterJTLFileName), DirectoryFileFilter.DIRECTORY); for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) { File file = (File) iterator.next(); parse(file); } } catch (Exception e) { e.printStackTrace(); } } public void parse(File jmeterJTLfile) throws IOException { if(totalAll == null){ totalAll = new JtlTotals(); totalUrlMap = new HashMap<String, JtlTotals>(); } totalAll.incrementFiles(); Pattern pattern = Pattern.compile(regEx); HashMap <String, Integer> threadCounter = new HashMap<String, Integer>(); BufferedReader reader = new BufferedReader(new FileReader(jmeterJTLfile)); try { String line = reader.readLine(); while(line != null) { Matcher matcher = pattern.matcher(line); if(matcher.find()) { add(matcher, totalAll); String url = matcher.group(GROUP_LB); JtlTotals urlTotals = totalUrlMap.get(url); if(urlTotals == null) { urlTotals = new JtlTotals(); totalUrlMap.put(url, urlTotals); } add(matcher, urlTotals); String threadName = matcher.group(GROUP_TN); Integer threadCnt = threadCounter.get(threadName); if(threadCnt == null) { threadCnt = new Integer(1); }else{ threadCnt = Integer.valueOf(threadCnt.intValue()+1); } threadCounter.put(threadName, threadCnt); } line = reader.readLine(); } } finally { reader.close(); } totalAll.setThreadMap(threadCounter); if(totalAll.getCount() == 0) { System.out.println("JmeterJTLParser - No results found!"); return; } } public JtlTotals getResults() { return totalAll; } public Map<String, JtlTotals> getResultsByUrl() { return totalUrlMap; } private void add(Matcher matcher, JtlTotals total) { long timestamp = Long.parseLong(matcher.group(GROUP_TS)); total.addTimestamp(timestamp); int time = Integer.parseInt(matcher.group(GROUP_T)); total.addTime(time); String rc = matcher.group(GROUP_RC); total.addReturnCode(rc); if(!matcher.group(GROUP_S).equalsIgnoreCase("true")) { total.incrementFailures(); } String strFlightCount = matcher.group(GROUP_FLIGHTTOCOUNT); if (strFlightCount != null && !strFlightCount.isEmpty()){ int count = Integer.parseInt(strFlightCount); total.addToFlight(count); } strFlightCount = matcher.group(GROUP_FLIGHTRETCOUNT); if (strFlightCount != null && !strFlightCount.isEmpty()){ total.addFlightRetCount(Integer.parseInt(strFlightCount)); } String oneWay = matcher.group(GROUP_ONEWAY); if (oneWay != null && oneWay.equalsIgnoreCase("true")){ total.incrementOneWayCount(); } } }
8,622
33.770161
116
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterSummariserParser.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter.parser.component; import java.io.File; import com.acmeair.reporter.parser.IndividualChartResults; import com.acmeair.reporter.parser.ResultParser; import com.acmeair.reporter.parser.ResultParserHelper; public class JmeterSummariserParser extends ResultParser { private static boolean SKIP_JMETER_DROPOUTS = false; static { SKIP_JMETER_DROPOUTS = System.getProperty("SKIP_JMETER_DROPOUTS") != null; } private String jmeterFileName = "AcmeAir[1-9].log"; private String testDate = ""; @Override protected void processFile(File file) { IndividualChartResults result= getData(file.getPath()); super.processData(ResultParserHelper.scaleDown(result.getInputList(),8),false); IndividualChartResults individualResults = new IndividualChartResults(); if(result.getTitle() != null){ individualResults.setTitle(result.getTitle()); } else { individualResults.setTitle(file.getName()); } individualResults.setInputList(ResultParserHelper.scaleDown(result.getInputList(),6)); individualResults.setTimeList(ResultParserHelper.scaleDown(result.getTimeList(),3)); super.getMultipleChartResults().getResults().add(individualResults); } @Override public String getFileName() { return jmeterFileName; } @Override public void setFileName(String fileName) { jmeterFileName = fileName; } public String getTestDate(){ return testDate; } @Override protected void processLine(IndividualChartResults results, String strLine) { if (strLine.indexOf("summary +") > 0) { String[] tokens = strLine.split(" "); results.getTimeList().add(tokens[1].trim()); testDate = tokens[0].trim(); int endposition = strLine.indexOf("/s"); int startposition = strLine.indexOf("="); String thoughputS = strLine.substring(startposition + 1, endposition).trim(); Double throughput = Double.parseDouble(thoughputS); if (throughput == 0.0 && SKIP_JMETER_DROPOUTS) { return; } results.getInputList().add(throughput); } else if (strLine.indexOf("Name:") > 0) { int startIndex = strLine.indexOf(" Name:")+7; int endIndex = strLine.indexOf(" ", startIndex); String name = strLine.substring(startIndex, endIndex); results.setTitle(name); } } }
2,978
34.464286
88
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JtlTotals.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter.parser.component; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry; public class JtlTotals { private static final String DECIMAL_PATTERN = "#,##0.0##"; private static final double MILLIS_PER_SECOND = 1000.0; private static int millisPerBucket = 500; private int files = 0; private int request_count = 0; private int time_sum = 0; private int time_max = 0; private int time_min = Integer.MAX_VALUE; private int failures = 0; private long timestamp_start = Long.MAX_VALUE; private long timestamp_end = 0; private Map<String, Integer> rcMap = new HashMap<String, Integer>(); // key rc, value count private Map<Integer, Integer> millisMap = new TreeMap<Integer, Integer>(); // key bucket Integer, value count private Map <String, Integer> threadMap = new HashMap<String,Integer>(); private ArrayList<Integer> timeList = new ArrayList<Integer>(); private long flight_to_sum = 0; private long flight_to_count = 0; private int flight_to_empty_count = 0; private long flight_ret_count = 0; private long one_way_count = 0; public JtlTotals() { } public void add(JtlTotals totals){ rcMap.putAll(totals.getReturnCodeCounts()); millisMap.putAll(totals.getMillisMap()); threadMap.putAll(totals.getThreadMap()); one_way_count += totals.getOneWayCount(); flight_ret_count += totals.getFlightRetCount(); flight_to_empty_count += totals.getEmptyToFlightCount(); flight_to_sum += totals.getFlightToSum(); flight_to_count += totals.getFlightToCount(); failures += totals.getFailures(); request_count += totals.getCount(); } public long getFlightToCount() { return flight_to_count; } public void addTime(int time){ request_count++; time_sum+=time; time_max = Math.max(time_max, time); time_min = Math.min(time_min, time); timeList.add(time); Integer bucket = new Integer(time / millisPerBucket); Integer count = millisMap.get(bucket); if(count == null) { count = new Integer(0); } millisMap.put(bucket, new Integer(count.intValue() + 1)); } public Map<Integer, Integer> getMillisMap() { return millisMap; } public void addReturnCode(String rc){ Integer rc_count = rcMap.get(rc); if(rc_count == null) { rc_count = new Integer(0); } rcMap.put(rc, new Integer(rc_count.intValue() + 1)); } public void setThreadMap(Map<String,Integer> threadMap){ this.threadMap = threadMap; } public void addTimestamp(long timestamp){ timestamp_end = Math.max(timestamp_end, timestamp); timestamp_start = Math.min(timestamp_start, timestamp); } public void incrementFailures(){ failures++; } public void addToFlight(int count){ this.flight_to_count++; this.flight_to_sum += count; if(count == 0) this.flight_to_empty_count++; } public void addFlightRetCount(int count){ this.flight_ret_count += count; } public void incrementOneWayCount(){ one_way_count++; } public void incrementFiles(){ files++; } public int getFilesCount(){ return files; } public int getCount(){ return request_count; } public Map<String,Integer> getThreadMap(){ return this.threadMap; } public int getAverageResponseTime(){ //in case .jtl file doesn't exist, request_count could be 0 //adding this condition to avoid "divide by zero" runtime exception if (request_count==0) { return time_sum; } return (time_sum/request_count); } public int getMaxResponseTime(){ return time_max; } public int getMinResponseTime(){ return time_min; } public int getFailures(){ return failures; } public int get90thPrecentile(){ if(timeList.isEmpty()){ return Integer.MAX_VALUE; } int target = (int)Math.round(timeList.size() * .90 ); Collections.sort(timeList); if(target == timeList.size()){target--;} return timeList.get(target); } public Map<String, Integer> getReturnCodeCounts(){ return rcMap; } public long getElapsedTimeInSeconds(){ double secondsElaspsed = (timestamp_end - timestamp_start) / MILLIS_PER_SECOND; return Math.round(secondsElaspsed); } public long getRequestsPerSecond (){ return Math.round(request_count / getElapsedTimeInSeconds()); } public long getFlightToSum(){ return flight_to_sum; } public long getEmptyToFlightCount(){ return flight_to_empty_count; } public float getAverageToFlights(){ return (float)flight_to_sum/flight_to_count; } public long getFlightRetCount(){ return flight_ret_count; } public long getOneWayCount(){ return one_way_count; } public static void setResponseTimeStepping(int milliseconds){ millisPerBucket = milliseconds; } public static int getResponseTimeStepping(){ return millisPerBucket; } public String cntByTimeString() { DecimalFormat df = new DecimalFormat(DECIMAL_PATTERN); List<String> millisStr = new LinkedList<String>(); Iterator <Entry<Integer,Integer>>iter = millisMap.entrySet().iterator(); while(iter.hasNext()) { Entry<Integer,Integer> millisEntry = iter.next(); Integer bucket = (Integer)millisEntry.getKey(); Integer bucketCount = (Integer)millisEntry.getValue(); int minMillis = bucket.intValue() * millisPerBucket; int maxMillis = (bucket.intValue() + 1) * millisPerBucket; millisStr.add( df.format(minMillis/MILLIS_PER_SECOND)+" s "+ "- "+ df.format(maxMillis/MILLIS_PER_SECOND)+" s "+ "= " + bucketCount); } return millisStr.toString(); } public HashMap<String, Integer> cntByTime() { DecimalFormat df = new DecimalFormat(DECIMAL_PATTERN); LinkedHashMap<String, Integer> millisStr = new LinkedHashMap<String, Integer>(); Iterator <Entry<Integer,Integer>>iter = millisMap.entrySet().iterator(); while(iter.hasNext()) { Entry<Integer,Integer> millisEntry = iter.next(); Integer bucket = (Integer)millisEntry.getKey(); Integer bucketCount = (Integer)millisEntry.getValue(); int minMillis = bucket.intValue() * millisPerBucket; int maxMillis = (bucket.intValue() + 1) * millisPerBucket; millisStr.put( df.format(minMillis/MILLIS_PER_SECOND)+" s "+ "- "+ df.format(maxMillis/MILLIS_PER_SECOND)+" s " , bucketCount); } return millisStr; } }
8,096
30.142308
113
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/NmonParser.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.reporter.parser.component; import java.io.File; import com.acmeair.reporter.parser.IndividualChartResults; import com.acmeair.reporter.parser.ResultParser; import com.acmeair.reporter.parser.ResultParserHelper; public class NmonParser extends ResultParser{ private String nmonFileName = "output.nmon"; public NmonParser(){ super.setMultipleYAxisLabel("usr%+sys%"); //default label } @Override protected void processFile(File file) { IndividualChartResults result= getData(file.getPath()); super.processData(ResultParserHelper.scaleDown(result.getInputList(),8),false); IndividualChartResults individualResults = new IndividualChartResults(); individualResults.setTitle(result.getTitle()); individualResults.setInputList(ResultParserHelper.scaleDown(result.getInputList(),6)); individualResults.setTimeList(ResultParserHelper.scaleDown(result.getTimeList(),3)); super.getMultipleChartResults().getResults().add(individualResults); } @Override public String getFileName() { return nmonFileName; } @Override public void setFileName(String fileName) { nmonFileName = fileName; } @Override protected void processLine(IndividualChartResults results, String strLine) { if(strLine.startsWith("AAA,host,")){ String[] tokens = strLine.split(","); results.setTitle(tokens[2].trim()); } if (strLine.indexOf("ZZZZ") >=0){ String[] tokens = strLine.split(","); results.getTimeList().add(tokens[2].trim()); } if (strLine.indexOf("CPU_ALL") >=0 && strLine.indexOf("CPU Total")<0) { String[] tokens = strLine.split(","); String user = tokens[2].trim(); String sys = tokens[3].trim(); Double userDouble = Double.parseDouble(user); Double sysDouble = Double.parseDouble(sys); results.getInputList().add(userDouble+sysDouble); } } }
2,579
32.076923
88
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/util/Messages.java
package com.acmeair.reporter.util; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.SystemConfiguration; import org.apache.commons.configuration.XMLConfiguration; public class Messages { static ResourceBundle RESOURCE_BUNDLE; static CompositeConfiguration config; static { try { config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); config.addConfiguration(new PropertiesConfiguration("messages.properties")); config.addConfiguration(new XMLConfiguration("config.xml")); } catch (Exception e) { System.out.println(e); } } private Messages() { } public static String getString(String key) { try { return config.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } public static Configuration getConfiguration(){ return config; } }
1,108
23.644444
79
java
acmeair
acmeair-master/acmeair-reporter/src/main/java/com/acmeair/reporter/util/StatResult.java
package com.acmeair.reporter.util; import java.util.ArrayList; public class StatResult { public double min; public double max; public double average; public int count; public double sum; public double numberOfResults; public double getMin() { return min; } public void setMin(double min) { this.min = min; } public double getMax() { return max; } public void setMax(double max) { this.max = max; } public double getAverage() { return average; } public void setAverage(double average) { this.average = average; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getSum() { return sum; } public void setSum(double sum) { this.sum = sum; } public double getNumberOfResults() { return numberOfResults; } public void setNumberOfResults(double numberOfResults) { this.numberOfResults = numberOfResults; } public static StatResult getStatistics(ArrayList <Double> list){ StatResult result = new StatResult(); result.average = 0; result.sum = 0; if (list.size()>1) result.min = list.get(1); result.max = 0; result.count = 0; for (int i = 0; i< list.size();i++){ double current = list.get(i).doubleValue(); if(i > 0 && i < list.size()-1){ result.sum += current; result.count ++; result.min = Math.min(result.min, current); result.max = Math.max(result.max, current); } } if(result.count > 0 && result.sum > 0) result.average = (result.sum/result.count); return result; } }
1,577
20.916667
68
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/BigDecimalConverter.java
package com.acmeair.morphia; import java.math.BigDecimal; import org.mongodb.morphia.converters.SimpleValueConverter; import org.mongodb.morphia.converters.TypeConverter; import org.mongodb.morphia.mapping.MappedField; import org.mongodb.morphia.mapping.MappingException; public class BigDecimalConverter extends TypeConverter implements SimpleValueConverter{ public BigDecimalConverter() { super(BigDecimal.class); } @Override public Object encode(Object value, MappedField optionalExtraInfo) { return value.toString(); } @Override public Object decode(Class targetClass, Object fromDBObject, MappedField optionalExtraInfo) throws MappingException { if (fromDBObject == null) return null; return new BigDecimal(fromDBObject.toString()); } }
812
29.111111
121
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/BigIntegerConverter.java
package com.acmeair.morphia; import java.math.BigInteger; import org.mongodb.morphia.converters.SimpleValueConverter; import org.mongodb.morphia.converters.TypeConverter; import org.mongodb.morphia.mapping.MappedField; import org.mongodb.morphia.mapping.MappingException; public class BigIntegerConverter extends TypeConverter implements SimpleValueConverter{ public BigIntegerConverter() { super(BigInteger.class); } @Override public Object encode(Object value, MappedField optionalExtraInfo) { return value.toString(); } @Override public Object decode(Class targetClass, Object fromDBObject, MappedField optionalExtraInfo) throws MappingException { if (fromDBObject == null) return null; return new BigInteger(fromDBObject.toString()); } }
813
28.071429
121
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/DatastoreFactory.java
package com.acmeair.morphia; import java.util.Properties; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import com.acmeair.entities.Booking; import com.acmeair.entities.Flight; import com.acmeair.entities.FlightSegment; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Morphia; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientURI; import com.mongodb.WriteConcern; public class DatastoreFactory { private static String mongourl = null; static { String vcapJSONString = System.getenv("VCAP_SERVICES"); if (vcapJSONString != null) { System.out.println("Reading VCAP_SERVICES"); Object jsonObject = JSONValue.parse(vcapJSONString); JSONObject json = (JSONObject)jsonObject; System.out.println("jsonObject = " + json.toJSONString()); for (Object key: json.keySet()) { if (((String)key).contains("mongo")) { System.out.println("Found mongo service:" +key); JSONArray mongoServiceArray = (JSONArray)json.get(key); JSONObject mongoService = (JSONObject) mongoServiceArray.get(0); JSONObject credentials = (JSONObject)mongoService.get("credentials"); mongourl = (String)credentials.get("url"); if (mongourl==null) mongourl= (String)credentials.get("uri"); System.out.println("service url = " + mongourl); break; } } } } public static Datastore getDatastore(Datastore ds) { Datastore result =ds; if (mongourl!=null) { try{ Properties prop = new Properties(); prop.load(DatastoreFactory.class.getResource("/acmeair-mongo.properties").openStream()); boolean fsync = new Boolean(prop.getProperty("mongo.fsync")); int w = new Integer(prop.getProperty("mongo.w")); int connectionsPerHost = new Integer(prop.getProperty("mongo.connectionsPerHost")); int threadsAllowedToBlockForConnectionMultiplier = new Integer(prop.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier")); // To match the local options MongoClientOptions.Builder builder = new MongoClientOptions.Builder() .writeConcern(new WriteConcern(w, 0, fsync)) .connectionsPerHost(connectionsPerHost) .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier); MongoClientURI mongoURI = new MongoClientURI(mongourl, builder); MongoClient mongo = new MongoClient(mongoURI); Morphia morphia = new Morphia(); result = morphia.createDatastore( mongo ,mongoURI.getDatabase()); System.out.println("create mongo datastore with options:"+result.getMongo().getMongoClientOptions()); }catch (Exception e) { e.printStackTrace(); } } // The converter is added for handing JDK 7 issue // result.getMapper().getConverters().addConverter(new BigDecimalConverter()); // result.getMapper().getConverters().addConverter(new BigIntegerConverter()); // Enable index result.ensureIndex(Booking.class, "pkey.customerId"); result.ensureIndex(Flight.class, "pkey.flightSegmentId,scheduledDepartureTime"); result.ensureIndex(FlightSegment.class, "originPort,destPort"); return result; } }
3,217
33.978261
139
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/MorphiaConstants.java
package com.acmeair.morphia; import com.acmeair.AcmeAirConstants; public interface MorphiaConstants extends AcmeAirConstants { public static final String JNDI_NAME = "mongo/acmeairMongodb"; public static final String KEY = "morphia"; public static final String KEY_DESCRIPTION = "mongoDB with morphia implementation"; public static final String HOSTNAME = "mongohostname"; public static final String PORT = "mongoport"; public static final String DATABASE = "mongodatabase"; }
492
28
84
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/AirportCodeMappingImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.morphia.entities; import java.io.Serializable; import org.mongodb.morphia.annotations.Entity; import com.acmeair.entities.AirportCodeMapping; @Entity(value="airportCodeMapping") public class AirportCodeMappingImpl implements AirportCodeMapping, Serializable{ private static final long serialVersionUID = 1L; private String _id; private String airportName; public AirportCodeMappingImpl() { } public AirportCodeMappingImpl(String airportCode, String airportName) { this._id = airportCode; this.airportName = airportName; } public String getAirportCode() { return _id; } public void setAirportCode(String airportCode) { this._id = airportCode; } public String getAirportName() { return airportName; } public void setAirportName(String airportName) { this.airportName = airportName; } }
1,593
27.464286
80
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/BookingImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.morphia.entities; import java.io.Serializable; import java.util.Date; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Id; import com.acmeair.entities.Booking; import com.acmeair.entities.Customer; import com.acmeair.entities.Flight; @Entity(value="booking") public class BookingImpl implements Booking, Serializable{ private static final long serialVersionUID = 1L; @Id private String _id; private String flightId; private String customerId; private Date dateOfBooking; public BookingImpl() { } public BookingImpl(String bookingId, Date dateOfFlight, String customerId, String flightId) { this._id = bookingId; this.flightId = flightId; this.customerId = customerId; this.dateOfBooking = dateOfFlight; } public BookingImpl(String bookingId, Date dateOfFlight, Customer customer, Flight flight) { this._id = bookingId; this.flightId = flight.getFlightId(); this.dateOfBooking = dateOfFlight; this.customerId = customer.getCustomerId(); } public String getBookingId() { return _id; } public void setBookingId(String bookingId) { this._id = bookingId; } public String getFlightId() { return flightId; } public void setFlightId(String flightId) { this.flightId = flightId; } public Date getDateOfBooking() { return dateOfBooking; } public void setDateOfBooking(Date dateOfBooking) { this.dateOfBooking = dateOfBooking; } public String getCustomerId() { return customerId; } public void setCustomer(String customerId) { this.customerId = customerId; } @Override public String toString() { return "Booking [key=" + _id + ", flightId=" + flightId + ", dateOfBooking=" + dateOfBooking + ", customerId=" + customerId + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BookingImpl other = (BookingImpl) obj; if (customerId == null) { if (other.customerId != null) return false; } else if (!customerId.equals(other.customerId)) return false; if (dateOfBooking == null) { if (other.dateOfBooking != null) return false; } else if (!dateOfBooking.equals(other.dateOfBooking)) return false; if (flightId == null) { if (other.flightId != null) return false; } else if (!flightId.equals(other.flightId)) return false; return true; } }
3,211
24.291339
94
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/CustomerAddressImpl.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.morphia.entities; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.CustomerAddress; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement public class CustomerAddressImpl implements CustomerAddress, Serializable{ private static final long serialVersionUID = 1L; private String streetAddress1; private String streetAddress2; private String city; private String stateProvince; private String country; private String postalCode; public CustomerAddressImpl() { } public CustomerAddressImpl(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode) { super(); this.streetAddress1 = streetAddress1; this.streetAddress2 = streetAddress2; this.city = city; this.stateProvince = stateProvince; this.country = country; this.postalCode = postalCode; } public String getStreetAddress1() { return streetAddress1; } public void setStreetAddress1(String streetAddress1) { this.streetAddress1 = streetAddress1; } public String getStreetAddress2() { return streetAddress2; } public void setStreetAddress2(String streetAddress2) { this.streetAddress2 = streetAddress2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStateProvince() { return stateProvince; } public void setStateProvince(String stateProvince) { this.stateProvince = stateProvince; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } @Override public String toString() { return "CustomerAddress [streetAddress1=" + streetAddress1 + ", streetAddress2=" + streetAddress2 + ", city=" + city + ", stateProvince=" + stateProvince + ", country=" + country + ", postalCode=" + postalCode + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CustomerAddressImpl other = (CustomerAddressImpl) obj; if (city == null) { if (other.city != null) return false; } else if (!city.equals(other.city)) return false; if (country == null) { if (other.country != null) return false; } else if (!country.equals(other.country)) return false; if (postalCode == null) { if (other.postalCode != null) return false; } else if (!postalCode.equals(other.postalCode)) return false; if (stateProvince == null) { if (other.stateProvince != null) return false; } else if (!stateProvince.equals(other.stateProvince)) return false; if (streetAddress1 == null) { if (other.streetAddress1 != null) return false; } else if (!streetAddress1.equals(other.streetAddress1)) return false; if (streetAddress2 == null) { if (other.streetAddress2 != null) return false; } else if (!streetAddress2.equals(other.streetAddress2)) return false; return true; } }
4,028
27.778571
80
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/CustomerImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.morphia.entities; import java.io.Serializable; import org.mongodb.morphia.annotations.Entity; import com.acmeair.entities.Customer; import com.acmeair.entities.CustomerAddress; @Entity(value="customer") public class CustomerImpl implements Customer, Serializable{ private static final long serialVersionUID = 1L; private String _id; private String password; private MemberShipStatus status; private int total_miles; private int miles_ytd; private CustomerAddress address; private String phoneNumber; private PhoneType phoneNumberType; public CustomerImpl() { } public CustomerImpl(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, CustomerAddress address, String phoneNumber, PhoneType phoneNumberType) { this._id = username; this.password = password; this.status = status; this.total_miles = total_miles; this.miles_ytd = miles_ytd; this.address = address; this.phoneNumber = phoneNumber; this.phoneNumberType = phoneNumberType; } public String getCustomerId(){ return _id; } public String getUsername() { return _id; } public void setUsername(String username) { this._id = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public MemberShipStatus getStatus() { return status; } public void setStatus(MemberShipStatus status) { this.status = status; } public int getTotal_miles() { return total_miles; } public void setTotal_miles(int total_miles) { this.total_miles = total_miles; } public int getMiles_ytd() { return miles_ytd; } public void setMiles_ytd(int miles_ytd) { this.miles_ytd = miles_ytd; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public PhoneType getPhoneNumberType() { return phoneNumberType; } public void setPhoneNumberType(PhoneType phoneNumberType) { this.phoneNumberType = phoneNumberType; } public CustomerAddress getAddress() { return address; } public void setAddress(CustomerAddress address) { this.address = address; } @Override public String toString() { return "Customer [id=" + _id + ", password=" + password + ", status=" + status + ", total_miles=" + total_miles + ", miles_ytd=" + miles_ytd + ", address=" + address + ", phoneNumber=" + phoneNumber + ", phoneNumberType=" + phoneNumberType + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CustomerImpl other = (CustomerImpl) obj; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; if (_id == null) { if (other._id != null) return false; } else if (!_id.equals(other._id)) return false; if (miles_ytd != other.miles_ytd) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (phoneNumber == null) { if (other.phoneNumber != null) return false; } else if (!phoneNumber.equals(other.phoneNumber)) return false; if (phoneNumberType != other.phoneNumberType) return false; if (status != other.status) return false; if (total_miles != other.total_miles) return false; return true; } }
4,272
23.988304
185
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/CustomerSessionImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.morphia.entities; import java.io.Serializable; import java.util.Date; import org.mongodb.morphia.annotations.Entity; import com.acmeair.entities.CustomerSession; @Entity(value="customerSession") public class CustomerSessionImpl implements CustomerSession, Serializable { private static final long serialVersionUID = 1L; private String _id; private String customerid; private Date lastAccessedTime; private Date timeoutTime; public CustomerSessionImpl() { } public CustomerSessionImpl(String id, String customerid, Date lastAccessedTime, Date timeoutTime) { this._id= id; this.customerid = customerid; this.lastAccessedTime = lastAccessedTime; this.timeoutTime = timeoutTime; } public String getId() { return _id; } public void setId(String id) { this._id = id; } public String getCustomerid() { return customerid; } public void setCustomerid(String customerid) { this.customerid = customerid; } public Date getLastAccessedTime() { return lastAccessedTime; } public void setLastAccessedTime(Date lastAccessedTime) { this.lastAccessedTime = lastAccessedTime; } public Date getTimeoutTime() { return timeoutTime; } public void setTimeoutTime(Date timeoutTime) { this.timeoutTime = timeoutTime; } @Override public String toString() { return "CustomerSession [id=" + _id + ", customerid=" + customerid + ", lastAccessedTime=" + lastAccessedTime + ", timeoutTime=" + timeoutTime + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CustomerSessionImpl other = (CustomerSessionImpl) obj; if (customerid == null) { if (other.customerid != null) return false; } else if (!customerid.equals(other.customerid)) return false; if (_id == null) { if (other._id != null) return false; } else if (!_id.equals(other._id)) return false; if (lastAccessedTime == null) { if (other.lastAccessedTime != null) return false; } else if (!lastAccessedTime.equals(other.lastAccessedTime)) return false; if (timeoutTime == null) { if (other.timeoutTime != null) return false; } else if (!timeoutTime.equals(other.timeoutTime)) return false; return true; } }
3,070
24.380165
100
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.morphia.entities; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Id; import com.acmeair.entities.Flight; import com.acmeair.entities.FlightSegment; @Entity(value="flight") public class FlightImpl implements Flight, Serializable{ private static final long serialVersionUID = 1L; @Id private String _id; private String flightSegmentId; private Date scheduledDepartureTime; private Date scheduledArrivalTime; private BigDecimal firstClassBaseCost; private BigDecimal economyClassBaseCost; private int numFirstClassSeats; private int numEconomyClassSeats; private String airplaneTypeId; private FlightSegment flightSegment; public FlightImpl() { } public FlightImpl(String id, String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId) { this._id = id; this.flightSegmentId = flightSegmentId; this.scheduledDepartureTime = scheduledDepartureTime; this.scheduledArrivalTime = scheduledArrivalTime; this.firstClassBaseCost = firstClassBaseCost; this.economyClassBaseCost = economyClassBaseCost; this.numFirstClassSeats = numFirstClassSeats; this.numEconomyClassSeats = numEconomyClassSeats; this.airplaneTypeId = airplaneTypeId; } public String getFlightId(){ return _id; } public void setFlightId(String id){ this._id = id; } public String getFlightSegmentId() { return flightSegmentId; } public void setFlightSegmentId(String segmentId){ this.flightSegmentId = segmentId; } public Date getScheduledDepartureTime() { return scheduledDepartureTime; } public void setScheduledDepartureTime(Date scheduledDepartureTime) { this.scheduledDepartureTime = scheduledDepartureTime; } public Date getScheduledArrivalTime() { return scheduledArrivalTime; } public void setScheduledArrivalTime(Date scheduledArrivalTime) { this.scheduledArrivalTime = scheduledArrivalTime; } public BigDecimal getFirstClassBaseCost() { return firstClassBaseCost; } public void setFirstClassBaseCost(BigDecimal firstClassBaseCost) { this.firstClassBaseCost = firstClassBaseCost; } public BigDecimal getEconomyClassBaseCost() { return economyClassBaseCost; } public void setEconomyClassBaseCost(BigDecimal economyClassBaseCost) { this.economyClassBaseCost = economyClassBaseCost; } public int getNumFirstClassSeats() { return numFirstClassSeats; } public void setNumFirstClassSeats(int numFirstClassSeats) { this.numFirstClassSeats = numFirstClassSeats; } public int getNumEconomyClassSeats() { return numEconomyClassSeats; } public void setNumEconomyClassSeats(int numEconomyClassSeats) { this.numEconomyClassSeats = numEconomyClassSeats; } public String getAirplaneTypeId() { return airplaneTypeId; } public void setAirplaneTypeId(String airplaneTypeId) { this.airplaneTypeId = airplaneTypeId; } public FlightSegment getFlightSegment() { return flightSegment; } public void setFlightSegment(FlightSegment flightSegment) { this.flightSegment = flightSegment; } @Override public String toString() { return "Flight key="+_id + ", scheduledDepartureTime=" + scheduledDepartureTime + ", scheduledArrivalTime=" + scheduledArrivalTime + ", firstClassBaseCost=" + firstClassBaseCost + ", economyClassBaseCost=" + economyClassBaseCost + ", numFirstClassSeats=" + numFirstClassSeats + ", numEconomyClassSeats=" + numEconomyClassSeats + ", airplaneTypeId=" + airplaneTypeId + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FlightImpl other = (FlightImpl) obj; if (airplaneTypeId == null) { if (other.airplaneTypeId != null) return false; } else if (!airplaneTypeId.equals(other.airplaneTypeId)) return false; if (economyClassBaseCost == null) { if (other.economyClassBaseCost != null) return false; } else if (!economyClassBaseCost.equals(other.economyClassBaseCost)) return false; if (firstClassBaseCost == null) { if (other.firstClassBaseCost != null) return false; } else if (!firstClassBaseCost.equals(other.firstClassBaseCost)) return false; if (flightSegment == null) { if (other.flightSegment != null) return false; } else if (!flightSegment.equals(other.flightSegment)) return false; if (_id == null) { if (other._id != null) return false; } else if (!_id.equals(other._id)) return false; if (numEconomyClassSeats != other.numEconomyClassSeats) return false; if (numFirstClassSeats != other.numFirstClassSeats) return false; if (scheduledArrivalTime == null) { if (other.scheduledArrivalTime != null) return false; } else if (!scheduledArrivalTime.equals(other.scheduledArrivalTime)) return false; if (scheduledDepartureTime == null) { if (other.scheduledDepartureTime != null) return false; } else if (!scheduledDepartureTime.equals(other.scheduledDepartureTime)) return false; return true; } }
6,066
25.845133
80
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightSegmentImpl.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.morphia.entities; import java.io.Serializable; import org.mongodb.morphia.annotations.Entity; import com.acmeair.entities.FlightSegment; @Entity(value="flightSegment") public class FlightSegmentImpl implements FlightSegment, Serializable{ private static final long serialVersionUID = 1L; private String _id; private String originPort; private String destPort; private int miles; public FlightSegmentImpl() { } public FlightSegmentImpl(String flightName, String origPort, String destPort, int miles) { this._id = flightName; this.originPort = origPort; this.destPort = destPort; this.miles = miles; } public String getFlightName() { return _id; } public void setFlightName(String flightName) { this._id = flightName; } public String getOriginPort() { return originPort; } public void setOriginPort(String originPort) { this.originPort = originPort; } public String getDestPort() { return destPort; } public void setDestPort(String destPort) { this.destPort = destPort; } public int getMiles() { return miles; } public void setMiles(int miles) { this.miles = miles; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("FlightSegment ").append(_id).append(" originating from:\"").append(originPort).append("\" arriving at:\"").append(destPort).append("\""); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FlightSegmentImpl other = (FlightSegmentImpl) obj; if (destPort == null) { if (other.destPort != null) return false; } else if (!destPort.equals(other.destPort)) return false; if (_id == null) { if (other._id != null) return false; } else if (!_id.equals(other._id)) return false; if (miles != other.miles) return false; if (originPort == null) { if (other.originPort != null) return false; } else if (!originPort.equals(other.originPort)) return false; return true; } }
2,853
24.256637
150
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/BookingServiceImpl.java
package com.acmeair.morphia.services; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.mongodb.morphia.Datastore; import com.acmeair.entities.Booking; import com.acmeair.entities.Customer; import com.acmeair.entities.Flight; import com.acmeair.morphia.MorphiaConstants; import com.acmeair.morphia.entities.BookingImpl; import com.acmeair.morphia.services.util.MongoConnectionManager; import com.acmeair.service.BookingService; import com.acmeair.service.CustomerService; import com.acmeair.service.DataService; import com.acmeair.service.FlightService; import com.acmeair.service.KeyGenerator; import com.acmeair.service.ServiceLocator; import org.mongodb.morphia.query.Query; @DataService(name=MorphiaConstants.KEY,description=MorphiaConstants.KEY_DESCRIPTION) public class BookingServiceImpl implements BookingService, MorphiaConstants { //private final static Logger logger = Logger.getLogger(BookingService.class.getName()); Datastore datastore; @Inject KeyGenerator keyGenerator; private FlightService flightService = ServiceLocator.instance().getService(FlightService.class); private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); @PostConstruct public void initialization() { datastore = MongoConnectionManager.getConnectionManager().getDatastore(); } public String bookFlight(String customerId, String flightId) { try{ Flight f = flightService.getFlightByFlightId(flightId, null); Customer c = customerService.getCustomerByUsername(customerId); Booking newBooking = new BookingImpl(keyGenerator.generate().toString(), new Date(), c, f); datastore.save(newBooking); return newBooking.getBookingId(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public String bookFlight(String customerId, String flightSegmentId, String flightId) { return bookFlight(customerId, flightId); } @Override public Booking getBooking(String user, String bookingId) { try{ Query<BookingImpl> q = datastore.find(BookingImpl.class).field("_id").equal(bookingId); Booking booking = q.get(); return booking; } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<Booking> getBookingsByUser(String user) { try{ Query<BookingImpl> q = datastore.find(BookingImpl.class).disableValidation().field("customerId").equal(user); List<BookingImpl> bookingImpls = q.asList(); List<Booking> bookings = new ArrayList<Booking>(); for(Booking b: bookingImpls){ bookings.add(b); } return bookings; } catch (Exception e) { throw new RuntimeException(e); } } @Override public void cancelBooking(String user, String bookingId) { try{ datastore.delete(BookingImpl.class, bookingId); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Long count() { return datastore.find(BookingImpl.class).countAll(); } }
3,058
26.3125
112
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/CustomerServiceImpl.java
package com.acmeair.morphia.services; import java.util.Date; import javax.annotation.PostConstruct; import com.acmeair.entities.Customer; import com.acmeair.entities.Customer.MemberShipStatus; import com.acmeair.entities.Customer.PhoneType; import com.acmeair.entities.CustomerAddress; import com.acmeair.entities.CustomerSession; import com.acmeair.morphia.entities.CustomerAddressImpl; import com.acmeair.morphia.entities.CustomerSessionImpl; import com.acmeair.morphia.MorphiaConstants; import com.acmeair.morphia.entities.CustomerImpl; import com.acmeair.morphia.services.util.MongoConnectionManager; import com.acmeair.service.DataService; import com.acmeair.service.CustomerService; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.query.Query; @DataService(name=MorphiaConstants.KEY,description=MorphiaConstants.KEY_DESCRIPTION) public class CustomerServiceImpl extends CustomerService implements MorphiaConstants { // private final static Logger logger = Logger.getLogger(CustomerService.class.getName()); protected Datastore datastore; @PostConstruct public void initialization() { datastore = MongoConnectionManager.getConnectionManager().getDatastore(); } @Override public Long count() { return datastore.find(CustomerImpl.class).countAll(); } @Override public Long countSessions() { return datastore.find(CustomerSessionImpl.class).countAll(); } @Override public Customer createCustomer(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber, PhoneType phoneNumberType, CustomerAddress address) { Customer customer = new CustomerImpl(username, password, status, total_miles, miles_ytd, address, phoneNumber, phoneNumberType); datastore.save(customer); return customer; } @Override public CustomerAddress createAddress (String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode){ CustomerAddress address = new CustomerAddressImpl(streetAddress1, streetAddress2, city, stateProvince, country, postalCode); return address; } @Override public Customer updateCustomer(Customer customer) { datastore.save(customer); return customer; } @Override protected Customer getCustomer(String username) { Query<CustomerImpl> q = datastore.find(CustomerImpl.class).field("_id").equal(username); Customer customer = q.get(); return customer; } @Override public Customer getCustomerByUsername(String username) { Query<CustomerImpl> q = datastore.find(CustomerImpl.class).field("_id").equal(username); Customer customer = q.get(); if (customer != null) { customer.setPassword(null); } return customer; } @Override protected CustomerSession getSession(String sessionid){ Query<CustomerSessionImpl> q = datastore.find(CustomerSessionImpl.class).field("_id").equal(sessionid); return q.get(); } @Override protected void removeSession(CustomerSession session){ datastore.delete(session); } @Override protected CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration) { CustomerSession cSession = new CustomerSessionImpl(sessionId, customerId, creation, expiration); datastore.save(cSession); return cSession; } @Override public void invalidateSession(String sessionid) { Query<CustomerSessionImpl> q = datastore.find(CustomerSessionImpl.class).field("_id").equal(sessionid); datastore.delete(q); } }
3,528
29.686957
130
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/FlightServiceImpl.java
/******************************************************************************* * Copyright (c) 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.morphia.services; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import com.acmeair.entities.AirportCodeMapping; import com.acmeair.entities.Flight; import com.acmeair.entities.FlightSegment; import com.acmeair.morphia.MorphiaConstants; import com.acmeair.morphia.entities.AirportCodeMappingImpl; import com.acmeair.morphia.entities.FlightImpl; import com.acmeair.morphia.entities.FlightSegmentImpl; import com.acmeair.morphia.services.util.MongoConnectionManager; import com.acmeair.service.DataService; import com.acmeair.service.FlightService; import com.acmeair.service.KeyGenerator; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.query.Query; @DataService(name=MorphiaConstants.KEY,description=MorphiaConstants.KEY_DESCRIPTION) public class FlightServiceImpl extends FlightService implements MorphiaConstants { //private final static Logger logger = Logger.getLogger(FlightService.class.getName()); Datastore datastore; @Inject KeyGenerator keyGenerator; @PostConstruct public void initialization() { datastore = MongoConnectionManager.getConnectionManager().getDatastore(); } @Override public Long countFlights() { return datastore.find(FlightImpl.class).countAll(); } @Override public Long countFlightSegments() { return datastore.find(FlightSegmentImpl.class).countAll(); } @Override public Long countAirports() { return datastore.find(AirportCodeMappingImpl.class).countAll(); } /* @Override public Flight getFlightByFlightId(String flightId, String flightSegmentId) { try { Flight flight = flightPKtoFlightCache.get(flightId); if (flight == null) { Query<FlightImpl> q = datastore.find(FlightImpl.class).field("_id").equal(flightId); flight = q.get(); if (flightId != null && flight != null) { flightPKtoFlightCache.putIfAbsent(flight, flight); } } return flight; } catch (Exception e) { throw new RuntimeException(e); } } */ protected Flight getFlight(String flightId, String segmentId) { Query<FlightImpl> q = datastore.find(FlightImpl.class).field("_id").equal(flightId); return q.get(); } @Override protected FlightSegment getFlightSegment(String fromAirport, String toAirport){ Query<FlightSegmentImpl> q = datastore.find(FlightSegmentImpl.class).field("originPort").equal(fromAirport).field("destPort").equal(toAirport); FlightSegment segment = q.get(); if (segment == null) { segment = new FlightSegmentImpl(); // put a sentinel value of a non-populated flightsegment } return segment; } @Override protected List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate){ Query<FlightImpl> q2; if(deptDate != null) { q2 = datastore.find(FlightImpl.class).disableValidation().field("flightSegmentId").equal(segment.getFlightName()).field("scheduledDepartureTime").equal(deptDate); } else { q2 = datastore.find(FlightImpl.class).disableValidation().field("flightSegmentId").equal(segment.getFlightName()); } List<FlightImpl> flightImpls = q2.asList(); List<Flight> flights; if (flightImpls != null) { flights = new ArrayList<Flight>(); for (Flight flight : flightImpls) { flight.setFlightSegment(segment); flights.add(flight); } } else { flights = new ArrayList<Flight>(); // put an empty list into the cache in the cache in the case where no matching flights } return flights; } @Override public void storeAirportMapping(AirportCodeMapping mapping) { try{ datastore.save(mapping); } catch (Exception e) { throw new RuntimeException(e); } } @Override public AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName){ AirportCodeMapping acm = new AirportCodeMappingImpl(airportCode, airportName); return acm; } @Override public Flight createNewFlight(String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId) { String id = keyGenerator.generate().toString(); Flight flight = new FlightImpl(id, flightSegmentId, scheduledDepartureTime, scheduledArrivalTime, firstClassBaseCost, economyClassBaseCost, numFirstClassSeats, numEconomyClassSeats, airplaneTypeId); try{ datastore.save(flight); return flight; } catch (Exception e) { throw new RuntimeException(e); } } @Override public void storeFlightSegment(FlightSegment flightSeg) { try{ datastore.save(flightSeg); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void storeFlightSegment(String flightName, String origPort, String destPort, int miles) { FlightSegment flightSeg = new FlightSegmentImpl(flightName, origPort, destPort, miles); storeFlightSegment(flightSeg); } }
5,739
30.538462
165
java
acmeair
acmeair-master/acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/util/MongoConnectionManager.java
package com.acmeair.morphia.services.util; import java.io.IOException; import java.net.URL; import java.net.UnknownHostException; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; import javax.annotation.Resource; import javax.naming.InitialContext; import javax.naming.NamingException; import com.acmeair.morphia.BigDecimalConverter; import com.acmeair.morphia.MorphiaConstants; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Morphia; import com.mongodb.DB; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientURI; import com.mongodb.ServerAddress; import com.mongodb.WriteConcern; public class MongoConnectionManager implements MorphiaConstants{ private static AtomicReference<MongoConnectionManager> connectionManager = new AtomicReference<MongoConnectionManager>(); private final static Logger logger = Logger.getLogger(MongoConnectionManager.class.getName()); @Resource(name = JNDI_NAME) protected DB db; private static Datastore datastore; public static MongoConnectionManager getConnectionManager() { if (connectionManager.get() == null) { synchronized (connectionManager) { if (connectionManager.get() == null) { connectionManager.set(new MongoConnectionManager()); } } } return connectionManager.get(); } private MongoConnectionManager (){ Morphia morphia = new Morphia(); // Set default client options, and then check if there is a properties file. boolean fsync = false; int w = 0; int connectionsPerHost = 5; int threadsAllowedToBlockForConnectionMultiplier = 10; int connectTimeout= 0; int socketTimeout= 0; boolean socketKeepAlive = true; int maxWaitTime = 2000; Properties prop = new Properties(); URL mongoPropertyFile = MongoConnectionManager.class.getResource("/com/acmeair/morphia/services/util/mongo.properties"); if(mongoPropertyFile != null){ try { logger.info("Reading mongo.properties file"); prop.load(mongoPropertyFile.openStream()); fsync = new Boolean(prop.getProperty("mongo.fsync")); w = new Integer(prop.getProperty("mongo.w")); connectionsPerHost = new Integer(prop.getProperty("mongo.connectionsPerHost")); threadsAllowedToBlockForConnectionMultiplier = new Integer(prop.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier")); connectTimeout= new Integer(prop.getProperty("mongo.connectTimeout")); socketTimeout= new Integer(prop.getProperty("mongo.socketTimeout")); socketKeepAlive = new Boolean(prop.getProperty("mongo.socketKeepAlive")); maxWaitTime =new Integer(prop.getProperty("mongo.maxWaitTime")); }catch (IOException ioe){ logger.severe("Exception when trying to read from the mongo.properties file" + ioe.getMessage()); } } // Set the client options MongoClientOptions.Builder builder = new MongoClientOptions.Builder() .writeConcern(new WriteConcern(w, 0, fsync)) .connectionsPerHost(connectionsPerHost) .connectTimeout(connectTimeout) .socketTimeout(socketTimeout) .socketKeepAlive(socketKeepAlive) .maxWaitTime(maxWaitTime) .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier); try { //Check if VCAP_SERVICES exist, and if it does, look up the url from the credentials. String vcapJSONString = System.getenv("VCAP_SERVICES"); if (vcapJSONString != null) { logger.info("Reading VCAP_SERVICES"); Object jsonObject = JSONValue.parse(vcapJSONString); JSONObject vcapServices = (JSONObject)jsonObject; JSONArray mongoServiceArray =null; for (Object key : vcapServices.keySet()){ if (key.toString().startsWith("mongo")){ mongoServiceArray = (JSONArray) vcapServices.get(key); break; } } if (mongoServiceArray == null) { logger.severe("VCAP_SERVICES existed, but a mongo service was not definied."); } else { JSONObject mongoService = (JSONObject)mongoServiceArray.get(0); JSONObject credentials = (JSONObject)mongoService.get("credentials"); String url = (String) credentials.get("url"); logger.fine("service url = " + url); MongoClientURI mongoURI = new MongoClientURI(url, builder); MongoClient mongo = new MongoClient(mongoURI); morphia.getMapper().getConverters().addConverter(new BigDecimalConverter()); datastore = morphia.createDatastore( mongo ,mongoURI.getDatabase()); } } else { //VCAP_SERVICES don't exist, so use the DB resource logger.fine("No VCAP_SERVICES found"); if(db == null){ try { logger.warning("Resource Injection failed. Attempting to look up " + JNDI_NAME + " via JNDI."); db = (DB) new InitialContext().lookup(JNDI_NAME); } catch (NamingException e) { logger.severe("Caught NamingException : " + e.getMessage() ); } } if(db == null){ String host; String port; String database; logger.info("Creating the MongoDB Client connection. Looking up host and port information " ); try { host = (String) new InitialContext().lookup("java:comp/env/" + HOSTNAME); port = (String) new InitialContext().lookup("java:comp/env/" + PORT); database = (String) new InitialContext().lookup("java:comp/env/" + DATABASE); ServerAddress server = new ServerAddress(host, Integer.parseInt(port)); MongoClient mongo = new MongoClient(server); db = mongo.getDB(database); } catch (NamingException e) { logger.severe("Caught NamingException : " + e.getMessage() ); } catch (Exception e) { logger.severe("Caught Exception : " + e.getMessage() ); } } if(db == null){ logger.severe("Unable to retreive reference to database, please check the server logs."); } else { morphia.getMapper().getConverters().addConverter(new BigDecimalConverter()); datastore = morphia.createDatastore(new MongoClient(db.getMongo().getConnectPoint(),builder.build()), db.getName()); } } } catch (UnknownHostException e) { logger.severe("Caught Exception : " + e.getMessage() ); } logger.info("created mongo datastore with options:"+datastore.getMongo().getMongoClientOptions()); } public DB getDB(){ return db; } public Datastore getDatastore(){ return datastore; } @SuppressWarnings("deprecation") public String getDriverVersion(){ return datastore.getMongo().getVersion(); } public String getMongoVersion(){ return datastore.getDB().command("buildInfo").getString("version"); } }
6,739
34.851064
135
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/entities/BookingPK.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.entities; public interface BookingPK { public String getId(); public String getCustomerId(); }
862
36.521739
80
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/entities/FlightPK.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.entities; public interface FlightPK { }
805
37.380952
80
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/WXSConstants.java
package com.acmeair.wxs; public interface WXSConstants { public static final String JNDI_NAME = "wxs/acmeair"; public static final String KEY = "wxs"; public static final String KEY_DESCRIPTION = "eXtreme Scale"; }
222
21.3
62
java
acmeair
acmeair-master/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/AirportCodeMappingImpl.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.wxs.entities; import java.io.Serializable; import com.acmeair.entities.AirportCodeMapping; public class AirportCodeMappingImpl implements AirportCodeMapping, Serializable{ private static final long serialVersionUID = 1L; private String _id; private String airportName; public AirportCodeMappingImpl() { } public AirportCodeMappingImpl(String airportCode, String airportName) { this._id = airportCode; this.airportName = airportName; } public String getAirportCode() { return _id; } public void setAirportCode(String airportCode) { this._id = airportCode; } public String getAirportName() { return airportName; } public void setAirportName(String airportName) { this.airportName = airportName; } }
1,500
27.320755
80
java