src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
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); }
@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()); }
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); }
@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); }
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); }
@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()); }
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); }
@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); }
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); }
@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); }
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); }
@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(); }
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); }
@Test public void createTest() { BankAccessBankingModelFactory bankAccessBankingModelFactory = new BankAccessBankingModelFactory(); BankAccessCredential credential = new BankAccessCredential("test", "test", "test"); BankAccessBankingModel testModel = bankAccessBankingModelFactory.createBankAccessBankingModel("1", credential); Assert.assertNotNull(testModel); }
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); }
@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()); }
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); }
@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()); }
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); }
@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()); }
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); }
@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); }
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); }
@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); }
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); }
@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); }
AuthMigrator { public Task<Void> migrate(boolean cleanupDigitsSession) { final FirebaseUser currentUser = mFirebaseAuth.getCurrentUser(); final String sessionJson = mStorageHelpers.getDigitsSessionJson(); final Context context = mApp.getApplicationContext(); final RedeemableDigitsSessionBuilder builder; if (currentUser != null) { Log.d(TAG, "Found existing firebase session. Skipping Exchange."); return cleanupAndCreateEmptyResult(cleanupDigitsSession); } if(sessionJson == null) { Log.d(TAG, "No digits session found"); return cleanupAndCreateEmptyResult(cleanupDigitsSession); } Log.d(TAG, "Exchanging digits session"); try { builder = RedeemableDigitsSessionBuilder.fromSessionJson(sessionJson); } catch (JSONException e) { Log.d(TAG, "Digits sesion is corrupt"); return cleanupAndCreateEmptyResult(cleanupDigitsSession); } builder.setConsumerKey(mStorageHelpers.getApiKeyFromManifest(context, StorageHelpers.DIGITS_CONSUMER_KEY_KEY)) .setConsumerSecret(mStorageHelpers.getApiKeyFromManifest(context, StorageHelpers.DIGITS_CONSUMER_SECRET_KEY)) .setFabricApiKey(mStorageHelpers.getApiKeyFromManifest(context, StorageHelpers.FABRIC_API_KEY_KEY)); Task<Void> exchangeTask = mFirebaseAuth.signInWithCustomToken( mStorageHelpers.getUnsignedJWT(builder.build().getPayload())) .continueWithTask(VOID_CONTINUATION); return cleanupDigitsSession ? exchangeTask.continueWithTask(mClearSessionContinuation) : exchangeTask; } @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(); }
@Test public void migrateAndClear_tokenFound() throws JSONException { when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(VALID_DIGITS_SESSION); when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT); when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(authResultTask); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.migrate(true).isSuccessful()); verify(mockFirebaseAuth).signInWithCustomToken(DIGITS_JWT); verify(mockStorageHelpers).clearDigitsSession(); checkCompleteJsonObject(mjsonCaptor.getValue()); } @Test public void migrateCustomSession() throws JSONException { when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT); when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(authResultTask); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); RedeemableDigitsSessionBuilder builder = new RedeemableDigitsSessionBuilder() .setAuthToken(AUTH_TOKEN) .setAuthTokenSecret(AUTH_TOKEN_SECRET) .setConsumerKey(DIGITS_CONSUMER_KEY) .setConsumerSecret(DIGITS_CONSUMER_SECRET) .setFabricApiKey(FABRIC_API_KEY); assertTrue(authMigrator.migrate(builder).isSuccessful()); verify(mockFirebaseAuth).signInWithCustomToken(DIGITS_JWT); JSONObject jsonObject = mjsonCaptor.getValue(); assertTrue(jsonObject.isNull("id")); assertTrue(jsonObject.isNull("phone_number")); assertTrue(jsonObject.isNull("email_address")); assertTrue(jsonObject.isNull("is_email_verified")); assertTrue(jsonObject.isNull(DIGITS_CONSUMER_KEY)); assertTrue(jsonObject.isNull(DIGITS_CONSUMER_SECRET)); assertTrue(jsonObject.isNull(FABRIC_API_KEY)); assertEquals(AUTH_TOKEN, jsonObject.getString("auth_token")); assertEquals(AUTH_TOKEN_SECRET, jsonObject.getString("auth_token_secret")); } @Test public void migrateAndClear_badSessionResponse() throws JSONException { Task<AuthResult> task = Tasks.forException(new FirebaseWebRequestException("msg", 400)); when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(VALID_DIGITS_SESSION); when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT); when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(task); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertFalse(authMigrator.migrate(true).isSuccessful()); verify(mockFirebaseAuth).signInWithCustomToken(DIGITS_JWT); verify(mockStorageHelpers).clearDigitsSession(); checkCompleteJsonObject(mjsonCaptor.getValue()); } @Test public void migrateAndClear_unauthorizedSessionResponse() throws JSONException { Task<AuthResult> task = Tasks.forException(new FirebaseWebRequestException("msg", 403)); when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(VALID_DIGITS_SESSION); when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT); when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(task); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertFalse(authMigrator.migrate(true).isSuccessful()); verify(mockFirebaseAuth).signInWithCustomToken(DIGITS_JWT); verify(mockStorageHelpers).clearDigitsSession(); checkCompleteJsonObject(mjsonCaptor.getValue()); } @Test public void migrateAndKeep_unauthorizedSessionResponse() throws JSONException { Task<AuthResult> task = Tasks.forException(new FirebaseWebRequestException("msg", 403)); when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(VALID_DIGITS_SESSION); when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT); when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(task); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertFalse(authMigrator.migrate(false).isSuccessful()); verify(mockFirebaseAuth).signInWithCustomToken(DIGITS_JWT); verify(mockStorageHelpers, times(0)).clearDigitsSession(); checkCompleteJsonObject(mjsonCaptor.getValue()); } @Test public void migrateAndKeep_tokenFound() throws JSONException { when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(VALID_DIGITS_SESSION); when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT); when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(authResultTask); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.migrate(false).isSuccessful()); verify(mockFirebaseAuth).signInWithCustomToken(DIGITS_JWT); verify(mockStorageHelpers, times(0)).clearDigitsSession(); checkCompleteJsonObject(mjsonCaptor.getValue()); } @Test public void migrateAndClear_foundFirebaseSession() throws JSONException { when(mockFirebaseAuth.getCurrentUser()).thenReturn(mockFirebaseUser); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.migrate(true).isSuccessful()); verify(mockStorageHelpers).clearDigitsSession(); verify(mockFirebaseAuth, times(0)).signInWithCustomToken(any(String.class)); } @Test public void migrateAndKeep_foundFirebaseSession() throws JSONException { when(mockFirebaseAuth.getCurrentUser()).thenReturn(mockFirebaseUser); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.migrate(false).isSuccessful()); verify(mockStorageHelpers, times(0)).clearDigitsSession(); verify(mockFirebaseAuth, times(0)).signInWithCustomToken(any(String.class)); } @Test public void migrate_noLegacyToken() { when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(null); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.migrate(true).isSuccessful()); verify(mockFirebaseAuth, times(0)).signInWithCustomToken(any(String.class)); } @Test public void migrateAndClear_invalidToken() { when(mockStorageHelpers.getDigitsSessionJson()).thenReturn("invalid_session"); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.migrate(true).isSuccessful()); verify(mockStorageHelpers).clearDigitsSession(); verify(mockFirebaseAuth, times(0)).signInWithCustomToken(any(String.class)); } @Test public void migrateAndKeep_invalidToken() { when(mockStorageHelpers.getDigitsSessionJson()).thenReturn("invalid_session"); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.migrate(false).isSuccessful()); verify(mockStorageHelpers,times(0)).clearDigitsSession(); verify(mockFirebaseAuth, times(0)).signInWithCustomToken(any(String.class)); }
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(); }
@Test public void hasLegacyAuth() throws JSONException { when(mockStorageHelpers.hasDigitsSession()).thenReturn(true); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.hasLegacyAuth()); }
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(); }
@Test public void clearLegacyAuth() throws JSONException { AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); authMigrator.clearLegacyAuth(); verify(mockStorageHelpers).clearDigitsSession(); }
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(); }
@Test(expected=JSONException.class) public void testInvalidFromDigitsSessionJson() throws JSONException { RedeemableDigitsSessionBuilder.fromSessionJson("invalid_json"); }
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); }
@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")); }
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(); }
@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); }
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); }
@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); }
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); }
@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); }
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); }
@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 \\\\")); }
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); }
@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("")); }
JobCallbackUtil { public static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum status) { if (props == null || status == null) { throw new NullPointerException("One of the argument is null"); } String jobCallBackUrl = firstJobcallbackPropertyMap.get(status); return props.containsKey(jobCallBackUrl); } static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum status); static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum... jobStatuses); static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback); static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback, Logger privateLogger); static Header[] parseHttpHeaders(String headers); static Map<String, String> buildJobContextInfoMap(Event event, String server); static String replaceTokens(String value, Map<String, String> contextInfo, boolean withEncoding); }
@Test public void multipleStatusesWithJobCallbackTest() { Props props = new Props(); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", "def"); Assert.assertTrue(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED, JobCallbackStatusEnum.COMPLETED, JobCallbackStatusEnum.FAILURE, JobCallbackStatusEnum.SUCCESS)); props = new Props(); props.put("job.notification." + JobCallbackStatusEnum.COMPLETED.name().toLowerCase() + ".1.url", "def"); Assert.assertTrue(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED, JobCallbackStatusEnum.COMPLETED, JobCallbackStatusEnum.FAILURE, JobCallbackStatusEnum.SUCCESS)); props = new Props(); props.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.url", "def"); Assert.assertTrue(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED, JobCallbackStatusEnum.COMPLETED, JobCallbackStatusEnum.FAILURE, JobCallbackStatusEnum.SUCCESS)); props = new Props(); props.put("job.notification." + JobCallbackStatusEnum.SUCCESS.name().toLowerCase() + ".1.url", "def"); Assert.assertTrue(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED, JobCallbackStatusEnum.COMPLETED, JobCallbackStatusEnum.FAILURE, JobCallbackStatusEnum.SUCCESS)); } @Test public void hasCallbackPropertiesWithGapTest() { Props props = new Props(); for (JobCallbackStatusEnum jobStatus : JobCallbackStatusEnum.values()) { props.put( "job.notification." + jobStatus.name().toLowerCase() + ".2.url", "def"); } System.out.println(props); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED)); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.COMPLETED)); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.FAILURE)); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.SUCCESS)); } @Test public void noCallbackPropertiesTest() { Props props = new Props(); props.put("abc", "def"); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED)); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.COMPLETED)); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.FAILURE)); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.SUCCESS)); } @Test public void hasCallbackPropertiesTest() { Props props = new Props(); for (JobCallbackStatusEnum jobStatus : JobCallbackStatusEnum.values()) { props.put( "job.notification." + jobStatus.name().toLowerCase() + ".1.url", "def"); } System.out.println(props); Assert.assertTrue(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED)); Assert.assertTrue(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.COMPLETED)); Assert.assertTrue(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.FAILURE)); Assert.assertTrue(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.SUCCESS)); } @Test public void multipleStatusWithNoJobCallbackTest() { Props props = new Props(); props.put("abc", "def"); Assert.assertFalse(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED, JobCallbackStatusEnum.COMPLETED, JobCallbackStatusEnum.FAILURE, JobCallbackStatusEnum.SUCCESS)); }
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); }
@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("")); }
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); }
@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")); }
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); }
@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")); }
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); }
@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); }
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); }
@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")); }
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); }
@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))); }
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); }
@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))); }
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); }
@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")); }
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; }
@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)); }
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; }
@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)); }
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; }
@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; }
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); }
@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)); }
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); }
@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"); }
JobCallbackUtil { public static String replaceTokens(String value, Map<String, String> contextInfo, boolean withEncoding) { String result = value; String tokenValue = encodeQueryParam(contextInfo.get(CONTEXT_SERVER_TOKEN), withEncoding); result = result.replaceFirst(Pattern.quote(CONTEXT_SERVER_TOKEN), tokenValue); tokenValue = encodeQueryParam(contextInfo.get(CONTEXT_PROJECT_TOKEN), withEncoding); result = result.replaceFirst(Pattern.quote(CONTEXT_PROJECT_TOKEN), tokenValue); tokenValue = encodeQueryParam(contextInfo.get(CONTEXT_FLOW_TOKEN), withEncoding); result = result.replaceFirst(Pattern.quote(CONTEXT_FLOW_TOKEN), tokenValue); tokenValue = encodeQueryParam(contextInfo.get(CONTEXT_JOB_TOKEN), withEncoding); result = result.replaceFirst(Pattern.quote(CONTEXT_JOB_TOKEN), tokenValue); tokenValue = encodeQueryParam(contextInfo.get(CONTEXT_EXECUTION_ID_TOKEN), withEncoding); result = result.replaceFirst(Pattern.quote(CONTEXT_EXECUTION_ID_TOKEN), tokenValue); tokenValue = encodeQueryParam(contextInfo.get(CONTEXT_JOB_STATUS_TOKEN), withEncoding); result = result.replaceFirst(Pattern.quote(CONTEXT_JOB_STATUS_TOKEN), tokenValue); return result; } static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum status); static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum... jobStatuses); static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback); static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback, Logger privateLogger); static Header[] parseHttpHeaders(String headers); static Map<String, String> buildJobContextInfoMap(Event event, String server); static String replaceTokens(String value, Map<String, String> contextInfo, boolean withEncoding); }
@Test public void noTokenTest() { String urlWithNoToken = "http: String result = JobCallbackUtil.replaceTokens(urlWithNoToken, contextInfo, true); Assert.assertEquals(urlWithNoToken, result); } @Test public void oneTokenTest() { String urlWithOneToken = "http: String result = JobCallbackUtil.replaceTokens(urlWithOneToken, contextInfo, true); Assert.assertEquals("http: + "&another=yes", result); } @Test public void twoTokensTest() { String urlWithOneToken = "http: + CONTEXT_FLOW_TOKEN; String result = JobCallbackUtil.replaceTokens(urlWithOneToken, contextInfo, true); Assert.assertEquals("http: + "&flow=" + FLOW_NAME, result); } @Test public void allTokensTest() { String urlWithOneToken = "http: + CONTEXT_PROJECT_TOKEN + "&flow=" + CONTEXT_FLOW_TOKEN + "&executionId=" + CONTEXT_EXECUTION_ID_TOKEN + "&job=" + CONTEXT_JOB_TOKEN + "&status=" + CONTEXT_JOB_STATUS_TOKEN; String result = JobCallbackUtil.replaceTokens(urlWithOneToken, contextInfo, true); String expectedResult = "http: + PROJECT_NAME + "&flow=" + FLOW_NAME + "&executionId=" + EXECUTION_ID + "&job=" + JOB_NAME + "&status=" + JOB_STATUS_NAME; Assert.assertEquals(expectedResult, result); } @Test public void tokenWithEncoding() throws Exception { String jobNameWithSpaces = "my job"; String encodedJobName = URLEncoder.encode(jobNameWithSpaces, "UTF-8"); Map<String, String> customContextInfo = new HashMap<String, String>(); customContextInfo = new HashMap<String, String>(); customContextInfo.put(CONTEXT_SERVER_TOKEN, SERVER_NAME); customContextInfo.put(CONTEXT_PROJECT_TOKEN, PROJECT_NAME); customContextInfo.put(CONTEXT_FLOW_TOKEN, FLOW_NAME); customContextInfo.put(CONTEXT_EXECUTION_ID_TOKEN, EXECUTION_ID); customContextInfo.put(CONTEXT_JOB_TOKEN, jobNameWithSpaces); customContextInfo.put(CONTEXT_JOB_STATUS_TOKEN, JOB_STATUS_NAME); String urlWithOneToken = "http: String result = JobCallbackUtil.replaceTokens(urlWithOneToken, customContextInfo, true); Assert.assertEquals("http: + "&flow=" + FLOW_NAME, result); }
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); }
@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)); }
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); }
@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); } }
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); }
@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); } }
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; }
@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); }
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; }
@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"); }
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); }
@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"); }
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); }
@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()); } }
ProcessJob extends AbstractProcessJob { @Override public void run() throws Exception { try { resolveProps(); } catch (Exception e) { handleError("Bad property definition! " + e.getMessage(), e); } getLog().info("ProcessJob sysProps:" + sysProps); getLog().info("ProcessJob jobProps:" + jobProps); if (sysProps.getBoolean(MEMCHECK_ENABLED, false) && jobProps.getBoolean(AZKABAN_MEMORY_CHECK, false)) { long freeMemDecrAmt = sysProps.getLong(MEMCHECK_FREEMEMDECRAMT, 0); Pair<Long, Long> memPair = getProcMemoryRequirement(); boolean isMemGranted = SystemMemoryInfo.canSystemGrantMemory(memPair.getFirst(), memPair.getSecond(), freeMemDecrAmt); if (!isMemGranted) { throw new Exception( String .format( "Cannot request memory (Xms %d kb, Xmx %d kb) from system for job %s", memPair.getFirst(), memPair.getSecond(), getId())); } } List<String> commands = null; try { commands = getCommandList(); } catch (Exception e) { handleError("Job set up failed " + e.getCause(), e); } long startMs = System.currentTimeMillis(); if (commands == null) { handleError("There are no commands to execute", null); } info(commands.size() + " commands to execute."); File[] propFiles = initPropsFiles(); Map<String, String> envVars = getEnvironmentVariables(); envVars.put(KRB5CCNAME, getKrb5ccname(jobProps)); String executeAsUserBinaryPath = null; String effectiveUser = null; boolean isExecuteAsUser = sysProps.getBoolean(EXECUTE_AS_USER, true); if (isExecuteAsUser) { String nativeLibFolder = sysProps.getString(NATIVE_LIB_FOLDER); executeAsUserBinaryPath = String.format("%s/%s", nativeLibFolder, "execute-as-user"); effectiveUser = getEffectiveUser(jobProps); if ("root".equals(effectiveUser)) { throw new RuntimeException( "Not permitted to proxy as root through Azkaban"); } } for (String command : commands) { AzkabanProcessBuilder builder = null; if (isExecuteAsUser) { command = String.format("%s %s %s", executeAsUserBinaryPath, effectiveUser, command); info("Command: " + command); builder = new AzkabanProcessBuilder(partitionCommandLine(command)) .setEnv(envVars).setWorkingDir(getCwd()).setLogger(getLog()) .enableExecuteAsUser().setExecuteAsUserBinaryPath(executeAsUserBinaryPath) .setEffectiveUser(effectiveUser); } else { info("Command: " + command); builder = new AzkabanProcessBuilder(partitionCommandLine(command)) .setEnv(envVars).setWorkingDir(getCwd()).setLogger(getLog()); } if (builder.getEnv().size() > 0) { info("Environment variables: " + builder.getEnv()); } info("Working directory: " + builder.getWorkingDir()); this.logJobProperties(); boolean success = false; this.process = builder.build(); try { this.process.run(); success = true; } catch (Throwable e) { for (File file : propFiles) if (file != null && file.exists()) file.delete(); throw new RuntimeException(e); } finally { this.process = null; info("Process completed " + (success ? "successfully" : "unsuccessfully") + " in " + ((System.currentTimeMillis() - startMs) / 1000) + " seconds."); } } generateProperties(propFiles[1]); } 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; }
@Test public void testOneUnixCommand() throws Exception { props.put(ProcessJob.COMMAND, "ls -al"); job.run(); } @Test public void testOneUnixCommandWithProxyUserInsteadOfSubmitUser() throws Exception { props.removeLocal(CommonJobProperties.SUBMIT_USER); props.put("user.to.proxy", "test_user"); props.put(ProcessJob.COMMAND, "ls -al"); job.run(); } @Test (expected=RuntimeException.class) public void testOneUnixCommandWithNoUser() throws Exception { props.removeLocal(CommonJobProperties.SUBMIT_USER); props.put(ProcessJob.COMMAND, "ls -al"); job.run(); } @Test public void testFailedUnixCommand() throws Exception { props.put(ProcessJob.COMMAND, "xls -al"); try { job.run(); } catch (RuntimeException e) { Assert.assertTrue(true); e.printStackTrace(); } } @Test public void testMultipleUnixCommands() throws Exception { props.put(ProcessJob.COMMAND, "pwd"); props.put("command.1", "date"); props.put("command.2", "whoami"); job.run(); }
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; }
@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)); }
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); }
@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()); } }
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); }
@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()); }
LoginAbstractAzkabanServlet extends AbstractAzkabanServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Session session = getSessionFromRequest(req); logRequest(req, session); if (ServletFileUpload.isMultipartContent(req)) { Map<String, Object> params = multipartParser.parseMultipart(req); if (session == null) { if (params.containsKey("session.id")) { String sessionId = (String) params.get("session.id"); String ip = getRealClientIpAddr(req); session = getSessionFromSessionId(sessionId, ip); if (session != null) { handleMultiformPost(req, resp, params, session); return; } } if (!params.containsKey("username") || !params.containsKey("password")) { writeResponse(resp, "Login error. Need username and password"); return; } String username = (String) params.get("username"); String password = (String) params.get("password"); String ip = getRealClientIpAddr(req); try { session = createSession(username, password, ip); } catch (UserManagerException e) { writeResponse(resp, "Login error: " + e.getMessage()); return; } } handleMultiformPost(req, resp, params, session); } else if (hasParam(req, "action") && getParam(req, "action").equals("login")) { HashMap<String, Object> obj = new HashMap<String, Object>(); handleAjaxLoginAction(req, resp, obj); this.writeJSON(resp, obj); } else if (session == null) { if (hasParam(req, "username") && hasParam(req, "password")) { try { session = createSession(req); } catch (UserManagerException e) { writeResponse(resp, "Login error: " + e.getMessage()); } handlePost(req, resp, session); } else { if (isAjaxCall(req)) { String response = createJsonResponse("error", "Invalid Session. Need to re-login", "login", null); writeResponse(resp, response); } else { handleLogin(req, resp, "Enter username and password"); } } } else { handlePost(req, resp, session); } } @Override void init(ServletConfig config); void setResourceDirectory(File file); }
@Test public void testWhenPostRequestSessionIsValid() throws Exception{ String clientIp = "127.0.0.1:10000"; String sessionId = "111"; HttpServletRequest req = MockLoginAzkabanServlet.getRequestWithNoUpstream(clientIp, sessionId, "POST"); StringWriter writer = new StringWriter(); HttpServletResponse resp = getResponse(writer); MockLoginAzkabanServlet servlet = MockLoginAzkabanServlet.getServletWithSession(sessionId, "user", "127.0.0.1"); servlet.doPost(req, resp); assertEquals("SUCCESS_MOCK_LOGIN_SERVLET", writer.toString()); } @Test public void testWhenPostRequestChangedClientIpSessionIsInvalid() throws Exception{ String clientIp = "127.0.0.2:10000"; String sessionId = "111"; HttpServletRequest req = MockLoginAzkabanServlet.getRequestWithNoUpstream(clientIp, sessionId, "POST"); StringWriter writer = new StringWriter(); HttpServletResponse resp = getResponse(writer); MockLoginAzkabanServlet servlet = MockLoginAzkabanServlet.getServletWithSession(sessionId, "user", "127.0.0.1"); servlet.doPost(req, resp); assertNotSame("SUCCESS_MOCK_LOGIN_SERVLET", writer.toString()); } @Test public void testWhenPostRequestChangedClientPortSessionIsValid() throws Exception{ String clientIp = "127.0.0.1:10000"; String sessionId = "111"; HttpServletRequest req = MockLoginAzkabanServlet.getRequestWithNoUpstream(clientIp, sessionId, "POST"); StringWriter writer = new StringWriter(); HttpServletResponse resp = getResponse(writer); MockLoginAzkabanServlet servlet = MockLoginAzkabanServlet.getServletWithSession(sessionId, "user", "127.0.0.1"); servlet.doPost(req, resp); assertEquals("SUCCESS_MOCK_LOGIN_SERVLET", writer.toString()); } @Test public void testWhenPostRequestWithUpstreamSessionIsValid() throws Exception{ String clientIp = "127.0.0.1:10000"; String upstreamIp = "192.168.1.1:11111"; String sessionId = "111"; HttpServletRequest req = MockLoginAzkabanServlet.getRequestWithUpstream(clientIp, upstreamIp, sessionId, "POST"); StringWriter writer = new StringWriter(); HttpServletResponse resp = getResponse(writer); MockLoginAzkabanServlet servlet = MockLoginAzkabanServlet.getServletWithSession(sessionId, "user", "192.168.1.1"); servlet.doPost(req, resp); assertEquals("SUCCESS_MOCK_LOGIN_SERVLET", writer.toString()); } @Test public void testWhenPostRequestWithMultipleUpstreamsSessionIsValid() throws Exception{ String clientIp = "127.0.0.1:10000"; String upstreamIp = "192.168.1.1:11111,888.8.8.8:2222,5.5.5.5:5555"; String sessionId = "111"; HttpServletRequest req = MockLoginAzkabanServlet.getRequestWithUpstream(clientIp, upstreamIp, sessionId, "POST"); StringWriter writer = new StringWriter(); HttpServletResponse resp = getResponse(writer); MockLoginAzkabanServlet servlet = MockLoginAzkabanServlet.getServletWithSession(sessionId, "user", "192.168.1.1"); servlet.doPost(req, resp); assertEquals("SUCCESS_MOCK_LOGIN_SERVLET", writer.toString()); }
JobCallbackUtil { public static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback) { return parseJobCallbackProperties(props, status, contextInfo, maxNumCallback, logger); } static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum status); static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum... jobStatuses); static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback); static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback, Logger privateLogger); static Header[] parseHttpHeaders(String headers); static Map<String, String> buildJobContextInfoMap(Event event, String server); static String replaceTokens(String value, Map<String, String> contextInfo, boolean withEncoding); }
@Test public void parseJobCallbackOneGetTest() { Props props = new Props(); String url = "http: props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", url); List<HttpRequestBase> result = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo, 3); Assert.assertEquals(1, result.size()); Assert.assertEquals(HTTP_GET, result.get(0).getMethod()); Assert.assertEquals(url, result.get(0).getURI().toString()); } @Test public void parseJobCallbackWithInvalidURLTest() { Props props = new Props(); String url = "linkedin.com"; props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", url); List<HttpRequestBase> result = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo, 3); Assert.assertEquals(1, result.size()); Assert.assertEquals(HTTP_GET, result.get(0).getMethod()); Assert.assertEquals(url, result.get(0).getURI().toString()); } @Test public void parseJobCallbackTwoGetsTest() { Props props = new Props(); String[] urls = { "http: "http: props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", urls[0]); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".2.url", urls[1]); List<HttpRequestBase> result = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo, 3); Assert.assertEquals(2, result.size()); for (int i = 0; i < urls.length; i++) { Assert.assertEquals(HTTP_GET, result.get(i).getMethod()); Assert.assertEquals(urls[i], result.get(i).getURI().toString()); } } @Test public void parseJobCallbackWithGapTest() { Props props = new Props(); String[] urls = { "http: "http: props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", urls[0]); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".3.url", urls[1]); List<HttpRequestBase> result = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo, 3); Assert.assertEquals(1, result.size()); Assert.assertEquals(HTTP_GET, result.get(0).getMethod()); Assert.assertEquals(urls[0], result.get(0).getURI().toString()); } @Test public void parseJobCallbackWithPostTest() { Props props = new Props(); String url = "http: String bodyText = "{name:\"you\"}"; props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", url); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.method", HTTP_POST); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.body", bodyText); List<HttpRequestBase> result = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo, 3); Assert.assertEquals(1, result.size()); HttpPost httpPost = (HttpPost) result.get(0); Assert.assertEquals(url, httpPost.getURI().toString()); Assert.assertEquals(HTTP_POST, httpPost.getMethod()); Assert.assertEquals(bodyText.length(), httpPost.getEntity() .getContentLength()); }
JobCallbackUtil { public static Header[] parseHttpHeaders(String headers) { if (headers == null || headers.length() == 0) { return null; } String[] headerArray = headers.split(HEADER_ELEMENT_DELIMITER); List<Header> headerList = new ArrayList<Header>(headerArray.length); for (int i = 0; i < headerArray.length; i++) { String headerPair = headerArray[i]; int index = headerPair.indexOf(HEADER_NAME_VALUE_DELIMITER); if (index != -1) { headerList.add(new BasicHeader(headerPair.substring(0, index), headerPair.substring(index + 1))); } } return headerList.toArray(new BasicHeader[0]); } static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum status); static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum... jobStatuses); static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback); static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback, Logger privateLogger); static Header[] parseHttpHeaders(String headers); static Map<String, String> buildJobContextInfoMap(Event event, String server); static String replaceTokens(String value, Map<String, String> contextInfo, boolean withEncoding); }
@Test public void noHeaderElementTest() { Header[] headerArr = JobCallbackUtil.parseHttpHeaders("this is an amazing day"); Assert.assertNotNull(headerArr); Assert.assertEquals(0, headerArr.length); } @Test public void oneHeaderElementTest() { String name = "Content-type"; String value = "application/json"; String headers = name + JobCallbackConstants.HEADER_NAME_VALUE_DELIMITER + value; Header[] headerArr = JobCallbackUtil.parseHttpHeaders(headers); Assert.assertNotNull(headerArr); Assert.assertEquals(1, headerArr.length); Assert.assertEquals(name, headerArr[0].getName()); Assert.assertEquals(value, headerArr[0].getValue()); String headersWithExtraDelimiter = name + JobCallbackConstants.HEADER_NAME_VALUE_DELIMITER + value + JobCallbackConstants.HEADER_ELEMENT_DELIMITER; headerArr = JobCallbackUtil.parseHttpHeaders(headersWithExtraDelimiter); Assert.assertNotNull(headerArr); Assert.assertEquals(1, headerArr.length); Assert.assertEquals(name, headerArr[0].getName()); Assert.assertEquals(value, headerArr[0].getValue()); } @Test public void multipleHeaderElementTest() { String name1 = "Content-type"; String value1 = "application/json"; String name2 = "Accept"; String value2 = "application/xml"; String name3 = "User-Agent"; String value3 = "Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/21.0"; String headers = makeHeaderElement(name1, value1); headers += JobCallbackConstants.HEADER_ELEMENT_DELIMITER; headers += makeHeaderElement(name2, value2); headers += JobCallbackConstants.HEADER_ELEMENT_DELIMITER; headers += makeHeaderElement(name3, value3); System.out.println("headers: " + headers); Header[] headerArr = JobCallbackUtil.parseHttpHeaders(headers); Assert.assertNotNull(headerArr); Assert.assertEquals(3, headerArr.length); Assert.assertEquals(name1, headerArr[0].getName()); Assert.assertEquals(value1, headerArr[0].getValue()); Assert.assertEquals(name2, headerArr[1].getName()); Assert.assertEquals(value2, headerArr[1].getValue()); Assert.assertEquals(name3, headerArr[2].getName()); Assert.assertEquals(value3, headerArr[2].getValue()); } @Test public void partialHeaderElementTest() { String name1 = "Content-type"; String value1 = "application/json"; String name2 = "Accept"; String value2 = ""; String name3 = "User-Agent"; String value3 = "Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/21.0"; String headers = makeHeaderElement(name1, value1); headers += JobCallbackConstants.HEADER_ELEMENT_DELIMITER; headers += makeHeaderElement(name2, value2); headers += JobCallbackConstants.HEADER_ELEMENT_DELIMITER; headers += makeHeaderElement(name3, value3); System.out.println("headers: " + headers); Header[] headerArr = JobCallbackUtil.parseHttpHeaders(headers); Assert.assertNotNull(headerArr); Assert.assertEquals(3, headerArr.length); Assert.assertEquals(name1, headerArr[0].getName()); Assert.assertEquals(value1, headerArr[0].getValue()); Assert.assertEquals(name2, headerArr[1].getName()); Assert.assertEquals(value2, headerArr[1].getValue()); Assert.assertEquals(name3, headerArr[2].getName()); Assert.assertEquals(value3, headerArr[2].getValue()); }
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; }
@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, "", ""); }
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(); }
@Test public void testEmptyPermissionCreation() throws Exception { Permission permission = new Permission(); permission.addPermissionsByName(new String[] {}); }
ExecutorManager extends EventHandler implements ExecutorManagerAdapter { @Override public Collection<Executor> getAllActiveExecutors() { return Collections.unmodifiableCollection(activeExecutors); } ExecutorManager(Props azkProps, ExecutorLoader loader, Map<String, Alerter> alerters); @Override void setupExecutors(); @Override void disableQueueProcessorThread(); @Override void enableQueueProcessorThread(); State getQueueProcessorThreadState(); boolean isQueueProcessorThreadActive(); long getLastSuccessfulExecutorInfoRefresh(); Set<String> getAvailableExecutorComparatorNames(); Set<String> getAvailableExecutorFilterNames(); @Override State getExecutorManagerThreadState(); String getExecutorThreadStage(); @Override boolean isExecutorManagerThreadActive(); @Override long getLastExecutorManagerThreadCheckTime(); long getLastCleanerThreadCheckTime(); @Override Collection<Executor> getAllActiveExecutors(); @Override Executor fetchExecutor(int executorId); @Override Set<String> getPrimaryServerHosts(); @Override Set<String> getAllActiveExecutorServerHosts(); @Override List<Integer> getRunningFlows(int projectId, String flowId); @Override List<Pair<ExecutableFlow, Executor>> getActiveFlowsWithExecutor(); @Override boolean isFlowRunning(int projectId, String flowId); @Override ExecutableFlow getExecutableFlow(int execId); @Override List<ExecutableFlow> getRunningFlows(); String getRunningFlowIds(); String getQueuedFlowIds(); long getQueuedFlowSize(); List<ExecutableFlow> getRecentlyFinishedFlows(); @Override List<ExecutableFlow> getExecutableFlows(Project project, String flowId, int skip, int size); @Override List<ExecutableFlow> getExecutableFlows(int skip, int size); @Override List<ExecutableFlow> getExecutableFlows(String flowIdContains, int skip, int size); @Override List<ExecutableFlow> getExecutableFlows(String projContain, String flowContain, String userContain, int status, long begin, long end, int skip, int size); @Override List<ExecutableJobInfo> getExecutableJobs(Project project, String jobId, int skip, int size); @Override int getNumberOfJobExecutions(Project project, String jobId); @Override int getNumberOfExecutions(Project project, String flowId); @Override LogData getExecutableFlowLog(ExecutableFlow exFlow, int offset, int length); @Override LogData getExecutionJobLog(ExecutableFlow exFlow, String jobId, int offset, int length, int attempt); @Override List<Object> getExecutionJobStats(ExecutableFlow exFlow, String jobId, int attempt); @Override JobMetaData getExecutionJobMetaData(ExecutableFlow exFlow, String jobId, int offset, int length, int attempt); @Override void cancelFlow(ExecutableFlow exFlow, String userId); @Override void resumeFlow(ExecutableFlow exFlow, String userId); @Override void pauseFlow(ExecutableFlow exFlow, String userId); @Override void pauseExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void resumeExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void retryFailures(ExecutableFlow exFlow, String userId); @Override void retryExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void disableExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void enableExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void cancelExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override String submitExecutableFlow(ExecutableFlow exflow, String userId); @Override Map<String, Object> callExecutorStats(int executorId, String action, Pair<String, String>... params); @Override Map<String, Object> callExecutorJMX(String hostPort, String action, String mBean); @Override void shutdown(); boolean isFinished(ExecutableFlow flow); @Override int getExecutableFlows(int projectId, String flowId, int from, int length, List<ExecutableFlow> outputList); @Override List<ExecutableFlow> getExecutableFlows(int projectId, String flowId, int from, int length, Status status); @Override Props fetchExecutionJobInputProps(int execId, String jobId); @Override void updateExecutionJobInputProps(int execId, int projectId, String flowId, String jobId, Props props); }
@Test public void testLocalExecutorScenario() throws ExecutorManagerException { Props props = new Props(); props.put("executor.port", 12345); ExecutorLoader loader = new MockExecutorLoader(); ExecutorManager manager = new ExecutorManager(props, loader, new HashMap<String, Alerter>()); Set<Executor> activeExecutors = new HashSet(manager.getAllActiveExecutors()); Assert.assertEquals(activeExecutors.size(), 1); Executor executor = activeExecutors.iterator().next(); Assert.assertEquals(executor.getHost(), "localhost"); Assert.assertEquals(executor.getPort(), 12345); Assert.assertArrayEquals(activeExecutors.toArray(), loader .fetchActiveExecutors().toArray()); } @Test public void testMultipleExecutorScenario() throws ExecutorManagerException { Props props = new Props(); props.put(ExecutorManager.AZKABAN_USE_MULTIPLE_EXECUTORS, "true"); ExecutorLoader loader = new MockExecutorLoader(); Executor executor1 = loader.addExecutor("localhost", 12345); Executor executor2 = loader.addExecutor("localhost", 12346); ExecutorManager manager = new ExecutorManager(props, loader, new HashMap<String, Alerter>()); Set<Executor> activeExecutors = new HashSet(manager.getAllActiveExecutors()); Assert.assertArrayEquals(activeExecutors.toArray(), new Executor[] { executor1, executor2 }); }
ExecutorManager extends EventHandler implements ExecutorManagerAdapter { @Override public String submitExecutableFlow(ExecutableFlow exflow, String userId) throws ExecutorManagerException { synchronized (exflow) { String flowId = exflow.getFlowId(); logger.info("Submitting execution flow " + flowId + " by " + userId); String message = ""; if (queuedFlows.isFull()) { message = String .format( "Failed to submit %s for project %s. Azkaban has overrun its webserver queue capacity", flowId, exflow.getProjectName()); logger.error(message); } else { int projectId = exflow.getProjectId(); exflow.setSubmitUser(userId); exflow.setSubmitTime(System.currentTimeMillis()); List<Integer> running = getRunningFlows(projectId, flowId); ExecutionOptions options = exflow.getExecutionOptions(); if (options == null) { options = new ExecutionOptions(); } if (options.getDisabledJobs() != null) { FlowUtils.applyDisabledJobs(options.getDisabledJobs(), exflow); } if (!running.isEmpty()) { if (options.getConcurrentOption().equals( ExecutionOptions.CONCURRENT_OPTION_PIPELINE)) { Collections.sort(running); Integer runningExecId = running.get(running.size() - 1); options.setPipelineExecutionId(runningExecId); message = "Flow " + flowId + " is already running with exec id " + runningExecId + ". Pipelining level " + options.getPipelineLevel() + ". \n"; } else if (options.getConcurrentOption().equals( ExecutionOptions.CONCURRENT_OPTION_SKIP)) { throw new ExecutorManagerException("Flow " + flowId + " is already running. Skipping execution.", ExecutorManagerException.Reason.SkippedExecution); } else { message = "Flow " + flowId + " is already running with exec id " + StringUtils.join(running, ",") + ". Will execute concurrently. \n"; } } boolean memoryCheck = !ProjectWhitelist.isProjectWhitelisted(exflow.getProjectId(), ProjectWhitelist.WhitelistType.MemoryCheck); options.setMemoryCheck(memoryCheck); executorLoader.uploadExecutableFlow(exflow); ExecutionReference reference = new ExecutionReference(exflow.getExecutionId()); if (isMultiExecutorMode()) { executorLoader.addActiveExecutableReference(reference); queuedFlows.enqueue(exflow, reference); } else { Executor choosenExecutor = activeExecutors.iterator().next(); executorLoader.addActiveExecutableReference(reference); try { dispatch(reference, exflow, choosenExecutor); } catch (ExecutorManagerException e) { executorLoader.removeActiveExecutableReference(reference .getExecId()); throw e; } } message += "Execution submitted successfully with exec id " + exflow.getExecutionId(); } return message; } } ExecutorManager(Props azkProps, ExecutorLoader loader, Map<String, Alerter> alerters); @Override void setupExecutors(); @Override void disableQueueProcessorThread(); @Override void enableQueueProcessorThread(); State getQueueProcessorThreadState(); boolean isQueueProcessorThreadActive(); long getLastSuccessfulExecutorInfoRefresh(); Set<String> getAvailableExecutorComparatorNames(); Set<String> getAvailableExecutorFilterNames(); @Override State getExecutorManagerThreadState(); String getExecutorThreadStage(); @Override boolean isExecutorManagerThreadActive(); @Override long getLastExecutorManagerThreadCheckTime(); long getLastCleanerThreadCheckTime(); @Override Collection<Executor> getAllActiveExecutors(); @Override Executor fetchExecutor(int executorId); @Override Set<String> getPrimaryServerHosts(); @Override Set<String> getAllActiveExecutorServerHosts(); @Override List<Integer> getRunningFlows(int projectId, String flowId); @Override List<Pair<ExecutableFlow, Executor>> getActiveFlowsWithExecutor(); @Override boolean isFlowRunning(int projectId, String flowId); @Override ExecutableFlow getExecutableFlow(int execId); @Override List<ExecutableFlow> getRunningFlows(); String getRunningFlowIds(); String getQueuedFlowIds(); long getQueuedFlowSize(); List<ExecutableFlow> getRecentlyFinishedFlows(); @Override List<ExecutableFlow> getExecutableFlows(Project project, String flowId, int skip, int size); @Override List<ExecutableFlow> getExecutableFlows(int skip, int size); @Override List<ExecutableFlow> getExecutableFlows(String flowIdContains, int skip, int size); @Override List<ExecutableFlow> getExecutableFlows(String projContain, String flowContain, String userContain, int status, long begin, long end, int skip, int size); @Override List<ExecutableJobInfo> getExecutableJobs(Project project, String jobId, int skip, int size); @Override int getNumberOfJobExecutions(Project project, String jobId); @Override int getNumberOfExecutions(Project project, String flowId); @Override LogData getExecutableFlowLog(ExecutableFlow exFlow, int offset, int length); @Override LogData getExecutionJobLog(ExecutableFlow exFlow, String jobId, int offset, int length, int attempt); @Override List<Object> getExecutionJobStats(ExecutableFlow exFlow, String jobId, int attempt); @Override JobMetaData getExecutionJobMetaData(ExecutableFlow exFlow, String jobId, int offset, int length, int attempt); @Override void cancelFlow(ExecutableFlow exFlow, String userId); @Override void resumeFlow(ExecutableFlow exFlow, String userId); @Override void pauseFlow(ExecutableFlow exFlow, String userId); @Override void pauseExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void resumeExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void retryFailures(ExecutableFlow exFlow, String userId); @Override void retryExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void disableExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void enableExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override void cancelExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds); @Override String submitExecutableFlow(ExecutableFlow exflow, String userId); @Override Map<String, Object> callExecutorStats(int executorId, String action, Pair<String, String>... params); @Override Map<String, Object> callExecutorJMX(String hostPort, String action, String mBean); @Override void shutdown(); boolean isFinished(ExecutableFlow flow); @Override int getExecutableFlows(int projectId, String flowId, int from, int length, List<ExecutableFlow> outputList); @Override List<ExecutableFlow> getExecutableFlows(int projectId, String flowId, int from, int length, Status status); @Override Props fetchExecutionJobInputProps(int execId, String jobId); @Override void updateExecutionJobInputProps(int execId, int projectId, String flowId, String jobId, Props props); }
@Test(expected = ExecutorManagerException.class) public void testDuplicateQueuedFlows() throws ExecutorManagerException, IOException { ExecutorManager manager = createMultiExecutorManagerInstance(); ExecutableFlow flow1 = TestUtils.createExecutableFlow("exectest1", "exec1"); flow1.getExecutionOptions().setConcurrentOption( ExecutionOptions.CONCURRENT_OPTION_SKIP); User testUser = TestUtils.getTestUser(); manager.submitExecutableFlow(flow1, testUser.getUserId()); manager.submitExecutableFlow(flow1, testUser.getUserId()); }
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; }
@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()); }
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(); }
@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()); }
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(); }
@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())); }
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(); }
@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); }
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(); }
@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))); }
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(); }
@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); }
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(); }
@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()); }
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(); }
@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)); }
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); }
@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); }
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(); }
@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()); }
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(); }
@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)); }
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(); }
@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())); } }
JdbcExecutorLoader extends AbstractJdbcLoader implements ExecutorLoader { @Override public void uploadExecutableNode(ExecutableNode node, Props inputProps) throws ExecutorManagerException { final String INSERT_EXECUTION_NODE = "INSERT INTO execution_jobs " + "(exec_id, project_id, version, flow_id, job_id, start_time, " + "end_time, status, input_params, attempt) VALUES (?,?,?,?,?,?,?,?,?,?)"; String inputParam = null; if (inputProps != null) { try { logger.info("inputProps ==> " + inputProps); inputParam = JSONUtils.toJSON(PropsUtils.toHierarchicalMap(PropsUtils.resolveProps(inputProps))); logger.info("inputParam ==> " + inputParam); } catch (Exception e) { throw new ExecutorManagerException("Error encoding input params"); } } ExecutableFlow flow = node.getExecutableFlow(); String flowId = node.getParentFlow().getFlowPath(); System.out.println("Uploading flowId " + flowId); QueryRunner runner = createQueryRunner(); try { runner.update(INSERT_EXECUTION_NODE, flow.getExecutionId(), flow.getProjectId(), flow.getVersion(), flowId, node.getId(), node.getStartTime(), node.getEndTime(), node.getStatus().getNumVal(), inputParam, node.getAttempt()); } catch (SQLException e) { throw new ExecutorManagerException("Error writing job " + node.getId(), e); } } 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); }
@Test public void testUploadExecutableNode() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); ExecutableFlow flow = createExecutableFlow(10, "exec1"); flow.setExecutionId(10); File jobFile = new File(UNIT_BASE_DIR + "/exectest1", "job10.job"); Props props = new Props(null, jobFile); props.put("test", "test2"); ExecutableNode oldNode = flow.getExecutableNode("job10"); oldNode.setStartTime(System.currentTimeMillis()); loader.uploadExecutableNode(oldNode, props); ExecutableJobInfo info = loader.fetchJobInfo(10, "job10", 0); Assert.assertEquals(flow.getExecutionId(), info.getExecId()); Assert.assertEquals(flow.getProjectId(), info.getProjectId()); Assert.assertEquals(flow.getVersion(), info.getVersion()); Assert.assertEquals(flow.getFlowId(), info.getFlowId()); Assert.assertEquals(oldNode.getId(), info.getJobId()); Assert.assertEquals(oldNode.getStatus(), info.getStatus()); Assert.assertEquals(oldNode.getStartTime(), info.getStartTime()); Assert.assertEquals("endTime = " + oldNode.getEndTime() + " info endTime = " + info.getEndTime(), oldNode.getEndTime(), info.getEndTime()); Props outputProps = new Props(); outputProps.put("hello", "output"); oldNode.setOutputProps(outputProps); oldNode.setEndTime(System.currentTimeMillis()); loader.updateExecutableNode(oldNode); Props fInputProps = loader.fetchExecutionJobInputProps(10, "job10"); Props fOutputProps = loader.fetchExecutionJobOutputProps(10, "job10"); Pair<Props, Props> inOutProps = loader.fetchExecutionJobProps(10, "job10"); Assert.assertEquals(fInputProps.get("test"), "test2"); Assert.assertEquals(fOutputProps.get("hello"), "output"); Assert.assertEquals(inOutProps.getFirst().get("test"), "test2"); Assert.assertEquals(inOutProps.getSecond().get("hello"), "output"); }
JdbcExecutorLoader extends AbstractJdbcLoader implements ExecutorLoader { @Override public void unassignExecutor(int executionId) throws ExecutorManagerException { final String UPDATE = "UPDATE execution_flows SET executor_id=NULL where exec_id=?"; QueryRunner runner = createQueryRunner(); try { int rows = runner.update(UPDATE, executionId); if (rows == 0) { throw new ExecutorManagerException(String.format( "Failed to unassign executor for execution : %d ", executionId)); } } catch (SQLException e) { throw new ExecutorManagerException("Error updating execution id " + executionId, e); } } 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); }
@Test public void testUnassignExecutorException() throws ExecutorManagerException, IOException { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); try { loader.unassignExecutor(2); Assert.fail("Expecting exception, but didn't get one"); } catch (ExecutorManagerException ex) { System.out.println("Test true"); } } @Test public void testUnassignExecutor() throws ExecutorManagerException, IOException { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); String host = "localhost"; int port = 12345; Executor executor = loader.addExecutor(host, port); ExecutableFlow flow = TestUtils.createExecutableFlow("exectest1", "exec1"); loader.uploadExecutableFlow(flow); loader.assignExecutor(executor.getId(), flow.getExecutionId()); Assert.assertEquals( loader.fetchExecutorByExecutionId(flow.getExecutionId()), executor); loader.unassignExecutor(flow.getExecutionId()); Assert.assertEquals( loader.fetchExecutorByExecutionId(flow.getExecutionId()), null); }
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); }
@Test public void testFetchMissingExecutorByExecution() throws ExecutorManagerException, IOException { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Assert.assertEquals(loader.fetchExecutorByExecutionId(1), null); }
JdbcExecutorLoader extends AbstractJdbcLoader implements ExecutorLoader { @Override public List<Pair<ExecutionReference, ExecutableFlow>> fetchQueuedFlows() throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchQueuedExecutableFlows flowHandler = new FetchQueuedExecutableFlows(); try { List<Pair<ExecutionReference, ExecutableFlow>> flows = runner.query(FetchQueuedExecutableFlows.FETCH_QUEUED_EXECUTABLE_FLOW, flowHandler); return flows; } catch (SQLException e) { throw new ExecutorManagerException("Error fetching active flows", e); } } 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); }
@Test public void testFetchQueuedFlows() throws ExecutorManagerException, IOException { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Pair<ExecutionReference, ExecutableFlow>> queuedFlows = new LinkedList<Pair<ExecutionReference, ExecutableFlow>>(); ExecutableFlow flow = TestUtils.createExecutableFlow("exectest1", "exec1"); loader.uploadExecutableFlow(flow); ExecutableFlow flow2 = TestUtils.createExecutableFlow("exectest1", "exec2"); loader.uploadExecutableFlow(flow); ExecutionReference ref2 = new ExecutionReference(flow2.getExecutionId()); loader.addActiveExecutableReference(ref2); ExecutionReference ref = new ExecutionReference(flow.getExecutionId()); loader.addActiveExecutableReference(ref); queuedFlows.add(new Pair<ExecutionReference, ExecutableFlow>(ref, flow)); queuedFlows.add(new Pair<ExecutionReference, ExecutableFlow>(ref2, flow2)); Assert.assertArrayEquals(loader.fetchQueuedFlows().toArray(), queuedFlows.toArray()); }
JdbcExecutorLoader extends AbstractJdbcLoader implements ExecutorLoader { @Override public List<Executor> fetchAllExecutors() throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchExecutorHandler executorHandler = new FetchExecutorHandler(); try { List<Executor> executors = runner.query(FetchExecutorHandler.FETCH_ALL_EXECUTORS, executorHandler); return executors; } catch (Exception e) { throw new ExecutorManagerException("Error fetching executors", e); } } 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); }
@Test public void testFetchEmptyExecutors() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Executor> executors = loader.fetchAllExecutors(); Assert.assertEquals(executors.size(), 0); } @Test public void testFetchAllExecutors() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Executor> executors = addTestExecutors(loader); executors.get(0).setActive(false); loader.updateExecutor(executors.get(0)); List<Executor> fetchedExecutors = loader.fetchAllExecutors(); Assert.assertEquals(executors.size(), fetchedExecutors.size()); Assert.assertArrayEquals(executors.toArray(), fetchedExecutors.toArray()); }
JdbcExecutorLoader extends AbstractJdbcLoader implements ExecutorLoader { @Override public List<Executor> fetchActiveExecutors() throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchExecutorHandler executorHandler = new FetchExecutorHandler(); try { List<Executor> executors = runner.query(FetchExecutorHandler.FETCH_ACTIVE_EXECUTORS, executorHandler); return executors; } catch (Exception e) { throw new ExecutorManagerException("Error fetching active executors", e); } } 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); }
@Test public void testFetchEmptyActiveExecutors() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Executor> executors = loader.fetchActiveExecutors(); Assert.assertEquals(executors.size(), 0); } @Test public void testFetchActiveExecutors() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Executor> executors = addTestExecutors(loader); executors.get(0).setActive(false); loader.updateExecutor(executors.get(0)); List<Executor> fetchedExecutors = loader.fetchActiveExecutors(); Assert.assertEquals(executors.size(), fetchedExecutors.size() + 1); executors.remove(0); Assert.assertArrayEquals(executors.toArray(), fetchedExecutors.toArray()); }
JdbcExecutorLoader extends AbstractJdbcLoader implements ExecutorLoader { @Override public Executor fetchExecutor(String host, int port) throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchExecutorHandler executorHandler = new FetchExecutorHandler(); try { List<Executor> executors = runner.query(FetchExecutorHandler.FETCH_EXECUTOR_BY_HOST_PORT, executorHandler, host, port); if (executors.isEmpty()) { return null; } else { return executors.get(0); } } catch (Exception e) { throw new ExecutorManagerException(String.format( "Error fetching executor %s:%d", host, port), e); } } 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); }
@Test public void testFetchMissingExecutorId() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Executor executor = loader.fetchExecutor(0); Assert.assertEquals(executor, null); } @Test public void testFetchMissingExecutorHostPort() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Executor executor = loader.fetchExecutor("localhost", 12345); Assert.assertEquals(executor, null); } @Test public void testSingleExecutorFetchById() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Executor> executors = addTestExecutors(loader); for (Executor executor : executors) { Executor fetchedExecutor = loader.fetchExecutor(executor.getId()); Assert.assertEquals(executor, fetchedExecutor); } } @Test public void testSingleExecutorFetchHostPort() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Executor> executors = addTestExecutors(loader); for (Executor executor : executors) { Executor fetchedExecutor = loader.fetchExecutor(executor.getHost(), executor.getPort()); Assert.assertEquals(executor, fetchedExecutor); } }
JdbcExecutorLoader extends AbstractJdbcLoader implements ExecutorLoader { @Override public List<ExecutorLogEvent> getExecutorEvents(Executor executor, int num, int offset) throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); ExecutorLogsResultHandler logHandler = new ExecutorLogsResultHandler(); List<ExecutorLogEvent> events = null; try { events = runner.query(ExecutorLogsResultHandler.SELECT_EXECUTOR_EVENTS_ORDER, logHandler, executor.getId(), num, offset); } catch (SQLException e) { throw new ExecutorManagerException( "Failed to fetch events for executor id : " + executor.getId(), e); } return events; } 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); }
@Test public void testFetchEmptyExecutorEvents() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Executor executor = new Executor(1, "localhost", 12345, true); List<ExecutorLogEvent> executorEvents = loader.getExecutorEvents(executor, 5, 0); Assert.assertEquals(executorEvents.size(), 0); }
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); }
@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"); } }
JdbcExecutorLoader extends AbstractJdbcLoader implements ExecutorLoader { @Override public void updateExecutor(Executor executor) throws ExecutorManagerException { final String UPDATE = "UPDATE executors SET host=?, port=?, active=? where id=?"; QueryRunner runner = createQueryRunner(); try { int rows = runner.update(UPDATE, executor.getHost(), executor.getPort(), executor.isActive(), executor.getId()); if (rows == 0) { throw new ExecutorManagerException("No executor with id :" + executor.getId()); } } catch (SQLException e) { throw new ExecutorManagerException("Error inactivating executor " + executor.getId(), e); } } 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); }
@Test public void testMissingExecutorUpdate() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); try { Executor executor = new Executor(1, "localhost", 1234, true); loader.updateExecutor(executor); Assert.fail("Expecting exception, but didn't get one"); } catch (ExecutorManagerException ex) { System.out.println("Test true"); } clearDB(); }
JdbcExecutorLoader extends AbstractJdbcLoader implements ExecutorLoader { @Override public int removeExecutionLogsByTime(long millis) throws ExecutorManagerException { final String DELETE_BY_TIME = "DELETE FROM execution_logs WHERE upload_time < ?"; QueryRunner runner = createQueryRunner(); int updateNum = 0; try { updateNum = runner.update(DELETE_BY_TIME, millis); } catch (SQLException e) { e.printStackTrace(); throw new ExecutorManagerException( "Error deleting old execution_logs before " + millis, e); } return updateNum; } 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); }
@SuppressWarnings("static-access") @Ignore @Test public void testRemoveExecutionLogsByTime() throws ExecutorManagerException, IOException, InterruptedException { ExecutorLoader loader = createLoader(); File logDir = new File(UNIT_BASE_DIR + "logtest"); File[] largelog = { new File(logDir, "largeLog1.log"), new File(logDir, "largeLog2.log"), new File(logDir, "largeLog3.log") }; DateTime time1 = DateTime.now(); loader.uploadLogFile(1, "oldlog", 0, largelog); Thread.currentThread().sleep(5000); loader.uploadLogFile(2, "newlog", 0, largelog); DateTime time2 = time1.plusMillis(2500); int count = loader.removeExecutionLogsByTime(time2.getMillis()); System.out.print("Removed " + count + " records"); LogData logs = loader.fetchLogs(1, "oldlog", 0, 0, 22222); Assert.assertTrue(logs == null); logs = loader.fetchLogs(2, "newlog", 0, 0, 22222); Assert.assertFalse(logs == null); }
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; }
@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()); }
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; }
@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()); }
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; }
@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()); }
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); }
@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 }); }
JobCallbackValidator { public static int validate(String jobName, Props serverProps, Props jobProps, Collection<String> errors) { int maxNumCallback = serverProps.getInt( JobCallbackConstants.MAX_CALLBACK_COUNT_PROPERTY_KEY, JobCallbackConstants.DEFAULT_MAX_CALLBACK_COUNT); int maxPostBodyLength = serverProps.getInt(MAX_POST_BODY_LENGTH_PROPERTY_KEY, DEFAULT_POST_BODY_LENGTH); int totalCallbackCount = 0; for (JobCallbackStatusEnum jobStatus : JobCallbackStatusEnum.values()) { totalCallbackCount += validateBasedOnStatus(jobProps, errors, jobStatus, maxNumCallback, maxPostBodyLength); } if (logger.isDebugEnabled()) { logger.debug("Found " + totalCallbackCount + " job callbacks for job " + jobName); } return totalCallbackCount; } static int validate(String jobName, Props serverProps, Props jobProps, Collection<String> errors); }
@Test public void noJobCallbackProps() { Props jobProps = new Props(); Set<String> errors = new HashSet<String>(); Assert.assertEquals(0, JobCallbackValidator.validate("bogusJob", serverProps, jobProps, errors)); Assert.assertEquals(0, errors.size()); } @Test public void sequenceStartWithZeroProps() { Props jobProps = new Props(); Set<String> errors = new HashSet<String>(); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".0.url", "http: jobProps.put("job.notification." + JobCallbackStatusEnum.COMPLETED.name().toLowerCase() + ".1.url", "http: Assert.assertEquals(1, JobCallbackValidator.validate("bogusJob", serverProps, jobProps, errors)); Assert.assertEquals(1, errors.size()); } @Test public void oneGetJobCallback() { Props jobProps = new Props(); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.url", "http: Set<String> errors = new HashSet<String>(); Assert.assertEquals(1, JobCallbackValidator.validate("bogusJob", serverProps, jobProps, errors)); Assert.assertEquals(0, errors.size()); } @Test public void onePostJobCallback() { Props jobProps = new Props(); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.url", "http: jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.method", JobCallbackConstants.HTTP_POST); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.body", "doc:id"); Set<String> errors = new HashSet<String>(); Assert.assertEquals(1, JobCallbackValidator.validate("bogusJob", serverProps, jobProps, errors)); Assert.assertEquals(0, errors.size()); } @Test public void multiplePostJobCallbacks() { Props jobProps = new Props(); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.url", "http: jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.method", JobCallbackConstants.HTTP_POST); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.body", "doc:id"); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".2.url", "http: jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".2.method", JobCallbackConstants.HTTP_POST); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".2.body", "doc2:id"); Set<String> errors = new HashSet<String>(); Assert.assertEquals(2, JobCallbackValidator.validate("bogusJob", serverProps, jobProps, errors)); Assert.assertEquals(0, errors.size()); } @Test public void noPostBodyJobCallback() { Props jobProps = new Props(); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.url", "http: jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.method", JobCallbackConstants.HTTP_POST); Set<String> errors = new HashSet<String>(); Assert.assertEquals(0, JobCallbackValidator.validate("bogusJob", serverProps, jobProps, errors)); Assert.assertEquals(1, errors.size()); System.out.println(errors); } @Test public void multipleGetJobCallbacks() { Props jobProps = new Props(); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.url", "http: jobProps.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", "http: Set<String> errors = new HashSet<String>(); Assert.assertEquals(2, JobCallbackValidator.validate("bogusJob", serverProps, jobProps, errors)); Assert.assertEquals(0, errors.size()); } @Test public void multipleGetJobCallbackWithGap() { Props jobProps = new Props(); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.url", "http: jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".2.url", "http: jobProps.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".2.url", "http: Set<String> errors = new HashSet<String>(); Assert.assertEquals(2, JobCallbackValidator.validate("bogusJob", serverProps, jobProps, errors)); Assert.assertEquals(0, errors.size()); } @Test public void postBodyLengthTooLargeTest() { Props jobProps = new Props(); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.url", "http: jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.method", JobCallbackConstants.HTTP_POST); String postBodyValue = "abcdefghijklmnopqrstuvwxyz"; int postBodyLength = 20; Assert.assertTrue(postBodyValue.length() > postBodyLength); jobProps.put("job.notification." + JobCallbackStatusEnum.FAILURE.name().toLowerCase() + ".1.body", postBodyValue); Props localServerProps = new Props(); localServerProps.put(MAX_POST_BODY_LENGTH_PROPERTY_KEY, postBodyLength); Set<String> errors = new HashSet<String>(); Assert.assertEquals(0, JobCallbackValidator.validate("bogusJob", localServerProps, jobProps, errors)); System.out.println(errors); Assert.assertEquals(1, errors.size()); }
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); }
@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()); }
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); }
@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()); } } }
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); }
@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()); }
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); }
@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); }
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; }
@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")); }
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; }
@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")); }
PropsUtils { public static Props resolveProps(Props props) { if (props == null) return null; Props resolvedProps = new Props(); LinkedHashSet<String> visitedVariables = new LinkedHashSet<String>(); for (String key : props.getKeySet()) { String value = props.get(key); visitedVariables.add(key); String replacedValue = resolveVariableReplacement(value, props, visitedVariables); visitedVariables.clear(); resolvedProps.put(key, replacedValue); } for (String key : resolvedProps.getKeySet()) { String value = resolvedProps.get(key); String expressedValue = resolveVariableExpression(value); resolvedProps.put(key, expressedValue); } return resolvedProps; } 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); }
@Test public void testGoodResolveProps() throws IOException { Props propsGrandParent = new Props(); Props propsParent = new Props(propsGrandParent); Props props = new Props(propsParent); props.put("letter", "a"); propsParent.put("letter", "b"); propsGrandParent.put("letter", "c"); Assert.assertEquals("a", props.get("letter")); propsParent.put("my", "name"); propsParent.put("your", "eyes"); propsGrandParent.put("their", "ears"); propsGrandParent.put("your", "hair"); Assert.assertEquals("name", props.get("my")); Assert.assertEquals("eyes", props.get("your")); Assert.assertEquals("ears", props.get("their")); props.put("res1", "${my}"); props.put("res2", "${their} ${letter}"); props.put("res7", "${my} ${res5}"); propsParent.put("res3", "${your} ${their} ${res4}"); propsGrandParent.put("res4", "${letter}"); propsGrandParent.put("res5", "${their}"); propsParent.put("res6", " t ${your} ${your} ${their} ${res5}"); Props resolved = PropsUtils.resolveProps(props); Assert.assertEquals("name", resolved.get("res1")); Assert.assertEquals("ears a", resolved.get("res2")); Assert.assertEquals("eyes ears a", resolved.get("res3")); Assert.assertEquals("a", resolved.get("res4")); Assert.assertEquals("ears", resolved.get("res5")); Assert.assertEquals(" t eyes eyes ears ears", resolved.get("res6")); Assert.assertEquals("name ears", resolved.get("res7")); } @Test public void testInvalidSyntax() throws Exception { Props propsGrandParent = new Props(); Props propsParent = new Props(propsGrandParent); Props props = new Props(propsParent); propsParent.put("my", "name"); props.put("res1", "$(my)"); Props resolved = PropsUtils.resolveProps(props); Assert.assertEquals("$(my)", resolved.get("res1")); } @Test public void testExpressionResolution() throws IOException { Props props = Props.of("normkey", "normal", "num1", "1", "num2", "2", "num3", "3", "variablereplaced", "${num1}", "expression1", "$(1+10)", "expression2", "$(1+10)*2", "expression3", "$($(${num1} + ${num3})*10)", "expression4", "$(${num1} + ${expression3})", "expression5", "$($($(2+3)) + 3) + $(${expression3} + 1)", "expression6", "$(1 + ${normkey})", "expression7", "$(\"${normkey}\" + 1)", "expression8", "${expression1}", "expression9", "$((2+3) + 3)"); Props resolved = PropsUtils.resolveProps(props); Assert.assertEquals("normal", resolved.get("normkey")); Assert.assertEquals("1", resolved.get("num1")); Assert.assertEquals("2", resolved.get("num2")); Assert.assertEquals("3", resolved.get("num3")); Assert.assertEquals("1", resolved.get("variablereplaced")); Assert.assertEquals("11", resolved.get("expression1")); Assert.assertEquals("11*2", resolved.get("expression2")); Assert.assertEquals("40", resolved.get("expression3")); Assert.assertEquals("41", resolved.get("expression4")); Assert.assertEquals("8 + 41", resolved.get("expression5")); Assert.assertEquals("1", resolved.get("expression6")); Assert.assertEquals("normal1", resolved.get("expression7")); Assert.assertEquals("11", resolved.get("expression8")); Assert.assertEquals("8", resolved.get("expression9")); } @Test public void testLookupInterpolate() { Props props = Props.of("YYYY", "${DD:(YYYY)}", "YYYY-1", "${DD:(YYYY-1)}", "MM", "${DD:(MM)}", "MM-1", "${DD:(MM-1)}", "DD", "${DD:(DD)}", "DD-1", "${DD:(DD-1)}", "HH", "${DD:(HH)}", "HH-1", "${DD:(HH-1)}", "HH+2", "${DD:(HH+2)}", "mm", "${DD:(mm)}"); Props resolved = PropsUtils.resolveProps(props); DateTime now = new DateTime(); Assert.assertEquals(now.yearOfEra().getAsString(), resolved.get("YYYY")); Assert.assertEquals(now.plusYears(-1).yearOfEra().getAsString(), resolved.get("YYYY-1")); Assert.assertEquals(DateFormatLookup.paddingZero(now.monthOfYear().getAsString(), 2), resolved.get("MM")); Assert.assertEquals(DateFormatLookup.paddingZero(now.plusMonths(-1).monthOfYear().getAsString(), 2), resolved.get("MM-1")); Assert.assertEquals(DateFormatLookup.paddingZero(now.dayOfMonth().getAsString(), 2), resolved.get("DD")); Assert.assertEquals(DateFormatLookup.paddingZero(now.plusDays(-1).dayOfMonth().getAsString(), 2), resolved.get("DD-1")); Assert.assertEquals(DateFormatLookup.paddingZero(now.hourOfDay().getAsString(), 2), resolved.get("HH")); Assert.assertEquals(DateFormatLookup.paddingZero(now.plusHours(-1).hourOfDay().getAsString(), 2), resolved.get("HH-1")); Assert.assertEquals(DateFormatLookup.paddingZero(now.plusHours(2).hourOfDay().getAsString(), 2), resolved.get("HH+2")); Assert.assertEquals(DateFormatLookup.paddingZero(now.minuteOfHour().getAsString(), 2), resolved.get("mm")); }
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); }
@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"); }
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; }
@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")); } }
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; }
@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"); }
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(); }
@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(); } }
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); }
@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")); }
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); }
@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); }
Money implements Serializable { @Override public String toString() { return format.format(amount); } @Override String toString(); static final NumberFormat format; }
@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(); }
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); }
@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()); }
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); }
@Test public void disable() throws Exception { changeDisable("/disable", true); }