method2testcases
stringlengths 118
6.63k
|
---|
### Question:
AbstractSupplier implements Observer, Supplier<T> { @Override public void addDataListeningObject(DataListening observer) { if (this.dataListenings.isEmpty()) { this.dataManager().addObserver(this); } this.dataListenings.add(observer); } @Override List<T> getAll(); @Override void onResume(); @Override void addDataListeningObject(DataListening observer); @Override void deregister(DataListening observer); @Override void onPause(); @Override void update(Observable observable, Object o); }### Answer:
@Test public void teste_addDataListening_shouldRegisterItselfOnDataManager() { StubbedDataManager dataManager = new StubbedDataManager(); FullfilledSupplier componenet_under_test = new FullfilledSupplier(dataManager); DummyDataListening dataListening = new DummyDataListening(); componenet_under_test.addDataListeningObject(dataListening); assertThat(dataManager.observers()).containsExactly(componenet_under_test); }
|
### Question:
BankingDateInformation { public double getAmountDelta() { double amountDelta = 0.0; for (Transaction transaction : this.transactionSupplier.getAll()) { amountDelta += transaction.booking().getAmount(); } return amountDelta; } BankingDateInformation(double amount, Supplier<Transaction> transactionSupplier); double getAmount(); double getAmountDelta(); Supplier<Transaction> getTransactionSuppllier(); }### Answer:
@Test public void getAmountDelta_noBookings() { double amount = 123.456; BankingDateInformation bankingDateInformation = new BankingDateInformation(amount, new StubbedBankTransactionSupplier()); assertThat(bankingDateInformation.getAmountDelta()).isZero(); }
@Test public void getAmountDelta_bookings() { double amount = 123.456; double amount1 = 500.00; double amount2 = -100.00; Booking booking1 = new Booking(new Date(), amount1); Transaction transaction1 = new Transaction("some name","some id",booking1); Booking booking2 = new Booking(new Date(), amount2); Transaction transaction2 = new Transaction("some name","some id",booking2); BankingDateInformation bankingDateInformation = new BankingDateInformation(amount, new StubbedBankTransactionSupplier(transaction1, transaction2)); assertThat(bankingDateInformation.getAmountDelta()).isEqualTo(amount1+amount2); }
|
### Question:
SavingsComparator implements Comparator<SavingsAccount> { @Override public int compare(SavingsAccount t1, SavingsAccount t2) { return t1.getFinaldate().compareTo(t2.getFinaldate()); } @Override int compare(SavingsAccount t1, SavingsAccount t2); }### Answer:
@Test public void teste_compare_withEqualSavings_shouldReturnZero() { SavingsComparator component_under_test = new SavingsComparator(); SavingsAccount account = new SavingsAccount(123, "some anme", 10, 0, any(), any()); assertThat(component_under_test.compare(account, account)).isEqualTo(0); }
@Test public void teste_compare_firstDateLaterThenSecond_shouldReturnOne() throws Exception { SavingsComparator component_under_test = new SavingsComparator(); SavingsAccount earlyAccount = new SavingsAccount(123, "some anme", 10, 0, toDate("10/10/16"), any()); SavingsAccount lateAccount = new SavingsAccount(123, "some anme", 10, 0, toDate("10/10/17"), any()); assertThat(component_under_test.compare(lateAccount, earlyAccount)).isEqualTo(1); }
@Test public void teste_compare_firstDateBeforeThenSecond_shouldReturnMinusOne() throws Exception { SavingsComparator component_under_test = new SavingsComparator(); SavingsAccount earlyAccount = new SavingsAccount(123, "some anme", 10, 0, toDate("10/10/16"), any()); SavingsAccount lateAccount = new SavingsAccount(123, "some anme", 10, 0, toDate("10/10/17"), any()); assertThat(component_under_test.compare(earlyAccount, lateAccount)).isEqualTo(-1); }
|
### Question:
BankingApiFacade { public List<BankAccessBankingModel> getBankAccesses(final String userId) throws BankingException { return binder.getBankAccessEndpoint(userId).getBankAccesses(); } @Autowired BankingApiFacade(final BankingApiBinder binder); protected BankingApiFacade(); List<BankAccessBankingModel> getBankAccesses(final String userId); List<BankAccountBankingModel> getBankAccounts(final String userId, final String bankAccessId); List<BookingModel> syncBankAccount(final String userId, final String bankAccessId, final String bankAccountId, final String pin); BankAccessBankingModel addBankAccess(final String userId, final BankAccessBankingModel bankAccess); }### Answer:
@Test public void getAccessesBinderCalled() { DummyBankAccessEndpoint endpoint = mock(DummyBankAccessEndpoint.class); when(bankingApiBinder.getBankAccessEndpoint(anyString())).thenReturn(endpoint); BankingApiFacade bankingApiFacade = new BankingApiFacade(bankingApiBinder); try { bankingApiFacade.getBankAccesses("test"); } catch (BankingException ex) { fail("An Banking Exception was thrown! " + ex.getMessage()); } Mockito.verify(bankingApiBinder, times(1)).getBankAccessEndpoint(anyString()); }
|
### Question:
BankingApiFacade { public List<BankAccountBankingModel> getBankAccounts(final String userId, final String bankAccessId) throws BankingException { return binder.getBankAccountEndpoint(userId).getBankAccounts(bankAccessId); } @Autowired BankingApiFacade(final BankingApiBinder binder); protected BankingApiFacade(); List<BankAccessBankingModel> getBankAccesses(final String userId); List<BankAccountBankingModel> getBankAccounts(final String userId, final String bankAccessId); List<BookingModel> syncBankAccount(final String userId, final String bankAccessId, final String bankAccountId, final String pin); BankAccessBankingModel addBankAccess(final String userId, final BankAccessBankingModel bankAccess); }### Answer:
@Test public void getAccountsBinderCalled() { DummyBankAccountEndpoint endpoint = mock(DummyBankAccountEndpoint.class); when(bankingApiBinder.getBankAccountEndpoint(anyString())).thenReturn(endpoint); BankingApiFacade bankingApiFacade = new BankingApiFacade(bankingApiBinder); try { bankingApiFacade.getBankAccounts("test", "test"); } catch (BankingException ex) { fail("An Banking Exception was thrown! " + ex.getMessage()); } Mockito.verify(bankingApiBinder, times(1)).getBankAccountEndpoint(anyString()); }
|
### Question:
BankingApiFacade { public List<BookingModel> syncBankAccount(final String userId, final String bankAccessId, final String bankAccountId, final String pin) throws BankingException { return binder.getBankAccountEndpoint(userId).syncBankAccount(bankAccessId, bankAccountId, pin); } @Autowired BankingApiFacade(final BankingApiBinder binder); protected BankingApiFacade(); List<BankAccessBankingModel> getBankAccesses(final String userId); List<BankAccountBankingModel> getBankAccounts(final String userId, final String bankAccessId); List<BookingModel> syncBankAccount(final String userId, final String bankAccessId, final String bankAccountId, final String pin); BankAccessBankingModel addBankAccess(final String userId, final BankAccessBankingModel bankAccess); }### Answer:
@Test public void syncAccountBinderCalled() { DummyBankAccountEndpoint endpoint = mock(DummyBankAccountEndpoint.class); when(bankingApiBinder.getBankAccountEndpoint(anyString())).thenReturn(endpoint); BankingApiFacade bankingApiFacade = new BankingApiFacade(bankingApiBinder); try { bankingApiFacade.syncBankAccount("test", "test", "test", "test"); } catch (BankingException ex) { fail("An Banking Exception was thrown! " + ex.getMessage()); } Mockito.verify(bankingApiBinder, times(1)).getBankAccountEndpoint(anyString()); }
|
### Question:
DummyBankAccountEndpoint implements BankAccountEndpoint { @Override public List<BankAccountBankingModel> getBankAccounts(String bankingAccessId) throws BankingException { if (!dummyBankAccessEndpoint.existsBankAccess(bankingAccessId)) { return new ArrayList<BankAccountBankingModel>(); } if (!bankAccountBankingModelRepository.existBankAccountsForAccessId(bankingAccessId)) { this.generateDummyBankAccountModels(bankingAccessId); } List<DummyBankAccountBankingModelEntity> allByAccessId = bankAccountBankingModelRepository.findAllByAccessId(bankingAccessId); List<BankAccountBankingModel> bankAccountBankingModelList = new ArrayList<>(); for (DummyBankAccountBankingModelEntity bankAccountBankingModelEntity : allByAccessId) { if (!bookingModelMap.containsKey(bankAccountBankingModelEntity.getId())) { generateDummyBookingModels(bankAccountBankingModelEntity.getId()); updateAccountBalance(bankAccountBankingModelEntity.getId()); } bankAccountBankingModelEntity.setBankAccountBalance(accountBalanceMap.get(bankAccountBankingModelEntity.getId())); bankAccountBankingModelList.add(bankAccountBankingModelEntity.transformIntoBankAccountBankingModel()); } return bankAccountBankingModelList; } @Autowired DummyBankAccountEndpoint(DummyBankAccountBankingModelRepository bankAccountBankingModelRepository, DummyBankAccessEndpointRepository bankAccessEndpointRepository, @Qualifier("dummy") DummyBankAccessEndpoint dummyBankAccessEndpoint); protected DummyBankAccountEndpoint(); @Override List<BankAccountBankingModel> getBankAccounts(String bankingAccessId); @Override List<BookingModel> syncBankAccount(String bankAccessId, String bankAccountId, String pin); }### Answer:
@Test public void getBankAccountsAccountsExist() throws Exception { String testUserId = "userId"; DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class); DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class); DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpoint.existsBankAccess(anyString())).thenReturn(true); when(dummyBankAccountBankingModelRepository.existBankAccountsForAccessId(anyString())).thenReturn(true); when(dummyBankAccountBankingModelRepository.findAllByAccessId(anyString())).thenReturn(generateBankingAccounts()); DummyBankAccountEndpoint dummyBankAccountEndpoint = new DummyBankAccountEndpoint(dummyBankAccountBankingModelRepository, dummyBankAccessEndpointRepository, dummyBankAccessEndpoint); List<BankAccountBankingModel> bankAccounts = dummyBankAccountEndpoint.getBankAccounts( "bankAccessId"); assertNotNull(bankAccounts); assertTrue(bankAccounts.size() == amountAccountsToGenerate); verify(dummyBankAccountBankingModelRepository, times(1)).findAllByAccessId(anyString()); }
@Test public void getBankAccountsAccountsNotExist() throws Exception { String testUserId = "userId"; DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class); DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class); DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpoint.existsBankAccess(anyString())).thenReturn(true); when(dummyBankAccountBankingModelRepository.existBankAccountsForAccessId(anyString())).thenReturn(false); DummyBankAccountEndpoint dummyBankAccountEndpoint = new DummyBankAccountEndpoint(dummyBankAccountBankingModelRepository, dummyBankAccessEndpointRepository, dummyBankAccessEndpoint); List<BankAccountBankingModel> bankAccounts = dummyBankAccountEndpoint.getBankAccounts( "bankAccessId"); assertNotNull(bankAccounts); assertTrue(bankAccounts.size() >= 0); verify(dummyBankAccountBankingModelRepository, times(1)).findAllByAccessId(anyString()); verify(dummyBankAccountBankingModelRepository, atLeastOnce()).save(any(List.class)); }
|
### Question:
AbstractDataManager extends Observable implements DataManager<T> { @Override public SyncStatus getSyncStatus() { return syncStatus; } AbstractDataManager(DataProvider<T> dataProvider); @Override void sync(); @Override SyncStatus getSyncStatus(); @Override List<T> getAll(); @Override void add(final T element, final ServerCallStatusHandler handler); @Override void delete(final T element, final ServerCallStatusHandler handler); }### Answer:
@Test public void test_initialState_isNotInSync(){ FullfilledDataManager component_under_test = new FullfilledDataManager(new StubbedSavingsProvider()); assertThat(component_under_test.getSyncStatus()).isEqualTo(SyncStatus.NOT_SYNCED); }
|
### Question:
DummyBankAccountEndpoint implements BankAccountEndpoint { @Override public List<BookingModel> syncBankAccount(String bankAccessId, String bankAccountId, String pin) throws BankingException { if (!bookingModelMap.containsKey(bankAccountId)) { generateDummyBookingModels(bankAccountId); updateAccountBalance(bankAccountId); } return bookingModelMap.get(bankAccountId); } @Autowired DummyBankAccountEndpoint(DummyBankAccountBankingModelRepository bankAccountBankingModelRepository, DummyBankAccessEndpointRepository bankAccessEndpointRepository, @Qualifier("dummy") DummyBankAccessEndpoint dummyBankAccessEndpoint); protected DummyBankAccountEndpoint(); @Override List<BankAccountBankingModel> getBankAccounts(String bankingAccessId); @Override List<BookingModel> syncBankAccount(String bankAccessId, String bankAccountId, String pin); }### Answer:
@Test public void syncBankAccountsAccountsNotExist() throws Exception { String testUserId = "userId"; DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class); DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class); DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); DummyBankAccountEndpoint dummyBankAccountEndpoint = new DummyBankAccountEndpoint(dummyBankAccountBankingModelRepository, dummyBankAccessEndpointRepository, dummyBankAccessEndpoint); List<BookingModel> bookings = dummyBankAccountEndpoint.syncBankAccount( "bankAccessId", "bankAccountId", "pin"); assertNotNull(bookings); assertTrue(bookings.size() >= 0); }
|
### Question:
BankingApiBinder { BankAccountEndpoint getBankAccountEndpoint(final String userId) { return isTestUser(userId) ? dummyBankAccountEndpoint : httpBankAccountEndpoint; } @Autowired BankingApiBinder(final BankingApiConfiguration bankingApiConfiguration,
@Qualifier("default") final BankAccessEndpoint httpBankAccessEndpoint,
@Qualifier("dummy") final BankAccessEndpoint dummyBankAccessEndpoint,
@Qualifier("default") final BankAccountEndpoint httpBankAccountEndpoint,
@Qualifier("dummy") final BankAccountEndpoint dummyBankAccountEndpoint); protected BankingApiBinder(); }### Answer:
@Test public void getBankAccountEndpointDummy() { String username = "[email protected]"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, null, null, new HttpBankAccountEndpoint(null, null), new DummyBankAccountEndpoint(null, null, null)); BankAccountEndpoint endpoint = bankingApiBinder.getBankAccountEndpoint(username); Assert.assertNotNull(endpoint); Assert.assertTrue(endpoint instanceof DummyBankAccountEndpoint); verify(bankingApiConfiguration, times(1)).getTestUserNames(); }
@Test public void getBankAccountEndpointHttp() { String username = "[email protected]"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, null, null, new HttpBankAccountEndpoint(null, null), new DummyBankAccountEndpoint(null, null, null)); BankAccountEndpoint endpoint = bankingApiBinder.getBankAccountEndpoint(username); Assert.assertNotNull(endpoint); Assert.assertTrue(endpoint instanceof HttpBankAccountEndpoint); verify(bankingApiConfiguration, times(1)).getTestUserNames(); }
|
### Question:
BankingApiBinder { BankAccessEndpoint getBankAccessEndpoint(final String userId) { return isTestUser(userId) ? dummyBankAccessEndpoint : httpBankAccessEndpoint; } @Autowired BankingApiBinder(final BankingApiConfiguration bankingApiConfiguration,
@Qualifier("default") final BankAccessEndpoint httpBankAccessEndpoint,
@Qualifier("dummy") final BankAccessEndpoint dummyBankAccessEndpoint,
@Qualifier("default") final BankAccountEndpoint httpBankAccountEndpoint,
@Qualifier("dummy") final BankAccountEndpoint dummyBankAccountEndpoint); protected BankingApiBinder(); }### Answer:
@Test public void getBankAccessEndpointDummy() { String username = "[email protected]"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, new HttpBankAccessEndpoint(null, null), new DummyBankAccessEndpoint(), null, null); BankAccessEndpoint endpoint = bankingApiBinder.getBankAccessEndpoint(username); Assert.assertNotNull(endpoint); Assert.assertTrue(endpoint instanceof DummyBankAccessEndpoint); verify(bankingApiConfiguration, times(1)).getTestUserNames(); }
@Test public void getBankAccessEndpointHttp() { String username = "[email protected]"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, new HttpBankAccessEndpoint(null, null), new DummyBankAccessEndpoint(), null, null); BankAccessEndpoint endpoint = bankingApiBinder.getBankAccessEndpoint(username); Assert.assertNotNull(endpoint); Assert.assertTrue(endpoint instanceof HttpBankAccessEndpoint); verify(bankingApiConfiguration, times(1)).getTestUserNames(); }
|
### Question:
DummyBankAccessEndpoint implements BankAccessEndpoint { @Override public BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess) throws BankingException { BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setId("TestID" + number + "_" + System.nanoTime()); bankAccessBankingModel.setBankLogin(bankAccess.getBankLogin()); bankAccessBankingModel.setBankCode(bankAccess.getBankCode()); bankAccessBankingModel.setBankName("TestBank" + number); bankAccessBankingModel.setPin(null); bankAccessBankingModel.setPassportState("testPassportState"); bankAccessEndpointRepository.save(new DummyBankAccessBankingModelEntity(bankAccessBankingModel)); number++; return bankAccessBankingModel; } DummyBankAccessEndpoint(DummyBankAccessEndpointRepository bankAccessEndpointRepository); DummyBankAccessEndpoint(); @Override List<BankAccessBankingModel> getBankAccesses(); @Override BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess); boolean existsBankAccess(String bankAccessId); }### Answer:
@Test public void addRepositoryCalled() throws Exception { String testUser = "user"; String testBankCode = "testCode"; String testBankLogin = "testLogin"; BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setUserId(testUser); bankAccessBankingModel.setBankLogin(testBankLogin); bankAccessBankingModel.setBankCode(testBankCode); DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); DummyBankAccessEndpoint dummyBankAccessEndpoint = new DummyBankAccessEndpoint(dummyBankAccessEndpointRepository); dummyBankAccessEndpoint.addBankAccess(bankAccessBankingModel); verify(dummyBankAccessEndpointRepository, times(1)).save(any(DummyBankAccessBankingModelEntity.class)); }
|
### Question:
DummyBankAccessEndpoint implements BankAccessEndpoint { public boolean existsBankAccess(String bankAccessId) { return bankAccessEndpointRepository.exists(bankAccessId); } DummyBankAccessEndpoint(DummyBankAccessEndpointRepository bankAccessEndpointRepository); DummyBankAccessEndpoint(); @Override List<BankAccessBankingModel> getBankAccesses(); @Override BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess); boolean existsBankAccess(String bankAccessId); }### Answer:
@Test public void existsRepositoryCalled() throws Exception { String testId = "test"; DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpointRepository.exists(anyString())).thenReturn(true); DummyBankAccessEndpoint dummyBankAccessEndpoint = new DummyBankAccessEndpoint(dummyBankAccessEndpointRepository); boolean existsPreChange = dummyBankAccessEndpoint.existsBankAccess(testId); verify(dummyBankAccessEndpointRepository, times(1)).exists(anyString()); }
|
### Question:
DummyBankAccessEndpoint implements BankAccessEndpoint { @Override public List<BankAccessBankingModel> getBankAccesses() throws BankingException { List<DummyBankAccessBankingModelEntity> dummyBankAccessBankingModelEntities = bankAccessEndpointRepository.findAll(); List<BankAccessBankingModel> bankAccessBankingModelList = new ArrayList<>(); for (DummyBankAccessBankingModelEntity dummyBankAccessBankingModelEntity : dummyBankAccessBankingModelEntities) { bankAccessBankingModelList.add(dummyBankAccessBankingModelEntity.transformToBankAccessBankingModel()); } return bankAccessBankingModelList; } DummyBankAccessEndpoint(DummyBankAccessEndpointRepository bankAccessEndpointRepository); DummyBankAccessEndpoint(); @Override List<BankAccessBankingModel> getBankAccesses(); @Override BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess); boolean existsBankAccess(String bankAccessId); }### Answer:
@Test public void getRepositoryCalled() throws Exception { String testId = "test"; DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpointRepository.findAll()).thenReturn(new ArrayList<DummyBankAccessBankingModelEntity>()); DummyBankAccessEndpoint dummyBankAccessEndpoint = new DummyBankAccessEndpoint(dummyBankAccessEndpointRepository); List<BankAccessBankingModel> bankAccessBankingModelList = dummyBankAccessEndpoint.getBankAccesses(); verify(dummyBankAccessEndpointRepository, times(1)).findAll(); }
|
### Question:
AbstractDataManager extends Observable implements DataManager<T> { @Override public void add(final T element, final ServerCallStatusHandler handler) { logger().info("Adding element: " + element); Consumer<StringApiModel> onNext = new Consumer<StringApiModel>() { @Override public void accept(@NonNull final StringApiModel s) throws Exception { handler.onOk(); AbstractDataManager.this.sync(); } }; subscribe(handler, onNext, dataProvider.add(element)); } AbstractDataManager(DataProvider<T> dataProvider); @Override void sync(); @Override SyncStatus getSyncStatus(); @Override List<T> getAll(); @Override void add(final T element, final ServerCallStatusHandler handler); @Override void delete(final T element, final ServerCallStatusHandler handler); }### Answer:
@Test public void test_add_shouldAddItemOnDataProvider() throws Exception{ StubbedSavingsProvider dataProvider = new StubbedSavingsProvider(); FullfilledDataManager component_under_test = new FullfilledDataManager(dataProvider); SavingsAccount savingsAccount = new SavingsAccount(); component_under_test.add(savingsAccount, null); assertThat(dataProvider.accounts()).containsExactly(savingsAccount); }
|
### Question:
AuthenticationController { public String register(User user) throws VirtualLedgerAuthenticationException, UserAlreadyExistsException { if (user == null || user.getEmail() == null || user.getFirstName() == null || user.getLastName() == null) { throw new VirtualLedgerAuthenticationException( "Please check your inserts! At least one was not formatted correctly!"); } if (this.userRepository.existsUserWithEmail(user.getEmail())) { throw new UserAlreadyExistsException(); } this.userRepository.save(user); return "You were registered! " + user.getEmail(); } @Autowired AuthenticationController(UserRepository userRepository); protected AuthenticationController(); String register(User user); }### Answer:
@Test(expected = UserAlreadyExistsException.class) public void testRegisterWithExistingUserShouldThrowException() throws Exception { UserRepository userRepositoryMock = mock(UserRepository.class); when(userRepositoryMock.existsUserWithEmail(someEmail())).thenReturn(Boolean.TRUE); AuthenticationController componentUnderTest = new AuthenticationController(userRepositoryMock); User user = getValidUserCredential(); user.setEmail(someEmail()); componentUnderTest.register(user); }
@Test public void testRegisterWithValidUserShouldRegister() throws Exception { UserRepository userRepositoryMock = mock(UserRepository.class); AuthenticationController componentUnderTest = new AuthenticationController(userRepositoryMock); String result = componentUnderTest.register(getValidUserCredential()); assertThat(result).isEqualTo("You were registered! [email protected]"); }
|
### Question:
StringApiModelFactory { public StringApiModel createStringApiModel(String string) { StringApiModel stringApiModel = new StringApiModel(); stringApiModel.setData(string); return stringApiModel; } StringApiModel createStringApiModel(String string); }### Answer:
@Test public void createSuccessful() { String testString = "test"; StringApiModel stringApiModel = stringApiModelFactory.createStringApiModel(testString); Assert.assertNotNull(stringApiModel); Assert.assertEquals(testString, stringApiModel.getData()); }
|
### Question:
AbstractDataManager extends Observable implements DataManager<T> { @Override public List<T> getAll() throws SyncFailedException { if (syncFailedException != null) throw syncFailedException; if (syncStatus != SYNCED) throw new IllegalStateException("Sync not completed"); logger().info("Number items synct: " + this.allCachedItems.size()); return new LinkedList<>(allCachedItems); } AbstractDataManager(DataProvider<T> dataProvider); @Override void sync(); @Override SyncStatus getSyncStatus(); @Override List<T> getAll(); @Override void add(final T element, final ServerCallStatusHandler handler); @Override void delete(final T element, final ServerCallStatusHandler handler); }### Answer:
@Test(expected = IllegalStateException.class) public void test_initialState_get_shouldThrowIllegalArgumentException() throws Exception{ FullfilledDataManager component_under_test = new FullfilledDataManager(new StubbedSavingsProvider()); component_under_test.getAll(); }
|
### Question:
BankAccessFactory { public BankAccess createBankAccess(BankAccessBankingModel bankingModel) { BankAccess bankAccess = new BankAccess(bankingModel.getId(), bankingModel.getBankName(), bankingModel.getBankCode(), bankingModel.getBankLogin()); return bankAccess; } BankAccess createBankAccess(BankAccessBankingModel bankingModel); List<BankAccess> createBankAccesses(List<BankAccessBankingModel> bankingModelList); }### Answer:
@Test public void createSuccess() { String accessId = "accessID"; String bankName = "bankName"; String bankCode = "bankCode"; String bankLogin = "bankLogin"; BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setBankName(bankName); bankAccessBankingModel.setBankCode(bankCode); bankAccessBankingModel.setBankLogin(bankLogin); bankAccessBankingModel.setId(accessId); BankAccess bankAccess = bankAccessFactory.createBankAccess(bankAccessBankingModel); Assert.assertNotNull(bankAccess); Assert.assertEquals(accessId, bankAccess.getId()); Assert.assertEquals(bankCode, bankAccess.getBankcode()); Assert.assertEquals(bankLogin, bankAccess.getBanklogin()); Assert.assertEquals(bankName, bankAccess.getName()); }
|
### Question:
BankAccessFactory { public List<BankAccess> createBankAccesses(List<BankAccessBankingModel> bankingModelList) { List<BankAccess> bankAccessesResult = new ArrayList<BankAccess>(); for (BankAccessBankingModel bankingModel : bankingModelList) { bankAccessesResult.add(this.createBankAccess(bankingModel)); } return bankAccessesResult; } BankAccess createBankAccess(BankAccessBankingModel bankingModel); List<BankAccess> createBankAccesses(List<BankAccessBankingModel> bankingModelList); }### Answer:
@Test public void createListSuccess() { String accessId = "accessID"; String bankName = "bankName"; String bankCode = "bankCode"; String bankLogin = "bankLogin"; BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setBankName(bankName); bankAccessBankingModel.setBankCode(bankCode); bankAccessBankingModel.setBankLogin(bankLogin); bankAccessBankingModel.setId(accessId); List<BankAccessBankingModel> bankAccessBankingModelList = new ArrayList<>(); bankAccessBankingModelList.add(bankAccessBankingModel); List<BankAccess> bankAccesses = bankAccessFactory.createBankAccesses(bankAccessBankingModelList); Assert.assertNotNull(bankAccesses); Assert.assertEquals(bankAccesses.size(), 1); Assert.assertEquals(accessId, bankAccesses.get(0).getId()); Assert.assertEquals(bankCode, bankAccesses.get(0).getBankcode()); Assert.assertEquals(bankLogin, bankAccesses.get(0).getBanklogin()); Assert.assertEquals(bankName, bankAccesses.get(0).getName()); }
|
### Question:
SavingsAccountIntoEntityTransformer { public SavingsAccountEntity transformSavingAccountIntoEntity(SavingsAccount savingsAccount, User currentUser) { SavingsAccountEntity savingsAccountEntity = new SavingsAccountEntity( savingsAccount.getName(), savingsAccount.getGoalbalance(), savingsAccount.getCurrentbalance(), savingsAccount.getFinalGoalFinishedDate(), savingsAccount.getFinalGoalFinishedDate()); Set<SavingsAccountSubGoalEntity> savingsAccountSubGoalEntities = transformSavingsAccountSubGoalIdentifierIntoEntity(savingsAccount.getSubGoals()); savingsAccountEntity.setSubGoals(savingsAccountSubGoalEntities); List<BankAccountIdentifierEntity> bankAccountIdentifierEntities = transformBankAccountIdentifierIntoEntity(savingsAccount.getAssignedBankAccounts()); Set<SavingsAccountUserRelation> savingsAccountUserRelations = new HashSet<>(); savingsAccountUserRelations.add(new SavingsAccountUserRelation(currentUser, bankAccountIdentifierEntities)); for (Contact contact : savingsAccount.getAdditionalAssignedUsers()) { savingsAccountUserRelations.add(new SavingsAccountUserRelation(transformContactIntoEntity(contact))); } savingsAccountEntity.setUserRelations(savingsAccountUserRelations); return savingsAccountEntity; } SavingsAccountEntity transformSavingAccountIntoEntity(SavingsAccount savingsAccount, User currentUser); User transformContactIntoEntity(Contact contact); List<BankAccountIdentifierEntity> transformBankAccountIdentifierIntoEntity(List<BankAccountIdentifier> assignedBankAccounts); BankAccountIdentifierEntity transformBankAccountIdentifierIntoEntity(BankAccountIdentifier bankAccountIdentifier); Set<SavingsAccountSubGoalEntity> transformSavingsAccountSubGoalIdentifierIntoEntity(List<SavingsAccountSubGoal> subGoals); SavingsAccountSubGoalEntity transformSavingsAccountSubGoalIdentifierIntoEntity(SavingsAccountSubGoal savingsAccountSubGoal); }### Answer:
@Test public void transformSavingAccountIntoEntity() { SavingsAccount savingsAccount = new SavingsAccount(savingsAccountId, savingsAccountName, savingsAccountGoal, savingsAccountCurrent, savingsAccountFinalDate, savingsAccountfinalGoalFinishedDate); User currentUser = new User(userEmail, userFirstName, userLastName); SavingsAccountEntity result = transformer.transformSavingAccountIntoEntity(savingsAccount, currentUser); assertNotNull(result); assertEquals(result.getName(), savingsAccount.getName()); assertEquals(result.getCurrentbalance(), savingsAccount.getCurrentbalance(), delta); assertEquals(result.getGoalbalance(), savingsAccount.getGoalbalance(), delta); assertEquals(result.getFinaldate().getTime(), savingsAccount.getFinaldate().getTime()); assertEquals(result.getFinalGoalFinishedDate().getTime(), savingsAccount.getFinalGoalFinishedDate().getTime()); assertEquals(result.getSubGoals().size(), 0); assertEquals(result.getUserRelations().size(), 1); }
|
### Question:
SavingsAccountIntoEntityTransformer { public User transformContactIntoEntity(Contact contact) { return new User(contact.getEmail(), contact.getFirstName(), contact.getLastName()); } SavingsAccountEntity transformSavingAccountIntoEntity(SavingsAccount savingsAccount, User currentUser); User transformContactIntoEntity(Contact contact); List<BankAccountIdentifierEntity> transformBankAccountIdentifierIntoEntity(List<BankAccountIdentifier> assignedBankAccounts); BankAccountIdentifierEntity transformBankAccountIdentifierIntoEntity(BankAccountIdentifier bankAccountIdentifier); Set<SavingsAccountSubGoalEntity> transformSavingsAccountSubGoalIdentifierIntoEntity(List<SavingsAccountSubGoal> subGoals); SavingsAccountSubGoalEntity transformSavingsAccountSubGoalIdentifierIntoEntity(SavingsAccountSubGoal savingsAccountSubGoal); }### Answer:
@Test public void transformContactIntoEntity() { Contact contact = new Contact(userEmail, userFirstName, userLastName); User result = transformer.transformContactIntoEntity(contact); assertNotNull(result); assertEquals(userEmail, result.getEmail()); assertEquals(userFirstName, result.getFirstName()); assertEquals(userLastName, result.getLastName()); }
|
### Question:
SavingsAccountIntoEntityTransformer { public List<BankAccountIdentifierEntity> transformBankAccountIdentifierIntoEntity(List<BankAccountIdentifier> assignedBankAccounts) { List<BankAccountIdentifierEntity> bankAccountIdentifierEntities = new ArrayList<>(); if (assignedBankAccounts == null) { return bankAccountIdentifierEntities; } for (BankAccountIdentifier bankAccountIdentifier : assignedBankAccounts) { bankAccountIdentifierEntities.add(transformBankAccountIdentifierIntoEntity(bankAccountIdentifier)); } return bankAccountIdentifierEntities; } SavingsAccountEntity transformSavingAccountIntoEntity(SavingsAccount savingsAccount, User currentUser); User transformContactIntoEntity(Contact contact); List<BankAccountIdentifierEntity> transformBankAccountIdentifierIntoEntity(List<BankAccountIdentifier> assignedBankAccounts); BankAccountIdentifierEntity transformBankAccountIdentifierIntoEntity(BankAccountIdentifier bankAccountIdentifier); Set<SavingsAccountSubGoalEntity> transformSavingsAccountSubGoalIdentifierIntoEntity(List<SavingsAccountSubGoal> subGoals); SavingsAccountSubGoalEntity transformSavingsAccountSubGoalIdentifierIntoEntity(SavingsAccountSubGoal savingsAccountSubGoal); }### Answer:
@Test public void transformBankAccountIdentifierListIntoEntity() { List<BankAccountIdentifier> identifiers = new ArrayList<>(); BankAccountIdentifier accountIdentifier = new BankAccountIdentifier(accessId, accountId); identifiers.add(accountIdentifier); List<BankAccountIdentifierEntity> result = transformer.transformBankAccountIdentifierIntoEntity(identifiers); assertNotNull(result); assertEquals(result.size(), identifiers.size()); }
@Test public void transformBankAccountIdentifierIntoEntityInputNull() { List<BankAccountIdentifier> identifiers = null; List<BankAccountIdentifierEntity> result = transformer.transformBankAccountIdentifierIntoEntity(identifiers); assertNotNull(result); }
@Test public void transformBankAccountIdentifierIntoEntity() { BankAccountIdentifier accountIdentifier = new BankAccountIdentifier(accessId, accountId); BankAccountIdentifierEntity result = transformer.transformBankAccountIdentifierIntoEntity(accountIdentifier); assertNotNull(result); assertEquals(result.getAccessid(), accessId); assertEquals(result.getAccountid(), accountId); }
|
### Question:
SavingsAccountIntoEntityTransformer { public Set<SavingsAccountSubGoalEntity> transformSavingsAccountSubGoalIdentifierIntoEntity(List<SavingsAccountSubGoal> subGoals) { Set<SavingsAccountSubGoalEntity> savingsAccountSubGoalEntities = new HashSet<>(); if (subGoals == null) { return savingsAccountSubGoalEntities; } for (SavingsAccountSubGoal savingsAccountSubGoal : subGoals) { savingsAccountSubGoalEntities.add(transformSavingsAccountSubGoalIdentifierIntoEntity(savingsAccountSubGoal)); } return savingsAccountSubGoalEntities; } SavingsAccountEntity transformSavingAccountIntoEntity(SavingsAccount savingsAccount, User currentUser); User transformContactIntoEntity(Contact contact); List<BankAccountIdentifierEntity> transformBankAccountIdentifierIntoEntity(List<BankAccountIdentifier> assignedBankAccounts); BankAccountIdentifierEntity transformBankAccountIdentifierIntoEntity(BankAccountIdentifier bankAccountIdentifier); Set<SavingsAccountSubGoalEntity> transformSavingsAccountSubGoalIdentifierIntoEntity(List<SavingsAccountSubGoal> subGoals); SavingsAccountSubGoalEntity transformSavingsAccountSubGoalIdentifierIntoEntity(SavingsAccountSubGoal savingsAccountSubGoal); }### Answer:
@Test public void transformSavingsAccountSubGoalListIdentifierIntoEntity() { List<SavingsAccountSubGoal> subGoals = new ArrayList<SavingsAccountSubGoal>(); SavingsAccountSubGoal savingsAccountSubGoal = new SavingsAccountSubGoal(savingsAccountSubGoalTestName, savingsAccountSubGoalTestAmount); subGoals.add(savingsAccountSubGoal); Set<SavingsAccountSubGoalEntity> result = transformer.transformSavingsAccountSubGoalIdentifierIntoEntity(subGoals); assertNotNull(result); assertEquals(result.size(), subGoals.size()); }
@Test public void transformSavingsAccountSubGoalListIdentifierIntoEntityInputNull() { List<SavingsAccountSubGoal> subGoals = null; Set<SavingsAccountSubGoalEntity> result = transformer.transformSavingsAccountSubGoalIdentifierIntoEntity(subGoals); assertNotNull(result); }
@Test public void transformSavingsAccountSubGoalIdentifierIntoEntity() { SavingsAccountSubGoal savingsAccountSubGoal = new SavingsAccountSubGoal(savingsAccountSubGoalTestName, savingsAccountSubGoalTestAmount); SavingsAccountSubGoalEntity result = transformer.transformSavingsAccountSubGoalIdentifierIntoEntity(savingsAccountSubGoal); assertNotNull(result); assertEquals(result.getName(), savingsAccountSubGoalTestName); assertEquals(result.getAmount(), savingsAccountSubGoalTestAmount, delta); }
|
### Question:
CustomFilter implements Filter<Transaction> { @Override public boolean shouldBeRemoved(Transaction t) { if(this.startDate.after(t.booking().getDate())){ return true; } if(this.endDate.before(t.booking().getDate())){ return true; } return false; } CustomFilter(Date startDate, Date endDate); @Override boolean shouldBeRemoved(Transaction t); }### Answer:
@Test public void teste_filter_withEndDate_shouldReturnStay() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date start = sdf.parse("11/06/2017"); Date end = sdf.parse("11/07/2017"); Booking booking = new Booking(); booking.setDate(end); Transaction testTransaction = new Transaction("someBank", "some bank id", booking); Filter component_under_test = new CustomFilter(start, end); assertThat(component_under_test.shouldBeRemoved(testTransaction)).isFalse(); }
@Test public void teste_filter_withStartDate_shouldReturnStay() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date start = sdf.parse("11/06/2017"); Date end = sdf.parse("11/07/2017"); Booking booking = new Booking(); booking.setDate(start); Transaction testTransaction = new Transaction("someBank", "some bank id", booking); Filter component_under_test = new CustomFilter(start, end); assertThat(component_under_test.shouldBeRemoved(testTransaction)).isFalse(); }
@Test public void teste_filter_withDateBeforeStartDate_shouldReturnLeave() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date start = sdf.parse("11/06/2017"); Date end = sdf.parse("11/07/2017"); Date testDate = sdf.parse("11/04/2017"); Booking booking = new Booking(); booking.setDate(testDate); Transaction testTransaction = new Transaction("someBank", "some bank id", booking); Filter component_under_test = new CustomFilter(start, end); assertThat(component_under_test.shouldBeRemoved(testTransaction)).isTrue(); }
@Test public void teste_filter_withDateAfterEndDate_shouldReturnLeave() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date start = sdf.parse("11/06/2017"); Date end = sdf.parse("11/07/2017"); Date testDate = sdf.parse("11/08/2017"); Booking booking = new Booking(); booking.setDate(testDate); Transaction testTransaction = new Transaction("someBank", "some bank id", booking); Filter component_under_test = new CustomFilter(start, end); assertThat(component_under_test.shouldBeRemoved(testTransaction)).isTrue(); }
|
### Question:
BankAccessBankingModelFactory { public BankAccessBankingModel createBankAccessBankingModel(String userId, BankAccessCredential bankAccessCredential) { BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setUserId(userId); bankAccessBankingModel.setBankCode(bankAccessCredential.getBankcode()); bankAccessBankingModel.setBankLogin(bankAccessCredential.getBanklogin()); bankAccessBankingModel.setPin(bankAccessCredential.getPin()); return bankAccessBankingModel; } BankAccessBankingModel createBankAccessBankingModel(String userId, BankAccessCredential bankAccessCredential); }### Answer:
@Test public void createTest() { BankAccessBankingModelFactory bankAccessBankingModelFactory = new BankAccessBankingModelFactory(); BankAccessCredential credential = new BankAccessCredential("test", "test", "test"); BankAccessBankingModel testModel = bankAccessBankingModelFactory.createBankAccessBankingModel("1", credential); Assert.assertNotNull(testModel); }
|
### Question:
SavingsAccountFromEntityTransformer { public List<SavingsAccount> transformSavingAccountFromEntity(List<SavingsAccountEntity> savingsAccountEntityList, User currentUser) { List<SavingsAccount> savingsAccountList = new ArrayList<>(); for (SavingsAccountEntity savingsAccountEntity : savingsAccountEntityList) { savingsAccountList.add(transformSavingAccountFromEntity(savingsAccountEntity, currentUser)); } return savingsAccountList; } List<SavingsAccount> transformSavingAccountFromEntity(List<SavingsAccountEntity> savingsAccountEntityList, User currentUser); SavingsAccount transformSavingAccountFromEntity(SavingsAccountEntity savingsAccountEntity, User currentUser); List<Contact> transformContactFromEntity(Set<SavingsAccountUserRelation> savingsAccountUserRelations, User currentUser); Contact transformContactFromEntity(User user); List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(Set<SavingsAccountUserRelation> userRelations, User currentUser); List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(List<BankAccountIdentifierEntity> bankAccountIdentifierEntityList); BankAccountIdentifier transformBankAccountIdentifierFromEntity(BankAccountIdentifierEntity bankAccountIdentifierEntity); List<SavingsAccountSubGoal> transformSavingsAccountSubGoalIdentifierFromEntity(Set<SavingsAccountSubGoalEntity> subGoalEntities); SavingsAccountSubGoal transformSavingsAccountSubGoalIdentifierFromEntity(SavingsAccountSubGoalEntity savingsAccountSubGoalEntity); }### Answer:
@Test public void transformSavingAccountsFromEntity() throws Exception { User currentUser = generateUserEntity(0); List<SavingsAccountEntity> savingsAccountEntityList = new ArrayList<>(); final int numberSavingAccounts = 3; for (int i = 0; i < numberSavingAccounts; i++) { SavingsAccountEntity savingsAccountEntity = generateSavingAccountEntity(i); savingsAccountEntityList.add(savingsAccountEntity); } SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); List<SavingsAccount> resultSavingAccounts = transformer.transformSavingAccountFromEntity(savingsAccountEntityList, currentUser); Assert.assertNotNull(resultSavingAccounts); Assert.assertEquals(resultSavingAccounts.size(), numberSavingAccounts); }
@Test public void transformSavingAccountFromEntity() throws Exception { SavingsAccountEntity savingsAccountEntity = generateSavingAccountEntity(0); User currentUser = generateUserEntity(0); SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); SavingsAccount resultSavingAccount = transformer.transformSavingAccountFromEntity(savingsAccountEntity, currentUser); Assert.assertNotNull(resultSavingAccount); Assert.assertEquals(resultSavingAccount.getName(), savingsAccountEntity.getName()); Assert.assertEquals(resultSavingAccount.getCurrentbalance(), savingsAccountEntity.getCurrentbalance(), delta); Assert.assertEquals(resultSavingAccount.getGoalbalance(), savingsAccountEntity.getGoalbalance(), delta); Assert.assertEquals(resultSavingAccount.getFinaldate(), savingsAccountEntity.getFinaldate()); Assert.assertEquals(resultSavingAccount.getFinalGoalFinishedDate(), savingsAccountEntity.getFinalGoalFinishedDate()); }
|
### Question:
SavingsAccountFromEntityTransformer { public List<Contact> transformContactFromEntity(Set<SavingsAccountUserRelation> savingsAccountUserRelations, User currentUser) { List<Contact> contacts = new ArrayList<>(); if (savingsAccountUserRelations == null) { return contacts; } for (SavingsAccountUserRelation savingsAccountUserRelation : savingsAccountUserRelations) { if (!savingsAccountUserRelation.getUser().getEmail().equals(currentUser.getEmail())) { contacts.add(transformContactFromEntity(savingsAccountUserRelation.getUser())); } } return contacts; } List<SavingsAccount> transformSavingAccountFromEntity(List<SavingsAccountEntity> savingsAccountEntityList, User currentUser); SavingsAccount transformSavingAccountFromEntity(SavingsAccountEntity savingsAccountEntity, User currentUser); List<Contact> transformContactFromEntity(Set<SavingsAccountUserRelation> savingsAccountUserRelations, User currentUser); Contact transformContactFromEntity(User user); List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(Set<SavingsAccountUserRelation> userRelations, User currentUser); List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(List<BankAccountIdentifierEntity> bankAccountIdentifierEntityList); BankAccountIdentifier transformBankAccountIdentifierFromEntity(BankAccountIdentifierEntity bankAccountIdentifierEntity); List<SavingsAccountSubGoal> transformSavingsAccountSubGoalIdentifierFromEntity(Set<SavingsAccountSubGoalEntity> subGoalEntities); SavingsAccountSubGoal transformSavingsAccountSubGoalIdentifierFromEntity(SavingsAccountSubGoalEntity savingsAccountSubGoalEntity); }### Answer:
@Test public void transformContactsFromEntity() throws Exception { Set<SavingsAccountUserRelation> relationEntitySet = new HashSet<>(); final int numberOfUsers = 3; User mainUser = generateUserEntity(0); relationEntitySet.add(new SavingsAccountUserRelation(mainUser)); for (int i = 1; i < numberOfUsers; i++) { User user = generateUserEntity(i); relationEntitySet.add(new SavingsAccountUserRelation(user)); } SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); List<Contact> resultContactList = transformer.transformContactFromEntity(relationEntitySet, mainUser); Assert.assertNotNull(resultContactList); Assert.assertEquals(resultContactList.size(), numberOfUsers - 1); }
@Test public void transformContactFromEntityInputNull() throws Exception { Set<SavingsAccountUserRelation> relationEntitySet = null; SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); List<Contact> resultContactList = transformer.transformContactFromEntity(relationEntitySet, null); Assert.assertNotNull(resultContactList); Assert.assertEquals(resultContactList.size(), 0); }
@Test public void transformContactFromEntity() throws Exception { User user = generateUserEntity(1); SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); Contact resultContact = transformer.transformContactFromEntity(user); Assert.assertNotNull(resultContact); Assert.assertEquals(resultContact.getEmail(), user.getEmail()); Assert.assertEquals(resultContact.getFirstName(), user.getFirstName()); Assert.assertEquals(resultContact.getLastName(), user.getLastName()); }
|
### Question:
SavingsAccountFromEntityTransformer { public List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(Set<SavingsAccountUserRelation> userRelations, User currentUser) { List<BankAccountIdentifier> bankAccountIdentifiers = new ArrayList<>(); if (userRelations == null) { return bankAccountIdentifiers; } for (SavingsAccountUserRelation userRelation : userRelations) { if (userRelation.getUser().getEmail().equals(currentUser.getEmail())) { bankAccountIdentifiers.addAll(transformBankAccountIdentifierFromEntity(userRelation.getBankAccountIdentifierEntityList())); } } return bankAccountIdentifiers; } List<SavingsAccount> transformSavingAccountFromEntity(List<SavingsAccountEntity> savingsAccountEntityList, User currentUser); SavingsAccount transformSavingAccountFromEntity(SavingsAccountEntity savingsAccountEntity, User currentUser); List<Contact> transformContactFromEntity(Set<SavingsAccountUserRelation> savingsAccountUserRelations, User currentUser); Contact transformContactFromEntity(User user); List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(Set<SavingsAccountUserRelation> userRelations, User currentUser); List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(List<BankAccountIdentifierEntity> bankAccountIdentifierEntityList); BankAccountIdentifier transformBankAccountIdentifierFromEntity(BankAccountIdentifierEntity bankAccountIdentifierEntity); List<SavingsAccountSubGoal> transformSavingsAccountSubGoalIdentifierFromEntity(Set<SavingsAccountSubGoalEntity> subGoalEntities); SavingsAccountSubGoal transformSavingsAccountSubGoalIdentifierFromEntity(SavingsAccountSubGoalEntity savingsAccountSubGoalEntity); }### Answer:
@Test public void transformBankAccountIdentifiersFromEntityEvaluateUser() throws Exception { Set<SavingsAccountUserRelation> relationEntityList = new HashSet<>(); List<BankAccountIdentifierEntity> identifierEntityList = new ArrayList<>(); final int numberIdentifiers = 3; User currentUser = generateUserEntity(0); for (int i = 0; i < numberIdentifiers; i++) { identifierEntityList.add(generateBankAccountIdentifier(i)); } relationEntityList.add(new SavingsAccountUserRelation(currentUser, identifierEntityList)); identifierEntityList = new ArrayList<>(); User notCurrentUser = generateUserEntity(1); for (int i = 0; i < numberIdentifiers; i++) { identifierEntityList.add(generateBankAccountIdentifier(i)); } relationEntityList.add(new SavingsAccountUserRelation(notCurrentUser, identifierEntityList)); SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); List<BankAccountIdentifier> resultIdentifierList = transformer.transformBankAccountIdentifierFromEntity(relationEntityList, currentUser); Assert.assertNotNull(resultIdentifierList); Assert.assertEquals(resultIdentifierList.size(), numberIdentifiers); }
@Test public void transformBankAccountIdentifiersFromEntity() throws Exception { List<BankAccountIdentifierEntity> identifierEntityList = new ArrayList<>(); final int numberIdentifiers = 3; for (int i = 0; i < numberIdentifiers; i++) { identifierEntityList.add(generateBankAccountIdentifier(i)); } SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); List<BankAccountIdentifier> resultIdentifierList = transformer.transformBankAccountIdentifierFromEntity(identifierEntityList); Assert.assertNotNull(resultIdentifierList); Assert.assertEquals(resultIdentifierList.size(), numberIdentifiers); }
@Test public void transformBankAccountIdentifiersInputNull() throws Exception { List<BankAccountIdentifierEntity> identifierEntityList = null; SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); List<BankAccountIdentifier> resultIdentifierList = transformer.transformBankAccountIdentifierFromEntity(identifierEntityList); Assert.assertNotNull(resultIdentifierList); Assert.assertEquals(resultIdentifierList.size(), 0); }
@Test public void transformBankAccountIdentifierFromEntity() throws Exception { BankAccountIdentifierEntity identifierEntity = generateBankAccountIdentifier(1); SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); BankAccountIdentifier resultIdentifier = transformer.transformBankAccountIdentifierFromEntity(identifierEntity); Assert.assertNotNull(resultIdentifier); Assert.assertEquals(resultIdentifier.getAccessid(), identifierEntity.getAccessid()); Assert.assertEquals(resultIdentifier.getAccountid(), identifierEntity.getAccountid()); }
|
### Question:
SavingsAccountFromEntityTransformer { public List<SavingsAccountSubGoal> transformSavingsAccountSubGoalIdentifierFromEntity(Set<SavingsAccountSubGoalEntity> subGoalEntities) { List<SavingsAccountSubGoal> savingsAccountSubGoals = new ArrayList<>(); if (subGoalEntities == null) { return savingsAccountSubGoals; } for (SavingsAccountSubGoalEntity savingsAccountSubGoalEntity : subGoalEntities) { savingsAccountSubGoals.add(transformSavingsAccountSubGoalIdentifierFromEntity(savingsAccountSubGoalEntity)); } return savingsAccountSubGoals; } List<SavingsAccount> transformSavingAccountFromEntity(List<SavingsAccountEntity> savingsAccountEntityList, User currentUser); SavingsAccount transformSavingAccountFromEntity(SavingsAccountEntity savingsAccountEntity, User currentUser); List<Contact> transformContactFromEntity(Set<SavingsAccountUserRelation> savingsAccountUserRelations, User currentUser); Contact transformContactFromEntity(User user); List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(Set<SavingsAccountUserRelation> userRelations, User currentUser); List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(List<BankAccountIdentifierEntity> bankAccountIdentifierEntityList); BankAccountIdentifier transformBankAccountIdentifierFromEntity(BankAccountIdentifierEntity bankAccountIdentifierEntity); List<SavingsAccountSubGoal> transformSavingsAccountSubGoalIdentifierFromEntity(Set<SavingsAccountSubGoalEntity> subGoalEntities); SavingsAccountSubGoal transformSavingsAccountSubGoalIdentifierFromEntity(SavingsAccountSubGoalEntity savingsAccountSubGoalEntity); }### Answer:
@Test public void transformSavingsAccountSubGoalIdentifiersFromEntity() throws Exception { Set<SavingsAccountSubGoalEntity> subGoalEntityList = new HashSet<>(); final int numberSubGoals = 3; for (int i = 0; i < numberSubGoals; i++) { SavingsAccountSubGoalEntity subGoalEntity = generateSubGoalEntity(i); subGoalEntityList.add(subGoalEntity); } SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); List<SavingsAccountSubGoal> resultSubGoalList = transformer.transformSavingsAccountSubGoalIdentifierFromEntity(subGoalEntityList); Assert.assertNotNull(resultSubGoalList); Assert.assertEquals(resultSubGoalList.size(), numberSubGoals); }
@Test public void transformSavingsAccountSubGoalIdentifiersFromEntityListNull() throws Exception { Set<SavingsAccountSubGoalEntity> subGoalEntitySet = null; SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); List<SavingsAccountSubGoal> resultSubGoalList = transformer.transformSavingsAccountSubGoalIdentifierFromEntity(subGoalEntitySet); Assert.assertNotNull(resultSubGoalList); Assert.assertEquals(resultSubGoalList.size(), 0); }
@Test public void transformSavingsAccountSubGoalIdentifierFromEntity() throws Exception { SavingsAccountSubGoalEntity subGoalEntity = generateSubGoalEntity(1); SavingsAccountFromEntityTransformer transformer = new SavingsAccountFromEntityTransformer(); SavingsAccountSubGoal resultSubGoal = transformer.transformSavingsAccountSubGoalIdentifierFromEntity(subGoalEntity); Assert.assertNotNull(resultSubGoal); Assert.assertEquals(resultSubGoal.getName(), subGoalEntity.getName()); Assert.assertEquals(resultSubGoal.getAmount(), subGoalEntity.getAmount(), delta); }
|
### Question:
BankAccountFactory { public BankAccount createBankAccount(BankAccountBankingModel bankingModel) { double balance = 0; if (bankingModel.getBankAccountBalance() != null) { balance = bankingModel.getBankAccountBalance().getReadyHbciBalance(); } BankAccount bankAccount = new BankAccount(bankingModel.getId(), bankingModel.getType() != null ? bankingModel.getType() : "", balance); return bankAccount; } BankAccount createBankAccount(BankAccountBankingModel bankingModel); List<BankAccount> createBankAccounts(List<BankAccountBankingModel> bankingModelList); }### Answer:
@Test public void createSuccess() { final double testAmount = 123.22; BankAccountBalanceBankingModel bankAccountBalanceBankingModel = new BankAccountBalanceBankingModel(); bankAccountBalanceBankingModel.setReadyHbciBalance(testAmount); String accessId = "accessID"; String accountId = "accountId"; String type = "type"; BankAccountBankingModel bankAccountBankingModel = new BankAccountBankingModel(); bankAccountBankingModel.setBankAccessId(accessId); bankAccountBankingModel.setId(accountId); bankAccountBankingModel.setType(type); bankAccountBankingModel.setBankAccountBalance(bankAccountBalanceBankingModel); BankAccount bankAccount = bankAccountFactory.createBankAccount(bankAccountBankingModel); Assert.assertNotNull(bankAccount); Assert.assertEquals(accountId, bankAccount.getBankid()); Assert.assertEquals(type, bankAccount.getName()); Assert.assertEquals(testAmount, bankAccount.getBalance(), DELTA); }
|
### Question:
BankAccountFactory { public List<BankAccount> createBankAccounts(List<BankAccountBankingModel> bankingModelList) { List<BankAccount> bankAccountsResult = new ArrayList<BankAccount>(); for (BankAccountBankingModel bankingModel : bankingModelList) { bankAccountsResult.add(this.createBankAccount(bankingModel)); } return bankAccountsResult; } BankAccount createBankAccount(BankAccountBankingModel bankingModel); List<BankAccount> createBankAccounts(List<BankAccountBankingModel> bankingModelList); }### Answer:
@Test public void createListSuccess() { final double testAmount = 123.22; final int bankAccountActualSize = 1; BankAccountBalanceBankingModel bankAccountBalanceBankingModel = new BankAccountBalanceBankingModel(); bankAccountBalanceBankingModel.setReadyHbciBalance(testAmount); String accessId = "accessID"; String accountId = "accountId"; String type = "type"; BankAccountBankingModel bankAccountBankingModel = new BankAccountBankingModel(); bankAccountBankingModel.setBankAccessId(accessId); bankAccountBankingModel.setId(accountId); bankAccountBankingModel.setType(type); bankAccountBankingModel.setBankAccountBalance(bankAccountBalanceBankingModel); List<BankAccountBankingModel> bankAccountBankingModelList = new ArrayList<>(); bankAccountBankingModelList.add(bankAccountBankingModel); List<BankAccount> bankAccounts = bankAccountFactory.createBankAccounts(bankAccountBankingModelList); Assert.assertNotNull(bankAccounts); Assert.assertEquals(bankAccounts.size(), bankAccountActualSize); Assert.assertEquals(accountId, bankAccounts.get(0).getBankid()); Assert.assertEquals(type, bankAccounts.get(0).getName()); Assert.assertEquals(testAmount, bankAccounts.get(0).getBalance(), DELTA); }
|
### Question:
AuthMigrator { public boolean hasLegacyAuth() { return mStorageHelpers.hasDigitsSession(); } @VisibleForTesting(otherwise = PRIVATE) AuthMigrator(@NonNull FirebaseApp app, @NonNull StorageHelpers storageHelper,
@NonNull FirebaseAuth firebaseAuth); static AuthMigrator getInstance(FirebaseApp app); static AuthMigrator getInstance(); FirebaseApp getApp(); Task<Void> migrate(boolean cleanupDigitsSession); Task<Void> migrate(@NonNull RedeemableDigitsSessionBuilder builder); boolean hasLegacyAuth(); void clearLegacyAuth(); }### Answer:
@Test public void hasLegacyAuth() throws JSONException { when(mockStorageHelpers.hasDigitsSession()).thenReturn(true); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.hasLegacyAuth()); }
|
### Question:
AuthMigrator { public void clearLegacyAuth() { mStorageHelpers.clearDigitsSession(); } @VisibleForTesting(otherwise = PRIVATE) AuthMigrator(@NonNull FirebaseApp app, @NonNull StorageHelpers storageHelper,
@NonNull FirebaseAuth firebaseAuth); static AuthMigrator getInstance(FirebaseApp app); static AuthMigrator getInstance(); FirebaseApp getApp(); Task<Void> migrate(boolean cleanupDigitsSession); Task<Void> migrate(@NonNull RedeemableDigitsSessionBuilder builder); boolean hasLegacyAuth(); void clearLegacyAuth(); }### Answer:
@Test public void clearLegacyAuth() throws JSONException { AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); authMigrator.clearLegacyAuth(); verify(mockStorageHelpers).clearDigitsSession(); }
|
### Question:
RedeemableDigitsSessionBuilder { @NonNull static RedeemableDigitsSessionBuilder fromSessionJson(@NonNull String json) throws JSONException { RedeemableDigitsSessionBuilder builder = new RedeemableDigitsSessionBuilder(); JSONObject jsonObject = new JSONObject(json); JSONObject emailJsonObject = safeGetJsonObject(EMAIL_KEY, jsonObject); JSONObject authTokenJsonObject = safeGetJsonObject(AUTH_TOKEN_KEY, jsonObject); builder.setPhoneNumber(safeGetString(PHONE_NUMBER_KEY, jsonObject)); builder.setId(safeGetLong(ID_KEY, jsonObject)); JSONObject nestedAuthTokenJsonObject = safeGetJsonObject(AUTH_TOKEN_KEY, authTokenJsonObject); builder.setEmail(safeGetString(EMAIL_ADDRESS_KEY, emailJsonObject)); builder.setIsEmailVerified(safeGetBoolean(IS_EMAIL_ADDRESS_VERIFIED_KEY, emailJsonObject)); builder.setAuthToken(safeGetString(NESTED_TOKEN_KEY, nestedAuthTokenJsonObject)); builder.setAuthTokenSecret(safeGetString(NESTED_TOKEN_SECRET_KEY, nestedAuthTokenJsonObject)); return builder; } RedeemableDigitsSessionBuilder setId(Long id); RedeemableDigitsSessionBuilder setPhoneNumber(@Nullable String phoneNumber); RedeemableDigitsSessionBuilder setEmail(@Nullable String email); RedeemableDigitsSessionBuilder setIsEmailVerified(@Nullable Boolean isEmailVerified); RedeemableDigitsSessionBuilder setAuthToken(@Nullable String authToken); RedeemableDigitsSessionBuilder setAuthTokenSecret(@Nullable String authTokenSecret); RedeemableDigitsSessionBuilder setConsumerKey(@Nullable String consumerKey); RedeemableDigitsSessionBuilder setConsumerSecret(@Nullable String consumerSecret); RedeemableDigitsSessionBuilder setFabricApiKey(@Nullable String fabricApiKey); ClearSessionContinuation.RedeemableDigitsSession build(); }### Answer:
@Test(expected=JSONException.class) public void testInvalidFromDigitsSessionJson() throws JSONException { RedeemableDigitsSessionBuilder.fromSessionJson("invalid_json"); }
|
### Question:
StfCommander { private static JCommander createCommander(CommandContainer commandContainer, String[] args) { JCommander.Builder builder = JCommander.newBuilder(); for (String operation : commandContainer.getAllCommands()) { CommandContainer.Command command = commandContainer.getCommand(operation); builder.addCommand(operation, command); } JCommander commander = builder.build(); commander.setProgramName("stf"); commander.setCaseSensitiveOptions(false); commander.parseWithoutValidation(args); return commander; } private StfCommander(
String commandName,
CommandContainer commandContainer,
CommandContainer.Command defaultCommand,
ErrorHandler errorHandler); }### Answer:
@DisplayName("connect command is parsed with valid -l param") @Test void testConnectCommandWithValidCacheParam() throws IOException { createCommander("connect -l 1 2 3"); }
@DisplayName("connect command will throw the ParameterException if -l param is invalid") @Test void testConnectCommandWithInvalidValidCacheParam() { assertThrows(ParameterException.class, () -> createCommander("connect -l str")); }
@DisplayName("Connect command with valid -u parameter will be parsed successfully") @Test void testValidUrlParamsIsParsed() throws IOException { createCommander("connect -u http: }
@DisplayName("Connect command with valid -f parameter will be parsed successfully") @Test void testValidFileParamsIsParsed() throws IOException { createCommander("connect -f some/file.json"); }
@DisplayName("Connect command with invalid -u parameter will throw an error") @Test void testInvalidUrlParamsIsFailedToParse() { assertThrows(ParameterException.class, () -> createCommander(" connect -u not_a_url")); }
@DisplayName("Connect command with empty -u parameter will throw an error") @Test void testEmptyUrlParamsIsFailedToParse() { assertThrows(ParameterException.class, () -> createCommander(" connect -u")); }
@DisplayName("Connect command with empty -f parameter will throw an error") @Test void testEmptyFileParamsIsFailedToParse() { assertThrows(ParameterException.class, () -> createCommander(" connect -u")); }
|
### Question:
BlockingStatus { public void changeStatus(Status status) { synchronized (this) { this.status = status; if (Status.isStatusFinished(status)) { unblock(); } } } BlockingStatus(int execId, String jobId, Status initialStatus); Status blockOnFinishedStatus(); Status viewStatus(); void unblock(); void changeStatus(Status status); int getExecId(); String getJobId(); }### Answer:
@Ignore @Test public void testUnfinishedBlock() throws InterruptedException { BlockingStatus status = new BlockingStatus(1, "test", Status.QUEUED); WatchingThread thread = new WatchingThread(status); thread.start(); synchronized (this) { wait(3000); } status.changeStatus(Status.SUCCEEDED); thread.join(); System.out.println("Diff " + thread.getDiff()); Assert.assertTrue(thread.getDiff() >= 3000 && thread.getDiff() < 3100); }
@Ignore @Test public void testUnfinishedBlockSeveralChanges() throws InterruptedException { BlockingStatus status = new BlockingStatus(1, "test", Status.QUEUED); WatchingThread thread = new WatchingThread(status); thread.start(); synchronized (this) { wait(3000); } status.changeStatus(Status.PAUSED); synchronized (this) { wait(1000); } status.changeStatus(Status.FAILED); thread.join(1000); System.out.println("Diff " + thread.getDiff()); Assert.assertTrue(thread.getDiff() >= 4000 && thread.getDiff() < 4100); }
@Ignore @Test public void testMultipleWatchers() throws InterruptedException { BlockingStatus status = new BlockingStatus(1, "test", Status.QUEUED); WatchingThread thread1 = new WatchingThread(status); thread1.start(); synchronized (this) { wait(2000); } WatchingThread thread2 = new WatchingThread(status); thread2.start(); synchronized (this) { wait(2000); } status.changeStatus(Status.FAILED); thread2.join(1000); thread1.join(1000); System.out.println("Diff thread 1 " + thread1.getDiff()); System.out.println("Diff thread 2 " + thread2.getDiff()); Assert.assertTrue(thread1.getDiff() >= 4000 && thread1.getDiff() < 4200); Assert.assertTrue(thread2.getDiff() >= 2000 && thread2.getDiff() < 2200); }
|
### Question:
FileIOUtils { public static void createDeepHardlink(File sourceDir, File destDir) throws IOException { if (!sourceDir.exists()) { throw new IOException("Source directory " + sourceDir.getPath() + " doesn't exist"); } else if (!destDir.exists()) { throw new IOException("Destination directory " + destDir.getPath() + " doesn't exist"); } else if (sourceDir.isFile() && destDir.isFile()) { throw new IOException("Source or Destination is not a directory."); } Set<String> paths = new HashSet<String>(); createDirsFindFiles(sourceDir, sourceDir, destDir, paths); StringBuffer buffer = new StringBuffer(); for (String path : paths) { File sourceLink = new File(sourceDir, path); path = "." + path; buffer.append("ln ").append(sourceLink.getAbsolutePath()).append("/*") .append(" ").append(path).append(";"); } runShellCommand(buffer.toString(), destDir); } static String getSourcePathFromClass(Class<?> containedClass); static void createDeepHardlink(File sourceDir, File destDir); static Pair<Integer, Integer> readUtf8File(File file, int offset,
int length, OutputStream stream); static LogData readUtf8File(File file, int fileOffset, int length); static JobMetaData readUtf8MetaDataFile(File file, int fileOffset,
int length); static Pair<Integer, Integer> getUtf8Range(byte[] buffer, int offset,
int length); }### Answer:
@Test public void testHardlinkCopy() throws IOException { FileIOUtils.createDeepHardlink(sourceDir, destDir); assertTrue(areDirsEqual(sourceDir, destDir, true)); FileUtils.deleteDirectory(destDir); assertTrue(areDirsEqual(baseDir, sourceDir, true)); }
@Test public void testHardlinkCopyNonSource() { boolean exception = false; try { FileIOUtils.createDeepHardlink(new File(sourceDir, "idonotexist"), destDir); } catch (IOException e) { System.out.println(e.getMessage()); System.out.println("Handled this case nicely."); exception = true; } assertTrue(exception); }
|
### Question:
FileIOUtils { public static Pair<Integer, Integer> getUtf8Range(byte[] buffer, int offset, int length) { int start = getUtf8ByteStart(buffer, offset); int end = getUtf8ByteEnd(buffer, offset + length - 1); return new Pair<Integer, Integer>(start, end - start + 1); } static String getSourcePathFromClass(Class<?> containedClass); static void createDeepHardlink(File sourceDir, File destDir); static Pair<Integer, Integer> readUtf8File(File file, int offset,
int length, OutputStream stream); static LogData readUtf8File(File file, int fileOffset, int length); static JobMetaData readUtf8MetaDataFile(File file, int fileOffset,
int length); static Pair<Integer, Integer> getUtf8Range(byte[] buffer, int offset,
int length); }### Answer:
@Test public void testAsciiUTF() throws IOException { String foreignText = "abcdefghijklmnopqrstuvwxyz"; byte[] utf8ByteArray = createUTF8ByteArray(foreignText); int length = utf8ByteArray.length; System.out.println("char length:" + foreignText.length() + " utf8BytesLength:" + utf8ByteArray.length + " for:" + foreignText); Pair<Integer,Integer> pair = FileIOUtils.getUtf8Range(utf8ByteArray, 1, length - 6); System.out.println("Pair :" + pair.toString()); String recreatedString = new String(utf8ByteArray, 1, length - 6, "UTF-8"); System.out.println("recreatedString:" + recreatedString); String correctString = new String(utf8ByteArray, pair.getFirst(), pair.getSecond(), "UTF-8"); System.out.println("correctString:" + correctString); assertEquals(pair, new Pair<Integer,Integer>(1, 20)); assertEquals(correctString.length(), foreignText.length() - 6); }
@Test public void testForeignUTF() throws IOException { String foreignText = "안녕하세요, 제 이름은 박병호입니다"; byte[] utf8ByteArray = createUTF8ByteArray(foreignText); int length = utf8ByteArray.length; System.out.println("char length:" + foreignText.length() + " utf8BytesLength:" + utf8ByteArray.length + " for:" + foreignText); Pair<Integer,Integer> pair = FileIOUtils.getUtf8Range(utf8ByteArray, 1, length - 6); System.out.println("Pair :" + pair.toString()); String recreatedString = new String(utf8ByteArray, 1, length - 6, "UTF-8"); System.out.println("recreatedString:" + recreatedString); String correctString = new String(utf8ByteArray, pair.getFirst(), pair.getSecond(), "UTF-8"); System.out.println("correctString:" + correctString); assertEquals(pair, new Pair<Integer,Integer>(3, 40)); assertEquals(correctString.length(), foreignText.length() - 3); String mixedText = "abc안녕하세요, 제 이름은 박병호입니다"; byte[] mixedBytes = createUTF8ByteArray(mixedText); Pair<Integer,Integer> pair2 = FileIOUtils.getUtf8Range(mixedBytes, 1, length - 4); correctString = new String(mixedBytes, pair2.getFirst(), pair2.getSecond(), "UTF-8"); System.out.println("correctString:" + correctString); assertEquals(pair2, new Pair<Integer,Integer>(1, 45)); assertEquals(correctString.length(), mixedText.length() - 3); }
|
### Question:
PatternLayoutEscaped extends PatternLayout { @Override public String format(final LoggingEvent event) { if (event.getMessage() instanceof String) { return super.format(appendStackTraceToEvent(event)); } return super.format(event); } PatternLayoutEscaped(String s); PatternLayoutEscaped(); @Override String format(final LoggingEvent event); }### Answer:
@Test public void testWithException() { try { throw new Exception("This is an exception"); } catch (Exception e) { LoggingEvent event = createEventWithException("There was an exception", e); assertTrue(layout.format(event).startsWith("There was an exception\\njava.lang.Exception: This is an exception")); } }
@Test public void testNewLine() { LoggingEvent event = createMessageEvent("This message contains \n new lines"); assertTrue(layout.format(event).equals("This message contains \\n new lines")); }
@Test public void testQuote() { LoggingEvent event = createMessageEvent("This message contains \" quotes"); assertTrue(layout.format(event).equals("This message contains \\\" quotes")); }
@Test public void testTab() { LoggingEvent event = createMessageEvent("This message contains a tab \t"); assertTrue(layout.format(event).equals("This message contains a tab \\t")); }
@Test public void testBackSlash() { LoggingEvent event = createMessageEvent("This message contains a backslash \\"); assertTrue(layout.format(event).equals("This message contains a backslash \\\\")); }
|
### Question:
ExternalLinkUtils { public static String getExternalAnalyzerOnReq(Props azkProps, HttpServletRequest req) { if (!azkProps.containsKey(ServerProperties.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC)) { return ""; } String topic = azkProps.getString(ServerProperties.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC); return getLinkFromRequest(topic, azkProps, req); } static String getExternalAnalyzerOnReq(Props azkProps, HttpServletRequest req); static String getExternalLogViewer(Props azkProps, String jobId, Props jobProps); }### Answer:
@Test public void testGetExternalAnalyzerValidFormat() { azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC, EXTERNAL_ANALYZER_TOPIC); azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_TOPIC_URL.replace("${topic}", EXTERNAL_ANALYZER_TOPIC), EXTERNAL_ANALYZER_URL_VALID_FORMAT); when(mockRequest.getRequestURL()).thenReturn(new StringBuffer(EXEC_URL)); when(mockRequest.getQueryString()).thenReturn(EXEC_QUERY_STRING); String externalURL = ExternalLinkUtils.getExternalAnalyzerOnReq(azkProps, mockRequest); assertTrue(externalURL.equals(EXTERNAL_ANALYZER_EXPECTED_URL)); }
@Test public void testGetExternalAnalyzerNotConfigured() { String executionExternalLinkURL = ExternalLinkUtils.getExternalAnalyzerOnReq(azkProps, mockRequest); assertTrue(executionExternalLinkURL.equals("")); }
|
### Question:
ExternalLinkUtils { public static String getExternalLogViewer(Props azkProps, String jobId, Props jobProps) { if (!azkProps.containsKey(ServerProperties.AZKABAN_SERVER_EXTERNAL_LOGVIEWER_TOPIC)) { return ""; } String topic = azkProps.getString(ServerProperties.AZKABAN_SERVER_EXTERNAL_LOGVIEWER_TOPIC); return getLinkFromJobAndExecId(topic, azkProps, jobId, jobProps); } static String getExternalAnalyzerOnReq(Props azkProps, HttpServletRequest req); static String getExternalLogViewer(Props azkProps, String jobId, Props jobProps); }### Answer:
@Test public void testGetExternalLogViewerValidFormat() { azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_LOGVIEWER_TOPIC, EXTERNAL_LOGVIEWER_TOPIC); azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_TOPIC_URL.replace("${topic}", EXTERNAL_LOGVIEWER_TOPIC), EXTERNAL_LOGVIEWER_URL_VALID_FORMAT); String externalURL = ExternalLinkUtils.getExternalLogViewer(azkProps, jobId, jobProps); assertTrue(externalURL.equals(EXTERNAL_LOGVIEWER_EXPECTED_URL)); }
@Test public void testGetLogViewerNotConfigured() { String executionExternalLinkURL = ExternalLinkUtils.getExternalLogViewer(azkProps, jobId, jobProps); assertTrue(executionExternalLinkURL.equals("")); }
|
### Question:
ExternalLinkUtils { static String encodeToUTF8(String url) { try { return URLEncoder.encode(url, "UTF-8").replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { logger.error("Specified encoding is not supported", e); } return ""; } static String getExternalAnalyzerOnReq(Props azkProps, HttpServletRequest req); static String getExternalLogViewer(Props azkProps, String jobId, Props jobProps); }### Answer:
@Test public void testEncodingToUFT8() { assertTrue(ExternalLinkUtils.encodeToUTF8(" ").equals("%20")); assertTrue(ExternalLinkUtils.encodeToUTF8("+").equals("%2B")); assertTrue(ExternalLinkUtils.encodeToUTF8("/").equals("%2F")); assertTrue(ExternalLinkUtils.encodeToUTF8(":").equals("%3A")); assertTrue(ExternalLinkUtils.encodeToUTF8("?").equals("%3F")); assertTrue(ExternalLinkUtils.encodeToUTF8("=").equals("%3D")); }
|
### Question:
ExternalLinkUtils { static String getURLForTopic(String topic, Props azkProps) { return azkProps.getString(ServerProperties.AZKABAN_SERVER_EXTERNAL_TOPIC_URL.replace("${topic}", topic), ""); } static String getExternalAnalyzerOnReq(Props azkProps, HttpServletRequest req); static String getExternalLogViewer(Props azkProps, String jobId, Props jobProps); }### Answer:
@Test public void testFetchURL() { azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_TOPIC_URL.replace("${topic}", "someTopic"), "This is a link"); assertTrue(ExternalLinkUtils.getURLForTopic("someTopic", azkProps).equals("This is a link")); }
|
### Question:
Emailer extends AbstractMailer implements Alerter { public void sendErrorEmail(ExecutableFlow flow, String... extraReasons) { EmailMessage message = new EmailMessage(mailHost, mailPort, mailUser, mailPassword); message.setFromAddress(mailSender); message.setTLS(tls); message.setAuth(super.hasMailAuth()); ExecutionOptions option = flow.getExecutionOptions(); MailCreator mailCreator = DefaultMailCreator.getCreator(option.getMailCreator()); logger.debug("ExecutorMailer using mail creator:" + mailCreator.getClass().getCanonicalName()); boolean mailCreated = mailCreator.createErrorEmail(flow, message, azkabanName, scheme, clientHostname, clientPortNumber, extraReasons); if (mailCreated && !testMode) { try { message.sendEmail(); } catch (MessagingException e) { logger.error("Email message send failed", e); } } } Emailer(Props props); void sendFirstErrorMessage(ExecutableFlow flow); void sendErrorEmail(ExecutableFlow flow, String... extraReasons); void sendSuccessEmail(ExecutableFlow flow); static List<String> findFailedJobs(ExecutableFlow flow); @Override void alertOnSuccess(ExecutableFlow exflow); @Override void alertOnError(ExecutableFlow exflow, String... extraReasons); @Override void alertOnFirstError(ExecutableFlow exflow); @Override void alertOnSla(SlaOption slaOption, String slaMessage); }### Answer:
@Ignore @Test public void testSendEmail() throws Exception{ Flow flow = project.getFlow("jobe"); flow.addFailureEmails(receiveAddrList); Assert.assertNotNull(flow); ExecutableFlow exFlow = new ExecutableFlow(project, flow); Emailer emailer = new Emailer(props); emailer.sendErrorEmail(exFlow); }
|
### Question:
RestfulApiClient { public T httpGet(URI uri, List<NameValuePair> headerEntries) throws IOException{ if (null == uri){ logger.error(" unable to perform httpGet as the passed uri is null"); return null; } HttpGet get = new HttpGet(uri); return this.sendAndReturn((HttpGet)completeRequest(get, headerEntries)); } T httpGet(URI uri, List<NameValuePair> headerEntries); T httpPost(URI uri,
List<NameValuePair> headerEntries,
String postingBody); T httpDelete(URI uri, List<NameValuePair> headerEntries); T httpPut(URI uri, List<NameValuePair> headerEntries,
String postingBody); static URI buildUri(String host, int port, String path,
boolean isHttp, Pair<String, String>... params); static URI BuildUri(URI uri, Pair<String, String>... params); }### Answer:
@Test public void testHttpGet() throws Exception { MockRestfulApiClient mockClient = new MockRestfulApiClient(); @SuppressWarnings("unchecked") URI uri = MockRestfulApiClient.buildUri("test.com", 80, "test", true, new Pair <String,String>("Entry1","Value1")); String result = mockClient.httpGet(uri, null); Assert.assertTrue(result!= null && result.contains(uri.toString())); Assert.assertTrue(result.contains("METHOD = GET")); }
|
### Question:
RestfulApiClient { public T httpPost(URI uri, List<NameValuePair> headerEntries, String postingBody) throws UnsupportedEncodingException, IOException{ if (null == uri){ logger.error(" unable to perform httpPost as the passed uri is null."); return null; } HttpPost post = new HttpPost(uri); return this.sendAndReturn(completeRequest(post,headerEntries,postingBody)); } T httpGet(URI uri, List<NameValuePair> headerEntries); T httpPost(URI uri,
List<NameValuePair> headerEntries,
String postingBody); T httpDelete(URI uri, List<NameValuePair> headerEntries); T httpPut(URI uri, List<NameValuePair> headerEntries,
String postingBody); static URI buildUri(String host, int port, String path,
boolean isHttp, Pair<String, String>... params); static URI BuildUri(URI uri, Pair<String, String>... params); }### Answer:
@Test public void testHttpPost() throws Exception { MockRestfulApiClient mockClient = new MockRestfulApiClient(); @SuppressWarnings("unchecked") URI uri = MockRestfulApiClient.buildUri("test.com", 80, "test", true, new Pair <String,String>("Entry1","Value1")); ArrayList<NameValuePair> headerItems = new ArrayList<NameValuePair>(); headerItems.add(new BasicNameValuePair("h1","v1")); headerItems.add(new BasicNameValuePair("h2","v2")); String content = "123456789"; String result = mockClient.httpPost(uri, headerItems,content); Assert.assertTrue(result!= null && result.contains(uri.toString())); Assert.assertTrue(result.contains("METHOD = POST")); Assert.assertTrue(result.contains("h1 = v1")); Assert.assertTrue(result.contains("h2 = v2")); Assert.assertTrue(result.contains(String.format("%s = %s;", "BODY", content))); }
|
### Question:
RestfulApiClient { public T httpPut(URI uri, List<NameValuePair> headerEntries, String postingBody) throws UnsupportedEncodingException, IOException{ if (null == uri){ logger.error(" unable to perform httpPut as the passed url is null or empty."); return null; } HttpPut put = new HttpPut(uri); return this.sendAndReturn(completeRequest(put, headerEntries, postingBody)); } T httpGet(URI uri, List<NameValuePair> headerEntries); T httpPost(URI uri,
List<NameValuePair> headerEntries,
String postingBody); T httpDelete(URI uri, List<NameValuePair> headerEntries); T httpPut(URI uri, List<NameValuePair> headerEntries,
String postingBody); static URI buildUri(String host, int port, String path,
boolean isHttp, Pair<String, String>... params); static URI BuildUri(URI uri, Pair<String, String>... params); }### Answer:
@Test public void testHttpPut() throws Exception { MockRestfulApiClient mockClient = new MockRestfulApiClient(); @SuppressWarnings("unchecked") URI uri = MockRestfulApiClient.buildUri("test.com", 80, "test", true, new Pair <String,String>("Entry1","Value1")); ArrayList<NameValuePair> headerItems = new ArrayList<NameValuePair>(); headerItems.add(new BasicNameValuePair("h1","v1")); headerItems.add(new BasicNameValuePair("h2","v2")); String content = "123456789"; String result = mockClient.httpPut(uri, headerItems,content); Assert.assertTrue(result!= null && result.contains(uri.toString())); Assert.assertTrue(result.contains("METHOD = PUT")); Assert.assertTrue(result.contains("h1 = v1")); Assert.assertTrue(result.contains("h2 = v2")); Assert.assertTrue(result.contains(String.format("%s = %s;", "BODY", content))); }
|
### Question:
RestfulApiClient { public T httpDelete(URI uri, List<NameValuePair> headerEntries) throws IOException{ if (null == uri){ logger.error(" unable to perform httpDelete as the passed uri is null."); return null; } HttpDelete delete = new HttpDelete(uri); return this.sendAndReturn((HttpDelete)completeRequest(delete, headerEntries)); } T httpGet(URI uri, List<NameValuePair> headerEntries); T httpPost(URI uri,
List<NameValuePair> headerEntries,
String postingBody); T httpDelete(URI uri, List<NameValuePair> headerEntries); T httpPut(URI uri, List<NameValuePair> headerEntries,
String postingBody); static URI buildUri(String host, int port, String path,
boolean isHttp, Pair<String, String>... params); static URI BuildUri(URI uri, Pair<String, String>... params); }### Answer:
@Test public void testHttpDelete() throws Exception { MockRestfulApiClient mockClient = new MockRestfulApiClient(); @SuppressWarnings("unchecked") URI uri = MockRestfulApiClient.buildUri("test.com", 80, "test", true, new Pair <String,String>("Entry1","Value1")); ArrayList<NameValuePair> headerItems = new ArrayList<NameValuePair>(); headerItems.add(new BasicNameValuePair("h1","v1")); headerItems.add(new BasicNameValuePair("h2","v2")); String result = mockClient.httpDelete(uri, headerItems); Assert.assertTrue(result!= null && result.contains(uri.toString())); Assert.assertTrue(result.contains("METHOD = DELETE")); Assert.assertTrue(result.contains("h1 = v1")); Assert.assertTrue(result.contains("h2 = v2")); }
|
### Question:
Utils { public static boolean isValidPort(int port) { if (port >= 1 && port <= 65535) { return true; } return false; } private Utils(); static boolean equals(Object a, Object b); static T nonNull(T t); static File findFilefromDir(File dir, String fn); static void croak(String message, int exitCode); static boolean isValidPort(int port); static File createTempDir(); static File createTempDir(File parent); static void zip(File input, File output); static void zipFolderContent(File folder, File output); static void unzip(ZipFile source, File dest); static String flattenToString(Collection<?> collection,
String delimiter); static Double convertToDouble(Object obj); static Class<?>[] getTypes(Object... args); static Object callConstructor(Class<?> c, Object... args); static Object callConstructor(Class<?> c, Class<?>[] argTypes,
Object[] args); static String formatDuration(long startTime, long endTime); static Object invokeStaticMethod(ClassLoader loader, String className,
String methodName, Object... args); static void copyStream(InputStream input, OutputStream output); static ReadablePeriod parsePeriodString(String periodStr); static String createPeriodString(ReadablePeriod period); static long parseMemString(String strMemSize); static CronExpression parseCronExpression(String cronExpression, DateTimeZone timezone); static boolean isCronExpressionValid(String cronExpression, DateTimeZone timezone); static final Random RANDOM; }### Answer:
@Test public void testNegativePort() { Assert.assertFalse(Utils.isValidPort(-1)); Assert.assertFalse(Utils.isValidPort(-10)); }
@Test public void testZeroPort() { Assert.assertFalse(Utils.isValidPort(0)); }
@Test public void testOverflowPort() { Assert.assertFalse(Utils.isValidPort(70000)); Assert.assertFalse(Utils.isValidPort(65536)); }
@Test public void testValidPort() { Assert.assertTrue(Utils.isValidPort(1023)); Assert.assertTrue(Utils.isValidPort(10000)); Assert.assertTrue(Utils.isValidPort(3030)); Assert.assertTrue(Utils.isValidPort(1045)); }
|
### Question:
Utils { public static boolean isCronExpressionValid(String cronExpression, DateTimeZone timezone) { if (!CronExpression.isValidExpression(cronExpression)) { return false; } CronExpression cronExecutionTime = parseCronExpression(cronExpression, timezone); if (cronExecutionTime == null || cronExecutionTime.getNextValidTimeAfter(new Date()) == null) { return false; } return true; } private Utils(); static boolean equals(Object a, Object b); static T nonNull(T t); static File findFilefromDir(File dir, String fn); static void croak(String message, int exitCode); static boolean isValidPort(int port); static File createTempDir(); static File createTempDir(File parent); static void zip(File input, File output); static void zipFolderContent(File folder, File output); static void unzip(ZipFile source, File dest); static String flattenToString(Collection<?> collection,
String delimiter); static Double convertToDouble(Object obj); static Class<?>[] getTypes(Object... args); static Object callConstructor(Class<?> c, Object... args); static Object callConstructor(Class<?> c, Class<?>[] argTypes,
Object[] args); static String formatDuration(long startTime, long endTime); static Object invokeStaticMethod(ClassLoader loader, String className,
String methodName, Object... args); static void copyStream(InputStream input, OutputStream output); static ReadablePeriod parsePeriodString(String periodStr); static String createPeriodString(ReadablePeriod period); static long parseMemString(String strMemSize); static CronExpression parseCronExpression(String cronExpression, DateTimeZone timezone); static boolean isCronExpressionValid(String cronExpression, DateTimeZone timezone); static final Random RANDOM; }### Answer:
@Test public void testValidCronExpressionV() { DateTimeZone timezone = DateTimeZone.getDefault(); Assert.assertTrue(Utils.isCronExpressionValid("0 0 3 ? * *", timezone)); Assert.assertTrue(Utils.isCronExpressionValid("0 0 3 ? * * 2017", timezone)); Assert.assertTrue(Utils.isCronExpressionValid("0 0 * ? * *", timezone)); Assert.assertTrue(Utils.isCronExpressionValid("0 0 * ? * FRI", timezone)); Assert.assertTrue(Utils.isCronExpressionValid("0 0 3 ? * * 2017 22", timezone)); }
@Test public void testInvalidCronExpression() { DateTimeZone timezone = DateTimeZone.getDefault(); Assert.assertFalse(Utils.isCronExpressionValid("0 0 3 * * *", timezone)); Assert.assertFalse(Utils.isCronExpressionValid("0 66 * ? * *", timezone)); Assert.assertFalse(Utils.isCronExpressionValid("0 * * ? * 8", timezone)); Assert.assertFalse(Utils.isCronExpressionValid("0 * 25 ? * FRI", timezone)); }
|
### Question:
AbstractMailer { protected EmailMessage createEmailMessage(String subject, String mimetype, Collection<String> emailList) { EmailMessage message = new EmailMessage(mailHost, mailPort, mailUser, mailPassword); message.setFromAddress(mailSender); message.addAllToAddress(emailList); message.setMimeType(mimetype); message.setSubject(subject); message.setAuth(usesAuth); message.setTLS(tls); return message; } AbstractMailer(Props props); String getReferenceURL(); EmailMessage prepareEmailMessage(String subject, String mimetype,
Collection<String> emailList); String getAzkabanName(); String getMailHost(); String getMailUser(); String getMailPassword(); String getMailSender(); int getMailPort(); long getAttachmentMaxSize(); boolean hasMailAuth(); static final int DEFAULT_SMTP_PORT; }### Answer:
@Test public void testCreateEmailMessage(){ Props props = createMailProperties(); props.put("mail.port","445"); AbstractMailer mailer = new AbstractMailer(props); EmailMessage emailMessage = mailer.createEmailMessage("subject","text/html",senderList); assert emailMessage.getMailPort()==445; }
|
### Question:
HttpRequestUtils { public static void filterAdminOnlyFlowParams(UserManager userManager, ExecutionOptions options, User user) throws ExecutorManagerException { if (options == null || options.getFlowParameters() == null) return; Map<String, String> params = options.getFlowParameters(); if (!hasPermission(userManager, user, Type.ADMIN)) { params.remove(ExecutionOptions.FLOW_PRIORITY); params.remove(ExecutionOptions.USE_EXECUTOR); } else { validateIntegerParam(params, ExecutionOptions.FLOW_PRIORITY); validateIntegerParam(params, ExecutionOptions.USE_EXECUTOR); } } static ExecutionOptions parseFlowOptions(HttpServletRequest req); static void filterAdminOnlyFlowParams(UserManager userManager,
ExecutionOptions options, User user); static boolean validateIntegerParam(Map<String, String> params,
String paramName); static boolean hasPermission(UserManager userManager, User user,
Permission.Type type); static boolean hasParam(HttpServletRequest request, String param); static String getParam(HttpServletRequest request, String name); static String getParam(HttpServletRequest request, String name,
String defaultVal); static int getIntParam(HttpServletRequest request, String name); static int getIntParam(HttpServletRequest request, String name,
int defaultVal); static boolean getBooleanParam(HttpServletRequest request, String name); static boolean getBooleanParam(HttpServletRequest request,
String name, boolean defaultVal); static long getLongParam(HttpServletRequest request, String name); static long getLongParam(HttpServletRequest request, String name,
long defaultVal); static Map<String, String> getParamGroup(HttpServletRequest request,
String groupName); }### Answer:
@Test public void TestFilterNonAdminOnlyFlowParams() throws IOException, ExecutorManagerException, UserManagerException { ExecutableFlow flow = createExecutableFlow(); UserManager manager = TestUtils.createTestXmlUserManager(); User user = manager.getUser("testUser", "testUser"); HttpRequestUtils.filterAdminOnlyFlowParams(manager, flow.getExecutionOptions(), user); Assert.assertFalse(flow.getExecutionOptions().getFlowParameters() .containsKey(ExecutionOptions.FLOW_PRIORITY)); Assert.assertFalse(flow.getExecutionOptions().getFlowParameters() .containsKey(ExecutionOptions.USE_EXECUTOR)); }
@Test public void TestFilterAdminOnlyFlowParams() throws IOException, ExecutorManagerException, UserManagerException { ExecutableFlow flow = createExecutableFlow(); UserManager manager = TestUtils.createTestXmlUserManager(); User user = manager.getUser("testAdmin", "testAdmin"); HttpRequestUtils.filterAdminOnlyFlowParams(manager, flow.getExecutionOptions(), user); Assert.assertTrue(flow.getExecutionOptions().getFlowParameters() .containsKey(ExecutionOptions.FLOW_PRIORITY)); Assert.assertTrue(flow.getExecutionOptions().getFlowParameters() .containsKey(ExecutionOptions.USE_EXECUTOR)); }
|
### Question:
HttpRequestUtils { public static boolean validateIntegerParam(Map<String, String> params, String paramName) throws ExecutorManagerException { if (params != null && params.containsKey(paramName) && !StringUtils.isNumeric(params.get(paramName))) { throw new ExecutorManagerException(paramName + " should be an integer"); } return true; } static ExecutionOptions parseFlowOptions(HttpServletRequest req); static void filterAdminOnlyFlowParams(UserManager userManager,
ExecutionOptions options, User user); static boolean validateIntegerParam(Map<String, String> params,
String paramName); static boolean hasPermission(UserManager userManager, User user,
Permission.Type type); static boolean hasParam(HttpServletRequest request, String param); static String getParam(HttpServletRequest request, String name); static String getParam(HttpServletRequest request, String name,
String defaultVal); static int getIntParam(HttpServletRequest request, String name); static int getIntParam(HttpServletRequest request, String name,
int defaultVal); static boolean getBooleanParam(HttpServletRequest request, String name); static boolean getBooleanParam(HttpServletRequest request,
String name, boolean defaultVal); static long getLongParam(HttpServletRequest request, String name); static long getLongParam(HttpServletRequest request, String name,
long defaultVal); static Map<String, String> getParamGroup(HttpServletRequest request,
String groupName); }### Answer:
@Test public void testvalidIntegerParam() throws ExecutorManagerException { Map<String, String> params = new HashMap<String, String>(); params.put("param1", "123"); HttpRequestUtils.validateIntegerParam(params, "param1"); }
@Test(expected = ExecutorManagerException.class) public void testInvalidIntegerParam() throws ExecutorManagerException { Map<String, String> params = new HashMap<String, String>(); params.put("param1", "1dff2"); HttpRequestUtils.validateIntegerParam(params, "param1"); }
|
### Question:
HttpRequestUtils { public static boolean hasPermission(UserManager userManager, User user, Permission.Type type) { for (String roleName : user.getRoles()) { Role role = userManager.getRole(roleName); if (role.getPermission().isPermissionSet(type) || role.getPermission().isPermissionSet(Permission.Type.ADMIN)) { return true; } } return false; } static ExecutionOptions parseFlowOptions(HttpServletRequest req); static void filterAdminOnlyFlowParams(UserManager userManager,
ExecutionOptions options, User user); static boolean validateIntegerParam(Map<String, String> params,
String paramName); static boolean hasPermission(UserManager userManager, User user,
Permission.Type type); static boolean hasParam(HttpServletRequest request, String param); static String getParam(HttpServletRequest request, String name); static String getParam(HttpServletRequest request, String name,
String defaultVal); static int getIntParam(HttpServletRequest request, String name); static int getIntParam(HttpServletRequest request, String name,
int defaultVal); static boolean getBooleanParam(HttpServletRequest request, String name); static boolean getBooleanParam(HttpServletRequest request,
String name, boolean defaultVal); static long getLongParam(HttpServletRequest request, String name); static long getLongParam(HttpServletRequest request, String name,
long defaultVal); static Map<String, String> getParamGroup(HttpServletRequest request,
String groupName); }### Answer:
@Test public void testHasAdminPermission() throws UserManagerException { UserManager manager = TestUtils.createTestXmlUserManager(); User adminUser = manager.getUser("testAdmin", "testAdmin"); Assert.assertTrue(HttpRequestUtils.hasPermission(manager, adminUser, Type.ADMIN)); }
@Test public void testHasOrdinaryPermission() throws UserManagerException { UserManager manager = TestUtils.createTestXmlUserManager(); User testUser = manager.getUser("testUser", "testUser"); Assert.assertFalse(HttpRequestUtils.hasPermission(manager, testUser, Type.ADMIN)); }
|
### Question:
ValidationReport { public void addWarnLevelInfoMsg(String msg) { if (msg != null) { _infoMsgs.add("WARN" + msg); } } ValidationReport(); void addWarnLevelInfoMsg(String msg); void addErrorLevelInfoMsg(String msg); void addWarningMsgs(Set<String> msgs); void addErrorMsgs(Set<String> msgs); ValidationStatus getStatus(); Set<String> getInfoMsgs(); Set<String> getWarningMsgs(); Set<String> getErrorMsgs(); static ValidationStatus getInfoMsgLevel(String msg); static String getInfoMsg(String msg); }### Answer:
@Test public void testAddWarnLevelInfoMsg() { ValidationReport report = new ValidationReport(); String msg = "test warn level info message."; report.addWarnLevelInfoMsg(msg); for (String info : report.getInfoMsgs()) { assertEquals("Info message added through addWarnLevelInfoMsg should have level set to WARN", ValidationReport.getInfoMsgLevel(info), ValidationStatus.WARN); assertEquals("Retrieved info message does not match the original one.", ValidationReport.getInfoMsg(info), msg); } }
|
### Question:
ValidationReport { public void addErrorLevelInfoMsg(String msg) { if (msg != null) { _infoMsgs.add("ERROR" + msg); } } ValidationReport(); void addWarnLevelInfoMsg(String msg); void addErrorLevelInfoMsg(String msg); void addWarningMsgs(Set<String> msgs); void addErrorMsgs(Set<String> msgs); ValidationStatus getStatus(); Set<String> getInfoMsgs(); Set<String> getWarningMsgs(); Set<String> getErrorMsgs(); static ValidationStatus getInfoMsgLevel(String msg); static String getInfoMsg(String msg); }### Answer:
@Test public void testAddErrorLevelInfoMsg() { ValidationReport report = new ValidationReport(); String msg = "test error level error message."; report.addErrorLevelInfoMsg(msg); for (String info : report.getInfoMsgs()) { assertEquals("Info message added through addErrorLevelInfoMsg should have level set to ERROR", ValidationReport.getInfoMsgLevel(info), ValidationStatus.ERROR); assertEquals("Retrieved info message does not match the original one.", ValidationReport.getInfoMsg(info), msg); } }
|
### Question:
XmlValidatorManager implements ValidatorManager { @Override public List<String> getValidatorsInfo() { List<String> info = new ArrayList<String>(); for (String key : validators.keySet()) { info.add(key); } return info; } XmlValidatorManager(Props props); @Override void loadValidators(Props props, Logger log); @Override Map<String, ValidationReport> validate(Project project, File projectDir); @Override ProjectValidator getDefaultValidator(); @Override List<String> getValidatorsInfo(); static final String AZKABAN_VALIDATOR_TAG; static final String VALIDATOR_TAG; static final String CLASSNAME_ATTR; static final String ITEM_TAG; static final String DEFAULT_VALIDATOR_KEY; }### Answer:
@Test public void testNoValidatorsDir() { Props props = new Props(baseProps); XmlValidatorManager manager = new XmlValidatorManager(props); assertEquals("XmlValidatorManager should contain only the default validator when no xml configuration " + "file is present.", manager.getValidatorsInfo().size(), 1); assertEquals("XmlValidatorManager should contain only the default validator when no xml configuration " + "file is present.", manager.getValidatorsInfo().get(0), XmlValidatorManager.DEFAULT_VALIDATOR_KEY); }
@Test public void testDefaultValidator() { Props props = new Props(baseProps); URL validatorUrl = Resources.getResource("project/testValidators"); props.put(ValidatorConfigs.VALIDATOR_PLUGIN_DIR, validatorUrl.getPath()); XmlValidatorManager manager = new XmlValidatorManager(props); assertEquals("XmlValidatorManager should contain only the default validator when no xml configuration " + "file is present.", manager.getValidatorsInfo().size(), 1); assertEquals("XmlValidatorManager should contain only the default validator when no xml configuration " + "file is present.", manager.getValidatorsInfo().get(0), XmlValidatorManager.DEFAULT_VALIDATOR_KEY); }
|
### Question:
XmlValidatorManager implements ValidatorManager { @Override public void loadValidators(Props props, Logger log) { validators = new LinkedHashMap<String, ProjectValidator>(); DirectoryFlowLoader flowLoader = new DirectoryFlowLoader(props, log); validators.put(flowLoader.getValidatorName(), flowLoader); if (!props.containsKey(ValidatorConfigs.XML_FILE_PARAM)) { logger.warn("Azkaban properties file does not contain the key " + ValidatorConfigs.XML_FILE_PARAM); return; } String xmlPath = props.get(ValidatorConfigs.XML_FILE_PARAM); File file = new File(xmlPath); if (!file.exists()) { logger.error("Azkaban validator configuration file " + xmlPath + " does not exist."); return; } DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ValidatorManagerException( "Exception while parsing validator xml. Document builder not created.", e); } Document doc = null; try { doc = builder.parse(file); } catch (SAXException e) { throw new ValidatorManagerException("Exception while parsing " + xmlPath + ". Invalid XML.", e); } catch (IOException e) { throw new ValidatorManagerException("Exception while parsing " + xmlPath + ". Error reading file.", e); } NodeList tagList = doc.getChildNodes(); Node azkabanValidators = tagList.item(0); NodeList azkabanValidatorsList = azkabanValidators.getChildNodes(); for (int i = 0; i < azkabanValidatorsList.getLength(); ++i) { Node node = azkabanValidatorsList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals(VALIDATOR_TAG)) { parseValidatorTag(node, props, log); } } } } XmlValidatorManager(Props props); @Override void loadValidators(Props props, Logger log); @Override Map<String, ValidationReport> validate(Project project, File projectDir); @Override ProjectValidator getDefaultValidator(); @Override List<String> getValidatorsInfo(); static final String AZKABAN_VALIDATOR_TAG; static final String VALIDATOR_TAG; static final String CLASSNAME_ATTR; static final String ITEM_TAG; static final String DEFAULT_VALIDATOR_KEY; }### Answer:
@Test public void testLoadValidators() { Props props = new Props(baseProps); URL validatorUrl = Resources.getResource("project/testValidators"); URL configUrl = Resources.getResource("test-conf/azkaban-validators-test2.xml"); props.put(ValidatorConfigs.VALIDATOR_PLUGIN_DIR, validatorUrl.getPath()); props.put(ValidatorConfigs.XML_FILE_PARAM, configUrl.getPath()); XmlValidatorManager manager = new XmlValidatorManager(props); assertEquals("XmlValidatorManager should contain 2 validators.", manager.getValidatorsInfo().size(), 2); assertEquals("XmlValidatorManager should contain the validator specified in the xml configuration file.", manager.getValidatorsInfo().get(1), "Test"); }
|
### Question:
JdbcProjectLoader extends AbstractJdbcLoader implements
ProjectLoader { @Override public Project fetchProjectByName(String name) throws ProjectManagerException { Connection connection = getConnection(); Project project = null; try { project = fetchProjectByName(connection, name); } finally { DbUtils.closeQuietly(connection); } return project; } JdbcProjectLoader(Props props); @Override List<Project> fetchAllActiveProjects(); @Override Project fetchProjectById(int id); @Override Project fetchProjectByName(String name); @Override Project createNewProject(String name, String description, User creator); @Override void uploadProjectFile(Project project, int version, String filetype,
String filename, File localFile, String uploader); @Override ProjectFileHandler getUploadedFile(Project project, int version); @Override ProjectFileHandler getUploadedFile(int projectId, int version); @Override void changeProjectVersion(Project project, int version, String user); @Override void updatePermission(Project project, String name, Permission perm,
boolean isGroup); @Override void updateProjectSettings(Project project); @Override void removePermission(Project project, String name, boolean isGroup); @Override List<Triple<String, Boolean, Permission>> getProjectPermissions(
int projectId); @Override void removeProject(Project project, String user); @Override boolean postEvent(Project project, EventType type, String user,
String message); List<ProjectLogEvent> getProjectEvents(Project project, int num,
int skip); @Override void updateDescription(Project project, String description, String user); @Override int getLatestProjectVersion(Project project); @Override void uploadFlows(Project project, int version, Collection<Flow> flows); @Override void uploadFlow(Project project, int version, Flow flow); @Override void updateFlow(Project project, int version, Flow flow); EncodingType getDefaultEncodingType(); void setDefaultEncodingType(EncodingType defaultEncodingType); @Override Flow fetchFlow(Project project, String flowId); @Override List<Flow> fetchAllProjectFlows(Project project); @Override void uploadProjectProperties(Project project, List<Props> properties); @Override void uploadProjectProperty(Project project, Props props); @Override void updateProjectProperty(Project project, Props props); @Override Props fetchProjectProperty(int projectId, int projectVer,
String propsName); @Override Props fetchProjectProperty(Project project, String propsName); @Override void cleanOlderProjectVersion(int projectId, int version); @Override Map<String, Props> fetchProjectProperties(int projectId, int version); }### Answer:
@Test public void testInvalidProjectByFetchProjectByName() { if (!isTestSetup()) { return; } ProjectLoader loader = createLoader(); try { loader.fetchProjectByName("NonExistantProject"); } catch (ProjectManagerException ex) { System.out.println("Test true"); } Assert.fail("Expecting exception, but didn't get one"); }
|
### Question:
JdbcProjectLoader extends AbstractJdbcLoader implements
ProjectLoader { @Override public void removeProject(Project project, String user) throws ProjectManagerException { QueryRunner runner = createQueryRunner(); long updateTime = System.currentTimeMillis(); final String UPDATE_INACTIVE_PROJECT = "UPDATE projects SET active=false,modified_time=?,last_modified_by=? WHERE id=?"; try { runner.update(UPDATE_INACTIVE_PROJECT, updateTime, user, project.getId()); } catch (SQLException e) { logger.error(e); throw new ProjectManagerException("Error marking project " + project.getName() + " as inactive", e); } } JdbcProjectLoader(Props props); @Override List<Project> fetchAllActiveProjects(); @Override Project fetchProjectById(int id); @Override Project fetchProjectByName(String name); @Override Project createNewProject(String name, String description, User creator); @Override void uploadProjectFile(Project project, int version, String filetype,
String filename, File localFile, String uploader); @Override ProjectFileHandler getUploadedFile(Project project, int version); @Override ProjectFileHandler getUploadedFile(int projectId, int version); @Override void changeProjectVersion(Project project, int version, String user); @Override void updatePermission(Project project, String name, Permission perm,
boolean isGroup); @Override void updateProjectSettings(Project project); @Override void removePermission(Project project, String name, boolean isGroup); @Override List<Triple<String, Boolean, Permission>> getProjectPermissions(
int projectId); @Override void removeProject(Project project, String user); @Override boolean postEvent(Project project, EventType type, String user,
String message); List<ProjectLogEvent> getProjectEvents(Project project, int num,
int skip); @Override void updateDescription(Project project, String description, String user); @Override int getLatestProjectVersion(Project project); @Override void uploadFlows(Project project, int version, Collection<Flow> flows); @Override void uploadFlow(Project project, int version, Flow flow); @Override void updateFlow(Project project, int version, Flow flow); EncodingType getDefaultEncodingType(); void setDefaultEncodingType(EncodingType defaultEncodingType); @Override Flow fetchFlow(Project project, String flowId); @Override List<Flow> fetchAllProjectFlows(Project project); @Override void uploadProjectProperties(Project project, List<Props> properties); @Override void uploadProjectProperty(Project project, Props props); @Override void updateProjectProperty(Project project, Props props); @Override Props fetchProjectProperty(int projectId, int projectVer,
String propsName); @Override Props fetchProjectProperty(Project project, String propsName); @Override void cleanOlderProjectVersion(int projectId, int version); @Override Map<String, Props> fetchProjectProperties(int projectId, int version); }### Answer:
@Test public void testRemoveProject() throws ProjectManagerException { if (!isTestSetup()) { return; } ProjectLoader loader = createLoader(); String projectName = "testRemoveProject"; String projectDescription = "This is my new project"; User user = new User("testUser"); Project project = loader.createNewProject(projectName, projectDescription, user); Assert.assertTrue("Project Id set", project.getId() > -1); Assert.assertEquals("Project name", projectName, project.getName()); Assert.assertEquals("Project description", projectDescription, project.getDescription()); Project project2 = loader.fetchProjectById(project.getId()); assertProjectMemberEquals(project, project2); loader.removeProject(project, user.getUserId()); Project project3 = loader.fetchProjectById(project.getId()); Assert.assertFalse(project3.isActive()); List<Project> projList = loader.fetchAllActiveProjects(); for (Project proj : projList) { Assert.assertTrue(proj.getId() != project.getId()); } }
|
### Question:
ProcessJob extends AbstractProcessJob { public static String[] partitionCommandLine(final String command) { ArrayList<String> commands = new ArrayList<String>(); int index = 0; StringBuffer buffer = new StringBuffer(command.length()); boolean isApos = false; boolean isQuote = false; while (index < command.length()) { char c = command.charAt(index); switch (c) { case ' ': if (!isQuote && !isApos) { String arg = buffer.toString(); buffer = new StringBuffer(command.length() - index); if (arg.length() > 0) { commands.add(arg); } } else { buffer.append(c); } break; case '\'': if (!isQuote) { isApos = !isApos; } else { buffer.append(c); } break; case '"': if (!isApos) { isQuote = !isQuote; } else { buffer.append(c); } break; default: buffer.append(c); } index++; } if (buffer.length() > 0) { String arg = buffer.toString(); commands.add(arg); } return commands.toArray(new String[commands.size()]); } ProcessJob(final String jobId, final Props sysProps,
final Props jobProps, final Logger log); @Override void run(); @Override void cancel(); @Override double getProgress(); int getProcessId(); String getPath(); static String[] partitionCommandLine(final String command); static final String COMMAND; static final String AZKABAN_MEMORY_CHECK; static final String NATIVE_LIB_FOLDER; static final String EXECUTE_AS_USER; static final String USER_TO_PROXY; static final String KRB5CCNAME; }### Answer:
@Test public void testPartitionCommand() throws Exception { String test1 = "a b c"; Assert.assertArrayEquals(new String[] { "a", "b", "c" }, ProcessJob.partitionCommandLine(test1)); String test2 = "a 'b c'"; Assert.assertArrayEquals(new String[] { "a", "b c" }, ProcessJob.partitionCommandLine(test2)); String test3 = "a e='b c'"; Assert.assertArrayEquals(new String[] { "a", "e=b c" }, ProcessJob.partitionCommandLine(test3)); }
|
### Question:
PythonJob extends LongArgJob { public PythonJob(String jobid, Props sysProps, Props jobProps, Logger log) { super(jobid, new String[] { jobProps.getString(PYTHON_BINARY_KEY, "python"), jobProps.getString(SCRIPT_KEY) }, sysProps, jobProps, log, ImmutableSet.of(PYTHON_BINARY_KEY, SCRIPT_KEY, JOB_TYPE)); } PythonJob(String jobid, Props sysProps, Props jobProps, Logger log); }### Answer:
@Ignore("Test appears to hang.") @Test public void testPythonJob() { props = new Props(); props.put(AbstractProcessJob.WORKING_DIR, "."); props.put("type", "python"); props.put("script", scriptFile); props.put("t", "90"); props.put("type", "script"); props.put("fullPath", "."); job = new PythonJob("TestProcess", props, props, log); try { job.run(); } catch (Exception e) { e.printStackTrace(System.err); Assert.fail("Python job failed:" + e.getLocalizedMessage()); } }
|
### Question:
LoginAbstractAzkabanServlet extends
AbstractAzkabanServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Session session = getSessionFromRequest(req); logRequest(req, session); if (hasParam(req, "logout")) { resp.sendRedirect(req.getContextPath()); if (session != null) { getApplication().getSessionCache() .removeSession(session.getSessionId()); } return; } if (session != null) { if (logger.isDebugEnabled()) { logger.debug("Found session " + session.getUser()); } if (handleFileGet(req, resp)) { return; } handleGet(req, resp, session); } else { if (hasParam(req, "ajax")) { HashMap<String, String> retVal = new HashMap<String, String>(); retVal.put("error", "session"); this.writeJSON(resp, retVal); } else { handleLogin(req, resp); } } } @Override void init(ServletConfig config); void setResourceDirectory(File file); }### Answer:
@Test public void testWhenGetRequestSessionIsValid() throws Exception, IOException, ServletException { String clientIp = "127.0.0.1:10000"; String sessionId = "111"; HttpServletRequest req = MockLoginAzkabanServlet.getRequestWithNoUpstream(clientIp, sessionId, "GET"); StringWriter writer = new StringWriter(); HttpServletResponse resp = getResponse(writer); MockLoginAzkabanServlet servlet = MockLoginAzkabanServlet.getServletWithSession(sessionId, "user", "127.0.0.1"); servlet.doGet(req, resp); assertEquals("SUCCESS_MOCK_LOGIN_SERVLET", writer.toString()); }
|
### Question:
XmlUserManager implements UserManager { @Override public User getUser(String username, String password) throws UserManagerException { if (username == null || username.trim().isEmpty()) { throw new UserManagerException("Username is empty."); } else if (password == null || password.trim().isEmpty()) { throw new UserManagerException("Password is empty."); } String foundPassword = null; User user = null; synchronized (this) { foundPassword = userPassword.get(username); if (foundPassword != null) { user = users.get(username); } } if (foundPassword == null || !foundPassword.equals(password)) { throw new UserManagerException("Username/Password not found."); } if (user == null) { throw new UserManagerException("Internal error: User not found."); } resolveGroupRoles(user); user.setPermissions(new UserPermissions() { @Override public boolean hasPermission(String permission) { return true; } @Override public void addPermission(String permission) { } }); return user; } XmlUserManager(Props props); @Override User getUser(String username, String password); @Override boolean validateUser(String username); @Override Role getRole(String roleName); @Override boolean validateGroup(String group); @Override boolean validateProxyUser(String proxyUser, User realUser); static final String XML_FILE_PARAM; static final String AZKABAN_USERS_TAG; static final String USER_TAG; static final String ROLE_TAG; static final String GROUP_TAG; static final String ROLENAME_ATTR; static final String ROLEPERMISSIONS_ATTR; static final String USERNAME_ATTR; static final String PASSWORD_ATTR; static final String EMAIL_ATTR; static final String ROLES_ATTR; static final String PROXY_ATTR; static final String GROUPS_ATTR; static final String GROUPNAME_ATTR; }### Answer:
@Ignore @Test public void testBasicLoad() throws Exception { Props props = new Props(baseProps); props.put(XmlUserManager.XML_FILE_PARAM, "unit/test-conf/azkaban-users-test1.xml"); UserManager manager = null; try { manager = new XmlUserManager(props); } catch (RuntimeException e) { e.printStackTrace(); fail("XmlUserManager should've found file azkaban-users.xml"); } try { manager.getUser("user0", null); } catch (UserManagerException e) { System.out.println("Exception handled correctly: " + e.getMessage()); } try { manager.getUser(null, "etw"); } catch (UserManagerException e) { System.out.println("Exception handled correctly: " + e.getMessage()); } try { manager.getUser("user0", "user0"); } catch (UserManagerException e) { System.out.println("Exception handled correctly: " + e.getMessage()); } try { manager.getUser("user0", "password0"); } catch (UserManagerException e) { e.printStackTrace(); fail("XmlUserManager should've returned a user."); } User user0 = manager.getUser("user0", "password0"); checkUser(user0, "role0", "group0"); User user1 = manager.getUser("user1", "password1"); checkUser(user1, "role0,role1", "group1,group2"); User user2 = manager.getUser("user2", "password2"); checkUser(user2, "role0,role1,role2", "group1,group2,group3"); User user3 = manager.getUser("user3", "password3"); checkUser(user3, "role1,role2", "group1,group2"); User user4 = manager.getUser("user4", "password4"); checkUser(user4, "role1,role2", "group1,group2"); User user5 = manager.getUser("user5", "password5"); checkUser(user5, "role1,role2", "group1,group2"); User user6 = manager.getUser("user6", "password6"); checkUser(user6, "role3,role2", "group1,group2"); User user7 = manager.getUser("user7", "password7"); checkUser(user7, "", "group1"); User user8 = manager.getUser("user8", "password8"); checkUser(user8, "role3", ""); User user9 = manager.getUser("user9", "password9"); checkUser(user9, "", ""); }
|
### Question:
Permission { public void addPermissionsByName(String... list) { for (String perm : list) { Type type = Type.valueOf(perm); if (type != null) { addPermission(type); } ; } } Permission(); Permission(int flags); Permission(Type... list); void addPermissions(Permission perm); void setPermission(Type type, boolean set); void setPermissions(int flags); void addPermission(Type... list); void addPermissionsByName(String... list); void addPermissions(Collection<Type> list); void addPermissionsByName(Collection<String> list); Set<Type> getTypes(); void removePermissions(Type... list); void removePermissionsByName(String... list); boolean isPermissionSet(Type permission); boolean isPermissionNameSet(String permission); String[] toStringArray(); String toString(); @Override int hashCode(); @Override boolean equals(Object obj); int toFlags(); }### Answer:
@Test public void testEmptyPermissionCreation() throws Exception { Permission permission = new Permission(); permission.addPermissionsByName(new String[] {}); }
|
### Question:
ExecutableFlow extends ExecutableFlowBase { @Override public String getId() { return getFlowId(); } ExecutableFlow(Project project, Flow flow); ExecutableFlow(); @Override int getOid(); @Override void setOid(int oid); @Override String getId(); @Override ExecutableFlow getExecutableFlow(); void addAllProxyUsers(Collection<String> proxyUsers); Set<String> getProxyUsers(); void setExecutionOptions(ExecutionOptions options); ExecutionOptions getExecutionOptions(); @Override int getExecutionId(); void setExecutionId(int executionId); @Override long getLastModifiedTimestamp(); void setLastModifiedTimestamp(long lastModifiedTimestamp); @Override String getLastModifiedByUser(); void setLastModifiedByUser(String lastModifiedUser); @Override int getProjectId(); void setProjectId(int projectId); @Override String getProjectName(); int getScheduleId(); void setScheduleId(int scheduleId); String getExecutionPath(); void setExecutionPath(String executionPath); String getSubmitUser(); void setSubmitUser(String submitUser); @Override int getVersion(); void setVersion(int version); long getSubmitTime(); void setSubmitTime(long submitTime); @Override Map<String, Object> toObject(); @SuppressWarnings("unchecked") static ExecutableFlow createExecutableFlowFromObject(Object obj); @Override void fillExecutableFromMapObject(
TypedMapWrapper<String, Object> flowObj); @Override Map<String, Object> toUpdateObject(long lastUpdateTime); @Override void resetForRetry(); static final String EXECUTIONID_PARAM; static final String EXECUTIONPATH_PARAM; static final String EXECUTIONOPTIONS_PARAM; static final String PROJECTID_PARAM; static final String SCHEDULEID_PARAM; static final String SUBMITUSER_PARAM; static final String SUBMITTIME_PARAM; static final String VERSION_PARAM; static final String PROXYUSERS_PARAM; static final String PROJECTNAME_PARAM; static final String LASTMODIFIEDTIME_PARAM; static final String LASTMODIFIEDUSER_PARAM; }### Answer:
@Test public void testExecutorFlowCreation() throws Exception { Flow flow = project.getFlow("jobe"); Assert.assertNotNull(flow); ExecutableFlow exFlow = new ExecutableFlow(project, flow); Assert.assertNotNull(exFlow.getExecutableNode("joba")); Assert.assertNotNull(exFlow.getExecutableNode("jobb")); Assert.assertNotNull(exFlow.getExecutableNode("jobc")); Assert.assertNotNull(exFlow.getExecutableNode("jobd")); Assert.assertNotNull(exFlow.getExecutableNode("jobe")); Assert.assertFalse(exFlow.getExecutableNode("joba") instanceof ExecutableFlowBase); Assert.assertTrue(exFlow.getExecutableNode("jobb") instanceof ExecutableFlowBase); Assert.assertTrue(exFlow.getExecutableNode("jobc") instanceof ExecutableFlowBase); Assert.assertTrue(exFlow.getExecutableNode("jobd") instanceof ExecutableFlowBase); Assert.assertFalse(exFlow.getExecutableNode("jobe") instanceof ExecutableFlowBase); ExecutableFlowBase jobbFlow = (ExecutableFlowBase) exFlow.getExecutableNode("jobb"); ExecutableFlowBase jobcFlow = (ExecutableFlowBase) exFlow.getExecutableNode("jobc"); ExecutableFlowBase jobdFlow = (ExecutableFlowBase) exFlow.getExecutableNode("jobd"); Assert.assertEquals("innerFlow", jobbFlow.getFlowId()); Assert.assertEquals("jobb", jobbFlow.getId()); Assert.assertEquals(4, jobbFlow.getExecutableNodes().size()); Assert.assertEquals("innerFlow", jobcFlow.getFlowId()); Assert.assertEquals("jobc", jobcFlow.getId()); Assert.assertEquals(4, jobcFlow.getExecutableNodes().size()); Assert.assertEquals("innerFlow", jobdFlow.getFlowId()); Assert.assertEquals("jobd", jobdFlow.getId()); Assert.assertEquals(4, jobdFlow.getExecutableNodes().size()); }
|
### Question:
QueuedExecutions { public void enqueue(ExecutableFlow exflow, ExecutionReference ref) throws ExecutorManagerException { if (hasExecution(exflow.getExecutionId())) { String errMsg = "Flow already in queue " + exflow.getExecutionId(); throw new ExecutorManagerException(errMsg); } Pair<ExecutionReference, ExecutableFlow> pair = new Pair<ExecutionReference, ExecutableFlow>(ref, exflow); try { queuedFlowMap.put(exflow.getExecutionId(), pair); queuedFlowList.put(pair); } catch (InterruptedException e) { String errMsg = "Failed to insert flow " + exflow.getExecutionId(); logger.error(errMsg, e); throw new ExecutorManagerException(errMsg); } } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test(expected = ExecutorManagerException.class) public void testEnqueueDuplicateExecution() throws IOException, ExecutorManagerException { Pair<ExecutionReference, ExecutableFlow> pair1 = createExecutablePair("exec1", 1); QueuedExecutions queue = new QueuedExecutions(5); queue.enqueue(pair1.getSecond(), pair1.getFirst()); queue.enqueue(pair1.getSecond(), pair1.getFirst()); }
@Test(expected = ExecutorManagerException.class) public void testEnqueueOverflow() throws IOException, ExecutorManagerException { Pair<ExecutionReference, ExecutableFlow> pair1 = createExecutablePair("exec1", 1); QueuedExecutions queue = new QueuedExecutions(1); queue.enqueue(pair1.getSecond(), pair1.getFirst()); queue.enqueue(pair1.getSecond(), pair1.getFirst()); }
|
### Question:
QueuedExecutions { public void enqueueAll( Collection<Pair<ExecutionReference, ExecutableFlow>> collection) throws ExecutorManagerException { for (Pair<ExecutionReference, ExecutableFlow> pair : collection) { enqueue(pair.getSecond(), pair.getFirst()); } } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test public void testEnqueueAll() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); Assert.assertTrue(queue.getAllEntries().containsAll(dataList)); Assert.assertTrue(dataList.containsAll(queue.getAllEntries())); }
|
### Question:
QueuedExecutions { public long size() { return queuedFlowList.size(); } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test public void testSize() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); Assert.assertEquals(queue.size(), 2); }
|
### Question:
QueuedExecutions { public void dequeue(int executionId) { if (queuedFlowMap.containsKey(executionId)) { queuedFlowList.remove(queuedFlowMap.get(executionId)); queuedFlowMap.remove(executionId); } } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test public void testDequeue() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); queue.dequeue(dataList.get(0).getFirst().getExecId()); Assert.assertEquals(queue.size(), 1); Assert.assertTrue(queue.getAllEntries().contains(dataList.get(1))); }
|
### Question:
QueuedExecutions { public void clear() { for (Pair<ExecutionReference, ExecutableFlow> pair : queuedFlowMap.values()) { dequeue(pair.getFirst().getExecId()); } } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test public void testClear() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); Assert.assertEquals(queue.size(), 2); queue.clear(); Assert.assertEquals(queue.size(), 0); }
|
### Question:
QueuedExecutions { public boolean isEmpty() { return queuedFlowList.isEmpty() && queuedFlowMap.isEmpty(); } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test public void testIsEmpty() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); Assert.assertTrue(queue.isEmpty()); queue.enqueueAll(dataList); Assert.assertEquals(queue.size(), 2); queue.clear(); Assert.assertTrue(queue.isEmpty()); }
|
### Question:
QueuedExecutions { public Pair<ExecutionReference, ExecutableFlow> fetchHead() throws InterruptedException { Pair<ExecutionReference, ExecutableFlow> pair = queuedFlowList.take(); if (pair != null && pair.getFirst() != null) { queuedFlowMap.remove(pair.getFirst().getExecId()); } return pair; } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test public void testFetchHead() throws IOException, ExecutorManagerException, InterruptedException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); Assert.assertTrue(queue.isEmpty()); queue.enqueueAll(dataList); Assert.assertEquals(queue.fetchHead(), dataList.get(0)); Assert.assertEquals(queue.fetchHead(), dataList.get(1)); }
|
### Question:
JobCallbackRequestMaker { public void makeHttpRequest(String jobId, Logger logger, List<HttpRequestBase> httpRequestList) { if (httpRequestList == null || httpRequestList.isEmpty()) { logger.info("No HTTP requests to make"); return; } for (HttpRequestBase httpRequest : httpRequestList) { logger.info("Job callback http request: " + httpRequest.toString()); logger.info("headers ["); for (Header header : httpRequest.getAllHeaders()) { logger.info(String.format(" %s : %s", header.getName(), header.getValue())); } logger.info("]"); HttpRequestFutureTask<Integer> task = futureRequestExecutionService.execute(httpRequest, HttpClientContext.create(), new LoggingResponseHandler(logger)); try { Integer statusCode = task.get(responseWaitTimeoutMS, TimeUnit.MILLISECONDS); logger.info("http callback status code: " + statusCode); } catch (TimeoutException timeOutEx) { logger .warn("Job callback target took longer " + (responseWaitTimeoutMS / 1000) + " seconds to respond", timeOutEx); } catch (ExecutionException ee) { if (ee.getCause() instanceof SocketTimeoutException) { logger.warn("Job callback target took longer " + (responseWaitTimeoutMS / 1000) + " seconds to respond", ee); } else { logger.warn( "Encountered error while waiting for job callback to complete", ee); } } catch (Throwable e) { logger.warn( "Encountered error while waiting for job callback to complete", e); } } } private JobCallbackRequestMaker(Props props); static void initialize(Props props); static boolean isInitialized(); static JobCallbackRequestMaker getInstance(); FutureRequestExecutionMetrics getJobcallbackMetrics(); void makeHttpRequest(String jobId, Logger logger,
List<HttpRequestBase> httpRequestList); }### Answer:
@Test(timeout = 4000) public void basicGetTest() { Props props = new Props(); String url = buildUrlForDelay(1); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", url); List<HttpRequestBase> httpRequestList = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo, 3); jobCBMaker.makeHttpRequest(JOB_NANE, logger, httpRequestList); }
@Test(timeout = 4000) public void simulateNotOKStatusCodeTest() { Props props = new Props(); String url = buildUrlForStatusCode(404); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", url); List<HttpRequestBase> httpRequestList = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo, 3); jobCBMaker.makeHttpRequest(JOB_NANE, logger, httpRequestList); }
@Test(timeout = 4000) public void unResponsiveGetTest() { Props props = new Props(); String url = buildUrlForDelay(10); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", url); List<HttpRequestBase> httpRequestList = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo, 3); jobCBMaker.makeHttpRequest(JOB_NANE, logger, httpRequestList); }
@Test(timeout = 4000) public void basicPostTest() { Props props = new Props(); String url = buildUrlForDelay(1); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", url); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.method", JobCallbackConstants.HTTP_POST); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.body", "This is it"); List<HttpRequestBase> httpRequestList = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo, 3); jobCBMaker.makeHttpRequest(JOB_NANE, logger, httpRequestList); }
|
### Question:
QueuedExecutions { public boolean isFull() { return size() >= capacity; } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test public void testIsFull() throws IOException, ExecutorManagerException, InterruptedException { QueuedExecutions queue = new QueuedExecutions(2); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); Assert.assertTrue(queue.isFull()); }
|
### Question:
QueuedExecutions { public boolean hasExecution(int executionId) { return queuedFlowMap.containsKey(executionId); } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test public void testHasExecution() throws IOException, ExecutorManagerException, InterruptedException { QueuedExecutions queue = new QueuedExecutions(2); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); for (Pair<ExecutionReference, ExecutableFlow> pair : dataList) { Assert.assertTrue(queue.hasExecution(pair.getFirst().getExecId())); } Assert.assertFalse(queue.hasExecution(5)); Assert.assertFalse(queue.hasExecution(7)); Assert.assertFalse(queue.hasExecution(15)); }
|
### Question:
QueuedExecutions { public ExecutableFlow getFlow(int executionId) { if (hasExecution(executionId)) { return queuedFlowMap.get(executionId).getSecond(); } return null; } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFlow>> collection); Collection<Pair<ExecutionReference, ExecutableFlow>> getAllEntries(); boolean hasExecution(int executionId); ExecutableFlow getFlow(int executionId); ExecutionReference getReference(int executionId); long size(); boolean isFull(); boolean isEmpty(); void clear(); }### Answer:
@Test public void testGetFlow() throws IOException, ExecutorManagerException, InterruptedException { QueuedExecutions queue = new QueuedExecutions(2); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); for (Pair<ExecutionReference, ExecutableFlow> pair : dataList) { Assert.assertEquals(pair.getSecond(), queue.getFlow(pair.getFirst().getExecId())); } }
|
### Question:
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public Executor fetchExecutorByExecutionId(int executionId) throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchExecutorHandler executorHandler = new FetchExecutorHandler(); Executor executor = null; try { List<Executor> executors = runner.query(FetchExecutorHandler.FETCH_EXECUTION_EXECUTOR, executorHandler, executionId); if (executors.size() > 0) { executor = executors.get(0); } } catch (SQLException e) { throw new ExecutorManagerException( "Error fetching executor for exec_id : " + executionId, e); } return executor; } JdbcExecutorLoader(Props props); EncodingType getDefaultEncodingType(); void setDefaultEncodingType(EncodingType defaultEncodingType); @Override synchronized void uploadExecutableFlow(ExecutableFlow flow); @Override void updateExecutableFlow(ExecutableFlow flow); @Override ExecutableFlow fetchExecutableFlow(int id); @Override List<Pair<ExecutionReference, ExecutableFlow>> fetchQueuedFlows(); @Override Map<Integer, Pair<ExecutionReference, ExecutableFlow>> fetchActiveFlows(); @Override int fetchNumExecutableFlows(); @Override int fetchNumExecutableFlows(int projectId, String flowId); @Override int fetchNumExecutableNodes(int projectId, String jobId); @Override List<ExecutableFlow> fetchFlowHistory(int projectId, String flowId,
int skip, int num); @Override List<ExecutableFlow> fetchFlowHistory(int projectId, String flowId,
int skip, int num, Status status); @Override List<ExecutableFlow> fetchFlowHistory(int skip, int num); @Override List<ExecutableFlow> fetchFlowHistory(String projContain,
String flowContains, String userNameContains, int status, long startTime,
long endTime, int skip, int num); @Override void addActiveExecutableReference(ExecutionReference reference); @Override void removeActiveExecutableReference(int execid); @Override boolean updateExecutableReference(int execId, long updateTime); @Override void uploadExecutableNode(ExecutableNode node, Props inputProps); @Override void updateExecutableNode(ExecutableNode node); @Override void updateExecutableNodeInputParam(int execId, int projectId, String flowId, String jobId, Props inputProps); @Override List<ExecutableJobInfo> fetchJobInfoAttempts(int execId, String jobId); @Override ExecutableJobInfo fetchJobInfo(int execId, String jobId, int attempts); @Override Props fetchExecutionJobInputProps(int execId, String jobId); @Override Props fetchExecutionJobOutputProps(int execId, String jobId); @Override Pair<Props, Props> fetchExecutionJobProps(int execId, String jobId); @Override List<ExecutableJobInfo> fetchJobHistory(int projectId, String jobId,
int skip, int size); @Override LogData fetchLogs(int execId, String name, int attempt, int startByte,
int length); @Override List<Object> fetchAttachments(int execId, String jobId, int attempt); @Override void uploadLogFile(int execId, String name, int attempt, File... files); @Override void uploadAttachmentFile(ExecutableNode node, File file); @Override List<Executor> fetchAllExecutors(); @Override List<Executor> fetchActiveExecutors(); @Override Executor fetchExecutor(String host, int port); @Override Executor fetchExecutor(int executorId); @Override void updateExecutor(Executor executor); @Override Executor addExecutor(String host, int port); @Override void postExecutorEvent(Executor executor, EventType type, String user,
String message); @Override List<ExecutorLogEvent> getExecutorEvents(Executor executor, int num,
int offset); @Override void assignExecutor(int executorId, int executionId); @Override Executor fetchExecutorByExecutionId(int executionId); @Override int removeExecutionLogsByTime(long millis); @Override void unassignExecutor(int executionId); }### Answer:
@Test public void testFetchMissingExecutorByExecution() throws ExecutorManagerException, IOException { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Assert.assertEquals(loader.fetchExecutorByExecutionId(1), null); }
|
### Question:
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public Executor addExecutor(String host, int port) throws ExecutorManagerException { Executor executor = fetchExecutor(host, port); if (executor != null) { throw new ExecutorManagerException(String.format( "Executor %s:%d already exist", host, port)); } addExecutorHelper(host, port); executor = fetchExecutor(host, port); return executor; } JdbcExecutorLoader(Props props); EncodingType getDefaultEncodingType(); void setDefaultEncodingType(EncodingType defaultEncodingType); @Override synchronized void uploadExecutableFlow(ExecutableFlow flow); @Override void updateExecutableFlow(ExecutableFlow flow); @Override ExecutableFlow fetchExecutableFlow(int id); @Override List<Pair<ExecutionReference, ExecutableFlow>> fetchQueuedFlows(); @Override Map<Integer, Pair<ExecutionReference, ExecutableFlow>> fetchActiveFlows(); @Override int fetchNumExecutableFlows(); @Override int fetchNumExecutableFlows(int projectId, String flowId); @Override int fetchNumExecutableNodes(int projectId, String jobId); @Override List<ExecutableFlow> fetchFlowHistory(int projectId, String flowId,
int skip, int num); @Override List<ExecutableFlow> fetchFlowHistory(int projectId, String flowId,
int skip, int num, Status status); @Override List<ExecutableFlow> fetchFlowHistory(int skip, int num); @Override List<ExecutableFlow> fetchFlowHistory(String projContain,
String flowContains, String userNameContains, int status, long startTime,
long endTime, int skip, int num); @Override void addActiveExecutableReference(ExecutionReference reference); @Override void removeActiveExecutableReference(int execid); @Override boolean updateExecutableReference(int execId, long updateTime); @Override void uploadExecutableNode(ExecutableNode node, Props inputProps); @Override void updateExecutableNode(ExecutableNode node); @Override void updateExecutableNodeInputParam(int execId, int projectId, String flowId, String jobId, Props inputProps); @Override List<ExecutableJobInfo> fetchJobInfoAttempts(int execId, String jobId); @Override ExecutableJobInfo fetchJobInfo(int execId, String jobId, int attempts); @Override Props fetchExecutionJobInputProps(int execId, String jobId); @Override Props fetchExecutionJobOutputProps(int execId, String jobId); @Override Pair<Props, Props> fetchExecutionJobProps(int execId, String jobId); @Override List<ExecutableJobInfo> fetchJobHistory(int projectId, String jobId,
int skip, int size); @Override LogData fetchLogs(int execId, String name, int attempt, int startByte,
int length); @Override List<Object> fetchAttachments(int execId, String jobId, int attempt); @Override void uploadLogFile(int execId, String name, int attempt, File... files); @Override void uploadAttachmentFile(ExecutableNode node, File file); @Override List<Executor> fetchAllExecutors(); @Override List<Executor> fetchActiveExecutors(); @Override Executor fetchExecutor(String host, int port); @Override Executor fetchExecutor(int executorId); @Override void updateExecutor(Executor executor); @Override Executor addExecutor(String host, int port); @Override void postExecutorEvent(Executor executor, EventType type, String user,
String message); @Override List<ExecutorLogEvent> getExecutorEvents(Executor executor, int num,
int offset); @Override void assignExecutor(int executorId, int executionId); @Override Executor fetchExecutorByExecutionId(int executionId); @Override int removeExecutionLogsByTime(long millis); @Override void unassignExecutor(int executionId); }### Answer:
@Test public void testDuplicateAddExecutor() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); try { String host = "localhost"; int port = 12345; loader.addExecutor(host, port); loader.addExecutor(host, port); Assert.fail("Expecting exception, but didn't get one"); } catch (ExecutorManagerException ex) { System.out.println("Test true"); } }
|
### Question:
DefaultMailCreator implements MailCreator { @Override public boolean createErrorEmail(ExecutableFlow flow, EmailMessage message, String azkabanName, String scheme, String clientHostname, String clientPortNumber, String... vars) { ExecutionOptions option = flow.getExecutionOptions(); List<String> emailList = option.getFailureEmails(); int execId = flow.getExecutionId(); if (emailList != null && !emailList.isEmpty()) { message.addAllToAddress(emailList); message.setMimeType("text/html"); message.setSubject("Flow '" + flow.getFlowId() + "' has failed on " + azkabanName); message.println("<h2 style=\"color:#FF0000\"> Execution '" + execId + "' of flow '" + flow.getFlowId() + "' has failed on " + azkabanName + "</h2>"); message.println("<table>"); message.println("<tr><td>Start Time</td><td>" + convertMSToString(flow.getStartTime()) + "</td></tr>"); message.println("<tr><td>End Time</td><td>" + convertMSToString(flow.getEndTime()) + "</td></tr>"); message.println("<tr><td>Duration</td><td>" + Utils.formatDuration(flow.getStartTime(), flow.getEndTime()) + "</td></tr>"); message.println("<tr><td>Status</td><td>" + flow.getStatus() + "</td></tr>"); message.println("</table>"); message.println(""); String executionUrl = scheme + ": + "executor?" + "execid=" + execId; message.println("<a href=\"" + executionUrl + "\">" + flow.getFlowId() + " Execution Link</a>"); message.println(""); message.println("<h3>Reason</h3>"); List<String> failedJobs = Emailer.findFailedJobs(flow); message.println("<ul>"); for (String jobId : failedJobs) { message.println("<li><a href=\"" + executionUrl + "&job=" + jobId + "\">Failed job '" + jobId + "' Link</a></li>"); } for (String reasons : vars) { message.println("<li>" + reasons + "</li>"); } message.println("</ul>"); return true; } return false; } static void registerCreator(String name, MailCreator creator); static MailCreator getCreator(String name); @Override boolean createFirstErrorMessage(ExecutableFlow flow,
EmailMessage message, String azkabanName, String scheme,
String clientHostname, String clientPortNumber, String... vars); @Override boolean createErrorEmail(ExecutableFlow flow, EmailMessage message,
String azkabanName, String scheme, String clientHostname,
String clientPortNumber, String... vars); @Override boolean createSuccessEmail(ExecutableFlow flow, EmailMessage message,
String azkabanName, String scheme, String clientHostname,
String clientPortNumber, String... vars); static final String DEFAULT_MAIL_CREATOR; }### Answer:
@Test public void createErrorEmail() throws Exception { setJobStatus(Status.FAILED); executableFlow.setEndTime(END_TIME_MILLIS); executableFlow.setStatus(Status.FAILED); assertTrue(mailCreator.createErrorEmail( executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber)); assertEquals("Flow 'mail-creator-test' has failed on unit-tests", message.getSubject()); assertEquals(read("errorEmail.html"), message.getBody()); }
|
### Question:
DefaultMailCreator implements MailCreator { @Override public boolean createFirstErrorMessage(ExecutableFlow flow, EmailMessage message, String azkabanName, String scheme, String clientHostname, String clientPortNumber, String... vars) { ExecutionOptions option = flow.getExecutionOptions(); List<String> emailList = option.getFailureEmails(); int execId = flow.getExecutionId(); if (emailList != null && !emailList.isEmpty()) { message.addAllToAddress(emailList); message.setMimeType("text/html"); message.setSubject("Flow '" + flow.getFlowId() + "' has encountered a failure on " + azkabanName); message.println("<h2 style=\"color:#FF0000\"> Execution '" + flow.getExecutionId() + "' of flow '" + flow.getFlowId() + "' has encountered a failure on " + azkabanName + "</h2>"); if (option.getFailureAction() == FailureAction.CANCEL_ALL) { message .println("This flow is set to cancel all currently running jobs."); } else if (option.getFailureAction() == FailureAction.FINISH_ALL_POSSIBLE) { message .println("This flow is set to complete all jobs that aren't blocked by the failure."); } else { message .println("This flow is set to complete all currently running jobs before stopping."); } message.println("<table>"); message.println("<tr><td>Start Time</td><td>" + convertMSToString(flow.getStartTime()) + "</td></tr>"); message.println("<tr><td>End Time</td><td>" + convertMSToString(flow.getEndTime()) + "</td></tr>"); message.println("<tr><td>Duration</td><td>" + Utils.formatDuration(flow.getStartTime(), flow.getEndTime()) + "</td></tr>"); message.println("<tr><td>Status</td><td>" + flow.getStatus() + "</td></tr>"); message.println("</table>"); message.println(""); String executionUrl = scheme + ": + "executor?" + "execid=" + execId; message.println("<a href=\"" + executionUrl + "\">" + flow.getFlowId() + " Execution Link</a>"); message.println(""); message.println("<h3>Reason</h3>"); List<String> failedJobs = Emailer.findFailedJobs(flow); message.println("<ul>"); for (String jobId : failedJobs) { message.println("<li><a href=\"" + executionUrl + "&job=" + jobId + "\">Failed job '" + jobId + "' Link</a></li>"); } message.println("</ul>"); return true; } return false; } static void registerCreator(String name, MailCreator creator); static MailCreator getCreator(String name); @Override boolean createFirstErrorMessage(ExecutableFlow flow,
EmailMessage message, String azkabanName, String scheme,
String clientHostname, String clientPortNumber, String... vars); @Override boolean createErrorEmail(ExecutableFlow flow, EmailMessage message,
String azkabanName, String scheme, String clientHostname,
String clientPortNumber, String... vars); @Override boolean createSuccessEmail(ExecutableFlow flow, EmailMessage message,
String azkabanName, String scheme, String clientHostname,
String clientPortNumber, String... vars); static final String DEFAULT_MAIL_CREATOR; }### Answer:
@Test public void createFirstErrorMessage() throws Exception { setJobStatus(Status.FAILED); executableFlow.setStatus(Status.FAILED_FINISHING); assertTrue(mailCreator.createFirstErrorMessage( executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber)); assertEquals("Flow 'mail-creator-test' has encountered a failure on unit-tests", message.getSubject()); assertEquals(read("firstErrorMessage.html"), message.getBody()); }
|
### Question:
DefaultMailCreator implements MailCreator { @Override public boolean createSuccessEmail(ExecutableFlow flow, EmailMessage message, String azkabanName, String scheme, String clientHostname, String clientPortNumber, String... vars) { ExecutionOptions option = flow.getExecutionOptions(); List<String> emailList = option.getSuccessEmails(); int execId = flow.getExecutionId(); if (emailList != null && !emailList.isEmpty()) { message.addAllToAddress(emailList); message.setMimeType("text/html"); message.setSubject("Flow '" + flow.getFlowId() + "' has succeeded on " + azkabanName); message.println("<h2> Execution '" + flow.getExecutionId() + "' of flow '" + flow.getFlowId() + "' has succeeded on " + azkabanName + "</h2>"); message.println("<table>"); message.println("<tr><td>Start Time</td><td>" + convertMSToString(flow.getStartTime()) + "</td></tr>"); message.println("<tr><td>End Time</td><td>" + convertMSToString(flow.getEndTime()) + "</td></tr>"); message.println("<tr><td>Duration</td><td>" + Utils.formatDuration(flow.getStartTime(), flow.getEndTime()) + "</td></tr>"); message.println("<tr><td>Status</td><td>" + flow.getStatus() + "</td></tr>"); message.println("</table>"); message.println(""); String executionUrl = scheme + ": + "executor?" + "execid=" + execId; message.println("<a href=\"" + executionUrl + "\">" + flow.getFlowId() + " Execution Link</a>"); return true; } return false; } static void registerCreator(String name, MailCreator creator); static MailCreator getCreator(String name); @Override boolean createFirstErrorMessage(ExecutableFlow flow,
EmailMessage message, String azkabanName, String scheme,
String clientHostname, String clientPortNumber, String... vars); @Override boolean createErrorEmail(ExecutableFlow flow, EmailMessage message,
String azkabanName, String scheme, String clientHostname,
String clientPortNumber, String... vars); @Override boolean createSuccessEmail(ExecutableFlow flow, EmailMessage message,
String azkabanName, String scheme, String clientHostname,
String clientPortNumber, String... vars); static final String DEFAULT_MAIL_CREATOR; }### Answer:
@Test public void createSuccessEmail() throws Exception { setJobStatus(Status.SUCCEEDED); executableFlow.setEndTime(END_TIME_MILLIS); executableFlow.setStatus(Status.SUCCEEDED); assertTrue(mailCreator.createSuccessEmail( executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber)); assertEquals("Flow 'mail-creator-test' has succeeded on unit-tests", message.getSubject()); assertEquals(read("successEmail.html"), message.getBody()); }
|
### Question:
AzkabanDatabaseUpdater { public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser(); OptionSpec<String> scriptDirectory = parser .acceptsAll(Arrays.asList("s", "script"), "Directory of update scripts.").withRequiredArg() .describedAs("script").ofType(String.class); OptionSpec<Void> updateOption = parser.acceptsAll(Arrays.asList("u", "update"), "Will update if necessary"); Props props = AzkabanServer.loadProps(args, parser); if (props == null) { logger.error("Properties not found. Need it to connect to the db."); logger.error("Exiting..."); return; } OptionSet options = parser.parse(args); boolean updateDB = false; if (options.has(updateOption)) { updateDB = true; } else { logger.info("Running DatabaseUpdater in test mode"); } String scriptDir = "sql"; if (options.has(scriptDirectory)) { scriptDir = options.valueOf(scriptDirectory); } runDatabaseUpdater(props, scriptDir, updateDB); } static void main(String[] args); static void runDatabaseUpdater(Props props, String sqlDir,
boolean updateDB); }### Answer:
@Ignore @Test public void testMySQLAutoCreate() throws Exception { clearMySQLTestDb(); URL resourceUrl = Resources.getResource("conf/dbtestmysql"); assertNotNull(resourceUrl); File resource = new File(resourceUrl.toURI()); String confDir = resource.getParent(); System.out.println("1.***Now testing check"); AzkabanDatabaseUpdater.main(new String[] { "-c", confDir }); System.out.println("2.***Now testing update"); AzkabanDatabaseUpdater.main(new String[] { "-u", "-c", confDir }); System.out.println("3.***Now testing check again"); AzkabanDatabaseUpdater.main(new String[] { "-c", confDir }); System.out.println("4.***Now testing update again"); AzkabanDatabaseUpdater.main(new String[] { "-c", confDir, "-u" }); System.out.println("5.***Now testing check again"); AzkabanDatabaseUpdater.main(new String[] { "-c", confDir }); }
@Test public void testH2AutoCreate() throws Exception { URL resourceUrl = Resources.getResource("conf/dbtesth2"); assertNotNull(resourceUrl); File resource = new File(resourceUrl.toURI()); String confDir = resource.getParent(); System.out.println("1.***Now testing check"); AzkabanDatabaseUpdater.main(new String[] { "-c", confDir }); System.out.println("2.***Now testing update"); AzkabanDatabaseUpdater.main(new String[] { "-u", "-c", confDir }); System.out.println("3.***Now testing check again"); AzkabanDatabaseUpdater.main(new String[] { "-c", confDir }); System.out.println("4.***Now testing update again"); AzkabanDatabaseUpdater.main(new String[] { "-c", confDir, "-u" }); System.out.println("5.***Now testing check again"); AzkabanDatabaseUpdater.main(new String[] { "-c", confDir }); }
|
### Question:
Condition { public Condition(Map<String, ConditionChecker> checkers, String expr) { setCheckers(checkers); this.expression = jexl.createExpression(expr); updateNextCheckTime(); } Condition(Map<String, ConditionChecker> checkers, String expr); Condition(Map<String, ConditionChecker> checkers, String expr,
long nextCheckTime); synchronized static void setJexlEngine(JexlEngine jexl); synchronized static void setCheckerLoader(CheckerTypeLoader loader); long getNextCheckTime(); Map<String, ConditionChecker> getCheckers(); void setCheckers(Map<String, ConditionChecker> checkers); void updateCheckTime(Long ct); void resetCheckers(); String getExpression(); void setExpression(String expr); boolean isMet(); Object toJson(); @SuppressWarnings("unchecked") static Condition fromJson(Object obj); }### Answer:
@Test public void conditionTest() { Map<String, ConditionChecker> checkers = new HashMap<String, ConditionChecker>(); ThresholdChecker fake1 = new ThresholdChecker("thresholdchecker1", 10); ThresholdChecker fake2 = new ThresholdChecker("thresholdchecker2", 20); ThresholdChecker.setVal(15); checkers.put(fake1.getId(), fake1); checkers.put(fake2.getId(), fake2); String expr1 = "( " + fake1.getId() + ".eval()" + " && " + fake2.getId() + ".eval()" + " )" + " || " + "( " + fake1.getId() + ".eval()" + " && " + "!" + fake2.getId() + ".eval()" + " )"; String expr2 = "( " + fake1.getId() + ".eval()" + " && " + fake2.getId() + ".eval()" + " )" + " || " + "( " + fake1.getId() + ".eval()" + " && " + fake2.getId() + ".eval()" + " )"; Condition cond = new Condition(checkers, expr1); System.out.println("Setting expression " + expr1); assertTrue(cond.isMet()); cond.setExpression(expr2); System.out.println("Setting expression " + expr2); assertFalse(cond.isMet()); }
|
### Question:
JdbcTriggerLoader extends AbstractJdbcLoader implements
TriggerLoader { @Override public void addTrigger(Trigger t) throws TriggerLoaderException { logger.info("Inserting trigger " + t.toString() + " into db."); t.setLastModifyTime(System.currentTimeMillis()); Connection connection = getConnection(); try { addTrigger(connection, t, defaultEncodingType); } catch (Exception e) { throw new TriggerLoaderException("Error uploading trigger", e); } finally { DbUtils.closeQuietly(connection); } } JdbcTriggerLoader(Props props); EncodingType getDefaultEncodingType(); void setDefaultEncodingType(EncodingType defaultEncodingType); @Override List<Trigger> getUpdatedTriggers(long lastUpdateTime); @Override List<Trigger> loadTriggers(); @Override void removeTrigger(Trigger t); @Override void addTrigger(Trigger t); @Override void updateTrigger(Trigger t); @Override Trigger loadTrigger(int triggerId); }### Answer:
@Ignore @Test public void addTriggerTest() throws TriggerLoaderException { Trigger t1 = createTrigger("testProj1", "testFlow1", "source1"); Trigger t2 = createTrigger("testProj2", "testFlow2", "source2"); loader.addTrigger(t1); List<Trigger> ts = loader.loadTriggers(); assertTrue(ts.size() == 1); Trigger t3 = ts.get(0); assertTrue(t3.getSource().equals("source1")); loader.addTrigger(t2); ts = loader.loadTriggers(); assertTrue(ts.size() == 2); for (Trigger t : ts) { if (t.getTriggerId() == t2.getTriggerId()) { t.getSource().equals(t2.getSource()); } } }
|
### Question:
JdbcTriggerLoader extends AbstractJdbcLoader implements
TriggerLoader { @Override public void removeTrigger(Trigger t) throws TriggerLoaderException { logger.info("Removing trigger " + t.toString() + " from db."); QueryRunner runner = createQueryRunner(); try { int removes = runner.update(REMOVE_TRIGGER, t.getTriggerId()); if (removes == 0) { throw new TriggerLoaderException("No trigger has been removed."); } } catch (SQLException e) { logger.error(REMOVE_TRIGGER + " failed."); throw new TriggerLoaderException("Remove trigger " + t.toString() + " from db failed. ", e); } } JdbcTriggerLoader(Props props); EncodingType getDefaultEncodingType(); void setDefaultEncodingType(EncodingType defaultEncodingType); @Override List<Trigger> getUpdatedTriggers(long lastUpdateTime); @Override List<Trigger> loadTriggers(); @Override void removeTrigger(Trigger t); @Override void addTrigger(Trigger t); @Override void updateTrigger(Trigger t); @Override Trigger loadTrigger(int triggerId); }### Answer:
@Ignore @Test public void removeTriggerTest() throws TriggerLoaderException { Trigger t1 = createTrigger("testProj1", "testFlow1", "source1"); Trigger t2 = createTrigger("testProj2", "testFlow2", "source2"); loader.addTrigger(t1); loader.addTrigger(t2); List<Trigger> ts = loader.loadTriggers(); assertTrue(ts.size() == 2); loader.removeTrigger(t2); ts = loader.loadTriggers(); assertTrue(ts.size() == 1); assertTrue(ts.get(0).getTriggerId() == t1.getTriggerId()); }
|
### Question:
JdbcTriggerLoader extends AbstractJdbcLoader implements
TriggerLoader { @Override public void updateTrigger(Trigger t) throws TriggerLoaderException { if (logger.isDebugEnabled()) { logger.debug("Updating trigger " + t.getTriggerId() + " into db."); } t.setLastModifyTime(System.currentTimeMillis()); Connection connection = getConnection(); try { updateTrigger(connection, t, defaultEncodingType); } catch (Exception e) { e.printStackTrace(); throw new TriggerLoaderException("Failed to update trigger " + t.toString() + " into db!"); } finally { DbUtils.closeQuietly(connection); } } JdbcTriggerLoader(Props props); EncodingType getDefaultEncodingType(); void setDefaultEncodingType(EncodingType defaultEncodingType); @Override List<Trigger> getUpdatedTriggers(long lastUpdateTime); @Override List<Trigger> loadTriggers(); @Override void removeTrigger(Trigger t); @Override void addTrigger(Trigger t); @Override void updateTrigger(Trigger t); @Override Trigger loadTrigger(int triggerId); }### Answer:
@Ignore @Test public void updateTriggerTest() throws TriggerLoaderException { Trigger t1 = createTrigger("testProj1", "testFlow1", "source1"); t1.setResetOnExpire(true); loader.addTrigger(t1); List<Trigger> ts = loader.loadTriggers(); assertTrue(ts.get(0).isResetOnExpire() == true); t1.setResetOnExpire(false); loader.updateTrigger(t1); ts = loader.loadTriggers(); assertTrue(ts.get(0).isResetOnExpire() == false); }
|
### Question:
JobTypeManager { public synchronized JobTypePluginSet getJobTypePluginSet() { return this.pluginSet; } JobTypeManager(String jobtypePluginDir, Props globalProperties,
ClassLoader parentClassLoader); void loadPlugins(); Job buildJobExecutor(String jobId, Props jobProps, Logger logger); synchronized JobTypePluginSet getJobTypePluginSet(); static final String DEFAULT_JOBTYPEPLUGINDIR; }### Answer:
@Test public void testCommonPluginProps() throws Exception { JobTypePluginSet pluginSet = manager.getJobTypePluginSet(); Props props = pluginSet.getCommonPluginJobProps(); System.out.println(props.toString()); assertEquals("commonprop1", props.getString("commonprop1")); assertEquals("commonprop2", props.getString("commonprop2")); assertEquals("commonprop3", props.getString("commonprop3")); Props priv = pluginSet.getCommonPluginLoadProps(); assertEquals("commonprivate1", priv.getString("commonprivate1")); assertEquals("commonprivate2", priv.getString("commonprivate2")); assertEquals("commonprivate3", priv.getString("commonprivate3")); }
@Test public void testLoadedClasses() throws Exception { JobTypePluginSet pluginSet = manager.getJobTypePluginSet(); Props props = pluginSet.getCommonPluginJobProps(); System.out.println(props.toString()); assertEquals("commonprop1", props.getString("commonprop1")); assertEquals("commonprop2", props.getString("commonprop2")); assertEquals("commonprop3", props.getString("commonprop3")); assertNull(props.get("commonprivate1")); Props priv = pluginSet.getCommonPluginLoadProps(); assertEquals("commonprivate1", priv.getString("commonprivate1")); assertEquals("commonprivate2", priv.getString("commonprivate2")); assertEquals("commonprivate3", priv.getString("commonprivate3")); Class<? extends Job> aPluginClass = pluginSet.getPluginClass("anothertestjob"); assertEquals("azkaban.jobtype.FakeJavaJob", aPluginClass.getName()); Props ajobProps = pluginSet.getPluginJobProps("anothertestjob"); Props aloadProps = pluginSet.getPluginLoaderProps("anothertestjob"); assertEquals("lib/*", aloadProps.get("jobtype.classpath")); assertEquals("azkaban.jobtype.FakeJavaJob", aloadProps.get("jobtype.class")); assertEquals("commonprivate1", aloadProps.get("commonprivate1")); assertEquals("commonprivate2", aloadProps.get("commonprivate2")); assertEquals("commonprivate3", aloadProps.get("commonprivate3")); assertEquals("commonprop1", ajobProps.get("commonprop1")); assertEquals("commonprop2", ajobProps.get("commonprop2")); assertEquals("commonprop3", ajobProps.get("commonprop3")); assertNull(ajobProps.get("commonprivate1")); Class<? extends Job> tPluginClass = pluginSet.getPluginClass("testjob"); assertEquals("azkaban.jobtype.FakeJavaJob2", tPluginClass.getName()); Props tjobProps = pluginSet.getPluginJobProps("testjob"); Props tloadProps = pluginSet.getPluginLoaderProps("testjob"); assertNull(tloadProps.get("jobtype.classpath")); assertEquals("azkaban.jobtype.FakeJavaJob2", tloadProps.get("jobtype.class")); assertEquals("commonprivate1", tloadProps.get("commonprivate1")); assertEquals("commonprivate2", tloadProps.get("commonprivate2")); assertEquals("private3", tloadProps.get("commonprivate3")); assertEquals("0", tloadProps.get("testprivate")); assertEquals("commonprop1", tjobProps.get("commonprop1")); assertEquals("commonprop2", tjobProps.get("commonprop2")); assertEquals("1", tjobProps.get("pluginprops1")); assertEquals("2", tjobProps.get("pluginprops2")); assertEquals("3", tjobProps.get("pluginprops3")); assertEquals("pluginprops", tjobProps.get("commonprop3")); assertNull(tjobProps.get("commonprivate1")); assertNull(tjobProps.get("testprivate")); }
|
### Question:
JobTypeManager { public Job buildJobExecutor(String jobId, Props jobProps, Logger logger) throws JobTypeManagerException { final JobTypePluginSet pluginSet = getJobTypePluginSet(); Job job = null; try { String jobType = jobProps.getString("type"); if (jobType == null || jobType.length() == 0) { throw new JobExecutionException(String.format( "The 'type' parameter for job[%s] is null or empty", jobProps, logger)); } logger.info("Building " + jobType + " job executor. "); Class<? extends Object> executorClass = pluginSet.getPluginClass(jobType); if (executorClass == null) { throw new JobExecutionException(String.format("Job type '" + jobType + "' is unrecognized. Could not construct job[%s] of type[%s].", jobProps, jobType)); } Props pluginJobProps = pluginSet.getPluginJobProps(jobType); if(pluginJobProps == null) { pluginJobProps = pluginSet.getCommonPluginJobProps(); } if (pluginJobProps != null) { for (String k : pluginJobProps.getKeySet()) { if (!jobProps.containsKey(k)) { jobProps.put(k, pluginJobProps.get(k)); } } } jobProps = PropsUtils.resolveProps(jobProps); Props pluginLoadProps = pluginSet.getPluginLoaderProps(jobType); if (pluginLoadProps != null) { pluginLoadProps = PropsUtils.resolveProps(pluginLoadProps); } else { pluginLoadProps = pluginSet.getCommonPluginLoadProps(); if(pluginLoadProps == null) pluginLoadProps = new Props(); } job = (Job) Utils.callConstructor(executorClass, jobId, pluginLoadProps, jobProps, logger); } catch (Exception e) { logger.error("Failed to build job executor for job " + jobId + e.getMessage()); throw new JobTypeManagerException("Failed to build job executor for job " + jobId, e); } catch (Throwable t) { logger.error( "Failed to build job executor for job " + jobId + t.getMessage(), t); throw new JobTypeManagerException("Failed to build job executor for job " + jobId, t); } return job; } JobTypeManager(String jobtypePluginDir, Props globalProperties,
ClassLoader parentClassLoader); void loadPlugins(); Job buildJobExecutor(String jobId, Props jobProps, Logger logger); synchronized JobTypePluginSet getJobTypePluginSet(); static final String DEFAULT_JOBTYPEPLUGINDIR; }### Answer:
@Test public void testBuildClass() throws Exception { Props jobProps = new Props(); jobProps.put("type", "anothertestjob"); jobProps.put("test", "test1"); jobProps.put("pluginprops3", "4"); Job job = manager.buildJobExecutor("anothertestjob", jobProps, logger); assertTrue(job instanceof FakeJavaJob); FakeJavaJob fjj = (FakeJavaJob) job; Props props = fjj.getJobProps(); assertEquals("test1", props.get("test")); assertNull(props.get("pluginprops1")); assertEquals("4", props.get("pluginprops3")); assertEquals("commonprop1", props.get("commonprop1")); assertEquals("commonprop2", props.get("commonprop2")); assertEquals("commonprop3", props.get("commonprop3")); assertNull(props.get("commonprivate1")); }
@Test public void testBuildClass2() throws Exception { Props jobProps = new Props(); jobProps.put("type", "testjob"); jobProps.put("test", "test1"); jobProps.put("pluginprops3", "4"); Job job = manager.buildJobExecutor("testjob", jobProps, logger); assertTrue(job instanceof FakeJavaJob2); FakeJavaJob2 fjj = (FakeJavaJob2) job; Props props = fjj.getJobProps(); assertEquals("test1", props.get("test")); assertEquals("1", props.get("pluginprops1")); assertEquals("2", props.get("pluginprops2")); assertEquals("4", props.get("pluginprops3")); assertEquals("commonprop1", props.get("commonprop1")); assertEquals("commonprop2", props.get("commonprop2")); assertEquals("pluginprops", props.get("commonprop3")); assertNull(props.get("commonprivate1")); }
|
### Question:
PropsUtils { public static String getPropertyDiff(Props oldProps, Props newProps) { StringBuilder builder = new StringBuilder(""); MapDifference<String, String> md = Maps.difference(toStringMap(oldProps, false), toStringMap(newProps, false)); Map<String, String> newlyCreatedProperty = md.entriesOnlyOnRight(); if (newlyCreatedProperty != null && newlyCreatedProperty.size() > 0) { builder.append("Newly created Properties: "); newlyCreatedProperty.forEach((k, v) -> { builder.append("[ " + k + ", " + v + "], "); }); builder.append("\n"); } Map<String, String> deletedProperty = md.entriesOnlyOnLeft(); if (deletedProperty != null && deletedProperty.size() > 0) { builder.append("Deleted Properties: "); deletedProperty.forEach((k, v) -> { builder.append("[ " + k + ", " + v + "], "); }); builder.append("\n"); } Map<String, MapDifference.ValueDifference<String>> diffProperties = md.entriesDiffering(); if (diffProperties != null && diffProperties.size() > 0) { builder.append("Modified Properties: "); diffProperties.forEach((k, v) -> { builder.append("[ " + k + ", " + v.leftValue() + "-->" + v.rightValue() + "], "); }); } return builder.toString(); } static Props loadPropsInDir(File dir, String... suffixes); static Props loadPropsInDir(Props parent, File dir, String... suffixes); static Props loadProps(Props parent, File... propFiles); static Props loadPropsInDirs(List<File> dirs, String... suffixes); static void loadPropsBySuffix(File jobPath, Props props,
String... suffixes); static boolean endsWith(File file, String... suffixes); static boolean isVarialbeReplacementPattern(String str); static Props resolveProps(Props props); static Props addCommonFlowProperties(Props parentProps,
final ExecutableFlowBase flow); static String toJSONString(Props props, boolean localOnly); static Map<String, String> toStringMap(Props props, boolean localOnly); static Props fromJSONString(String json); @SuppressWarnings("unchecked") static Props fromHierarchicalMap(Map<String, Object> propsMap); static Map<String, Object> toHierarchicalMap(Props props); static String getPropertyDiff(Props oldProps, Props newProps); }### Answer:
@Test public void testGetPropertyDiff() throws IOException { Props oldProps = new Props(); Props newProps1 = new Props(); oldProps.put("a", "a_value1"); oldProps.put("b", "b_value1"); newProps1.put("b", "b_value2"); String message1 = PropsUtils.getPropertyDiff(oldProps, newProps1); Assert.assertEquals(message1, "Deleted Properties: [ a, a_value1], \nModified Properties: [ b, b_value1-->b_value2], "); Props newProps2 = new Props(); newProps2.put("a", "a_value1"); newProps2.put("b", "b_value1"); newProps2.put("c", "c_value1"); String message2 = PropsUtils.getPropertyDiff(oldProps, newProps2); Assert.assertEquals(message2, "Newly created Properties: [ c, c_value1], \n"); Props newProps3 = new Props(); newProps3.put("b", "b_value1"); newProps3.put("c", "a_value1"); String message3 = PropsUtils.getPropertyDiff(oldProps, newProps3); Assert.assertEquals(message3, "Newly created Properties: [ c, a_value1], \nDeleted Properties: [ a, a_value1], \n"); }
|
### Question:
StringUtils { public static boolean isFromBrowser(String userAgent) { if (userAgent == null) { return false; } if (BROWSWER_PATTERN.matcher(userAgent).matches()) { return true; } else { return false; } } static String shellQuote(String s, char quoteCh); @Deprecated static String join(List<String> list, String delimiter); static String join(Collection<String> list, String delimiter); static String join2(Collection<String> list, String delimiter); static boolean isFromBrowser(String userAgent); static final char SINGLE_QUOTE; static final char DOUBLE_QUOTE; }### Answer:
@Test public void isBrowser() throws Exception { for (String browser : browserVariants) { Assert.assertTrue(browser, StringUtils.isFromBrowser(browser)); } }
@Test public void notBrowserWithLowercase() throws Exception { for (String browser : browserVariants) { Assert.assertFalse(browser.toLowerCase(), StringUtils.isFromBrowser(browser.toLowerCase())); } }
@Test public void notBrowser() throws Exception { String testStr = "curl"; Assert.assertFalse(testStr, StringUtils.isFromBrowser(testStr)); }
@Test public void emptyBrowserString() throws Exception { Assert.assertFalse("empty string", StringUtils.isFromBrowser("")); }
@Test public void nullBrowserString() throws Exception { Assert.assertFalse("null string", StringUtils.isFromBrowser(null)); }
@Test public void startsWithBrowserName() { for (String name : BROWSER_NAMES) { Assert.assertTrue(StringUtils.isFromBrowser(name + " is awesome")); } }
@Test public void endsWithBrowserName() { for (String name : BROWSER_NAMES) { Assert.assertTrue(StringUtils.isFromBrowser("awesome is" + name)); } }
@Test public void containsBrowserName() { for (String name : BROWSER_NAMES) { Assert.assertTrue(StringUtils.isFromBrowser("awesome " + name + " is")); } }
|
### Question:
WebUtils { public String getRealClientIpAddr(Map<String, String> httpHeaders, String remoteAddr){ String clientIp = httpHeaders.getOrDefault(X_FORWARDED_FOR_HEADER, null); if(clientIp == null){ clientIp = remoteAddr; } else{ String ips[] = clientIp.split(","); clientIp = ips[0]; } String parts[] = clientIp.split(":"); clientIp = parts[0]; return clientIp; } String formatDate(long timeMS); String formatDuration(long startTime, long endTime); String formatStatus(Status status); String formatDateTime(DateTime dt); String formatDateTime(long timestamp); String formatPeriod(ReadablePeriod period); String extractNumericalId(String execId); String displayBytes(long sizeBytes); String getRealClientIpAddr(Map<String, String> httpHeaders, String remoteAddr); static final String DATE_TIME_STRING; static final String X_FORWARDED_FOR_HEADER; }### Answer:
@Test public void testWhenNoXForwardedForHeaderUseClientIp(){ String clientIp = "127.0.0.1:10000"; Map<String, String> headers = new HashMap<>(); WebUtils utils = new WebUtils(); String ip = utils.getRealClientIpAddr(headers, clientIp); assertEquals(ip, "127.0.0.1"); }
@Test public void testWhenClientIpNoPort(){ String clientIp = "192.168.1.1"; Map<String, String> headers = new HashMap<>(); WebUtils utils = new WebUtils(); String ip = utils.getRealClientIpAddr(headers, clientIp); assertEquals(ip, "192.168.1.1"); }
@Test public void testWhenXForwardedForHeaderUseHeader(){ String clientIp = "127.0.0.1:10000"; String upstreamIp = "192.168.1.1:10000"; Map<String, String> headers = new HashMap<>(); headers.put("X-Forwarded-For", upstreamIp); WebUtils utils = new WebUtils(); String ip = utils.getRealClientIpAddr(headers, clientIp); assertEquals(ip, "192.168.1.1"); }
@Test public void testWhenXForwardedForHeaderMultipleUpstreamsUseHeader(){ String clientIp = "127.0.0.1:10000"; String upstreamIp = "192.168.1.1:10000"; Map<String, String> headers = new HashMap<>(); headers.put("X-Forwarded-For", upstreamIp + ",127.0.0.1,55.55.55.55"); WebUtils utils = new WebUtils(); String ip = utils.getRealClientIpAddr(headers, clientIp); assertEquals(ip, "192.168.1.1"); }
|
### Question:
EmailMessage { public void sendEmail() throws MessagingException { checkSettings(); Properties props = new Properties(); if (_usesAuth) { props.put("mail." + protocol + ".auth", "true"); props.put("mail.user", _mailUser); props.put("mail.password", _mailPassword); } else { props.put("mail." + protocol + ".auth", "false"); } props.put("mail." + protocol + ".host", _mailHost); props.put("mail." + protocol + ".port", _mailPort); props.put("mail." + protocol + ".timeout", _mailTimeout); props.put("mail." + protocol + ".connectiontimeout", _connectionTimeout); props.put("mail.smtp.starttls.enable", _tls); props.put("mail.smtp.ssl.trust", _mailHost); Session session = Session.getInstance(props, null); Message message = new MimeMessage(session); InternetAddress from = new InternetAddress(_fromAddress, false); message.setFrom(from); for (String toAddr : _toAddress) message.addRecipient(Message.RecipientType.TO, new InternetAddress( toAddr, false)); message.setSubject(_subject); message.setSentDate(new Date()); if (_attachments.size() > 0) { MimeMultipart multipart = this._enableAttachementEmbedment ? new MimeMultipart("related") : new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(_body.toString(), _mimeType); multipart.addBodyPart(messageBodyPart); for (BodyPart part : _attachments) { multipart.addBodyPart(part); } message.setContent(multipart); } else { message.setContent(_body.toString(), _mimeType); } SMTPTransport t = (SMTPTransport) session.getTransport(protocol); try { connectToSMTPServer(t); } catch (MessagingException ste) { if (ste.getCause() instanceof SocketTimeoutException) { try { connectToSMTPServer(t); logger.info("Email retry on SocketTimeoutException succeeded"); } catch (MessagingException me) { logger.error("Email retry on SocketTimeoutException failed", me); throw me; } } else { logger.error("Encountered issue while connecting to email server", ste); throw ste; } } t.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); t.close(); } EmailMessage(); EmailMessage(String host, int port, String user, String password); static void setTimeout(int timeoutMillis); static void setConnectionTimeout(int timeoutMillis); static void setTotalAttachmentMaxSize(long sizeInBytes); EmailMessage setMailHost(String host); EmailMessage setMailUser(String user); EmailMessage enableAttachementEmbedment(boolean toEnable); EmailMessage setMailPassword(String password); EmailMessage addAllToAddress(Collection<? extends String> addresses); EmailMessage addToAddress(String address); EmailMessage setSubject(String subject); EmailMessage setFromAddress(String fromAddress); EmailMessage setTLS(String tls); EmailMessage setAuth(boolean auth); EmailMessage addAttachment(File file); EmailMessage addAttachment(String attachmentName, File file); EmailMessage addAttachment(String attachmentName, InputStream stream); void sendEmail(); void setBody(String body); void setBody(String body, String mimeType); EmailMessage setMimeType(String mimeType); EmailMessage println(Object str); String getBody(); String getSubject(); int getMailPort(); }### Answer:
@Ignore @Test public void testSendEmail() throws IOException { em.addToAddress(toAddr); em.setSubject("azkaban test email"); em.setBody("azkaban test email"); try { em.sendEmail(); } catch (MessagingException e) { e.printStackTrace(); } }
|
### Question:
StringUtils { public static boolean isRgbValue(String color){ Pattern pattern = Pattern.compile("^#(([0123456789abcdefABCDEF]{6})|([0123456789abcdefABCDEF]{8}))$"); Matcher matcher = pattern.matcher(color); return matcher.matches(); } static boolean isRgbValue(String color); }### Answer:
@Test public void testIsRgbValue() throws Exception { System.out.println("#6688 is color " + StringUtils.isRgbValue("#6688")); System.out.println("#070A01 is color " + StringUtils.isRgbValue("#668899")); System.out.println("dd8899 is color " + StringUtils.isRgbValue("dd8899")); System.out.println("#yy8899 is color " + StringUtils.isRgbValue("#yy8899")); System.out.println("#FFFFFF is color " + StringUtils.isRgbValue("#FFFFFf")); }
|
### Question:
EncodeUtils { public static String urlDecode(String encode){ try { return URLDecoder.decode(encode,"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } private EncodeUtils(); static String urlEncode(String s); static String urlDecode(String encode); }### Answer:
@Test public void urlDecode() throws Exception { String s = "%E4%B8%8A%E6%B5%B7%E5%B8%82%E6%99%AE%E9%99%80%E5%8C%BA%E5%85%89%E5%A4%8D%E8%A5%BF%E8%B7%AF%E9%9D%A0%E8%BF%91%E6%B1%87%E9%93%B6%E9%93%AD%E5%B0%8A6%E5%8F%B7%E6%A5%BC"; s = EncodeUtils.urlDecode(s); System.out.println(s); }
|
### Question:
Money implements Serializable { @Override public String toString() { return format.format(amount); } @Override String toString(); static final NumberFormat format; }### Answer:
@Test public void go() { Money money = new Money(BigDecimal.valueOf(new Random().nextDouble()).multiply(BigDecimal.valueOf(10000))); System.out.println(money.toString()); money = new Money(new BigDecimal("2820.00000000000000000000")); System.out.println(money.toString()); assertThat(true) .isTrue(); }
|
### Question:
ManageTagController { @DeleteMapping("/manage/tagList") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@RequestParam String name) { try { tagService.delete(name); } catch (Throwable ignored) { log.info("删除时错误", ignored); } } @GetMapping("/manageTag") String index(); @GetMapping("/manageTagAdd") String toAdd(); @GetMapping("/manage/tagDetail") String detail(@RequestParam String name, Model model); @GetMapping("/manage/tagEdit") String edit(@RequestParam String name, Model model); @GetMapping("/manage/tagList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/tagList") @Transactional String add(@RequestParam String name, Integer type
, @RequestParam(required = false, defaultValue = "0") Integer weight, String icon); @PostMapping("/manage/addTag") @ResponseBody String add(String name); @DeleteMapping("/manage/tagList") @ResponseStatus(HttpStatus.NO_CONTENT) void delete(@RequestParam String name); @GetMapping("/manage/tagList/check") @ResponseBody String checkName(@RequestParam String name); @PutMapping("/manage/tagList/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@RequestParam String name); @PutMapping("/manage/tagList/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@RequestParam String name); }### Answer:
@Test public void testDelete() throws Exception { int randomNum = random.nextInt(10); while (randomNum-- > 0) { toAdd(); } Tag tag = tagRepository.findAll().stream().max(new RandomComparator()).orElse(null); if (tag == null) { return; } MainGood mainGood = mainGoodService.forSale().stream().max(new RandomComparator()).orElse(null); if (mainGood.getTags() == null) mainGood.setTags(new HashSet<>()); mainGood.getTags().add(tag); mainGoodRepository.save(mainGood); assertThat(mainGoodRepository.findOne(mainGood.getId()).getTags()).contains(tag); assertThat(mainGoodService.forSale(null,null,null,tag.getName())).contains(mainGood); List<MainGood> tagMainGood = mainGoodService.forSale(null,null,null,tag.getName()); tagMainGood.forEach(good -> good.getTags().remove(tag)); mainGoodRepository.save(tagMainGood); if (!CollectionUtils.isEmpty(mainGood.getTags())) assertThat(mainGoodRepository.findOne(mainGood.getId()).getTags()).doesNotContain(tag); else assertThat(mainGoodRepository.findOne(mainGood.getId()).getTags()).isNull(); assertThat(mainGoodService.forSale(null,null,null,tag.getName())).doesNotContain(mainGood); }
@Test public void delete() throws Exception { toAdd(); Tag tag = tagRepository.findAll().stream().max(new RandomComparator()).orElse(null); if (tag == null) { return; } MainGood mainGood = mainGoodService.forSale().stream().max(new RandomComparator()).orElse(null); if (mainGood.getTags() == null) mainGood.setTags(new HashSet<>()); mainGood.getTags().add(tag); mainGoodRepository.saveAndFlush(mainGood); log.debug("set good tag success"); assertThat(mainGoodRepository.findOne(mainGood.getId()).getTags()).contains(tag); mockMvc.perform(delete(TAG_LIST_URL) .param("name",tag.getName())) .andExpect(status().is2xxSuccessful()); }
|
### Question:
ManageTagController { @PutMapping("/manage/tagList/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void disable(@RequestParam String name) { tagRepository.getOne(name).setDisabled(true); } @GetMapping("/manageTag") String index(); @GetMapping("/manageTagAdd") String toAdd(); @GetMapping("/manage/tagDetail") String detail(@RequestParam String name, Model model); @GetMapping("/manage/tagEdit") String edit(@RequestParam String name, Model model); @GetMapping("/manage/tagList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/tagList") @Transactional String add(@RequestParam String name, Integer type
, @RequestParam(required = false, defaultValue = "0") Integer weight, String icon); @PostMapping("/manage/addTag") @ResponseBody String add(String name); @DeleteMapping("/manage/tagList") @ResponseStatus(HttpStatus.NO_CONTENT) void delete(@RequestParam String name); @GetMapping("/manage/tagList/check") @ResponseBody String checkName(@RequestParam String name); @PutMapping("/manage/tagList/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@RequestParam String name); @PutMapping("/manage/tagList/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@RequestParam String name); }### Answer:
@Test public void disable() throws Exception { changeDisable("/disable", true); }
|
### Question:
ManageTagController { @PutMapping("/manage/tagList/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void enable(@RequestParam String name) { tagRepository.getOne(name).setDisabled(false); } @GetMapping("/manageTag") String index(); @GetMapping("/manageTagAdd") String toAdd(); @GetMapping("/manage/tagDetail") String detail(@RequestParam String name, Model model); @GetMapping("/manage/tagEdit") String edit(@RequestParam String name, Model model); @GetMapping("/manage/tagList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/tagList") @Transactional String add(@RequestParam String name, Integer type
, @RequestParam(required = false, defaultValue = "0") Integer weight, String icon); @PostMapping("/manage/addTag") @ResponseBody String add(String name); @DeleteMapping("/manage/tagList") @ResponseStatus(HttpStatus.NO_CONTENT) void delete(@RequestParam String name); @GetMapping("/manage/tagList/check") @ResponseBody String checkName(@RequestParam String name); @PutMapping("/manage/tagList/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@RequestParam String name); @PutMapping("/manage/tagList/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@RequestParam String name); }### Answer:
@Test public void enable() throws Exception { changeDisable("/enable", false); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.