src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
PersonSpecifications { public static Specification<Person> lastNameIsLike(final String searchTerm) { return new Specification<Person>() { @Override public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) { String likePattern = getLikePattern(searchTerm); return cb.like(cb.lower(personRoot.<String>get(Person_.lastName)), likePattern); } private String getLikePattern(final String searchTerm) { StringBuilder pattern = new StringBuilder(); pattern.append(searchTerm.toLowerCase()); pattern.append("%"); return pattern.toString(); } }; } static Specification<Person> lastNameIsLike(final String searchTerm); }
@Test public void lastNameIsLike() { Path lastNamePathMock = mock(Path.class); when(personRootMock.get(Person_.lastName)).thenReturn(lastNamePathMock); Expression lastNameToLowerExpressionMock = mock(Expression.class); when(criteriaBuilderMock.lower(lastNamePathMock)).thenReturn(lastNameToLowerExpressionMock); Predicate lastNameIsLikePredicateMock = mock(Predicate.class); when(criteriaBuilderMock.like(lastNameToLowerExpressionMock, SEARCH_TERM_LIKE_PATTERN)).thenReturn(lastNameIsLikePredicateMock); Specification<Person> actual = PersonSpecifications.lastNameIsLike(SEARCH_TERM); Predicate actualPredicate = actual.toPredicate(personRootMock, criteriaQueryMock, criteriaBuilderMock); verify(personRootMock, times(1)).get(Person_.lastName); verifyNoMoreInteractions(personRootMock); verify(criteriaBuilderMock, times(1)).lower(lastNamePathMock); verify(criteriaBuilderMock, times(1)).like(lastNameToLowerExpressionMock, SEARCH_TERM_LIKE_PATTERN); verifyNoMoreInteractions(criteriaBuilderMock); verifyZeroInteractions(criteriaQueryMock, lastNamePathMock, lastNameIsLikePredicateMock); assertEquals(lastNameIsLikePredicateMock, actualPredicate); }
RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person update(PersonDTO updated) throws PersonNotFoundException { LOGGER.debug("Updating person with information: " + updated); Person person = personRepository.findOne(updated.getId()); if (person == null) { LOGGER.debug("No person found with id: " + updated.getId()); throw new PersonNotFoundException(); } person.update(updated.getFirstName(), updated.getLastName()); return person; } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void update() throws PersonNotFoundException { PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, FIRST_NAME_UPDATED, LAST_NAME_UPDATED); Person person = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personRepositoryMock.findOne(updated.getId())).thenReturn(person); Person returned = personService.update(updated); verify(personRepositoryMock, times(1)).findOne(updated.getId()); verifyNoMoreInteractions(personRepositoryMock); assertPerson(updated, returned); } @Test(expected = PersonNotFoundException.class) public void updateWhenPersonIsNotFound() throws PersonNotFoundException { PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, FIRST_NAME_UPDATED, LAST_NAME_UPDATED); when(personRepositoryMock.findOne(updated.getId())).thenReturn(null); personService.update(updated); verify(personRepositoryMock, times(1)).findOne(updated.getId()); verifyNoMoreInteractions(personRepositoryMock); }
PersonController extends AbstractController { @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody public Long count(@RequestBody SearchDTO searchCriteria) { String searchTerm = searchCriteria.getSearchTerm(); LOGGER.debug("Finding person count for search term: " + searchTerm); return personService.count(searchTerm); } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }
@Test public void count() { SearchDTO searchCriteria = createSearchDTO(); when(personServiceMock.count(searchCriteria.getSearchTerm())).thenReturn(PERSON_COUNT); long personCount = controller.count(searchCriteria); verify(personServiceMock, times(1)).count(searchCriteria.getSearchTerm()); verifyNoMoreInteractions(personServiceMock); assertEquals(PERSON_COUNT, personCount); }
PersonController extends AbstractController { @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) public String delete(@PathVariable("id") Long id, RedirectAttributes attributes) { LOGGER.debug("Deleting person with id: " + id); try { Person deleted = personService.delete(id); addFeedbackMessage(attributes, FEEDBACK_MESSAGE_KEY_PERSON_DELETED, deleted.getName()); } catch (PersonNotFoundException e) { LOGGER.debug("No person found with id: " + id); addErrorMessage(attributes, ERROR_MESSAGE_KEY_DELETED_PERSON_WAS_NOT_FOUND); } return createRedirectViewPath(REQUEST_MAPPING_LIST); } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }
@Test public void delete() throws PersonNotFoundException { Person deleted = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personServiceMock.delete(PERSON_ID)).thenReturn(deleted); initMessageSourceForFeedbackMessage(PersonController.FEEDBACK_MESSAGE_KEY_PERSON_DELETED); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.delete(PERSON_ID, attributes); verify(personServiceMock, times(1)).delete(PERSON_ID); verifyNoMoreInteractions(personServiceMock); assertFeedbackMessage(attributes, PersonController.FEEDBACK_MESSAGE_KEY_PERSON_DELETED); String expectedView = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST); assertEquals(expectedView, view); } @Test public void deleteWhenPersonIsNotFound() throws PersonNotFoundException { when(personServiceMock.delete(PERSON_ID)).thenThrow(new PersonNotFoundException()); initMessageSourceForErrorMessage(PersonController.ERROR_MESSAGE_KEY_DELETED_PERSON_WAS_NOT_FOUND); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.delete(PERSON_ID, attributes); verify(personServiceMock, times(1)).delete(PERSON_ID); verifyNoMoreInteractions(personServiceMock); assertErrorMessage(attributes, PersonController.ERROR_MESSAGE_KEY_DELETED_PERSON_WAS_NOT_FOUND); String expectedView = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST); assertEquals(expectedView, view); }
PersonController extends AbstractController { @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody public List<PersonDTO> search(@RequestBody SearchDTO searchCriteria) { LOGGER.debug("Searching persons with search criteria: " + searchCriteria); String searchTerm = searchCriteria.getSearchTerm(); List<Person> persons = personService.search(searchTerm, searchCriteria.getPageIndex()); LOGGER.debug("Found " + persons.size() + " persons"); return constructDTOs(persons); } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }
@Test public void searchWhenNoPersonsIsFound() { SearchDTO searchCriteria = createSearchDTO(); List<Person> expected = new ArrayList<Person>(); when(personServiceMock.search(searchCriteria.getSearchTerm(), searchCriteria.getPageIndex())).thenReturn(expected); List<PersonDTO> actual = controller.search(searchCriteria); verify(personServiceMock, times(1)).search(searchCriteria.getSearchTerm(), searchCriteria.getPageIndex()); verifyNoMoreInteractions(personServiceMock); assertDtos(expected, actual); } @Test public void search() { SearchDTO searchCriteria = createSearchDTO(); List<Person> expected = createModels(); when(personServiceMock.search(searchCriteria.getSearchTerm(), searchCriteria.getPageIndex())).thenReturn(expected); List<PersonDTO> actual = controller.search(searchCriteria); verify(personServiceMock, times(1)).search(searchCriteria.getSearchTerm(), searchCriteria.getPageIndex()); verifyNoMoreInteractions(personServiceMock); assertDtos(expected, actual); }
PersonController extends AbstractController { @RequestMapping(value = "/person/create", method = RequestMethod.GET) public String showCreatePersonForm(Model model) { LOGGER.debug("Rendering create person form"); model.addAttribute(MODEL_ATTIRUTE_PERSON, new PersonDTO()); return PERSON_ADD_FORM_VIEW; } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }
@Test public void showCreatePersonForm() { Model model = new BindingAwareModelMap(); String view = controller.showCreatePersonForm(model); verifyZeroInteractions(personServiceMock); assertEquals(PersonController.PERSON_ADD_FORM_VIEW, view); PersonDTO added = (PersonDTO) model.asMap().get(PersonController.MODEL_ATTIRUTE_PERSON); assertNotNull(added); assertNull(added.getId()); assertNull(added.getFirstName()); assertNull(added.getLastName()); }
PersonController extends AbstractController { @RequestMapping(value = "/person/create", method = RequestMethod.POST) public String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes) { LOGGER.debug("Create person form was submitted with information: " + created); if (bindingResult.hasErrors()) { return PERSON_ADD_FORM_VIEW; } Person person = personService.create(created); addFeedbackMessage(attributes, FEEDBACK_MESSAGE_KEY_PERSON_CREATED, person.getName()); return createRedirectViewPath(REQUEST_MAPPING_LIST); } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }
@Test public void submitCreatePersonForm() { MockHttpServletRequest mockRequest = new MockHttpServletRequest("/person/create", "POST"); PersonDTO created = PersonTestUtil.createDTO(PERSON_ID, FIRST_NAME, LAST_NAME); Person model = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personServiceMock.create(created)).thenReturn(model); initMessageSourceForFeedbackMessage(PersonController.FEEDBACK_MESSAGE_KEY_PERSON_CREATED); RedirectAttributes attributes = new RedirectAttributesModelMap(); BindingResult result = bindAndValidate(mockRequest, created); String view = controller.submitCreatePersonForm(created, result, attributes); verify(personServiceMock, times(1)).create(created); verifyNoMoreInteractions(personServiceMock); String expectedViewPath = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST); assertEquals(expectedViewPath, view); assertFeedbackMessage(attributes, PersonController.FEEDBACK_MESSAGE_KEY_PERSON_CREATED); verify(personServiceMock, times(1)).create(created); verifyNoMoreInteractions(personServiceMock); } @Test public void submitEmptyCreatePersonForm() { MockHttpServletRequest mockRequest = new MockHttpServletRequest("/person/create", "POST"); PersonDTO created = new PersonDTO(); RedirectAttributes attributes = new RedirectAttributesModelMap(); BindingResult result = bindAndValidate(mockRequest, created); String view = controller.submitCreatePersonForm(created, result, attributes); verifyZeroInteractions(personServiceMock); assertEquals(PersonController.PERSON_ADD_FORM_VIEW, view); assertFieldErrors(result, FIELD_NAME_FIRST_NAME, FIELD_NAME_LAST_NAME); } @Test public void submitCreatePersonFormWithEmptyFirstName() { MockHttpServletRequest mockRequest = new MockHttpServletRequest("/person/create", "POST"); PersonDTO created = PersonTestUtil.createDTO(null, null, LAST_NAME); RedirectAttributes attributes = new RedirectAttributesModelMap(); BindingResult result = bindAndValidate(mockRequest, created); String view = controller.submitCreatePersonForm(created, result, attributes); verifyZeroInteractions(personServiceMock); assertEquals(PersonController.PERSON_ADD_FORM_VIEW, view); assertFieldErrors(result, FIELD_NAME_FIRST_NAME); } @Test public void submitCreatePersonFormWithEmptyLastName() { MockHttpServletRequest mockRequest = new MockHttpServletRequest("/person/create", "POST"); PersonDTO created = PersonTestUtil.createDTO(null, FIRST_NAME, null); RedirectAttributes attributes = new RedirectAttributesModelMap(); BindingResult result = bindAndValidate(mockRequest, created); String view = controller.submitCreatePersonForm(created, result, attributes); verifyZeroInteractions(personServiceMock); assertEquals(PersonController.PERSON_ADD_FORM_VIEW, view); assertFieldErrors(result, FIELD_NAME_LAST_NAME); }
Person { @PrePersist public void prePersist() { Date now = new Date(); creationTime = now; modificationTime = now; } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModificationTime(); long getVersion(); void update(String firstName, String lastName); @PreUpdate void preUpdate(); @PrePersist void prePersist(); @Override String toString(); void setId(Long id); }
@Test public void prePersist() { Person built = Person.getBuilder(FIRST_NAME, LAST_NAME).build(); built.prePersist(); Date creationTime = built.getCreationTime(); Date modificationTime = built.getModificationTime(); assertNotNull(creationTime); assertNotNull(modificationTime); assertEquals(creationTime, modificationTime); }
PersonController extends AbstractController { @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) public String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes) { LOGGER.debug("Rendering edit person form for person with id: " + id); Person person = personService.findById(id); if (person == null) { LOGGER.debug("No person found with id: " + id); addErrorMessage(attributes, ERROR_MESSAGE_KEY_EDITED_PERSON_WAS_NOT_FOUND); return createRedirectViewPath(REQUEST_MAPPING_LIST); } model.addAttribute(MODEL_ATTIRUTE_PERSON, constructFormObject(person)); return PERSON_EDIT_FORM_VIEW; } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }
@Test public void showEditPersonForm() { Person person = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personServiceMock.findById(PERSON_ID)).thenReturn(person); Model model = new BindingAwareModelMap(); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.showEditPersonForm(PERSON_ID, model, attributes); verify(personServiceMock, times(1)).findById(PERSON_ID); verifyNoMoreInteractions(personServiceMock); assertEquals(PersonController.PERSON_EDIT_FORM_VIEW, view); PersonDTO formObject = (PersonDTO) model.asMap().get(PersonController.MODEL_ATTIRUTE_PERSON); assertNotNull(formObject); assertEquals(person.getId(), formObject.getId()); assertEquals(person.getFirstName(), formObject.getFirstName()); assertEquals(person.getLastName(), formObject.getLastName()); } @Test public void showEditPersonFormWhenPersonIsNotFound() { when(personServiceMock.findById(PERSON_ID)).thenReturn(null); initMessageSourceForErrorMessage(PersonController.ERROR_MESSAGE_KEY_EDITED_PERSON_WAS_NOT_FOUND); Model model = new BindingAwareModelMap(); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.showEditPersonForm(PERSON_ID, model, attributes); verify(personServiceMock, times(1)).findById(PERSON_ID); verifyNoMoreInteractions(personServiceMock); String expectedView = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST); assertEquals(expectedView, view); assertErrorMessage(attributes, PersonController.ERROR_MESSAGE_KEY_EDITED_PERSON_WAS_NOT_FOUND); }
PersonController extends AbstractController { @RequestMapping(value = "/person/edit", method = RequestMethod.POST) public String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes) { LOGGER.debug("Edit person form was submitted with information: " + updated); if (bindingResult.hasErrors()) { LOGGER.debug("Edit person form contains validation errors. Rendering form view."); return PERSON_EDIT_FORM_VIEW; } try { Person person = personService.update(updated); addFeedbackMessage(attributes, FEEDBACK_MESSAGE_KEY_PERSON_EDITED, person.getName()); } catch (PersonNotFoundException e) { LOGGER.debug("No person was found with id: " + updated.getId()); addErrorMessage(attributes, ERROR_MESSAGE_KEY_EDITED_PERSON_WAS_NOT_FOUND); } return createRedirectViewPath(REQUEST_MAPPING_LIST); } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }
@Test public void submitEditPersonForm() throws PersonNotFoundException { MockHttpServletRequest mockRequest = new MockHttpServletRequest("/person/edit", "POST"); PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, FIRST_NAME_UPDATED, LAST_NAME_UPDATED); Person person = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME_UPDATED, LAST_NAME_UPDATED); when(personServiceMock.update(updated)).thenReturn(person); initMessageSourceForFeedbackMessage(PersonController.FEEDBACK_MESSAGE_KEY_PERSON_EDITED); BindingResult bindingResult = bindAndValidate(mockRequest, updated); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.submitEditPersonForm(updated, bindingResult, attributes); verify(personServiceMock, times(1)).update(updated); verifyNoMoreInteractions(personServiceMock); String expectedView = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST); assertEquals(expectedView, view); assertFeedbackMessage(attributes, PersonController.FEEDBACK_MESSAGE_KEY_PERSON_EDITED); assertEquals(updated.getFirstName(), person.getFirstName()); assertEquals(updated.getLastName(), person.getLastName()); } @Test public void submitEditPersonFormWhenPersonIsNotFound() throws PersonNotFoundException { MockHttpServletRequest mockRequest = new MockHttpServletRequest("/person/edit", "POST"); PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, FIRST_NAME_UPDATED, LAST_NAME_UPDATED); when(personServiceMock.update(updated)).thenThrow(new PersonNotFoundException()); initMessageSourceForErrorMessage(PersonController.ERROR_MESSAGE_KEY_EDITED_PERSON_WAS_NOT_FOUND); BindingResult bindingResult = bindAndValidate(mockRequest, updated); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.submitEditPersonForm(updated, bindingResult, attributes); verify(personServiceMock, times(1)).update(updated); verifyNoMoreInteractions(personServiceMock); String expectedView = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST); assertEquals(expectedView, view); assertErrorMessage(attributes, PersonController.ERROR_MESSAGE_KEY_EDITED_PERSON_WAS_NOT_FOUND); } @Test public void submitEmptyEditPersonForm() { MockHttpServletRequest mockRequest = new MockHttpServletRequest("/person/edit", "POST"); PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, null, null); BindingResult bindingResult = bindAndValidate(mockRequest, updated); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.submitEditPersonForm(updated, bindingResult, attributes); verifyZeroInteractions(personServiceMock); assertEquals(PersonController.PERSON_EDIT_FORM_VIEW, view); assertFieldErrors(bindingResult, FIELD_NAME_FIRST_NAME, FIELD_NAME_LAST_NAME); } @Test public void submitEditPersonFormWhenFirstNameIsEmpty() { MockHttpServletRequest mockRequest = new MockHttpServletRequest("/person/edit", "POST"); PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, null, LAST_NAME_UPDATED); BindingResult bindingResult = bindAndValidate(mockRequest, updated); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.submitEditPersonForm(updated, bindingResult, attributes); verifyZeroInteractions(personServiceMock); assertEquals(PersonController.PERSON_EDIT_FORM_VIEW, view); assertFieldErrors(bindingResult, FIELD_NAME_FIRST_NAME); } @Test public void submitEditPersonFormWhenLastNameIsEmpty() { MockHttpServletRequest mockRequest = new MockHttpServletRequest("/person/edit", "POST"); PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, FIRST_NAME_UPDATED, null); BindingResult bindingResult = bindAndValidate(mockRequest, updated); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.submitEditPersonForm(updated, bindingResult, attributes); verifyZeroInteractions(personServiceMock); assertEquals(PersonController.PERSON_EDIT_FORM_VIEW, view); assertFieldErrors(bindingResult, FIELD_NAME_LAST_NAME); }
Person { @PreUpdate public void preUpdate() { modificationTime = new Date(); } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModificationTime(); long getVersion(); void update(String firstName, String lastName); @PreUpdate void preUpdate(); @PrePersist void prePersist(); @Override String toString(); void setId(Long id); }
@Test public void preUpdate() { Person built = Person.getBuilder(FIRST_NAME, LAST_NAME).build(); built.prePersist(); try { Thread.sleep(1000); } catch (InterruptedException e) { } built.preUpdate(); Date creationTime = built.getCreationTime(); Date modificationTime = built.getModificationTime(); assertNotNull(creationTime); assertNotNull(modificationTime); assertTrue(modificationTime.after(creationTime)); }
PersonController extends AbstractController { @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) public String showList(Model model) { LOGGER.debug("Rendering person list page"); List<Person> persons = personService.findAll(); model.addAttribute(MODEL_ATTRIBUTE_PERSONS, persons); model.addAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA, new SearchDTO()); return PERSON_LIST_VIEW; } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }
@Test public void showList() { List<Person> persons = new ArrayList<Person>(); when(personServiceMock.findAll()).thenReturn(persons); Model model = new BindingAwareModelMap(); String view = controller.showList(model); verify(personServiceMock, times(1)).findAll(); verifyNoMoreInteractions(personServiceMock); assertEquals(PersonController.PERSON_LIST_VIEW, view); assertEquals(persons, model.asMap().get(PersonController.MODEL_ATTRIBUTE_PERSONS)); SearchDTO searchCriteria = (SearchDTO) model.asMap().get(PersonController.MODEL_ATTRIBUTE_SEARCH_CRITERIA); assertNotNull(searchCriteria); assertNull(searchCriteria.getSearchTerm()); }
PersonController extends AbstractController { @RequestMapping(value = "/person/search", method=RequestMethod.POST) public String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model) { LOGGER.debug("Rendering search result page for search criteria: " + searchCriteria); model.addAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA, searchCriteria); return PERSON_SEARCH_RESULT_VIEW; } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }
@Test public void showSearchResultPage() { SearchDTO searchCriteria = createSearchDTO(); Model model = new BindingAwareModelMap(); String view = controller.showSearchResultPage(searchCriteria, model); SearchDTO modelAttribute = (SearchDTO) model.asMap().get(PersonController.MODEL_ATTRIBUTE_SEARCH_CRITERIA); assertEquals(searchCriteria.getPageIndex(), modelAttribute.getPageIndex()); assertEquals(searchCriteria.getSearchTerm(), modelAttribute.getSearchTerm()); assertEquals(PersonController.PERSON_SEARCH_RESULT_VIEW, view); }
AbstractController { protected void addErrorMessage(RedirectAttributes model, String code, Object... params) { LOGGER.debug("adding error message with code: " + code + " and params: " + params); Locale current = LocaleContextHolder.getLocale(); LOGGER.debug("Current locale is " + current); String localizedErrorMessage = messageSource.getMessage(code, params, current); LOGGER.debug("Localized message is: " + localizedErrorMessage); model.addFlashAttribute(FLASH_ERROR_MESSAGE, localizedErrorMessage); } }
@Test public void addErrorMessage() { RedirectAttributes model = new RedirectAttributesModelMap(); Object[] params = new Object[0]; when(messageSourceMock.getMessage(eq(ERROR_MESSAGE_CODE), eq(params), any(Locale.class))).thenReturn(ERROR_MESSAGE); controller.addErrorMessage(model, ERROR_MESSAGE_CODE, params); verify(messageSourceMock, times(1)).getMessage(eq(ERROR_MESSAGE_CODE), eq(params), any(Locale.class)); verifyNoMoreInteractions(messageSourceMock); String errorMessage = (String) model.getFlashAttributes().get(FLASH_ERROR_MESSAGE); assertEquals(ERROR_MESSAGE, errorMessage); }
AbstractController { protected void addFeedbackMessage(RedirectAttributes model, String code, Object... params) { LOGGER.debug("Adding feedback message with code: " + code + " and params: " + params); Locale current = LocaleContextHolder.getLocale(); LOGGER.debug("Current locale is " + current); String localizedFeedbackMessage = messageSource.getMessage(code, params, current); LOGGER.debug("Localized message is: " + localizedFeedbackMessage); model.addFlashAttribute(FLASH_FEEDBACK_MESSAGE, localizedFeedbackMessage); } }
@Test public void addFeedbackMessage() { RedirectAttributes model = new RedirectAttributesModelMap(); Object[] params = new Object[0]; when(messageSourceMock.getMessage(eq(FEEDBACK_MESSAGE_CODE), eq(params), any(Locale.class))).thenReturn(FEEDBACK_MESSAGE); controller.addFeedbackMessage(model, FEEDBACK_MESSAGE_CODE, params); verify(messageSourceMock, times(1)).getMessage(eq(FEEDBACK_MESSAGE_CODE), eq(params), any(Locale.class)); verifyNoMoreInteractions(messageSourceMock); String feedbackMessage = (String) model.getFlashAttributes().get(FLASH_FEEDBACK_MESSAGE); assertEquals(FEEDBACK_MESSAGE, feedbackMessage); }
AbstractController { protected String createRedirectViewPath(String path) { StringBuilder builder = new StringBuilder(); builder.append(VIEW_REDIRECT_PREFIX); builder.append(path); return builder.toString(); } }
@Test public void createRedirectViewPath() { String redirectView = controller.createRedirectViewPath(REDIRECT_PATH); String expectedView = buildExpectedRedirectViewPath(REDIRECT_PATH); verifyZeroInteractions(messageSourceMock); assertEquals(expectedView, redirectView); }
PaginatingPersonRepositoryImpl implements PaginatingPersonRepository { @Override public List<Person> findAllPersons() { LOGGER.debug("Finding all persons"); return personRepository.findAll(sortByLastNameAsc()); } PaginatingPersonRepositoryImpl(); @Override List<Person> findAllPersons(); @Override long findPersonCount(String searchTerm); @Override List<Person> findPersonsForPage(String searchTerm, int page); @PostConstruct void init(); }
@Test public void findAllPersons() { repository.findAllPersons(); ArgumentCaptor<Sort> sortArgument = ArgumentCaptor.forClass(Sort.class); verify(personRepositoryMock, times(1)).findAll(sortArgument.capture()); Sort sort = sortArgument.getValue(); assertEquals(Sort.Direction.ASC, sort.getOrderFor(PROPERTY_LASTNAME).getDirection()); }
PaginatingPersonRepositoryImpl implements PaginatingPersonRepository { @Override public long findPersonCount(String searchTerm) { LOGGER.debug("Finding person count with search term: " + searchTerm); return personRepository.count(lastNameIsLike(searchTerm)); } PaginatingPersonRepositoryImpl(); @Override List<Person> findAllPersons(); @Override long findPersonCount(String searchTerm); @Override List<Person> findPersonsForPage(String searchTerm, int page); @PostConstruct void init(); }
@Test public void findPersonCount() { when(personRepositoryMock.count(any(Predicate.class))).thenReturn(PERSON_COUNT); long actual = repository.findPersonCount(SEARCH_TERM); verify(personRepositoryMock, times(1)).count(any(Predicate.class)); verifyNoMoreInteractions(personRepositoryMock); assertEquals(PERSON_COUNT, actual); }
PaginatingPersonRepositoryImpl implements PaginatingPersonRepository { @Override public List<Person> findPersonsForPage(String searchTerm, int page) { LOGGER.debug("Finding persons for page " + page + " with search term: " + searchTerm); Page requestedPage = personRepository.findAll(lastNameIsLike(searchTerm), constructPageSpecification(page)); return requestedPage.getContent(); } PaginatingPersonRepositoryImpl(); @Override List<Person> findAllPersons(); @Override long findPersonCount(String searchTerm); @Override List<Person> findPersonsForPage(String searchTerm, int page); @PostConstruct void init(); }
@Test public void findPersonsForPage() { List<Person> expected = new ArrayList<Person>(); Page foundPage = new PageImpl<Person>(expected); when(personRepositoryMock.findAll(any(Predicate.class), any(Pageable.class))).thenReturn(foundPage); List<Person> actual = repository.findPersonsForPage(SEARCH_TERM, PAGE_INDEX); ArgumentCaptor<Pageable> pageSpecificationArgument = ArgumentCaptor.forClass(Pageable.class); verify(personRepositoryMock, times(1)).findAll(any(Predicate.class), pageSpecificationArgument.capture()); verifyNoMoreInteractions(personRepositoryMock); Pageable pageSpecification = pageSpecificationArgument.getValue(); assertEquals(PAGE_INDEX, pageSpecification.getPageNumber()); assertEquals(PaginatingPersonRepositoryImpl.NUMBER_OF_PERSONS_PER_PAGE, pageSpecification.getPageSize()); assertEquals(Sort.Direction.ASC, pageSpecification.getSort().getOrderFor(PROPERTY_LASTNAME).getDirection()); assertEquals(expected, actual); }
PreCondition { public static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments) { isTrue(expression, String.format(errorMessageTemplate, errorMessageArguments)); } private PreCondition(); static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments); static void isTrue(boolean expression, String errorMessage); static void notEmpty(String string, String errorMessage); static void notNull(Object reference, String errorMessage); }
@Test public void isTrueWithDynamicErrorMessage_ExpressionIsTrue_ShouldNotThrowException() { PreCondition.isTrue(true, "Dynamic error message with parameter: %d", 1L); } @Test public void isTrueWithDynamicErrorMessage_ExpressionIsFalse_ShouldThrowException() { assertThatThrownBy(() -> PreCondition.isTrue(false, "Dynamic error message with parameter: %d", 1L)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Dynamic error message with parameter: 1"); } @Test public void isTrueWithStaticErrorMessage_ExpressionIsTrue_ShouldNotThrowException() { PreCondition.isTrue(true, STATIC_ERROR_MESSAGE); } @Test public void isTrueWithStaticErrorMessage_ExpressionIsFalse_ShouldThrowException() { assertThatThrownBy(() -> PreCondition.isTrue(false, STATIC_ERROR_MESSAGE)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage(STATIC_ERROR_MESSAGE); }
Person { public void update(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModificationTime(); long getVersion(); void update(String firstName, String lastName); @PreUpdate void preUpdate(); @PrePersist void prePersist(); @Override String toString(); void setId(Long id); }
@Test public void update() { Person built = Person.getBuilder(FIRST_NAME, LAST_NAME).build(); built.update(FIRST_NAME_UPDATED, LAST_NAME_UPDATED); assertEquals(FIRST_NAME_UPDATED, built.getFirstName()); assertEquals(LAST_NAME_UPDATED, built.getLastName()); }
PreCondition { public static void notEmpty(String string, String errorMessage) { if (string.isEmpty()) { throw new IllegalArgumentException(errorMessage); } } private PreCondition(); static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments); static void isTrue(boolean expression, String errorMessage); static void notEmpty(String string, String errorMessage); static void notNull(Object reference, String errorMessage); }
@Test public void notEmpty_StringIsNotEmpty_ShouldNotThrowException() { PreCondition.notEmpty(" ", STATIC_ERROR_MESSAGE); } @Test public void notEmpty_StringIsEmpty_ShouldThrowException() { assertThatThrownBy(() -> PreCondition.notEmpty("", STATIC_ERROR_MESSAGE)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage(STATIC_ERROR_MESSAGE); }
PreCondition { public static void notNull(Object reference, String errorMessage) { if (reference == null) { throw new NullPointerException(errorMessage); } } private PreCondition(); static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments); static void isTrue(boolean expression, String errorMessage); static void notEmpty(String string, String errorMessage); static void notNull(Object reference, String errorMessage); }
@Test public void notNull_ObjectIsNotNull_ShouldNotThrowException() { PreCondition.notNull(new Object(), STATIC_ERROR_MESSAGE); } @Test public void notNull_ObjectIsNull_ShouldThrowException() { assertThatThrownBy(() -> PreCondition.notNull(null, STATIC_ERROR_MESSAGE)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage(STATIC_ERROR_MESSAGE); }
RepositoryPersonService implements PersonService { @Transactional @Override public long count(String searchTerm) { LOGGER.debug("Getting person count for search term: " + searchTerm); return personRepository.findPersonCount(searchTerm); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void count() { personService.count(SEARCH_TERM); verify(personRepositoryMock, times(1)).findPersonCount(SEARCH_TERM); verifyNoMoreInteractions(personRepositoryMock); }
RepositoryPersonService implements PersonService { @Transactional @Override public Person create(PersonDTO created) { LOGGER.debug("Creating a new person with information: " + created); Person person = Person.getBuilder(created.getFirstName(), created.getLastName()).build(); return personRepository.save(person); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void create() { PersonDTO created = PersonTestUtil.createDTO(null, FIRST_NAME, LAST_NAME); Person persisted = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personRepositoryMock.save(any(Person.class))).thenReturn(persisted); Person returned = personService.create(created); ArgumentCaptor<Person> personArgument = ArgumentCaptor.forClass(Person.class); verify(personRepositoryMock, times(1)).save(personArgument.capture()); verifyNoMoreInteractions(personRepositoryMock); assertPerson(created, personArgument.getValue()); assertEquals(persisted, returned); }
RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person delete(Long personId) throws PersonNotFoundException { LOGGER.debug("Deleting person with id: " + personId); Person deleted = personRepository.findOne(personId); if (deleted == null) { LOGGER.debug("No person found with id: " + personId); throw new PersonNotFoundException(); } personRepository.delete(deleted); return deleted; } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void delete() throws PersonNotFoundException { Person deleted = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personRepositoryMock.findOne(PERSON_ID)).thenReturn(deleted); Person returned = personService.delete(PERSON_ID); verify(personRepositoryMock, times(1)).findOne(PERSON_ID); verify(personRepositoryMock, times(1)).delete(deleted); verifyNoMoreInteractions(personRepositoryMock); assertEquals(deleted, returned); } @Test(expected = PersonNotFoundException.class) public void deleteWhenPersonIsNotFound() throws PersonNotFoundException { when(personRepositoryMock.findOne(PERSON_ID)).thenReturn(null); personService.delete(PERSON_ID); verify(personRepositoryMock, times(1)).findOne(PERSON_ID); verifyNoMoreInteractions(personRepositoryMock); }
Person { @Transient public String getName() { StringBuilder name = new StringBuilder(); name.append(firstName); name.append(" "); name.append(lastName); return name.toString(); } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModificationTime(); long getVersion(); void update(String firstName, String lastName); @PreUpdate void preUpdate(); @PrePersist void prePersist(); @Override String toString(); void setId(Long id); }
@Test public void getName() { Person built = Person.getBuilder(FIRST_NAME, LAST_NAME).build(); String expectedName = constructName(FIRST_NAME, LAST_NAME); assertEquals(expectedName, built.getName()); }
RepositoryPersonService implements PersonService { @Transactional @Override public long count(String searchTerm) { LOGGER.debug("Getting person count for search term: " + searchTerm); return personRepository.count(lastNameIsLike(searchTerm)); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void count() { when(personRepositoryMock.count(any(Specification.class))).thenReturn(PERSON_COUNT); long personCount = personService.count(SEARCH_TERM); verify(personRepositoryMock, times(1)).count(any(Specification.class)); verifyNoMoreInteractions(personRepositoryMock); assertEquals(PERSON_COUNT, personCount); }
RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> findAll() { LOGGER.debug("Finding all persons"); return personRepository.findAll(sortByLastNameAsc()); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void findAll() { List<Person> persons = new ArrayList<Person>(); when(personRepositoryMock.findAll(any(Sort.class))).thenReturn(persons); List<Person> returned = personService.findAll(); ArgumentCaptor<Sort> sortArgument = ArgumentCaptor.forClass(Sort.class); verify(personRepositoryMock, times(1)).findAll(sortArgument.capture()); verifyNoMoreInteractions(personRepositoryMock); Sort actualSort = sortArgument.getValue(); assertEquals(Sort.Direction.ASC, actualSort.getOrderFor("lastName").getDirection()); assertEquals(persons, returned); }
RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> search(String searchTerm, int pageIndex) { LOGGER.debug("Searching persons with search term: " + searchTerm); Page requestedPage = personRepository.findAll(lastNameIsLike(searchTerm), constructPageSpecification(pageIndex)); return requestedPage.getContent(); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void search() { List<Person> expected = new ArrayList<Person>(); Page expectedPage = new PageImpl(expected); when(personRepositoryMock.findAll(any(Specification.class), any(Pageable.class))).thenReturn(expectedPage); List<Person> actual = personService.search(SEARCH_TERM, PAGE_INDEX); ArgumentCaptor<Pageable> pageArgument = ArgumentCaptor.forClass(Pageable.class); verify(personRepositoryMock, times(1)).findAll(any(Specification.class), pageArgument.capture()); verifyNoMoreInteractions(personRepositoryMock); Pageable pageSpecification = pageArgument.getValue(); assertEquals(PAGE_INDEX, pageSpecification.getPageNumber()); assertEquals(RepositoryPersonService.NUMBER_OF_PERSONS_PER_PAGE, pageSpecification.getPageSize()); assertEquals(Sort.Direction.ASC, pageSpecification.getSort().getOrderFor("lastName").getDirection()); assertEquals(expected, actual); }
RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> findAll() { LOGGER.debug("Finding all persons"); return personRepository.findAllPersons(); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void findAll() { List<Person> persons = new ArrayList<Person>(); when(personRepositoryMock.findAllPersons()).thenReturn(persons); List<Person> returned = personService.findAll(); verify(personRepositoryMock, times(1)).findAllPersons(); verifyNoMoreInteractions(personRepositoryMock); assertEquals(persons, returned); }
RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public Person findById(Long id) { LOGGER.debug("Finding person by id: " + id); return personRepository.findOne(id); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void findById() { Person person = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personRepositoryMock.findOne(PERSON_ID)).thenReturn(person); Person returned = personService.findById(PERSON_ID); verify(personRepositoryMock, times(1)).findOne(PERSON_ID); verifyNoMoreInteractions(personRepositoryMock); assertEquals(person, returned); }
UserService extends BaseService { @Transactional(readOnly = false) public void registerUser(User user, String plainPassword) { entryptPassword(user, plainPassword); generateActKey(user); user.setRoles("user"); user.setRegisterDate(Calendar.getInstance().getTime()); user.setNiceName(user.getLoginName()); user.setStatusCode(UserStatus.Pending.code()); user.setCreatedBy(user.getLoginName()); user.setCreatedWhen(Calendar.getInstance().getTime()); userRepository.save(user); } User getUser(Long id); User findUserByLoginName(String loginName); User findUserByEmail(String email); @Transactional(readOnly = false) void registerUser(User user, String plainPassword); @Transactional(readOnly = false) void createUser(User user, String plainPassword); @Transactional(readOnly = false) void updateUser(User user, String plainPassword); @Transactional(readOnly = false) void updatePassword(User user, String plainPassword); @Transactional(readOnly = false) void deleteUser(Long id); @Transactional(readOnly = false) void activeUser(Long id); @Transactional(readOnly = false) void deactiveUser(Long id); Page<User> getUsers(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType); @Transactional(readOnly = false) void activeUser(String key); void sendResetPwdEmail(User user); @Transactional(readOnly = false) void resetPassword(String key); static final String HASH_ALGORITHM; static final int HASH_INTERATIONS; }
@Test public void registerUser() { User user = UserData.randomNewUser(); userService.registerUser(user, UserData.randomPassword()); assertEquals("user", user.getRoles()); assertNotNull(user.getPassword()); assertNotNull(user.getSalt()); }
UserService extends BaseService { @Transactional(readOnly = false) public void updateUser(User user, String plainPassword) { if (StringUtils.isNotBlank(plainPassword)) { entryptPassword(user, plainPassword); } userRepository.save(user); } User getUser(Long id); User findUserByLoginName(String loginName); User findUserByEmail(String email); @Transactional(readOnly = false) void registerUser(User user, String plainPassword); @Transactional(readOnly = false) void createUser(User user, String plainPassword); @Transactional(readOnly = false) void updateUser(User user, String plainPassword); @Transactional(readOnly = false) void updatePassword(User user, String plainPassword); @Transactional(readOnly = false) void deleteUser(Long id); @Transactional(readOnly = false) void activeUser(Long id); @Transactional(readOnly = false) void deactiveUser(Long id); Page<User> getUsers(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType); @Transactional(readOnly = false) void activeUser(String key); void sendResetPwdEmail(User user); @Transactional(readOnly = false) void resetPassword(String key); static final String HASH_ALGORITHM; static final int HASH_INTERATIONS; }
@Test public void updateUser() { User user = UserData.randomNewUser(); userService.updateUser(user, UserData.randomPassword()); assertNotNull(user.getSalt()); User user2 = UserData.randomNewUser(); userService.updateUser(user2, null); assertNull(user2.getSalt()); }
UserService extends BaseService { @Transactional(readOnly = false) public void deleteUser(Long id) { if (isSupervisor(id)) { logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName()); throw new ServiceException("不能删除超级管理员用户"); } userRepository.delete(id); } User getUser(Long id); User findUserByLoginName(String loginName); User findUserByEmail(String email); @Transactional(readOnly = false) void registerUser(User user, String plainPassword); @Transactional(readOnly = false) void createUser(User user, String plainPassword); @Transactional(readOnly = false) void updateUser(User user, String plainPassword); @Transactional(readOnly = false) void updatePassword(User user, String plainPassword); @Transactional(readOnly = false) void deleteUser(Long id); @Transactional(readOnly = false) void activeUser(Long id); @Transactional(readOnly = false) void deactiveUser(Long id); Page<User> getUsers(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType); @Transactional(readOnly = false) void activeUser(String key); void sendResetPwdEmail(User user); @Transactional(readOnly = false) void resetPassword(String key); static final String HASH_ALGORITHM; static final int HASH_INTERATIONS; }
@Test public void deleteUser() { userService.deleteUser(2L); Mockito.verify(mockUserDao).delete(2L); try { userService.deleteUser(1L); fail("expected ServicExcepton not be thrown"); } catch (ServiceException e) { } Mockito.verify(mockUserDao, Mockito.never()).delete(1L); }
UserService extends BaseService { void entryptPassword(User user, String plainPassword) { byte[] salt = Digests.generateSalt(SALT_SIZE); user.setSalt(Encodes.encodeHex(salt)); byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS); user.setPassword(Encodes.encodeHex(hashPassword)); } User getUser(Long id); User findUserByLoginName(String loginName); User findUserByEmail(String email); @Transactional(readOnly = false) void registerUser(User user, String plainPassword); @Transactional(readOnly = false) void createUser(User user, String plainPassword); @Transactional(readOnly = false) void updateUser(User user, String plainPassword); @Transactional(readOnly = false) void updatePassword(User user, String plainPassword); @Transactional(readOnly = false) void deleteUser(Long id); @Transactional(readOnly = false) void activeUser(Long id); @Transactional(readOnly = false) void deactiveUser(Long id); Page<User> getUsers(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType); @Transactional(readOnly = false) void activeUser(String key); void sendResetPwdEmail(User user); @Transactional(readOnly = false) void resetPassword(String key); static final String HASH_ALGORITHM; static final int HASH_INTERATIONS; }
@Test public void entryptPassword() { User user = UserData.randomNewUser(); userService.entryptPassword(user, "admin"); System.out.println(user.getLoginName()); System.out.println("salt: " + user.getSalt()); System.out.println("entrypt password: " + user.getPassword()); }
MD5DigestCalculatingInputStream extends SdkFilterInputStream { @Override public boolean markSupported() { return super.markSupported() && digestCanBeCloned; } MD5DigestCalculatingInputStream(InputStream in); @Override boolean markSupported(); byte[] getMd5Digest(); @Override void mark(int readlimit); @Override void reset(); @Override int read(); @Override int read(byte[] b, int off, int len); }
@Test public void testMD5CloneSupportedTrue() throws Exception { InputStream in = mock(InputStream.class); doReturn(true).when(in).markSupported();; MD5DigestCalculatingInputStream md5Digest = new MD5DigestCalculatingInputStream(in); assertTrue(md5Digest.markSupported()); } @Test public void testMD5CloneSupportedFalse() throws Exception { InputStream in = mock(InputStream.class); doReturn(false).when(in).markSupported();; MD5DigestCalculatingInputStream md5Digest = new MD5DigestCalculatingInputStream(in); assertFalse(md5Digest.markSupported()); }
AmazonS3Client extends AmazonWebServiceClient implements AmazonS3 { protected Request<CreateBucketRequest> addIAMHeaders(Request<CreateBucketRequest> request, CreateBucketRequest createBucketRequest){ if ((null != this.awsCredentialsProvider ) && (this.awsCredentialsProvider.getCredentials() instanceof IBMOAuthCredentials)) { if (null != createBucketRequest.getServiceInstanceId()) { request.addHeader(Headers.IBM_SERVICE_INSTANCE_ID, createBucketRequest.getServiceInstanceId()); if (null != createBucketRequest.getEncryptionType()) { request.addHeader(Headers.IBM_SSE_KP_ENCRYPTION_ALGORITHM, createBucketRequest.getEncryptionType().getKmsEncryptionAlgorithm()); request.addHeader(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN, createBucketRequest.getEncryptionType().getIBMSSEKMSCustomerRootKeyCrn()); } } else { IBMOAuthCredentials oAuthCreds = (IBMOAuthCredentials)this.awsCredentialsProvider.getCredentials(); if (oAuthCreds.getServiceInstanceId() != null) { request.addHeader(Headers.IBM_SERVICE_INSTANCE_ID, oAuthCreds.getServiceInstanceId()); if (null != createBucketRequest.getEncryptionType()) { request.addHeader(Headers.IBM_SSE_KP_ENCRYPTION_ALGORITHM, createBucketRequest.getEncryptionType().getKmsEncryptionAlgorithm()); request.addHeader(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN, createBucketRequest.getEncryptionType().getIBMSSEKMSCustomerRootKeyCrn()); } } } } return request; } @Deprecated AmazonS3Client(); @Deprecated AmazonS3Client(AWSCredentials awsCredentials); @Deprecated AmazonS3Client(AWSCredentials awsCredentials, ClientConfiguration clientConfiguration); @Deprecated AmazonS3Client(AWSCredentialsProvider credentialsProvider); @Deprecated AmazonS3Client(AWSCredentialsProvider credentialsProvider, ClientConfiguration clientConfiguration); @Deprecated AmazonS3Client(AWSCredentialsProvider credentialsProvider, ClientConfiguration clientConfiguration, RequestMetricCollector requestMetricCollector); @SdkTestInternalApi AmazonS3Client(AWSCredentialsProvider credentialsProvider, ClientConfiguration clientConfiguration, RequestMetricCollector requestMetricCollector, SkipMd5CheckStrategy skipMd5CheckStrategy); @Deprecated AmazonS3Client(ClientConfiguration clientConfiguration); @SdkInternalApi AmazonS3Client(AmazonS3ClientParams s3ClientParams); static AmazonS3ClientBuilder builder(); @Override @Deprecated synchronized void setEndpoint(String endpoint); @Override @Deprecated synchronized void setRegion(com.ibm.cloud.objectstorage.regions.Region region); @Override synchronized void setS3ClientOptions(S3ClientOptions clientOptions); @Override VersionListing listNextBatchOfVersions(VersionListing previousVersionListing); @Override VersionListing listNextBatchOfVersions(ListNextBatchOfVersionsRequest listNextBatchOfVersionsRequest); @Override VersionListing listVersions(String bucketName, String prefix); @Override VersionListing listVersions(String bucketName, String prefix, String keyMarker, String versionIdMarker, String delimiter, Integer maxKeys); @Override VersionListing listVersions(ListVersionsRequest listVersionsRequest); @Override ObjectListing listObjects(String bucketName); @Override ObjectListing listObjects(String bucketName, String prefix); @Override ObjectListing listObjects(ListObjectsRequest listObjectsRequest); @Override ListObjectsV2Result listObjectsV2(String bucketName); @Override ListObjectsV2Result listObjectsV2(String bucketName, String prefix); @Override ListObjectsV2Result listObjectsV2(ListObjectsV2Request listObjectsV2Request); @Override ObjectListing listNextBatchOfObjects(ObjectListing previousObjectListing); @Override ObjectListing listNextBatchOfObjects(ListNextBatchOfObjectsRequest listNextBatchOfObjectsRequest); @Override Owner getS3AccountOwner(); @Override Owner getS3AccountOwner(GetS3AccountOwnerRequest getS3AccountOwnerRequest); @Override List<Bucket> listBuckets(ListBucketsRequest listBucketsRequest); @Override List<Bucket> listBuckets(); @Override ListBucketsExtendedResponse listBucketsExtended(); @Override ListBucketsExtendedResponse listBucketsExtended(ListBucketsExtendedRequest listBucketsExtendedRequest); @Override Bucket createBucket(String bucketName); @Override @Deprecated Bucket createBucket(String bucketName, Region region); @Override @Deprecated Bucket createBucket(String bucketName, String region); @Override Bucket createBucket(CreateBucketRequest createBucketRequest); @Override AccessControlList getObjectAcl(String bucketName, String key); @Override AccessControlList getObjectAcl(String bucketName, String key, String versionId); @Override AccessControlList getObjectAcl(GetObjectAclRequest getObjectAclRequest); @Override void setObjectAcl(String bucketName, String key, AccessControlList acl); @Override void setObjectAcl(String bucketName, String key, CannedAccessControlList acl); @Override void setObjectAcl(String bucketName, String key, String versionId, AccessControlList acl); void setObjectAcl(String bucketName, String key, String versionId, AccessControlList acl, RequestMetricCollector requestMetricCollector); @Override void setObjectAcl(String bucketName, String key, String versionId, CannedAccessControlList acl); void setObjectAcl(String bucketName, String key, String versionId, CannedAccessControlList acl, RequestMetricCollector requestMetricCollector); @Override void setObjectAcl(SetObjectAclRequest setObjectAclRequest); @Override AccessControlList getBucketAcl(String bucketName); @Override AccessControlList getBucketAcl(GetBucketAclRequest getBucketAclRequest); @Override void setBucketAcl(String bucketName, AccessControlList acl); void setBucketAcl(String bucketName, AccessControlList acl, RequestMetricCollector requestMetricCollector); @Override void setBucketAcl(String bucketName, CannedAccessControlList cannedAcl); void setBucketAcl(String bucketName, CannedAccessControlList cannedAcl, RequestMetricCollector requestMetricCollector); @Override void setBucketAcl(SetBucketAclRequest setBucketAclRequest); @Override ObjectMetadata getObjectMetadata(String bucketName, String key); @Override ObjectMetadata getObjectMetadata(GetObjectMetadataRequest getObjectMetadataRequest); @Override S3Object getObject(String bucketName, String key); @Override boolean doesBucketExist(String bucketName); @Override boolean doesBucketExistV2(String bucketName); @Override boolean doesObjectExist(String bucketName, String objectName); @Override HeadBucketResult headBucket(HeadBucketRequest headBucketRequest); @Override void changeObjectStorageClass(String bucketName, String key, StorageClass newStorageClass); @Override void setObjectRedirectLocation(String bucketName, String key, String newRedirectLocation); @Override S3Object getObject(GetObjectRequest getObjectRequest); @Override ObjectMetadata getObject(final GetObjectRequest getObjectRequest, File destinationFile); @Override String getObjectAsString(String bucketName, String key); @Override void deleteBucket(String bucketName); @Override void deleteBucket(DeleteBucketRequest deleteBucketRequest); @Override PutObjectResult putObject(String bucketName, String key, File file); @Override PutObjectResult putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata); @Override PutObjectResult putObject(PutObjectRequest putObjectRequest); @Override CopyObjectResult copyObject(String sourceBucketName, String sourceKey, String destinationBucketName, String destinationKey); @Override CopyObjectResult copyObject(CopyObjectRequest copyObjectRequest); @Override CopyPartResult copyPart(CopyPartRequest copyPartRequest); @Override void deleteObject(String bucketName, String key); @Override void deleteObject(DeleteObjectRequest deleteObjectRequest); @Override DeleteObjectsResult deleteObjects(DeleteObjectsRequest deleteObjectsRequest); @Override void deleteVersion(String bucketName, String key, String versionId); @Override void deleteVersion(DeleteVersionRequest deleteVersionRequest); @Override void setBucketVersioningConfiguration(SetBucketVersioningConfigurationRequest setBucketVersioningConfigurationRequest); @Override BucketVersioningConfiguration getBucketVersioningConfiguration(String bucketName); @Override BucketVersioningConfiguration getBucketVersioningConfiguration(GetBucketVersioningConfigurationRequest getBucketVersioningConfigurationRequest); @Override BucketLifecycleConfiguration getBucketLifecycleConfiguration(String bucketName); @Override BucketLifecycleConfiguration getBucketLifecycleConfiguration(GetBucketLifecycleConfigurationRequest getBucketLifecycleConfigurationRequest); @Override void setBucketLifecycleConfiguration(String bucketName, BucketLifecycleConfiguration bucketLifecycleConfiguration); @Override void setBucketLifecycleConfiguration( SetBucketLifecycleConfigurationRequest setBucketLifecycleConfigurationRequest); @Override void deleteBucketLifecycleConfiguration(String bucketName); @Override void deleteBucketLifecycleConfiguration( DeleteBucketLifecycleConfigurationRequest deleteBucketLifecycleConfigurationRequest); @Override BucketCrossOriginConfiguration getBucketCrossOriginConfiguration(String bucketName); @Override BucketCrossOriginConfiguration getBucketCrossOriginConfiguration(GetBucketCrossOriginConfigurationRequest getBucketCrossOriginConfigurationRequest); @Override void setBucketCrossOriginConfiguration(String bucketName, BucketCrossOriginConfiguration bucketCrossOriginConfiguration); @Override void setBucketCrossOriginConfiguration( SetBucketCrossOriginConfigurationRequest setBucketCrossOriginConfigurationRequest); @Override void deleteBucketCrossOriginConfiguration(String bucketName); @Override void deleteBucketCrossOriginConfiguration( DeleteBucketCrossOriginConfigurationRequest deleteBucketCrossOriginConfigurationRequest); @Override BucketTaggingConfiguration getBucketTaggingConfiguration(String bucketName); @Override BucketTaggingConfiguration getBucketTaggingConfiguration(GetBucketTaggingConfigurationRequest getBucketTaggingConfigurationRequest); @Override void setBucketTaggingConfiguration(String bucketName, BucketTaggingConfiguration bucketTaggingConfiguration); @Override void setBucketTaggingConfiguration( SetBucketTaggingConfigurationRequest setBucketTaggingConfigurationRequest); @Override void deleteBucketTaggingConfiguration(String bucketName); @Override void deleteBucketTaggingConfiguration( DeleteBucketTaggingConfigurationRequest deleteBucketTaggingConfigurationRequest); @Override URL generatePresignedUrl(String bucketName, String key, Date expiration); @Override URL generatePresignedUrl(String bucketName, String key, Date expiration, HttpMethod method); @Override URL generatePresignedUrl(GeneratePresignedUrlRequest req); @Override void abortMultipartUpload(AbortMultipartUploadRequest abortMultipartUploadRequest); @Override CompleteMultipartUploadResult completeMultipartUpload( CompleteMultipartUploadRequest completeMultipartUploadRequest); @Override InitiateMultipartUploadResult initiateMultipartUpload( InitiateMultipartUploadRequest initiateMultipartUploadRequest); @Override MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest listMultipartUploadsRequest); @Override PartListing listParts(ListPartsRequest listPartsRequest); @Override UploadPartResult uploadPart(UploadPartRequest uploadPartRequest); @Override S3ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request); @Override void restoreObject(RestoreObjectRequest restoreObjectRequest); @Override void restoreObject(String bucketName, String key, int expirationInDays); @Override PutObjectResult putObject(String bucketName, String key, String content); String getResourceUrl(String bucketName, String key); @Override URL getUrl(String bucketName, String key); @Override synchronized Region getRegion(); @Override String getRegionName(); AmazonS3Waiters waiters(); @Override void setBucketProtectionConfiguration(SetBucketProtectionConfigurationRequest setBucketProtectionConfigurationRequest); @Override void setBucketProtection(String bucketName, BucketProtectionConfiguration protectionConfiguration); @Override BucketProtectionConfiguration getBucketProtection(String bucketName); @Override BucketProtectionConfiguration getBucketProtectionConfiguration( GetBucketProtectionConfigurationRequest getBucketProtectionRequest); @Override void addLegalHold(String bucketName, String key, String legalHoldId); @Override void addLegalHold(AddLegalHoldRequest addLegalHoldRequest); @Override ListLegalHoldsResult listLegalHolds(String bucketName, String key); @Override ListLegalHoldsResult listLegalHolds(ListLegalHoldsRequest listLegalHoldsRequest); @Override void deleteLegalHold(String bucketName, String key, String legalHoldId); @Override void deleteLegalHold(DeleteLegalHoldRequest deleteLegalHoldRequest); @Override void extendObjectRetention(String bucketName, String key, Long additionalRetentionPeriod, Long extendRetentionFromCurrentTime, Date newRetentionExpirationDate, Long newRetentionPeriod); @Override void extendObjectRetention(ExtendObjectRetentionRequest extendObjectRetentionRequest); FASPConnectionInfo getBucketFaspConnectionInfo(String bucketName); @Override FASPConnectionInfo getBucketFaspConnectionInfo( GetBucketFaspConnectionInfoRequest getBucketFaspConnectionInfoRequest); static final String S3_SERVICE_NAME; static final String OAUTH_SIGNER; }
@Test public void testServiceInstanceRuntimeParamTakesPrecedence() { String serviceInstanceId = "12345"; CreateBucketRequest request = new CreateBucketRequest("testbucket").withServiceInstanceId(serviceInstanceId); Request<CreateBucketRequest> defaultRequest = new DefaultRequest(Constants.S3_SERVICE_DISPLAY_NAME); AmazonS3Client s3Client = new AmazonS3Client(new BasicIBMOAuthCredentials(new TokenMangerUtilTest(), "54321")); defaultRequest = s3Client.addIAMHeaders(defaultRequest, request); assertEquals(defaultRequest.getHeaders().get(Headers.IBM_SERVICE_INSTANCE_ID), serviceInstanceId); } @Test public void testServiceInstanceHeaderIsAddedByCredentialProvdier() { String serviceInstanceId = "12345"; CreateBucketRequest request = new CreateBucketRequest("testbucket"); Request<CreateBucketRequest> defaultRequest = new DefaultRequest(Constants.S3_SERVICE_DISPLAY_NAME); AmazonS3Client s3Client = new AmazonS3Client(new BasicIBMOAuthCredentials(new TokenMangerUtilTest(), serviceInstanceId)); defaultRequest = s3Client.addIAMHeaders(defaultRequest, request); assertEquals(defaultRequest.getHeaders().get(Headers.IBM_SERVICE_INSTANCE_ID), serviceInstanceId); } @Test public void testNoIAMHeadersAreAdded() { CreateBucketRequest request = new CreateBucketRequest("testbucket"); Request<CreateBucketRequest> defaultRequest = new DefaultRequest(Constants.S3_SERVICE_DISPLAY_NAME); AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials("987654321", "123456789")); defaultRequest = s3Client.addIAMHeaders(defaultRequest, request); assertEquals(defaultRequest.getHeaders().get(Headers.IBM_SERVICE_INSTANCE_ID), null); }
StringUtils { public static String fromByteBuffer(ByteBuffer byteBuffer) { return Base64.encodeAsString(copyBytesFrom(byteBuffer)); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }
@Test public void testFromByteBuffer() { String expectedData = "hello world"; String expectedEncodedData = "aGVsbG8gd29ybGQ="; ByteBuffer byteBuffer = ByteBuffer.wrap(expectedData.getBytes()); String encodedData = StringUtils.fromByteBuffer(byteBuffer); assertEquals(expectedEncodedData, encodedData); }
StringUtils { public static String fromByte(Byte b) { return Byte.toString(b); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }
@Test public void testFromByte() { assertEquals("123", StringUtils.fromByte(new Byte("123"))); assertEquals("-99", StringUtils.fromByte(new Byte("-99"))); }
StringUtils { public static String replace( String originalString, String partToMatch, String replacement ) { StringBuilder buffer = new StringBuilder( originalString.length() ); buffer.append( originalString ); int indexOf = buffer.indexOf( partToMatch ); while (indexOf != -1) { buffer = buffer.replace(indexOf, indexOf + partToMatch.length(), replacement); indexOf = buffer.indexOf(partToMatch, indexOf + replacement.length()); } return buffer.toString(); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }
@Test(timeout = 10 * 1000) public void replace_ReplacementStringContainsMatchString_DoesNotCauseInfiniteLoop() { assertEquals("aabc", StringUtils.replace("abc", "a", "aa")); } @Test public void replace_EmptyReplacementString_RemovesAllOccurencesOfMatchString() { assertEquals("bbb", StringUtils.replace("ababab", "a", "")); } @Test public void replace_MatchNotFound_ReturnsOriginalString() { assertEquals("abc", StringUtils.replace("abc", "d", "e")); }
StringUtils { public static String lowerCase(String str) { if(isNullOrEmpty(str)) { return str; } return str.toLowerCase(LOCALE_ENGLISH); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }
@Test public void lowerCase_NonEmptyString() { String input = "x-amz-InvocAtion-typE"; String expected = "x-amz-invocation-type"; assertEquals(expected, StringUtils.lowerCase(input)); } @Test public void lowerCase_NullString() { assertNull(StringUtils.lowerCase(null)); } @Test public void lowerCase_EmptyString() { Assert.assertThat(StringUtils.lowerCase(""), Matchers.isEmptyString()); }
StringUtils { public static String upperCase(String str) { if(isNullOrEmpty(str)) { return str; } return str.toUpperCase(LOCALE_ENGLISH); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }
@Test public void upperCase_NonEmptyString() { String input = "dHkdjj139_)(e"; String expected = "DHKDJJ139_)(E"; assertEquals(expected, StringUtils.upperCase(input)); } @Test public void upperCase_NullString() { assertNull(StringUtils.upperCase((null))); } @Test public void upperCase_EmptyString() { Assert.assertThat(StringUtils.upperCase(""), Matchers.isEmptyString()); }
StringUtils { public static int compare(String str1, String str2) { if( str1 == null || str2 == null) { throw new IllegalArgumentException("Arguments cannot be null"); } Collator collator = Collator.getInstance(LOCALE_ENGLISH); return collator.compare(str1, str2); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }
@Test public void testCompare() { assertTrue(StringUtils.compare("truck", "Car") > 0); assertTrue(StringUtils.compare("", "dd") < 0); assertTrue(StringUtils.compare("dd", "") > 0); assertEquals(0, StringUtils.compare("", "")); assertTrue(StringUtils.compare(" ", "") > 0); } @Test (expected = IllegalArgumentException.class) public void testCompare_String1Null() { String str1 = null; String str2 = "test"; int result = StringUtils.compare(str1, str2); } @Test (expected = IllegalArgumentException.class) public void testCompare_String2Null() { String str1 = "test"; String str2 = null; int result = StringUtils.compare(str1, str2); }
StringUtils { public static boolean beginsWithIgnoreCase(final String data, final String seq) { return data.regionMatches(true, 0, seq, 0, seq.length()); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }
@Test public void begins_with_ignore_case() { Assert.assertTrue(StringUtils.beginsWithIgnoreCase("foobar", "FoO")); } @Test public void begins_with_ignore_case_returns_false_when_seq_doesnot_match() { Assert.assertFalse(StringUtils.beginsWithIgnoreCase("foobar", "baz")); }
StringUtils { public static boolean hasValue(String str) { return !isNullOrEmpty(str); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }
@Test public void hasValue() { Assert.assertTrue(StringUtils.hasValue("something")); Assert.assertFalse(StringUtils.hasValue(null)); Assert.assertFalse(StringUtils.hasValue("")); }
StringUtils { public static Character findFirstOccurrence(String s, char ...charsToMatch) { int lowestIndex = Integer.MAX_VALUE; for (char toMatch : charsToMatch) { int currentIndex = s.indexOf(toMatch); if (currentIndex != -1 && currentIndex < lowestIndex) { lowestIndex = currentIndex; } } return lowestIndex == Integer.MAX_VALUE ? null : s.charAt(lowestIndex); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }
@Test public void findFirstOccurrence() { Assert.assertEquals((Character) ':', StringUtils.findFirstOccurrence("abc:def/ghi:jkl/mno", ':', '/')); Assert.assertEquals((Character) ':', StringUtils.findFirstOccurrence("abc:def/ghi:jkl/mno", '/', ':')); } @Test public void findFirstOccurrence_NoMatch() { Assert.assertNull(StringUtils.findFirstOccurrence("abc", ':')); }
AsperaTransferManager { public void checkMultiSessionAllGlobalConfig(TransferSpecs transferSpecs) { if(asperaTransferManagerConfig.isMultiSession()){ for(TransferSpec transferSpec : transferSpecs.transfer_specs) { transferSpec.setRemote_host(updateRemoteHost(transferSpec.getRemote_host())); } } } protected AsperaTransferManager(AmazonS3 s3Client, TokenManager tokenManager, AsperaConfig asperaConfig, AsperaTransferManagerConfig asperaTransferManagerConfig); Future<AsperaTransaction> upload(String bucket, File localFileName, String remoteFileName); Future<AsperaTransaction> upload(String bucket, File localFileName, String remoteFileName, AsperaConfig sessionDetails, ProgressListener progressListener); Future<AsperaTransaction> download(String bucket, File localFileName, String remoteFileName); Future<AsperaTransaction> download(String bucket, File localFileName, String remoteFileName, AsperaConfig sessionDetails, ProgressListener listenerChain); Future<AsperaTransaction> downloadDirectory(String bucketName, String virtualDirectoryKeyPrefix, File directory); Future<AsperaTransaction> downloadDirectory(String bucketName, String virtualDirectoryKeyPrefix, File directory, AsperaConfig sessionDetails, ProgressListener progressListener); Future<AsperaTransaction> uploadDirectory(String bucketName, String virtualDirectoryKeyPrefix, File directory, boolean includeSubdirectories); Future<AsperaTransaction> uploadDirectory(String bucketName, String virtualDirectoryKeyPrefix, File directory, boolean includeSubdirectories, AsperaConfig sessionDetails, ProgressListener progressListener); AsperaTransaction processTransfer(String transferSpecStr, String bucketName, String key, String fileName, ProgressListener progressListener); FASPConnectionInfo getFaspConnectionInfo(String bucketName); TransferSpecs getTransferSpec(FASPConnectionInfo faspConnectionInfo, String localFileName, String remoteFileName, String direction); void checkMultiSessionAllGlobalConfig(TransferSpecs transferSpecs); void modifyTransferSpec(AsperaConfig sessionDetails, TransferSpecs transferSpecs); void excludeSubdirectories(File directory, TransferSpecs transferSpecs); void shutdownThreadPools(); }
@Test public void testRemoteHostUpdatedWhenAsperaTransferManagerConfigMultiSessionTrue() { AsperaTransferManagerConfig asperaTransferManagerConfig = new AsperaTransferManagerConfig(); asperaTransferManagerConfig.setMultiSession(true); TransferSpec transferSpec = new TransferSpec(); transferSpec.setRemote_host("mysubDomain.domain.realm"); TransferSpecs transferSpecs = new TransferSpecs(); List<TransferSpec> list = new ArrayList<TransferSpec>(); list.add(transferSpec); transferSpecs.setTransfer_specs(list); AsperaTransferManager atm = new AsperaTransferManager(mockS3Client, mockTokenManager, mockAsperaConfig, asperaTransferManagerConfig); atm.checkMultiSessionAllGlobalConfig(transferSpecs); TransferSpec modifiedTransferSpec = transferSpecs.getTransfer_specs().get(0); assertEquals("mysubDomain-all.domain.realm", modifiedTransferSpec.getRemote_host()); } @Test public void testRemoteHostUpdatedWhenAsperaTransferManagerConfigMultiSessionFalse() { PowerMockito .when( AsperaLibraryLoader.load() ).thenReturn("/tmp"); AsperaTransferManagerConfig asperaTransferManagerConfig = new AsperaTransferManagerConfig(); asperaTransferManagerConfig.setMultiSession(false); TransferSpec transferSpec = new TransferSpec(); transferSpec.setRemote_host("mysubDomain.domain.realm"); TransferSpecs transferSpecs = new TransferSpecs(); List<TransferSpec> list = new ArrayList<TransferSpec>(); list.add(transferSpec); transferSpecs.setTransfer_specs(list); AsperaTransferManager atm = new AsperaTransferManager(mockS3Client, mockTokenManager, mockAsperaConfig, asperaTransferManagerConfig); atm.checkMultiSessionAllGlobalConfig(transferSpecs); TransferSpec modifiedTransferSpec = transferSpecs.getTransfer_specs().get(0); assertEquals("mysubDomain.domain.realm", modifiedTransferSpec.getRemote_host()); }
AwsHostNameUtils { @Deprecated public static String parseServiceName(URI endpoint) { String host = endpoint.getHost(); if (!host.endsWith(".amazonaws.com")) { throw new IllegalArgumentException( "Cannot parse a service name from an unrecognized endpoint (" + host + ")."); } String serviceAndRegion = host.substring(0, host.indexOf(".amazonaws.com")); if (serviceAndRegion.endsWith(".s3") || S3_ENDPOINT_PATTERN.matcher(serviceAndRegion).matches()) { return "s3"; } char separator = '.'; if (serviceAndRegion.indexOf(separator) == -1) { return serviceAndRegion; } String service = serviceAndRegion.substring(0, serviceAndRegion.indexOf(separator)); return service; } @Deprecated static String parseRegionName(URI endpoint); @Deprecated static String parseRegionName(final String host, final String serviceHint); static String parseRegion(final String host, final String serviceHint); @Deprecated static String parseServiceName(URI endpoint); static String localHostName(); }
@Test public void testParseServiceName() { assertEquals("iam", AwsHostNameUtils.parseServiceName(IAM_ENDPOINT)); assertEquals("iam", AwsHostNameUtils.parseServiceName(IAM_REGION_ENDPOINT)); assertEquals("ec2", AwsHostNameUtils.parseServiceName(EC2_REGION_ENDPOINT)); assertEquals("s3", AwsHostNameUtils.parseServiceName(S3_ENDPOINT)); assertEquals("s3", AwsHostNameUtils.parseServiceName(S3_BUCKET_ENDPOINT)); assertEquals("s3", AwsHostNameUtils.parseServiceName(S3_REGION_ENDPOINT)); assertEquals("s3", AwsHostNameUtils.parseServiceName(S3_BUCKET_REGION_ENDPOINT)); }
AwsHostNameUtils { @Deprecated public static String parseRegionName(URI endpoint) { return parseRegionName(endpoint.getHost(), null); } @Deprecated static String parseRegionName(URI endpoint); @Deprecated static String parseRegionName(final String host, final String serviceHint); static String parseRegion(final String host, final String serviceHint); @Deprecated static String parseServiceName(URI endpoint); static String localHostName(); }
@Test public void testStandardNoHint() { assertEquals("us-east-1", AwsHostNameUtils.parseRegionName("iam.amazonaws.com", null)); assertEquals("us-west-2", AwsHostNameUtils.parseRegionName("iam.us-west-2.amazonaws.com", null)); assertEquals("us-west-2", AwsHostNameUtils.parseRegionName("ec2.us-west-2.amazonaws.com", null)); assertEquals("us-east-1", AwsHostNameUtils.parseRegionName("s3.amazonaws.com", null)); assertEquals("us-east-1", AwsHostNameUtils.parseRegionName("bucket.name.s3.amazonaws.com", null)); assertEquals("eu-west-1", AwsHostNameUtils.parseRegionName("s3-eu-west-1.amazonaws.com", null)); assertEquals("eu-west-1", AwsHostNameUtils.parseRegionName("s3.eu-west-1.amazonaws.com", null)); assertEquals("eu-west-1", AwsHostNameUtils.parseRegionName("bucket.name.with.periods.s3-eu-west-1.amazonaws.com", null)); assertEquals("eu-west-1", AwsHostNameUtils.parseRegionName("bucket.name.with.periods.s3.eu-west-1.amazonaws.com", null)); assertEquals("us-west-2", AwsHostNameUtils.parseRegionName("cloudsearch.us-west-2.amazonaws.com", null)); assertEquals("us-west-2", AwsHostNameUtils.parseRegionName("domain.us-west-2.cloudsearch.amazonaws.com", null)); } @Test public void testStandard() { assertEquals("us-east-1", AwsHostNameUtils.parseRegionName("iam.amazonaws.com", "iam")); assertEquals("us-west-2", AwsHostNameUtils.parseRegionName("iam.us-west-2.amazonaws.com", "iam")); assertEquals("us-west-2", AwsHostNameUtils.parseRegionName("ec2.us-west-2.amazonaws.com", "ec2")); assertEquals("us-east-1", AwsHostNameUtils.parseRegionName("s3.amazonaws.com", "s3")); assertEquals("us-east-1", AwsHostNameUtils.parseRegionName("bucket.name.s3.amazonaws.com", "s3")); assertEquals("eu-west-1", AwsHostNameUtils.parseRegionName("s3-eu-west-1.amazonaws.com", "s3")); assertEquals("eu-west-1", AwsHostNameUtils.parseRegionName("s3.eu-west-1.amazonaws.com", "s3")); assertEquals("eu-west-1", AwsHostNameUtils.parseRegionName("bucket.name.with.periods.s3-eu-west-1.amazonaws.com", "s3")); assertEquals("eu-west-1", AwsHostNameUtils.parseRegionName("bucket.name.with.periods.s3.eu-west-1.amazonaws.com", "s3")); assertEquals("us-west-2", AwsHostNameUtils.parseRegionName("cloudsearch.us-west-2.amazonaws.com", "cloudsearch")); assertEquals("us-west-2", AwsHostNameUtils.parseRegionName("domain.us-west-2.cloudsearch.amazonaws.com", "cloudsearch")); } @Test public void testBJS() { assertEquals("cn-north-1", AwsHostNameUtils.parseRegionName("iam.cn-north-1.amazonaws.com.cn", "iam")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegionName("ec2.cn-north-1.amazonaws.com.cn", "ec2")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegionName("s3.cn-north-1.amazonaws.com.cn", "s3")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegionName("bucket.name.with.periods.s3.cn-north-1.amazonaws.com.cn", "s3")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegionName("cloudsearch.cn-north-1.amazonaws.com.cn", "cloudsearch")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegionName("domain.cn-north-1.cloudsearch.amazonaws.com.cn", "cloudsearch")); } @Test public void testS3SpecialRegions() { assertEquals("us-east-1", AwsHostNameUtils.parseRegionName("s3-external-1.amazonaws.com", null)); assertEquals("us-east-1", AwsHostNameUtils.parseRegionName("bucket.name.with.periods.s3-external-1.amazonaws.com", null)); assertEquals("us-gov-west-1", AwsHostNameUtils.parseRegionName("s3-fips-us-gov-west-1.amazonaws.com", null)); assertEquals("us-gov-west-1", AwsHostNameUtils.parseRegionName("bucket.name.with.periods.s3-fips-us-gov-west-1.amazonaws.com", null)); }
AwsHostNameUtils { public static String parseRegion(final String host, final String serviceHint) { if (host == null) { throw new IllegalArgumentException("hostname cannot be null"); } String regionNameInInternalConfig = parseRegionNameByInternalConfig(host); if (regionNameInInternalConfig != null) { return regionNameInInternalConfig; } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN .matcher(host); if (matcher.matches()) { return matcher.group(1); } } Pattern pattern = Pattern.compile( "^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\." ); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return matcher.group(1); } } return null; } @Deprecated static String parseRegionName(URI endpoint); @Deprecated static String parseRegionName(final String host, final String serviceHint); static String parseRegion(final String host, final String serviceHint); @Deprecated static String parseServiceName(URI endpoint); static String localHostName(); }
@Test public void testParseRegionWithStandardEndpointsNoHint() { assertEquals("us-east-1", AwsHostNameUtils.parseRegion("iam.amazonaws.com", null)); assertEquals("us-west-2", AwsHostNameUtils.parseRegion("iam.us-west-2.amazonaws.com", null)); assertEquals("us-west-2", AwsHostNameUtils.parseRegion("ec2.us-west-2.amazonaws.com", null)); assertEquals("us-east-1", AwsHostNameUtils.parseRegion("s3.amazonaws.com", null)); assertEquals("us-east-1", AwsHostNameUtils.parseRegion("bucket.name.s3.amazonaws.com", null)); assertEquals("eu-west-1", AwsHostNameUtils.parseRegion("s3-eu-west-1.amazonaws.com", null)); assertEquals("eu-west-1", AwsHostNameUtils.parseRegion("s3.eu-west-1.amazonaws.com", null)); assertEquals("eu-west-1", AwsHostNameUtils.parseRegion("bucket.name.with.periods.s3-eu-west-1.amazonaws.com", null)); assertEquals("eu-west-1", AwsHostNameUtils.parseRegion("bucket.name.with.periods.s3.eu-west-1.amazonaws.com", null)); assertEquals("us-west-2", AwsHostNameUtils.parseRegion("cloudsearch.us-west-2.amazonaws.com", null)); assertEquals("us-west-2", AwsHostNameUtils.parseRegion("domain.us-west-2.cloudsearch.amazonaws.com", null)); } @Test public void testParseRegionWithStandardEndpointsWithServiceHint() { assertEquals("us-east-1", AwsHostNameUtils.parseRegion("iam.amazonaws.com", "iam")); assertEquals("us-west-2", AwsHostNameUtils.parseRegion("iam.us-west-2.amazonaws.com", "iam")); assertEquals("us-west-2", AwsHostNameUtils.parseRegion("ec2.us-west-2.amazonaws.com", "ec2")); assertEquals("us-east-1", AwsHostNameUtils.parseRegion("s3.amazonaws.com", "s3")); assertEquals("us-east-1", AwsHostNameUtils.parseRegion("bucket.name.s3.amazonaws.com", "s3")); assertEquals("eu-west-1", AwsHostNameUtils.parseRegion("s3-eu-west-1.amazonaws.com", "s3")); assertEquals("eu-west-1", AwsHostNameUtils.parseRegion("s3.eu-west-1.amazonaws.com", "s3")); assertEquals("eu-west-1", AwsHostNameUtils.parseRegion("bucket.name.with.periods.s3-eu-west-1.amazonaws.com", "s3")); assertEquals("eu-west-1", AwsHostNameUtils.parseRegion("bucket.name.with.periods.s3.eu-west-1.amazonaws.com", "s3")); assertEquals("us-west-2", AwsHostNameUtils.parseRegion("cloudsearch.us-west-2.amazonaws.com", "cloudsearch")); assertEquals("us-west-2", AwsHostNameUtils.parseRegion("domain.us-west-2.cloudsearch.amazonaws.com", "cloudsearch")); } @Test public void testParseRegionWithBJSEndpoints() { assertEquals("cn-north-1", AwsHostNameUtils.parseRegion("iam.cn-north-1.amazonaws.com.cn", "iam")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegion("ec2.cn-north-1.amazonaws.com.cn", "ec2")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegion("s3.cn-north-1.amazonaws.com.cn", "s3")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegion("bucket.name.with.periods.s3.cn-north-1.amazonaws.com.cn", "s3")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegion("cloudsearch.cn-north-1.amazonaws.com.cn", "cloudsearch")); assertEquals("cn-north-1", AwsHostNameUtils.parseRegion("domain.cn-north-1.cloudsearch.amazonaws.com.cn", "cloudsearch")); } @Test public void testParseRegionWithS3SpecialRegions() { assertEquals("us-east-1", AwsHostNameUtils.parseRegion("s3-external-1.amazonaws.com", null)); assertEquals("us-east-1", AwsHostNameUtils.parseRegion("bucket.name.with.periods.s3-external-1.amazonaws.com", null)); assertEquals("us-gov-west-1", AwsHostNameUtils.parseRegion("s3-fips-us-gov-west-1.amazonaws.com", null)); assertEquals("us-gov-west-1", AwsHostNameUtils.parseRegion("bucket.name.with.periods.s3-fips-us-gov-west-1.amazonaws.com", null)); } @Test public void testParseRegionWithIpv4() { assertNull(AwsHostNameUtils.parseRegion("54.231.16.200", null)); }
AsperaTransferManager { public void modifyTransferSpec(AsperaConfig sessionDetails, TransferSpecs transferSpecs) { for(TransferSpec transferSpec : transferSpecs.transfer_specs) { if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getTargetRateKbps()))) { transferSpec.setTarget_rate_kbps(sessionDetails.getTargetRateKbps()); } if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getTargetRateCapKbps()))) { transferSpec.setTarget_rate_cap_kbps(sessionDetails.getTargetRateCapKbps()); } if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getMinRateCapKbps()))) { transferSpec.setMin_rate_cap_kbps(sessionDetails.getMinRateCapKbps()); } if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getMinRateKbps()))) { transferSpec.setMin_rate_kbps(sessionDetails.getMinRateKbps()); } if (!StringUtils.isNullOrEmpty(sessionDetails.getRatePolicy())) { transferSpec.setRate_policy(sessionDetails.getRatePolicy()); } if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.isLockMinRate()))) { transferSpec.setLock_min_rate(sessionDetails.isLockMinRate()); } if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.isLockTargetRate()))) { transferSpec.setLock_target_rate(sessionDetails.isLockTargetRate()); } if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.isLockRatePolicy()))) { transferSpec.setLock_rate_policy(sessionDetails.isLockRatePolicy()); } if (!StringUtils.isNullOrEmpty(sessionDetails.getDestinationRoot())) { transferSpec.setDestination_root(sessionDetails.getDestinationRoot()); } if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getMultiSession()))) { transferSpec.setMulti_session(sessionDetails.getMultiSession()); } if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getMultiSessionThreshold()))) { transferSpec.setMulti_session_threshold(sessionDetails.getMultiSessionThreshold()); } } } protected AsperaTransferManager(AmazonS3 s3Client, TokenManager tokenManager, AsperaConfig asperaConfig, AsperaTransferManagerConfig asperaTransferManagerConfig); Future<AsperaTransaction> upload(String bucket, File localFileName, String remoteFileName); Future<AsperaTransaction> upload(String bucket, File localFileName, String remoteFileName, AsperaConfig sessionDetails, ProgressListener progressListener); Future<AsperaTransaction> download(String bucket, File localFileName, String remoteFileName); Future<AsperaTransaction> download(String bucket, File localFileName, String remoteFileName, AsperaConfig sessionDetails, ProgressListener listenerChain); Future<AsperaTransaction> downloadDirectory(String bucketName, String virtualDirectoryKeyPrefix, File directory); Future<AsperaTransaction> downloadDirectory(String bucketName, String virtualDirectoryKeyPrefix, File directory, AsperaConfig sessionDetails, ProgressListener progressListener); Future<AsperaTransaction> uploadDirectory(String bucketName, String virtualDirectoryKeyPrefix, File directory, boolean includeSubdirectories); Future<AsperaTransaction> uploadDirectory(String bucketName, String virtualDirectoryKeyPrefix, File directory, boolean includeSubdirectories, AsperaConfig sessionDetails, ProgressListener progressListener); AsperaTransaction processTransfer(String transferSpecStr, String bucketName, String key, String fileName, ProgressListener progressListener); FASPConnectionInfo getFaspConnectionInfo(String bucketName); TransferSpecs getTransferSpec(FASPConnectionInfo faspConnectionInfo, String localFileName, String remoteFileName, String direction); void checkMultiSessionAllGlobalConfig(TransferSpecs transferSpecs); void modifyTransferSpec(AsperaConfig sessionDetails, TransferSpecs transferSpecs); void excludeSubdirectories(File directory, TransferSpecs transferSpecs); void shutdownThreadPools(); }
@Test public void testRemoteHostUpdatedWhenAsperaTransferConfigMultiSession3RunTime() { AsperaConfig asperaConfig = new AsperaConfig(); asperaConfig.setMultiSession(3); TransferSpec transferSpec = new TransferSpec(); TransferSpecs transferSpecs = new TransferSpecs(); List<TransferSpec> list = new ArrayList<TransferSpec>(); list.add(transferSpec); transferSpecs.setTransfer_specs(list); AsperaTransferManager atm = new AsperaTransferManager(mockS3Client, mockTokenManager, mockAsperaConfig, mockAsperaTransferManagerConfig); atm.modifyTransferSpec(asperaConfig, transferSpecs); TransferSpec modifiedTransferSpec = transferSpecs.getTransfer_specs().get(0); assertEquals(3, modifiedTransferSpec.getMulti_session()); } @Test public void testMultiSessionThresholdUpdatedWhenAsperaTransferConfigRunTime() { AsperaConfig asperaConfig = new AsperaConfig(); asperaConfig.setMultiSessionThreshold(70000); TransferSpec transferSpec = new TransferSpec(); TransferSpecs transferSpecs = new TransferSpecs(); List<TransferSpec> list = new ArrayList<TransferSpec>(); list.add(transferSpec); transferSpecs.setTransfer_specs(list); AsperaTransferManager atm = new AsperaTransferManager(mockS3Client, mockTokenManager, mockAsperaConfig, mockAsperaTransferManagerConfig); atm.modifyTransferSpec(asperaConfig, transferSpecs); TransferSpec modifiedTransferSpec = transferSpecs.getTransfer_specs().get(0); assertEquals(70000, modifiedTransferSpec.getMulti_session_threshold()); } @Test public void testMultiSessionFieldIsNotSetToZeroIfDefault() throws JsonProcessingException { AsperaConfig asperaConfig = new AsperaConfig(); TransferSpec transferSpec = new TransferSpec(); TransferSpecs transferSpecs = new TransferSpecs(); List<TransferSpec> list = new ArrayList<TransferSpec>(); list.add(transferSpec); transferSpecs.setTransfer_specs(list); AsperaTransferManager atm = new AsperaTransferManager(mockS3Client, mockTokenManager, mockAsperaConfig, mockAsperaTransferManagerConfig); atm.modifyTransferSpec(asperaConfig, transferSpecs); ObjectMapper mapper = new ObjectMapper(); String transferSpecStr = mapper.writeValueAsString(transferSpecs); System.out.println(transferSpecStr); assertFalse(transferSpecStr.contains("multi_session")); } @Ignore @Test public void testMultiSessionFieldIsSetToZeroIfSpecified() throws JsonProcessingException { AsperaConfig asperaConfig = new AsperaConfig(); asperaConfig.setMultiSession(0); TransferSpec transferSpec = new TransferSpec(); TransferSpecs transferSpecs = new TransferSpecs(); List<TransferSpec> list = new ArrayList<TransferSpec>(); list.add(transferSpec); transferSpecs.setTransfer_specs(list); AsperaTransferManager atm = new AsperaTransferManager(mockS3Client, mockTokenManager, mockAsperaConfig, mockAsperaTransferManagerConfig); atm.modifyTransferSpec(asperaConfig, transferSpecs); ObjectMapper mapper = new ObjectMapper(); String transferSpecStr = mapper.writeValueAsString(transferSpecs); System.out.println(transferSpecStr); assertTrue(transferSpecStr.contains("multi_session")); }
VersionInfoUtils { static String userAgent() { String ua = InternalConfig.Factory.getInternalConfig() .getUserAgentTemplate(); if (ua == null) { return "aws-sdk-java"; } ua = ua .replace("aws","ibm-cos") .replace("{platform}", StringUtils.lowerCase(getPlatform())) .replace("{version}", getVersion()) .replace("{os.name}", replaceSpaces(System.getProperty("os.name"))) .replace("{os.version}", replaceSpaces(System.getProperty("os.version"))) .replace("{java.vm.name}", replaceSpaces(System.getProperty("java.vm.name"))) .replace("{java.vm.version}", replaceSpaces(System.getProperty("java.vm.version"))) .replace("{java.version}", replaceSpaces(System.getProperty("java.version"))) .replace("{additional.languages}", getAdditionalJvmLanguages()); String language = System.getProperty("user.language"); String region = System.getProperty("user.region"); String languageAndRegion = ""; if (language != null && region != null) { languageAndRegion = " " + replaceSpaces(language) + "_" + replaceSpaces(region); } ua = ua.replace("{language.and.region}", languageAndRegion); return ua; } static String getVersion(); static String getPlatform(); static String getUserAgent(); }
@Test public void userAgent() { String userAgent = VersionInfoUtils.userAgent(); assertNotNull(userAgent); }
XpathUtils { public static Document documentFrom(InputStream is) throws SAXException, IOException, ParserConfigurationException { is = new NamespaceRemovingInputStream(is); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(ERROR_HANDLER); Document doc = builder.parse(is); is.close(); return doc; } static XPath xpath(); static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static Double asDouble(String expression, Node node, XPath xpath); static String asString(String expression, Node node); static String asString(String expression, Node node, XPath xpath); static Integer asInteger(String expression, Node node); static Integer asInteger(String expression, Node node, XPath xpath); static Boolean asBoolean(String expression, Node node); static Boolean asBoolean(String expression, Node node, XPath xpath); static Float asFloat(String expression, Node node); static Float asFloat(String expression, Node node, XPath xpath); static Long asLong(String expression, Node node); static Long asLong(String expression, Node node, XPath xpath); static Byte asByte(String expression, Node node); static Byte asByte(String expression, Node node, XPath xpath); static Date asDate(String expression, Node node); static Date asDate(String expression, Node node, XPath xpath); static ByteBuffer asByteBuffer(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node, XPath xpath); static boolean isEmpty(Node node); static Node asNode(String nodeName, Node node); static Node asNode(String nodeName, Node node, XPath xpath); static int nodeLength(NodeList list); }
@Test public void testFromDocumentDoesNotWriteToStderrWhenXmlInvalid() throws SAXException, IOException, ParserConfigurationException { PrintStream err = System.err; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { PrintStream err2 = new PrintStream(bytes); System.setErr(err2); XpathUtils.documentFrom("a"); Assert.fail(); } catch (SAXParseException e) { assertEquals(0, bytes.toByteArray().length); } finally { System.setErr(err); } }
TransferListener extends ITransferListener { public synchronized void setStatus(String xferId, String sessionId, String status, long bytes) { log.trace("TransferListener.setStatus >> " + System.nanoTime() + ": " + new Exception().getStackTrace()[1].getClassName()); if(status.equals("INIT") && isNewSession(xferId, sessionId)) { ascpCount++; } else if (status.equals("DONE") || status.equals("STOP") || status.equals("ARGSTOP")){ removeTransactionSession(xferId, sessionId); removeTransactionFromAudit(xferId); } else if (status.equals("ERROR")) { log.error("Status marked as [ERROR] for xferId [" + xferId + "]"); ascpCount -= numberOfSessionsInTransaction(xferId); removeAllTransactionSessions(xferId); removeTransactionProgressData(xferId); removeTransactionFromAudit(xferId); } if(status.equals("ARGSTOP")) { removeTransactionFromAudit(xferId); removeAllTransactionSessions(xferId); } if(bytes > 0) { updateProgress(xferId, sessionId, status, bytes); } if(status.equals("DONE") || status.equals("STOP")) { if(totalPreTransferBytes.get(xferId) == null || ((bytesTransferred.get(xferId) != null && bytesTransferred.get(xferId) >= totalPreTransferBytes.get(xferId)))) { this.status.put(xferId, status); removeTransactionProgressData(xferId); removeTransactionFromAudit(xferId); log.info("Status marked as [" + status + "] for xferId [" + xferId + "]"); } } else { this.status.put(xferId, status); } log.trace("TransferListener.setStatus << " + System.nanoTime() + ": " + new Exception().getStackTrace()[1].getClassName()); } protected TransferListener(); static TransferListener getInstance(String xferId, AsperaTransaction transaction); synchronized void transferReporter(String xferId, String msg); String getStatus(String xferId); synchronized void setStatus(String xferId, String sessionId, String status, long bytes); static int getAscpCount(); void removeTransaction(String xferid); void removeAllTransactionSessions(String xferId); void shutdownThreadPools(); }
@Test public void testErrorLogWhenStatusUpdatedToError() throws Exception{ PowerMockito.mockStatic(faspmanager2.class); PowerMockito .when( faspmanager2.stopTransfer(anyString()) ).thenReturn(true); TransferListener spyTransferListener = spy(TransferListener.class); spyTransferListener.log = mockLog; spyTransferListener.setStatus("abc123", null, "ERROR", 0); verify(mockLog, times(1)).error(Mockito.eq("Status marked as [ERROR] for xferId [abc123]")); }
AsperaTransferManagerBuilder { public AsperaTransferManager build() { AsperaTransferManager transferManager = new AsperaTransferManager(this.s3Client, this.tokenManager, this.asperaConfig, this.asperaTransferManagerConfig); return transferManager; } AsperaTransferManagerBuilder(String apiKey, AmazonS3 s3Client); AsperaTransferManager build(); AsperaTransferManagerBuilder withTokenManager(TokenManager tokenManager); AsperaTransferManagerBuilder withAsperaTransferManagerConfig(AsperaTransferManagerConfig asperaTransferManagerConfig); AsperaTransferManagerBuilder withAsperaConfig(AsperaConfig asperaConfig); }
@Test public void testExceptionThrownWhenNullS3Client() { expectedEx.expect(SdkClientException.class); new AsperaTransferManagerBuilder("apiKey", null).build(); } @Test public void testExceptionThrownWhenNullS3ApiKey() { expectedEx.expect(SdkClientException.class); new AsperaTransferManagerBuilder(null, mockS3Client).build(); } @Test public void testAsperTransferManagerIsCreated() { AsperaTransferManager transferManager = new AsperaTransferManagerBuilder("apiKey", mockS3Client).build(); assertNotNull(transferManager); }
UriResourcePathUtils { public static String addStaticQueryParamtersToRequest(final Request<?> request, final String uriResourcePath) { if (request == null || uriResourcePath == null) { return null; } String resourcePath = uriResourcePath; int index = resourcePath.indexOf("?"); if (index != -1) { String queryString = resourcePath.substring(index + 1); resourcePath = resourcePath.substring(0, index); for (String s : queryString.split("[;&]")) { index = s.indexOf("="); if (index != -1) { request.addParameter(s.substring(0, index), s.substring(index + 1)); } else { request.addParameter(s, (String)null); } } } return resourcePath; } static String addStaticQueryParamtersToRequest(final Request<?> request, final String uriResourcePath); }
@Test public void request_null_returns_null(){ Assert.assertNull(UriResourcePathUtils.addStaticQueryParamtersToRequest(null, "foo")); } @Test public void uri_resource_path_null_returns_null(){ Assert.assertNull(UriResourcePathUtils .addStaticQueryParamtersToRequest(new DefaultRequest<Object> (null , null), null)); } @Test public void uri_resource_path_doesnot_have_static_query_params_returns_uri_resource_path(){ final String uriResourcePath = "/foo/bar"; Assert.assertEquals(uriResourcePath, UriResourcePathUtils .addStaticQueryParamtersToRequest(new DefaultRequest<Object> (null, null), uriResourcePath)); } @Test public void uri_resource_path_ends_with_question_mark_returns_path_removed_with_question_mark(){ final String expectedResourcePath = "/foo/bar"; final String pathWithEmptyStaticQueryParams = expectedResourcePath + "?"; Assert.assertEquals(expectedResourcePath, UriResourcePathUtils .addStaticQueryParamtersToRequest(new DefaultRequest<Object> (null, null), pathWithEmptyStaticQueryParams)); } @Test public void queryparam_value_empty_adds_parameter_with_empty_string_to_request() { final String uriResourcePath = "/foo/bar"; final String uriResourcePathWithParams = uriResourcePath + "?param1="; final Request<Object> request = new DefaultRequest<Object> (null, null); Assert.assertEquals(uriResourcePath, UriResourcePathUtils .addStaticQueryParamtersToRequest(request, uriResourcePathWithParams)); Assert.assertTrue(request.getParameters().containsKey("param1")); Assert.assertEquals(Arrays.asList(""), request.getParameters().get("param1")); } @Test public void static_queryparams_in_path_added_to_request(){ final String uriResourcePath = "/foo/bar"; final String uriResourcePathWithParams = uriResourcePath + "?param1=value1&param2=value2"; final Request<Object> request = new DefaultRequest<Object> (null, null); Assert.assertEquals(uriResourcePath, UriResourcePathUtils .addStaticQueryParamtersToRequest(request, uriResourcePathWithParams)); Assert.assertTrue(request.getParameters().containsKey("param1")); Assert.assertTrue(request.getParameters().containsKey("param2")); Assert.assertEquals(Arrays.asList("value1"), request.getParameters().get("param1")); Assert.assertEquals(Arrays.asList("value2"), request.getParameters().get("param2")); } @Test public void queryparam_without_value_returns_list_containing_null_value() { final String uriResourcePath = "/foo/bar"; final String uriResourcePathWithParams = uriResourcePath + "?param"; final Request<Object> request = new DefaultRequest<Object>(null, null); Assert.assertEquals(uriResourcePath, UriResourcePathUtils.addStaticQueryParamtersToRequest(request, uriResourcePathWithParams)); Assert.assertTrue(request.getParameters().containsKey("param")); Assert.assertEquals(Arrays.asList((String)null), request.getParameters().get("param")); }
AsperaFaspManagerWrapper { public long startTransfer(final String xferId, final String transferSpecStr) { log.info("Starting transfer with xferId [" + xferId + "]"); if (log.isDebugEnabled()) { log.debug("Transfer Spec for Session with xferId [" + xferId + "]"); log.debug(AsperaTransferManagerUtils.getRedactedJsonString( transferSpecStr, "token")); } log.trace("Calling method [startTransfer] with parameters [\"" + xferId + "\", null, transferSpecStr, transferListener]"); long rtn = faspmanager2.startTransfer(xferId, null, transferSpecStr, asperaTransaction.getTransferListener()); log.trace("Method [startTransfer] returned for xferId [\"" + xferId + "\"] with result: [" + rtn + "]"); return rtn; } AsperaFaspManagerWrapper(); AsperaFaspManagerWrapper(AsperaTransaction asperaTransaction); long startTransfer(final String xferId, final String transferSpecStr); boolean pause(final String xferId); boolean resume(final String xferId); boolean cancel(final String xferId); boolean isRunning(final String xferId); boolean configureLogLocation(final String ascpLogPath); void setAsperaTransaction(AsperaTransaction asperaTransaction); }
@Test public void testInfoLogCallsMadeForStartTransfer() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.startTransfer(anyString(), isNull(String.class), anyString(), any(TransferListener.class)) ).thenReturn(3L); when(mockLog.isDebugEnabled()).thenReturn(false); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(new AsperaTransactionImpl(null, null, null, null, null, null)); wrapper.log = mockLog; long rtn = wrapper.startTransfer("xyz123", "configString1"); assertEquals(3L, rtn); verify(mockLog, times(1)).info(Mockito.eq("Starting transfer with xferId [xyz123]")); } @Test public void testDebugLogCallsMadeForStartTransfer() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.startTransfer(anyString(), isNull(String.class), anyString(), any(TransferListener.class)) ).thenReturn(3L); when(mockLog.isDebugEnabled()).thenReturn(true); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(new AsperaTransactionImpl(null, null, null, null, null, null)); wrapper.log = mockLog; long rtn = wrapper.startTransfer("xyz123", "configString1"); assertEquals(3L, rtn); verify(mockLog, times(1)).debug(Mockito.eq("Transfer Spec for Session with xferId [xyz123]")); } @Test public void testTraceLogCallsMadeForStartTransfer() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.startTransfer(anyString(), isNull(String.class), anyString(), any(TransferListener.class)) ).thenReturn(3L); when(mockLog.isDebugEnabled()).thenReturn(true); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(new AsperaTransactionImpl(null, null, null, null, null, null)); wrapper.log = mockLog; long rtn = wrapper.startTransfer("xyz123", "configString1"); assertEquals(3L, rtn); verify(mockLog, times(1)).trace(Mockito.eq("Calling method [startTransfer] with parameters [\"xyz123\", null, transferSpecStr, transferListener]")); verify(mockLog, times(1)).trace(Mockito.eq("Method [startTransfer] returned for xferId [\"xyz123\"] with result: [3]")); }
AsperaFaspManagerWrapper { public boolean pause(final String xferId) { log.info("Pausing transfer with xferId [" + xferId + "]"); log.trace("Calling method [modifyTransfer] with parameters [\"" + xferId + "\", 4, 0]"); boolean rtn = faspmanager2.modifyTransfer(xferId, 4, 0); log.trace("Method [modifyTransfer] returned for xferId [\"" + xferId + "\"] with result: [" + rtn + "]"); return rtn; } AsperaFaspManagerWrapper(); AsperaFaspManagerWrapper(AsperaTransaction asperaTransaction); long startTransfer(final String xferId, final String transferSpecStr); boolean pause(final String xferId); boolean resume(final String xferId); boolean cancel(final String xferId); boolean isRunning(final String xferId); boolean configureLogLocation(final String ascpLogPath); void setAsperaTransaction(AsperaTransaction asperaTransaction); }
@Test public void testInfoLogCallsMadeForPause() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.modifyTransfer(anyString(), anyInt(), anyLong()) ).thenReturn(true); when(mockLog.isDebugEnabled()).thenReturn(false); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(); wrapper.log = mockLog; boolean rtn = wrapper.pause("xyz123"); assertTrue(rtn); verify(mockLog, times(1)).info(Mockito.eq("Pausing transfer with xferId [xyz123]")); } @Test public void testTraceLogCallsMadeForPause() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.modifyTransfer(anyString(), anyInt(), anyLong()) ).thenReturn(true); when(mockLog.isDebugEnabled()).thenReturn(true); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(); wrapper.log = mockLog; boolean rtn = wrapper.pause("xyz123"); assertTrue(rtn); verify(mockLog, times(1)).trace(Mockito.eq("Calling method [modifyTransfer] with parameters [\"xyz123\", 4, 0]")); verify(mockLog, times(1)).trace(Mockito.eq("Method [modifyTransfer] returned for xferId [\"xyz123\"] with result: [true]")); }
JsonErrorUnmarshaller extends AbstractErrorUnmarshaller<JsonNode> { @Override public AmazonServiceException unmarshall(JsonNode jsonContent) throws Exception { return MAPPER.treeToValue(jsonContent, exceptionClass); } JsonErrorUnmarshaller(Class<? extends AmazonServiceException> exceptionClass, String handledErrorCode); @Override AmazonServiceException unmarshall(JsonNode jsonContent); boolean matchErrorCode(String actualErrorCode); static final JsonErrorUnmarshaller DEFAULT_UNMARSHALLER; }
@Test public void unmarshall_ValidJsonContent_UnmarshallsCorrectly() throws Exception { CustomException ase = (CustomException) unmarshaller.unmarshall(JSON); assertEquals("Some error message", ase.getErrorMessage()); assertEquals("This is a customField", ase.getCustomField()); assertEquals(Integer.valueOf(42), ase.getCustomInt()); } @Test public void unmarshall_InvalidCaseJsonContent_DoesNotUnmarshallCustomFields() throws Exception { CustomException ase = (CustomException) unmarshaller.unmarshall(INVALID_CASE_JSON); assertEquals("Some error message", ase.getErrorMessage()); assertNull(ase.getCustomField()); assertNull(ase.getCustomInt()); }
AsperaFaspManagerWrapper { public boolean resume(final String xferId) { log.info("Resuming transfer with xferId [" + xferId + "]"); log.trace("Calling method [modifyTransfer] with parameters [\"" + xferId + "\", 5, 0]"); boolean rtn = faspmanager2.modifyTransfer(xferId, 5, 0); log.trace("Method [modifyTransfer] returned for xferId [\"" + xferId + "\"] with result: [" + rtn + "]"); return rtn; } AsperaFaspManagerWrapper(); AsperaFaspManagerWrapper(AsperaTransaction asperaTransaction); long startTransfer(final String xferId, final String transferSpecStr); boolean pause(final String xferId); boolean resume(final String xferId); boolean cancel(final String xferId); boolean isRunning(final String xferId); boolean configureLogLocation(final String ascpLogPath); void setAsperaTransaction(AsperaTransaction asperaTransaction); }
@Test public void testInfoLogCallsMadeForResume() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.modifyTransfer(anyString(), anyInt(), anyLong()) ).thenReturn(true); when(mockLog.isDebugEnabled()).thenReturn(false); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(); wrapper.log = mockLog; boolean rtn = wrapper.resume("xyz123"); assertTrue(rtn); verify(mockLog, times(1)).info(Mockito.eq("Resuming transfer with xferId [xyz123]")); } @Test public void testTraceLogCallsMadeForResume() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.modifyTransfer(anyString(), anyInt(), anyLong()) ).thenReturn(true); when(mockLog.isDebugEnabled()).thenReturn(true); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(); wrapper.log = mockLog; boolean rtn = wrapper.resume("xyz123"); assertTrue(rtn); verify(mockLog, times(1)).trace(Mockito.eq("Calling method [modifyTransfer] with parameters [\"xyz123\", 5, 0]")); verify(mockLog, times(1)).trace(Mockito.eq("Method [modifyTransfer] returned for xferId [\"xyz123\"] with result: [true]")); }
ClientConfiguration { public ApacheHttpClientConfig getApacheHttpClientConfig() { return apacheHttpClientConfig; } ClientConfiguration(); ClientConfiguration(ClientConfiguration other); Protocol getProtocol(); void setProtocol(Protocol protocol); ClientConfiguration withProtocol(Protocol protocol); int getMaxConnections(); void setMaxConnections(int maxConnections); ClientConfiguration withMaxConnections(int maxConnections); @Deprecated String getUserAgent(); @Deprecated void setUserAgent(String userAgent); @Deprecated ClientConfiguration withUserAgent(String userAgent); String getUserAgentPrefix(); void setUserAgentPrefix(String prefix); ClientConfiguration withUserAgentPrefix(String prefix); String getUserAgentSuffix(); void setUserAgentSuffix(String suffix); ClientConfiguration withUserAgentSuffix(String suffix); InetAddress getLocalAddress(); void setLocalAddress(InetAddress localAddress); ClientConfiguration withLocalAddress(InetAddress localAddress); Protocol getProxyProtocol(); ClientConfiguration withProxyProtocol(Protocol proxyProtocol); void setProxyProtocol(Protocol proxyProtocol); String getProxyHost(); void setProxyHost(String proxyHost); ClientConfiguration withProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); ClientConfiguration withProxyPort(int proxyPort); ClientConfiguration withDisableSocketProxy(boolean disableSocketProxy); void setDisableSocketProxy(boolean disableSocketProxy); boolean disableSocketProxy(); String getProxyUsername(); void setProxyUsername(String proxyUsername); ClientConfiguration withProxyUsername(String proxyUsername); String getProxyPassword(); void setProxyPassword(String proxyPassword); ClientConfiguration withProxyPassword(String proxyPassword); String getProxyDomain(); void setProxyDomain(String proxyDomain); ClientConfiguration withProxyDomain(String proxyDomain); String getProxyWorkstation(); void setProxyWorkstation(String proxyWorkstation); ClientConfiguration withProxyWorkstation(String proxyWorkstation); String getNonProxyHosts(); void setNonProxyHosts(String nonProxyHosts); ClientConfiguration withNonProxyHosts(String nonProxyHosts); List<ProxyAuthenticationMethod> getProxyAuthenticationMethods(); void setProxyAuthenticationMethods(List<ProxyAuthenticationMethod> proxyAuthenticationMethods); ClientConfiguration withProxyAuthenticationMethods(List<ProxyAuthenticationMethod> proxyAuthenticationMethods); RetryPolicy getRetryPolicy(); void setRetryPolicy(RetryPolicy retryPolicy); ClientConfiguration withRetryPolicy(RetryPolicy retryPolicy); int getMaxErrorRetry(); void setMaxErrorRetry(int maxErrorRetry); ClientConfiguration withMaxErrorRetry(int maxErrorRetry); int getSocketTimeout(); void setSocketTimeout(int socketTimeout); ClientConfiguration withSocketTimeout(int socketTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); ClientConfiguration withConnectionTimeout(int connectionTimeout); int getRequestTimeout(); void setRequestTimeout(int requestTimeout); ClientConfiguration withRequestTimeout(int requestTimeout); int getClientExecutionTimeout(); void setClientExecutionTimeout(int clientExecutionTimeout); ClientConfiguration withClientExecutionTimeout(int clientExecutionTimeout); boolean useReaper(); void setUseReaper(boolean use); ClientConfiguration withReaper(boolean use); boolean useThrottledRetries(); void setUseThrottleRetries(boolean use); ClientConfiguration withThrottledRetries(boolean use); void setMaxConsecutiveRetriesBeforeThrottling(int maxConsecutiveRetriesBeforeThrottling); ClientConfiguration withMaxConsecutiveRetriesBeforeThrottling(int maxConsecutiveRetriesBeforeThrottling); int getMaxConsecutiveRetriesBeforeThrottling(); boolean useGzip(); void setUseGzip(boolean use); ClientConfiguration withGzip(boolean use); int[] getSocketBufferSizeHints(); void setSocketBufferSizeHints(int socketSendBufferSizeHint, int socketReceiveBufferSizeHint); ClientConfiguration withSocketBufferSizeHints(int socketSendBufferSizeHint, int socketReceiveBufferSizeHint); String getSignerOverride(); void setSignerOverride(final String value); ClientConfiguration withSignerOverride(final String value); boolean isPreemptiveBasicProxyAuth(); void setPreemptiveBasicProxyAuth(Boolean preemptiveBasicProxyAuth); ClientConfiguration withPreemptiveBasicProxyAuth(boolean preemptiveBasicProxyAuth); long getConnectionTTL(); void setConnectionTTL(long connectionTTL); ClientConfiguration withConnectionTTL(long connectionTTL); long getConnectionMaxIdleMillis(); void setConnectionMaxIdleMillis(long connectionMaxIdleMillis); ClientConfiguration withConnectionMaxIdleMillis(long connectionMaxIdleMillis); int getValidateAfterInactivityMillis(); void setValidateAfterInactivityMillis(int validateAfterInactivityMillis); ClientConfiguration withValidateAfterInactivityMillis(int validateAfterInactivityMillis); boolean useTcpKeepAlive(); void setUseTcpKeepAlive(final boolean use); ClientConfiguration withTcpKeepAlive(final boolean use); DnsResolver getDnsResolver(); void setDnsResolver(final DnsResolver resolver); ClientConfiguration withDnsResolver(final DnsResolver resolver); boolean getCacheResponseMetadata(); void setCacheResponseMetadata(boolean shouldCache); ClientConfiguration withCacheResponseMetadata(final boolean shouldCache); int getResponseMetadataCacheSize(); void setResponseMetadataCacheSize(int responseMetadataCacheSize); ClientConfiguration withResponseMetadataCacheSize(int responseMetadataCacheSize); ApacheHttpClientConfig getApacheHttpClientConfig(); SecureRandom getSecureRandom(); void setSecureRandom(SecureRandom secureRandom); ClientConfiguration withSecureRandom(SecureRandom secureRandom); boolean isUseExpectContinue(); void setUseExpectContinue(boolean useExpectContinue); ClientConfiguration withUseExpectContinue(boolean useExpectContinue); ClientConfiguration withHeader(String name, String value); void addHeader(String name, String value); Map<String, String> getHeaders(); boolean isDisableHostPrefixInjection(); void setDisableHostPrefixInjection(boolean disableHostPrefixInjection); ClientConfiguration withDisableHostPrefixInjection(boolean disableHostPrefixInjection); TlsKeyManagersProvider getTlsKeyManagersProvider(); ClientConfiguration withTlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider); void setTlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider); static final int DEFAULT_CONNECTION_TIMEOUT; static final int DEFAULT_SOCKET_TIMEOUT; static final int DEFAULT_REQUEST_TIMEOUT; static final int DEFAULT_CLIENT_EXECUTION_TIMEOUT; static final boolean DEFAULT_DISABLE_SOCKET_PROXY; static final int DEFAULT_MAX_CONNECTIONS; static final boolean DEFAULT_USE_EXPECT_CONTINUE; static final String DEFAULT_USER_AGENT; static final RetryPolicy DEFAULT_RETRY_POLICY; static final boolean DEFAULT_USE_REAPER; static final boolean DEFAULT_USE_GZIP; static final long DEFAULT_CONNECTION_TTL; static final long DEFAULT_CONNECTION_MAX_IDLE_MILLIS; static final int DEFAULT_VALIDATE_AFTER_INACTIVITY_MILLIS; static final boolean DEFAULT_TCP_KEEP_ALIVE; static final boolean DEFAULT_THROTTLE_RETRIES; static final boolean DEFAULT_CACHE_RESPONSE_METADATA; static final int DEFAULT_RESPONSE_METADATA_CACHE_SIZE; static final int DEFAULT_MAX_CONSECUTIVE_RETRIES_BEFORE_THROTTLING; }
@Test public void clientConfigurationCopyConstructor_CopiesAllValues() throws Exception { ClientConfiguration customConfig = new ClientConfiguration(); for (Field field : ClientConfiguration.class.getDeclaredFields()) { if (isStaticField(field)) { continue; } field.setAccessible(true); final Class<?> clzz = field.getType(); if (clzz.isAssignableFrom(int.class) || clzz.isAssignableFrom(long.class)) { field.set(customConfig, Math.abs(RANDOM.nextInt())); } else if (clzz.isAssignableFrom(boolean.class)) { field.set(customConfig, !(Boolean) field.get(customConfig)); } else if (clzz.isAssignableFrom(String.class)) { field.set(customConfig, RandomStringUtils.random(10)); } else if (clzz.isAssignableFrom(RetryPolicy.class)) { field.set(customConfig, CUSTOM_RETRY_POLICY); } else if (clzz.isAssignableFrom(InetAddress.class)) { field.set(customConfig, InetAddress.getLocalHost()); } else if (clzz.isAssignableFrom(Protocol.class)) { if (field.getName().equals("protocol")) { field.set(customConfig, Protocol.HTTP); } else { field.set(customConfig, Protocol.HTTPS); } } else if (clzz.isAssignableFrom(DnsResolver.class)) { field.set(customConfig, new MyCustomDnsResolver()); } else if (clzz.isAssignableFrom(SecureRandom.class)) { field.set(customConfig, new SecureRandom()); } else if (field.getName().equals("headers")) { field.set(customConfig, ImmutableMapParameter.of("foo", "bar")); } else if (clzz.isAssignableFrom(ApacheHttpClientConfig.class)) { customConfig.getApacheHttpClientConfig() .setSslSocketFactory(Mockito.mock(ConnectionSocketFactory.class)); } else if (clzz.isAssignableFrom(List.class)) { field.set(customConfig, new ArrayList<Object>()); } else if (clzz.isAssignableFrom(AtomicReference.class)) { if (field.getName().equals("httpProxyHolder")) { field.set(customConfig, new AtomicReference<ClientConfiguration.URLHolder>(new ClientConfiguration.URLHolder())); } } else if (clzz.isAssignableFrom(TlsKeyManagersProvider.class)) { field.set(customConfig, new SystemPropertyTlsKeyManagersProvider()); } else { throw new RuntimeException( String.format("Field %s of type %s is not supported", field.getName(), field.getType())); } assertNotEquals( String.format("Field %s does not differ from default value", field.getName()), field.get(DEFAULT_CLIENT_CONFIG), field.get(customConfig)); } assertReflectionEquals(customConfig, new ClientConfiguration(customConfig)); }
ClientConfiguration { public int getSocketTimeout() { return socketTimeout; } ClientConfiguration(); ClientConfiguration(ClientConfiguration other); Protocol getProtocol(); void setProtocol(Protocol protocol); ClientConfiguration withProtocol(Protocol protocol); int getMaxConnections(); void setMaxConnections(int maxConnections); ClientConfiguration withMaxConnections(int maxConnections); @Deprecated String getUserAgent(); @Deprecated void setUserAgent(String userAgent); @Deprecated ClientConfiguration withUserAgent(String userAgent); String getUserAgentPrefix(); void setUserAgentPrefix(String prefix); ClientConfiguration withUserAgentPrefix(String prefix); String getUserAgentSuffix(); void setUserAgentSuffix(String suffix); ClientConfiguration withUserAgentSuffix(String suffix); InetAddress getLocalAddress(); void setLocalAddress(InetAddress localAddress); ClientConfiguration withLocalAddress(InetAddress localAddress); Protocol getProxyProtocol(); ClientConfiguration withProxyProtocol(Protocol proxyProtocol); void setProxyProtocol(Protocol proxyProtocol); String getProxyHost(); void setProxyHost(String proxyHost); ClientConfiguration withProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); ClientConfiguration withProxyPort(int proxyPort); ClientConfiguration withDisableSocketProxy(boolean disableSocketProxy); void setDisableSocketProxy(boolean disableSocketProxy); boolean disableSocketProxy(); String getProxyUsername(); void setProxyUsername(String proxyUsername); ClientConfiguration withProxyUsername(String proxyUsername); String getProxyPassword(); void setProxyPassword(String proxyPassword); ClientConfiguration withProxyPassword(String proxyPassword); String getProxyDomain(); void setProxyDomain(String proxyDomain); ClientConfiguration withProxyDomain(String proxyDomain); String getProxyWorkstation(); void setProxyWorkstation(String proxyWorkstation); ClientConfiguration withProxyWorkstation(String proxyWorkstation); String getNonProxyHosts(); void setNonProxyHosts(String nonProxyHosts); ClientConfiguration withNonProxyHosts(String nonProxyHosts); List<ProxyAuthenticationMethod> getProxyAuthenticationMethods(); void setProxyAuthenticationMethods(List<ProxyAuthenticationMethod> proxyAuthenticationMethods); ClientConfiguration withProxyAuthenticationMethods(List<ProxyAuthenticationMethod> proxyAuthenticationMethods); RetryPolicy getRetryPolicy(); void setRetryPolicy(RetryPolicy retryPolicy); ClientConfiguration withRetryPolicy(RetryPolicy retryPolicy); int getMaxErrorRetry(); void setMaxErrorRetry(int maxErrorRetry); ClientConfiguration withMaxErrorRetry(int maxErrorRetry); int getSocketTimeout(); void setSocketTimeout(int socketTimeout); ClientConfiguration withSocketTimeout(int socketTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); ClientConfiguration withConnectionTimeout(int connectionTimeout); int getRequestTimeout(); void setRequestTimeout(int requestTimeout); ClientConfiguration withRequestTimeout(int requestTimeout); int getClientExecutionTimeout(); void setClientExecutionTimeout(int clientExecutionTimeout); ClientConfiguration withClientExecutionTimeout(int clientExecutionTimeout); boolean useReaper(); void setUseReaper(boolean use); ClientConfiguration withReaper(boolean use); boolean useThrottledRetries(); void setUseThrottleRetries(boolean use); ClientConfiguration withThrottledRetries(boolean use); void setMaxConsecutiveRetriesBeforeThrottling(int maxConsecutiveRetriesBeforeThrottling); ClientConfiguration withMaxConsecutiveRetriesBeforeThrottling(int maxConsecutiveRetriesBeforeThrottling); int getMaxConsecutiveRetriesBeforeThrottling(); boolean useGzip(); void setUseGzip(boolean use); ClientConfiguration withGzip(boolean use); int[] getSocketBufferSizeHints(); void setSocketBufferSizeHints(int socketSendBufferSizeHint, int socketReceiveBufferSizeHint); ClientConfiguration withSocketBufferSizeHints(int socketSendBufferSizeHint, int socketReceiveBufferSizeHint); String getSignerOverride(); void setSignerOverride(final String value); ClientConfiguration withSignerOverride(final String value); boolean isPreemptiveBasicProxyAuth(); void setPreemptiveBasicProxyAuth(Boolean preemptiveBasicProxyAuth); ClientConfiguration withPreemptiveBasicProxyAuth(boolean preemptiveBasicProxyAuth); long getConnectionTTL(); void setConnectionTTL(long connectionTTL); ClientConfiguration withConnectionTTL(long connectionTTL); long getConnectionMaxIdleMillis(); void setConnectionMaxIdleMillis(long connectionMaxIdleMillis); ClientConfiguration withConnectionMaxIdleMillis(long connectionMaxIdleMillis); int getValidateAfterInactivityMillis(); void setValidateAfterInactivityMillis(int validateAfterInactivityMillis); ClientConfiguration withValidateAfterInactivityMillis(int validateAfterInactivityMillis); boolean useTcpKeepAlive(); void setUseTcpKeepAlive(final boolean use); ClientConfiguration withTcpKeepAlive(final boolean use); DnsResolver getDnsResolver(); void setDnsResolver(final DnsResolver resolver); ClientConfiguration withDnsResolver(final DnsResolver resolver); boolean getCacheResponseMetadata(); void setCacheResponseMetadata(boolean shouldCache); ClientConfiguration withCacheResponseMetadata(final boolean shouldCache); int getResponseMetadataCacheSize(); void setResponseMetadataCacheSize(int responseMetadataCacheSize); ClientConfiguration withResponseMetadataCacheSize(int responseMetadataCacheSize); ApacheHttpClientConfig getApacheHttpClientConfig(); SecureRandom getSecureRandom(); void setSecureRandom(SecureRandom secureRandom); ClientConfiguration withSecureRandom(SecureRandom secureRandom); boolean isUseExpectContinue(); void setUseExpectContinue(boolean useExpectContinue); ClientConfiguration withUseExpectContinue(boolean useExpectContinue); ClientConfiguration withHeader(String name, String value); void addHeader(String name, String value); Map<String, String> getHeaders(); boolean isDisableHostPrefixInjection(); void setDisableHostPrefixInjection(boolean disableHostPrefixInjection); ClientConfiguration withDisableHostPrefixInjection(boolean disableHostPrefixInjection); TlsKeyManagersProvider getTlsKeyManagersProvider(); ClientConfiguration withTlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider); void setTlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider); static final int DEFAULT_CONNECTION_TIMEOUT; static final int DEFAULT_SOCKET_TIMEOUT; static final int DEFAULT_REQUEST_TIMEOUT; static final int DEFAULT_CLIENT_EXECUTION_TIMEOUT; static final boolean DEFAULT_DISABLE_SOCKET_PROXY; static final int DEFAULT_MAX_CONNECTIONS; static final boolean DEFAULT_USE_EXPECT_CONTINUE; static final String DEFAULT_USER_AGENT; static final RetryPolicy DEFAULT_RETRY_POLICY; static final boolean DEFAULT_USE_REAPER; static final boolean DEFAULT_USE_GZIP; static final long DEFAULT_CONNECTION_TTL; static final long DEFAULT_CONNECTION_MAX_IDLE_MILLIS; static final int DEFAULT_VALIDATE_AFTER_INACTIVITY_MILLIS; static final boolean DEFAULT_TCP_KEEP_ALIVE; static final boolean DEFAULT_THROTTLE_RETRIES; static final boolean DEFAULT_CACHE_RESPONSE_METADATA; static final int DEFAULT_RESPONSE_METADATA_CACHE_SIZE; static final int DEFAULT_MAX_CONSECUTIVE_RETRIES_BEFORE_THROTTLING; }
@Test public void copyConstructorUsesAccessors() { ClientConfiguration config = new ClientConfiguration() { @Override public int getSocketTimeout() { return Integer.MAX_VALUE; } }; assertThat(new ClientConfiguration(config).getSocketTimeout(), equalTo(Integer.MAX_VALUE)); }
AmazonWebServiceRequest implements Cloneable, ReadLimitInfo, HandlerContextAware { protected final <T extends AmazonWebServiceRequest> T copyBaseTo(T target) { if (customRequestHeaders != null) { for (Map.Entry<String, String> e : customRequestHeaders.entrySet()) target.putCustomRequestHeader(e.getKey(), e.getValue()); } if (customQueryParameters != null) { for (Map.Entry<String, List<String>> e : customQueryParameters.entrySet()) { if (e.getValue() != null) { for (String value : e.getValue()) { target.putCustomQueryParameter(e.getKey(), value); } } } } target.setRequestCredentialsProvider(credentialsProvider); target.setGeneralProgressListener(progressListener); target.setRequestMetricCollector(requestMetricCollector); requestClientOptions.copyTo(target.getRequestClientOptions()); return target; } @Deprecated void setRequestCredentials(AWSCredentials credentials); @Deprecated AWSCredentials getRequestCredentials(); void setRequestCredentialsProvider(AWSCredentialsProvider credentialsProvider); AWSCredentialsProvider getRequestCredentialsProvider(); RequestClientOptions getRequestClientOptions(); RequestMetricCollector getRequestMetricCollector(); void setRequestMetricCollector(RequestMetricCollector requestMetricCollector); T withRequestMetricCollector(RequestMetricCollector metricCollector); void setGeneralProgressListener(ProgressListener progressListener); ProgressListener getGeneralProgressListener(); T withGeneralProgressListener(ProgressListener progressListener); Map<String, String> getCustomRequestHeaders(); String putCustomRequestHeader(String name, String value); Map<String, List<String>> getCustomQueryParameters(); void putCustomQueryParameter(String name, String value); @Override final int getReadLimit(); AmazonWebServiceRequest getCloneSource(); AmazonWebServiceRequest getCloneRoot(); Integer getSdkRequestTimeout(); void setSdkRequestTimeout(int sdkRequestTimeout); T withSdkRequestTimeout(int sdkRequestTimeout); Integer getSdkClientExecutionTimeout(); void setSdkClientExecutionTimeout(int sdkClientExecutionTimeout); T withSdkClientExecutionTimeout(int sdkClientExecutionTimeout); @Override void addHandlerContext(HandlerContextKey<X> key, X value); @Override @SuppressWarnings("unchecked") X getHandlerContext(HandlerContextKey<X> key); @Override AmazonWebServiceRequest clone(); static final AmazonWebServiceRequest NOOP; }
@Test public void copyBaseTo() { final ProgressListener listener = new SyncProgressListener() { @Override public void progressChanged(ProgressEvent progressEvent) { } }; final AWSCredentials credentials = new BasicAWSCredentials("accesskey", "accessid"); final RequestMetricCollector collector = new RequestMetricCollector() { @Override public void collectMetrics(Request<?> request, Response<?> response) { } }; final AmazonWebServiceRequest from = new AmazonWebServiceRequest() { }; from.setGeneralProgressListener(listener); from.setRequestCredentials(credentials); from.setRequestMetricCollector(collector); from.putCustomRequestHeader("k1", "v1"); from.putCustomRequestHeader("k2", "v2"); from.putCustomQueryParameter("k1", "v1"); from.putCustomQueryParameter("k2", "v2a"); from.putCustomQueryParameter("k2", "v2b"); from.getRequestClientOptions().setReadLimit(1234); final AmazonWebServiceRequest to = new AmazonWebServiceRequest() { }; RequestClientOptions toOptions; verifyBaseBeforeCopy(to); from.copyBaseTo(to); verifyBaseAfterCopy(listener, credentials, collector, from, to); }
RetryPolicyAdapter implements com.ibm.cloud.objectstorage.retry.v2.RetryPolicy { public RetryPolicy getLegacyRetryPolicy() { return this.legacyRetryPolicy; } RetryPolicyAdapter(RetryPolicy legacyRetryPolicy, ClientConfiguration clientConfiguration); @Override long computeDelayBeforeNextRetry(RetryPolicyContext context); @Override boolean shouldRetry(RetryPolicyContext context); boolean isRetryable(RetryPolicyContext context); RetryPolicy getLegacyRetryPolicy(); boolean maxRetriesExceeded(RetryPolicyContext context); }
@Test public void getLegacyRetryPolicy_ReturnsSamePolicy() { assertEquals(legacyPolicy, adapter.getLegacyRetryPolicy()); }
RetryPolicyAdapter implements com.ibm.cloud.objectstorage.retry.v2.RetryPolicy { @Override public long computeDelayBeforeNextRetry(RetryPolicyContext context) { return legacyRetryPolicy.getBackoffStrategy().delayBeforeNextRetry( (AmazonWebServiceRequest) context.originalRequest(), (AmazonClientException) context.exception(), context.retriesAttempted()); } RetryPolicyAdapter(RetryPolicy legacyRetryPolicy, ClientConfiguration clientConfiguration); @Override long computeDelayBeforeNextRetry(RetryPolicyContext context); @Override boolean shouldRetry(RetryPolicyContext context); boolean isRetryable(RetryPolicyContext context); RetryPolicy getLegacyRetryPolicy(); boolean maxRetriesExceeded(RetryPolicyContext context); }
@Test public void computeDelayBeforeNextRetry_DelegatesToLegacyPolicy() { final RetryPolicyContext context = RetryPolicyContexts.LEGACY; adapter.computeDelayBeforeNextRetry(context); verify(backoffStrategy).delayBeforeNextRetry( eq((AmazonWebServiceRequest) context.originalRequest()), eq((AmazonClientException) context.exception()), eq(context.retriesAttempted())); }
RetryPolicyAdapter implements com.ibm.cloud.objectstorage.retry.v2.RetryPolicy { @Override public boolean shouldRetry(RetryPolicyContext context) { return !maxRetriesExceeded(context) && isRetryable(context); } RetryPolicyAdapter(RetryPolicy legacyRetryPolicy, ClientConfiguration clientConfiguration); @Override long computeDelayBeforeNextRetry(RetryPolicyContext context); @Override boolean shouldRetry(RetryPolicyContext context); boolean isRetryable(RetryPolicyContext context); RetryPolicy getLegacyRetryPolicy(); boolean maxRetriesExceeded(RetryPolicyContext context); }
@Test public void shouldRetry_MaxErrorRetryReached() { assertFalse(adapter.shouldRetry(RetryPolicyContexts.withRetriesAttempted(3))); } @Test public void shouldRetry_MaxErrorInClientConfigHonored_DoesNotUseMaxErrorInPolicy() { when(retryCondition.shouldRetry(any(AmazonWebServiceRequest.class), any(AmazonClientException.class), anyInt())) .thenReturn(true); legacyPolicy = new RetryPolicy(retryCondition, backoffStrategy, 3, true); adapter = new RetryPolicyAdapter(legacyPolicy, clientConfiguration); assertTrue(adapter.shouldRetry(RetryPolicyContexts.withRetriesAttempted(3))); assertFalse(adapter.shouldRetry(RetryPolicyContexts.withRetriesAttempted(10))); } @Test public void shouldRetry_MaxErrorNotExceeded_DelegatesToLegacyRetryCondition() { final RetryPolicyContext context = RetryPolicyContexts.LEGACY; adapter.shouldRetry(context); verify(retryCondition).shouldRetry( eq((AmazonWebServiceRequest) context.originalRequest()), eq((AmazonClientException) context.exception()), eq(context.retriesAttempted())); }
S3ErrorResponseHandler implements HttpResponseHandler<AmazonServiceException> { @Override public AmazonServiceException handle(HttpResponse httpResponse) throws XMLStreamException { final AmazonServiceException exception = createException(httpResponse); exception.setHttpHeaders(httpResponse.getHeaders()); return exception; } @Override AmazonServiceException handle(HttpResponse httpResponse); boolean needsConnectionLeftOpen(); }
@Test public void testRegionHeaderIsAddedToExcpetion() throws XMLStreamException { String region = "myDummyRegion"; String strResponse = "<Error><Code>PermanentRedirect</Code><Message>The bucket is in this region: null. Please use this region to retry the request</Message></Error>"; ByteArrayInputStream content = new ByteArrayInputStream(strResponse.getBytes(Charset.forName("UTF-8"))); S3ErrorResponseHandler errorHandler = new S3ErrorResponseHandler(); Request request = new DefaultRequest("default"); request.setHttpMethod(HttpMethodName.GET); HttpResponse response = new HttpResponse(request, null); response.setContent(content); response.addHeader(Headers.S3_BUCKET_REGION, region); AmazonS3Exception exception = (AmazonS3Exception)errorHandler.handle(response); assertTrue(exception.getAdditionalDetails().get(Headers.S3_BUCKET_REGION).equals(region)); }
AsperaFaspManagerWrapper { public boolean cancel(final String xferId) { log.info("Cancel transfer with xferId [" + xferId + "]"); log.trace("Calling method [stopTransfer] with parameters [\"" + xferId + "\", 8, 0]"); boolean rtn = faspmanager2.stopTransfer(xferId); log.trace("Method [stopTransfer] returned for xferId [\"" + xferId + "\"] with result: [" + rtn + "]"); return rtn; } AsperaFaspManagerWrapper(); AsperaFaspManagerWrapper(AsperaTransaction asperaTransaction); long startTransfer(final String xferId, final String transferSpecStr); boolean pause(final String xferId); boolean resume(final String xferId); boolean cancel(final String xferId); boolean isRunning(final String xferId); boolean configureLogLocation(final String ascpLogPath); void setAsperaTransaction(AsperaTransaction asperaTransaction); }
@Test public void testInfoLogCallsMadeForCancel() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.stopTransfer(anyString()) ).thenReturn(true); when(mockLog.isDebugEnabled()).thenReturn(false); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(); wrapper.log = mockLog; boolean rtn = wrapper.cancel("xyz123"); assertTrue(rtn); verify(mockLog, times(1)).info(Mockito.eq("Cancel transfer with xferId [xyz123]")); } @Test public void testTraceLogCallsMadeForCancel() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.stopTransfer(anyString()) ).thenReturn(true); when(mockLog.isDebugEnabled()).thenReturn(true); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(); wrapper.log = mockLog; boolean rtn = wrapper.cancel("xyz123"); assertTrue(rtn); verify(mockLog, times(1)).trace(Mockito.eq("Calling method [stopTransfer] with parameters [\"xyz123\", 8, 0]")); verify(mockLog, times(1)).trace(Mockito.eq("Method [stopTransfer] returned for xferId [\"xyz123\"] with result: [true]")); }
AsperaFaspManagerWrapper { public boolean isRunning(final String xferId) { log.trace("Calling method [isRunning] with parameters [\"" + xferId + "\"]"); boolean rtn = faspmanager2.isRunning(xferId); log.trace("Method [isRunning] returned for xferId [\"" + xferId + "\"] with result: [" + rtn + "]"); return rtn; } AsperaFaspManagerWrapper(); AsperaFaspManagerWrapper(AsperaTransaction asperaTransaction); long startTransfer(final String xferId, final String transferSpecStr); boolean pause(final String xferId); boolean resume(final String xferId); boolean cancel(final String xferId); boolean isRunning(final String xferId); boolean configureLogLocation(final String ascpLogPath); void setAsperaTransaction(AsperaTransaction asperaTransaction); }
@Test public void testTraceLogCallsMadeForIsRunning() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.isRunning(anyString()) ).thenReturn(true); when(mockLog.isDebugEnabled()).thenReturn(true); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(); wrapper.log = mockLog; boolean rtn = wrapper.isRunning("xyz123"); assertTrue(rtn); verify(mockLog, times(1)).trace(Mockito.eq("Calling method [isRunning] with parameters [\"xyz123\"]")); verify(mockLog, times(1)).trace(Mockito.eq("Method [isRunning] returned for xferId [\"xyz123\"] with result: [true]")); }
RetryUtils { @Deprecated public static boolean isThrottlingException(AmazonServiceException exception) { return isThrottlingException((SdkBaseException) exception); } @Deprecated static boolean isRetryableServiceException(AmazonServiceException exception); static boolean isRetryableServiceException(SdkBaseException exception); @Deprecated static boolean isThrottlingException(AmazonServiceException exception); static boolean isThrottlingException(SdkBaseException exception); @Deprecated static boolean isRequestEntityTooLargeException(AmazonServiceException exception); static boolean isRequestEntityTooLargeException(SdkBaseException exception); @Deprecated static boolean isClockSkewError(AmazonServiceException exception); static boolean isClockSkewError(SdkBaseException exception); }
@Test public void isThrottlingException_TrueWhenErrorCodeMatchesKnownCodes() throws Exception { AmazonServiceException ase = new AmazonServiceException("msg"); ase.setErrorCode("ThrottlingException"); assertTrue("ThrottlingException error code should be true", RetryUtils.isThrottlingException(ase)); } @Test public void isThrottlingException_TrueWhenStatusCodeIs429() throws Exception { AmazonServiceException ase = new AmazonServiceException("msg"); ase.setStatusCode(429); assertTrue("ThrottlingException error code should be true", RetryUtils.isThrottlingException(ase)); } @Test public void isThrottlingException_FalseWhenErrorAndStatusCodeDoNotMatch() throws Exception { AmazonServiceException ase = new AmazonServiceException("msg"); ase.setStatusCode(500); ase.setErrorCode("InternalFailure"); assertFalse("InternalFailure error code should be false", RetryUtils.isThrottlingException(ase)); }
AsperaFaspManagerWrapper { public boolean configureLogLocation(final String ascpLogPath) { log.trace("Calling method [configureLogLocation] with parameters [\"" + ascpLogPath + "\"]"); boolean rtn = faspmanager2.configureLogLocation(ascpLogPath); log.trace("Method [configureLogLocation] returned for ascpLogPath [\"" + ascpLogPath + "\"] with result: [" + rtn + "]"); return rtn; } AsperaFaspManagerWrapper(); AsperaFaspManagerWrapper(AsperaTransaction asperaTransaction); long startTransfer(final String xferId, final String transferSpecStr); boolean pause(final String xferId); boolean resume(final String xferId); boolean cancel(final String xferId); boolean isRunning(final String xferId); boolean configureLogLocation(final String ascpLogPath); void setAsperaTransaction(AsperaTransaction asperaTransaction); }
@Test public void testTraceLogCallsMadeForConfigureLogLocation() throws Exception { PowerMockito .when( TransferListener.getInstance(null, null) ).thenReturn(mockTransferListener); PowerMockito .when( faspmanager2.configureLogLocation(anyString()) ).thenReturn(true); when(mockLog.isDebugEnabled()).thenReturn(true); AsperaFaspManagerWrapper wrapper = new AsperaFaspManagerWrapper(); wrapper.log = mockLog; boolean rtn = wrapper.configureLogLocation("somePath"); assertTrue(rtn); verify(mockLog, times(1)).trace(Mockito.eq("Calling method [configureLogLocation] with parameters [\"somePath\"]")); verify(mockLog, times(1)).trace(Mockito.eq("Method [configureLogLocation] returned for ascpLogPath [\"somePath\"] with result: [true]")); }
EC2ResourceFetcher { public abstract String readResource(URI endpoint, CredentialsEndpointRetryPolicy retryPolicy, Map<String, String> headers); EC2ResourceFetcher(); @SdkTestInternalApi EC2ResourceFetcher(ConnectionUtils connectionUtils); static EC2ResourceFetcher defaultResourceFetcher(); abstract String readResource(URI endpoint, CredentialsEndpointRetryPolicy retryPolicy, Map<String, String> headers); final String readResource(URI endpoint); final String readResource(URI endpoint, CredentialsEndpointRetryPolicy retryPolicy); }
@Test public void readResourceWithDefaultRetryPolicy_DoesNotRetry_ForIoException() throws IOException { Mockito.when(mockConnection.connectToEndpoint(eq(endpoint), any(Map.class), eq("GET"))).thenThrow(new IOException()); try { new DefaultEC2ResourceFetcher(mockConnection).readResource(endpoint); fail("Expected an IOexception"); } catch (Exception exception) { Mockito.verify(mockConnection, Mockito.times(1)).connectToEndpoint(eq(endpoint), any(Map.class), eq("GET")); } } @Test public void readResourceWithCustomRetryPolicy_DoesRetry_ForIoException() throws IOException { Mockito.when(mockConnection.connectToEndpoint(eq(endpoint), any(Map.class), eq("GET"))).thenThrow(new IOException()); try { new DefaultEC2ResourceFetcher(mockConnection).readResource(endpoint, customRetryPolicy); fail("Expected an IOexception"); } catch (Exception exception) { Mockito.verify(mockConnection, Mockito.times(CustomRetryPolicy.MAX_RETRIES + 1)).connectToEndpoint(eq(endpoint), any(Map.class), eq("GET")); } } @Test public void readResourceWithCustomRetryPolicy_DoesNotRetry_ForNonIoException() throws IOException { generateStub(500, "Non Json error body"); try { ec2ResourceFetcher.readResource(endpoint, customRetryPolicy, new HashMap<String, String>()); fail("Expected an AmazonServiceException"); } catch (AmazonServiceException ase) { assertEquals(500, ase.getStatusCode()); } } @Test public void readResourceThrowsIOExceptionWhenNoConnection() throws IOException, URISyntaxException { int port = 0; try { port = SocketUtils.getUnusedPort(); } catch (IOException ioexception) { fail("Unable to find an unused port"); } try { ec2ResourceFetcher.readResource(new URI("http: fail("no exception is thrown"); } catch (SdkClientException exception) { assertTrue(exception.getMessage().contains("Failed to connect")); } } @Test public void readResourceReturnsResponseBodyFor200Response() throws IOException { generateStub(200, SUCCESS_BODY); assertEquals(SUCCESS_BODY, ec2ResourceFetcher.readResource(endpoint)); } @Test public void readResourceReturnsAceFor404ErrorResponse() throws Exception { try { ec2ResourceFetcher.readResource(new URI("http: fail("Expected AmazonClientException"); } catch (AmazonClientException ace) { assertTrue(ace.getMessage().contains("The requested metadata is not found at")); } } @Test public void readResourceReturnsAseFor5xxResponse() throws IOException { generateStub(500, "{\"code\":\"500 Internal Server Error\",\"message\":\"ERROR_MESSAGE\"}"); try { ec2ResourceFetcher.readResource(endpoint); fail("Expected AmazonServiceException"); } catch (AmazonServiceException ase) { assertEquals(500, ase.getStatusCode()); assertEquals("500 Internal Server Error", ase.getErrorCode()); assertEquals("ERROR_MESSAGE", ase.getErrorMessage()); } } @Test public void readResourceNonJsonErrorBody() throws IOException { generateStub(500, "Non Json error body"); try { ec2ResourceFetcher.readResource(endpoint); fail("Expected AmazonServiceException"); } catch (AmazonServiceException ase) { assertEquals(500, ase.getStatusCode()); assertNotNull(ase.getErrorMessage()); } } @Test @SuppressWarnings("unchecked") public void readResourceWithDefaultRetryPolicy_DoesNotRetry_ForIoException() throws IOException { Mockito.when(mockConnection.connectToEndpoint(eq(endpoint), any(Map.class), eq("GET"))).thenThrow(new IOException()); try { new DefaultEC2ResourceFetcher(mockConnection).readResource(endpoint); fail("Expected an IOexception"); } catch (Exception exception) { Mockito.verify(mockConnection, Mockito.times(1)).connectToEndpoint(eq(endpoint), any(Map.class), eq("GET")); } } @Test @SuppressWarnings("unchecked") public void readResourceWithCustomRetryPolicy_DoesRetry_ForIoException() throws IOException { Mockito.when(mockConnection.connectToEndpoint(eq(endpoint), any(Map.class), eq("GET"))).thenThrow(new IOException()); try { new DefaultEC2ResourceFetcher(mockConnection).readResource(endpoint, customRetryPolicy); fail("Expected an IOexception"); } catch (Exception exception) { Mockito.verify(mockConnection, Mockito.times(CustomRetryPolicy.MAX_RETRIES + 1)).connectToEndpoint(eq(endpoint), any(Map.class), eq("GET")); } } @Test @SuppressWarnings("unchecked") public void readResourceWithCustomRetryPolicy_DoesNotRetry_ForNonIoException() throws IOException { generateStub(500, "Non Json error body"); try { ec2ResourceFetcher.readResource(endpoint, customRetryPolicy, new HashMap<String, String>()); fail("Expected an AmazonServiceException"); } catch (AmazonServiceException ase) { assertEquals(500, ase.getStatusCode()); } } @Test @SuppressWarnings("unchecked") public void readResource_AddsSDKUserAgent() throws IOException { Mockito.when(mockConnection.connectToEndpoint(eq(endpoint), any(Map.class), eq("GET"))).thenThrow(new IOException()); try { new DefaultEC2ResourceFetcher(mockConnection).readResource(endpoint); fail("Expected an IOexception"); } catch (Exception exception) { Matcher<Map<? extends String, ? extends String>> expectedHeaders = hasEntry("User-Agent", USER_AGENT); Mockito.verify(mockConnection, Mockito.times(1)).connectToEndpoint(eq(endpoint), (Map<String, String>) argThat(expectedHeaders), eq("GET")); } } @Test @SuppressWarnings("unchecked") public void readResourceWithCustomRetryPolicy_AddsSDKUserAgent() throws IOException { Mockito.when(mockConnection.connectToEndpoint(eq(endpoint), any(Map.class), eq("GET"))).thenThrow(new IOException()); try { new DefaultEC2ResourceFetcher(mockConnection).readResource(endpoint, customRetryPolicy, new HashMap<String, String>()); fail("Expected an IOexception"); } catch (Exception exception) { Matcher<Map<? extends String, ? extends String>> expectedHeaders = hasEntry("User-Agent", USER_AGENT); Mockito.verify(mockConnection, Mockito.times(CustomRetryPolicy.MAX_RETRIES + 1)).connectToEndpoint(eq(endpoint), (Map<String, String>) argThat(expectedHeaders), eq("GET")); } } @Test @SuppressWarnings("unchecked") public void readResourceWithCustomRetryPolicyAndHeaders_AddsSDKUserAgent() throws IOException { Mockito.when(mockConnection.connectToEndpoint(eq(endpoint), any(Map.class), eq("GET"))).thenThrow(new IOException()); try { Map<String, String> headers = new HashMap<String, String>(); headers.put("Foo","Bar"); new DefaultEC2ResourceFetcher(mockConnection).readResource(endpoint, customRetryPolicy, headers); fail("Expected an IOexception"); } catch (Exception exception) { Matcher<Map<? extends String, ? extends String>> expectedHeaders = allOf( hasEntry("User-Agent", USER_AGENT), hasEntry("Foo", "Bar") ); Mockito.verify(mockConnection, Mockito.times(CustomRetryPolicy.MAX_RETRIES + 1)).connectToEndpoint(eq(endpoint), (Map<String, String>) argThat(expectedHeaders), eq("GET")); } }
AsperaLibraryLoader { public static JarFile createJar() throws IOException, URISyntaxException { URL location = faspmanager2.class.getProtectionDomain().getCodeSource().getLocation(); return new JarFile(new File(location.toURI())); } static String load(); static JarFile createJar(); static String jarVersion(JarFile jar); static void extractJar(JarFile jar, File extractedLocation); static void extractFile(JarFile jar, JarEntry entry, File destPath); static List<String> osLibs(); static void loadLibrary(File extractedPath, List<String> candidates); }
@Test public void testJarIsCreatedSuccessfully() throws IOException, URISyntaxException { JarFile jar = AsperaLibraryLoader.createJar(); assertNotNull(jar); }
SdkFilterInputStream extends FilterInputStream implements MetricAware, Releasable { public void abort() { if (in instanceof SdkFilterInputStream) { ((SdkFilterInputStream) in).abort(); } aborted = true; } protected SdkFilterInputStream(InputStream in); @SdkProtectedApi InputStream getDelegateStream(); @Override boolean isMetricActivated(); void abort(); @Override int read(); @Override int read(byte b[], int off, int len); @Override long skip(long n); @Override int available(); @Override void close(); @Override synchronized void mark(int readlimit); @Override synchronized void reset(); @Override boolean markSupported(); @Override void release(); }
@Test public void testInputStreamAbortedIsCalled(){ SdkFilterInputStream in = mock(SdkFilterInputStream.class); SdkFilterInputStream sdkFilterInputStream = spy(new SdkFilterInputStream(in)); sdkFilterInputStream.abort(); verify(in, times(1)).abort(); }
ConnectionUtils { public HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers) throws IOException { return connectToEndpoint(endpoint, headers, "GET"); } private ConnectionUtils(); static ConnectionUtils getInstance(); HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers); HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers, String method); }
@Ignore @Test public void headersArePassedAsPartOfRequest() throws IOException { HttpURLConnection connection = sut.connectToEndpoint(URI.create("http: connection.getResponseCode(); mockServer.verify(getRequestedFor(urlMatching("/")).withHeader("HeaderA", equalTo("ValueA"))); } @Test public void proxiesAreNotUsedEvenIfPropertyIsSet() throws IOException { System.getProperties().put("http.proxyHost", "localhost"); System.getProperties().put("http.proxyPort", String.valueOf(mockProxyServer.port())); HttpURLConnection connection = sut.connectToEndpoint(URI.create("http: assertThat(connection.getRequestMethod(), is("GET")); assertThat(connection.usingProxy(), is(false)); } @Test public void headersArePassedAsPartOfRequest() throws IOException { HttpURLConnection connection = sut.connectToEndpoint(URI.create("http: connection.getResponseCode(); mockServer.verify(getRequestedFor(urlMatching("/")).withHeader("HeaderA", equalTo("ValueA"))); }
AsperaLibraryLoader { public static List<String> osLibs() { String OS = System.getProperty("os.name").toLowerCase(); if (OS.indexOf("win") >= 0){ return WINDOWS_DYNAMIC_LIBS; } else if (OS.indexOf("mac") >= 0) { return MAC_DYNAMIC_LIBS; } else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ) { return UNIX_DYNAMIC_LIBS; } else { throw new AsperaLibraryLoadException("OS is not supported for Aspera"); } } static String load(); static JarFile createJar(); static String jarVersion(JarFile jar); static void extractJar(JarFile jar, File extractedLocation); static void extractFile(JarFile jar, JarEntry entry, File destPath); static List<String> osLibs(); static void loadLibrary(File extractedPath, List<String> candidates); }
@Test public void testOSLibIsReturned() { String OS = System.getProperty("os.name").toLowerCase(); List<String> osNativeLibraries = AsperaLibraryLoader.osLibs(); assertNotNull(osNativeLibraries); if (OS.indexOf("win") >= 0){ assertTrue(osNativeLibraries.contains("faspmanager2.dll")); } else if (OS.indexOf("mac") >= 0) { assertTrue(osNativeLibraries.contains("libfaspmanager2.jnilib")); } else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ) { assertTrue(osNativeLibraries.contains("libfaspmanager2.so")); } }
AsperaTransactionImpl implements AsperaTransaction { @Override public boolean isDone() { return (doesStatusMatch(DONE)||doesStatusMatch(ERROR)||doesStatusMatch(STOP)||doesStatusMatch(ARGSTOP)); } AsperaTransactionImpl(String xferid, String bucketName, String key, String fileName, TransferProgress transferProgress, ProgressListenerChain listenerChain); @Override boolean pause(); @Override boolean resume(); @Override boolean cancel(); @Override boolean isDone(); @Override boolean progress(); @Override boolean onQueue(); @Override String getBucketName(); @Override String getKey(); @Override AsperaResult waitForCompletion(); @Override void addProgressListener(ProgressListener listener); @Override void removeProgressListener(ProgressListener listener); @Override ProgressListenerChain getProgressListenerChain(); @Override TransferProgress getProgress(); @Override ITransferListener getTransferListener(); }
@Test public void testAsperaTransactionIsDoneERROR(){ transferListener = TransferListener.getInstance(xferId, null); AsperaTransfer asperaTransaction = new AsperaTransactionImpl(xferId, null, null, null, null, null); transferListener.transferReporter(xferId, msgQueued); transferListener.transferReporter(xferId, msgStats); transferListener.transferReporter(xferId, msgError); assertTrue(asperaTransaction.isDone()); } @Test public void testAsperaTransactionIsDoneSuccess(){ transferListener = TransferListener.getInstance(xferId, null); AsperaTransfer asperaTransaction = new AsperaTransactionImpl(xferId, null, null, null, null, null); transferListener.transferReporter(xferId, msgQueued); transferListener.transferReporter(xferId, msgStats); transferListener.transferReporter(xferId, msgError); transferListener.transferReporter(xferId, msgDone); assertTrue(asperaTransaction.isDone()); }
AsperaTransactionImpl implements AsperaTransaction { @Override public boolean progress() { return doesStatusMatch(PROGRESS); } AsperaTransactionImpl(String xferid, String bucketName, String key, String fileName, TransferProgress transferProgress, ProgressListenerChain listenerChain); @Override boolean pause(); @Override boolean resume(); @Override boolean cancel(); @Override boolean isDone(); @Override boolean progress(); @Override boolean onQueue(); @Override String getBucketName(); @Override String getKey(); @Override AsperaResult waitForCompletion(); @Override void addProgressListener(ProgressListener listener); @Override void removeProgressListener(ProgressListener listener); @Override ProgressListenerChain getProgressListenerChain(); @Override TransferProgress getProgress(); @Override ITransferListener getTransferListener(); }
@Test public void testAsperaTransactionIsProgress(){ transferListener = TransferListener.getInstance(xferId, null); AsperaTransfer asperaTransaction = new AsperaTransactionImpl(xferId, null, null, null, null, null); transferListener.transferReporter(xferId, msgQueued); transferListener.transferReporter(xferId, msgStats); assertTrue(asperaTransaction.progress()); }
SDKGlobalConfiguration { public static boolean isCertCheckingDisabled() { return isPropertyEnabled(System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY)); } @Deprecated static void setGlobalTimeOffset(int timeOffset); @Deprecated static int getGlobalTimeOffset(); static boolean isInRegionOptimizedModeEnabled(); static boolean isCertCheckingDisabled(); static boolean isCborDisabled(); static boolean isIonBinaryDisabled(); static boolean isEc2MetadataDisabled(); static final String DISABLE_CERT_CHECKING_SYSTEM_PROPERTY; static final String DEFAULT_METRICS_SYSTEM_PROPERTY; static final String ACCESS_KEY_SYSTEM_PROPERTY; static final String SECRET_KEY_SYSTEM_PROPERTY; static final String EC2_METADATA_SERVICE_OVERRIDE_SYSTEM_PROPERTY; static final String RETRY_THROTTLING_SYSTEM_PROPERTY; static final String REGIONS_FILE_OVERRIDE_SYSTEM_PROPERTY; static final String DISABLE_REMOTE_REGIONS_FILE_SYSTEM_PROPERTY; @Deprecated static final String ENABLE_S3_SIGV4_SYSTEM_PROPERTY; @Deprecated static final String ENFORCE_S3_SIGV4_SYSTEM_PROPERTY; static final String DISABLE_S3_IMPLICIT_GLOBAL_CLIENTS_SYSTEM_PROPERTY; static final String ENABLE_IN_REGION_OPTIMIZED_MODE; @Deprecated static final String DEFAULT_S3_STREAM_BUFFER_SIZE; @Deprecated static final String PROFILING_SYSTEM_PROPERTY; static final String IBM_API_KEY_SYSTEM_PROPERTY; static final String IBM_SERVICE_INSTANCE_ID_SYSTEM_PROPERTY; static final String IBM_API_KEY; static final String IBM_SERVICE_INSTANCE_ID; static String IAM_ENDPOINT; static int IAM_MAX_RETRY; static double IAM_REFRESH_OFFSET; static final String ACCESS_KEY_ENV_VAR; static final String ALTERNATE_ACCESS_KEY_ENV_VAR; static final String SECRET_KEY_ENV_VAR; static final String ALTERNATE_SECRET_KEY_ENV_VAR; static final String AWS_SESSION_TOKEN_ENV_VAR; static final String AWS_WEB_IDENTITY_ENV_VAR; static final String AWS_ROLE_ARN_ENV_VAR; static final String AWS_ROLE_SESSION_NAME_ENV_VAR; static final String AWS_REGION_ENV_VAR; static final String AWS_CONFIG_FILE_ENV_VAR; static final String AWS_CBOR_DISABLE_ENV_VAR; static final String AWS_CBOR_DISABLE_SYSTEM_PROPERTY; static final String AWS_ION_BINARY_DISABLE_ENV_VAR; static final String AWS_ION_BINARY_DISABLE_SYSTEM_PROPERTY; static final String AWS_EC2_METADATA_DISABLED_ENV_VAR; static final String AWS_EC2_METADATA_DISABLED_SYSTEM_PROPERTY; }
@Test public void disableCertChecking_FlagEnabled_TurnsOffCertChecking() { System.setProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, ""); assertTrue(SDKGlobalConfiguration.isCertCheckingDisabled()); } @Test public void disableCertChecking_PropertySetToTrue_TurnsOffCertChecking() { System.setProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "true"); assertTrue(SDKGlobalConfiguration.isCertCheckingDisabled()); } @Test public void disableCertChecking_PropertySet_TurnsOffCertChecking() { System.setProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "anything"); assertTrue(SDKGlobalConfiguration.isCertCheckingDisabled()); } @Test public void disableCertChecking_PropertySetToFalse_TurnsOffCertChecking() { System.setProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "false"); assertFalse(SDKGlobalConfiguration.isCertCheckingDisabled()); } @Test public void disableCertChecking_PropertySetToFalseMixedCase_TurnsOffCertChecking() { System.setProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "FaLsE"); assertFalse(SDKGlobalConfiguration.isCertCheckingDisabled()); }
AwsClientBuilder { public abstract TypeToBuild build(); protected AwsClientBuilder(ClientConfigurationFactory clientConfigFactory); @SdkTestInternalApi protected AwsClientBuilder(ClientConfigurationFactory clientConfigFactory, AwsRegionProvider regionProvider); final AWSCredentialsProvider getCredentials(); final void setCredentials(AWSCredentialsProvider credentialsProvider); final Subclass withCredentials(AWSCredentialsProvider credentialsProvider); Subclass withIAMEndpoint(String iamEndpoint); Subclass withIAMTokenRefresh(double offset); Subclass withIAMMaxRetry(int retryCount); final ClientConfiguration getClientConfiguration(); final void setClientConfiguration(ClientConfiguration config); final Subclass withClientConfiguration(ClientConfiguration config); final void setMetricsCollector(RequestMetricCollector metrics); final Subclass withMetricsCollector(RequestMetricCollector metrics); final String getRegion(); final void setRegion(String region); final Subclass withRegion(Regions region); final RequestMetricCollector getMetricsCollector(); final Subclass withRegion(String region); final EndpointConfiguration getEndpoint(); final void setEndpointConfiguration(EndpointConfiguration endpointConfiguration); final Subclass withEndpointConfiguration(EndpointConfiguration endpointConfiguration); final List<RequestHandler2> getRequestHandlers(); final void setRequestHandlers(RequestHandler2... handlers); final Subclass withRequestHandlers(RequestHandler2... handlers); abstract TypeToBuild build(); }
@Test public void credentialsNotExplicitlySet_UsesDefaultCredentialChain() throws Exception { AwsAsyncClientParams params = builderWithRegion().build().getAsyncParams(); assertThat(params.getCredentialsProvider(), instanceOf(DefaultAWSCredentialsProviderChain.class)); } @Test public void metricCollectorNotExplicitlySet_UsesNullMetricsCollector() throws Exception { assertNull(builderWithRegion().build().getAsyncParams().getRequestMetricCollector()); } @Test public void defaultClientConfigAndNoExplicitExecutor_UsesDefaultExecutorBasedOnMaxConns() { ExecutorService executor = builderWithRegion().build().getAsyncParams().getExecutor(); assertThat(executor, instanceOf(ThreadPoolExecutor.class)); assertEquals(PredefinedClientConfigurations.defaultConfig().getMaxConnections(), ((ThreadPoolExecutor) executor).getMaximumPoolSize()); }
AsperaTransactionImpl implements AsperaTransaction { @Override public boolean onQueue() { return doesStatusMatch(QUEUED); } AsperaTransactionImpl(String xferid, String bucketName, String key, String fileName, TransferProgress transferProgress, ProgressListenerChain listenerChain); @Override boolean pause(); @Override boolean resume(); @Override boolean cancel(); @Override boolean isDone(); @Override boolean progress(); @Override boolean onQueue(); @Override String getBucketName(); @Override String getKey(); @Override AsperaResult waitForCompletion(); @Override void addProgressListener(ProgressListener listener); @Override void removeProgressListener(ProgressListener listener); @Override ProgressListenerChain getProgressListenerChain(); @Override TransferProgress getProgress(); @Override ITransferListener getTransferListener(); }
@Test public void testAsperaTransactionIsQueued(){ transferListener = TransferListener.getInstance(xferId, null); AsperaTransfer asperaTransaction = new AsperaTransactionImpl(xferId, null, null, null, null, null); transferListener.transferReporter(xferId, msgQueued); assertTrue(asperaTransaction.onQueue()); }
S3XmlResponseHandler extends AbstractS3ResponseHandler<T> { public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception { AmazonWebServiceResponse<T> awsResponse = parseResponseMetadata(response); responseHeaders = response.getHeaders(); if (responseUnmarshaller != null) { log.trace("Beginning to parse service response XML"); T result = responseUnmarshaller.unmarshall(response.getContent()); log.trace("Done parsing service response XML"); awsResponse.setResult(result); if (result instanceof ObjectListing) { if (!StringUtils.isNullOrEmpty(responseHeaders.get(Headers.IBM_SSE_KP_ENABLED))){ ((ObjectListing) result).setIBMSSEKPEnabled(Boolean.parseBoolean(responseHeaders.get(Headers.IBM_SSE_KP_ENABLED))); } if (!StringUtils.isNullOrEmpty(responseHeaders.get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN))) { ((ObjectListing) result).setIBMSSEKPCrk(responseHeaders.get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN)); } } } return awsResponse; } S3XmlResponseHandler(Unmarshaller<T, InputStream> responseUnmarshaller); AmazonWebServiceResponse<T> handle(HttpResponse response); Map<String, String> getResponseHeaders(); }
@Test public void testHeadersAddedToObjectListing() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); httpResponse.addHeader(Headers.IBM_SSE_KP_ENABLED, "True"); httpResponse.addHeader(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN, "123456"); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), "123456"); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), true); } @Test public void testNullKPHeadersAreHandled() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); httpResponse.addHeader(Headers.IBM_SSE_KP_ENABLED, null); httpResponse.addHeader(Headers.IBM_SSE_KP_CRK, null); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), null); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), false); } @Test public void testEmptyKPHeadersAreHandled() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), null); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), false); } @Test public void testOnlyKPEnabledHeaderIsSet() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); httpResponse.addHeader(Headers.IBM_SSE_KP_ENABLED, "True"); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), null); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), true); } @Test public void testOnlyCRKHeaderIsSet() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(null, null); httpResponse.addHeader(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN, "34567"); InputStream is = new ByteArrayInputStream(getXmlContent().getBytes());; httpResponse.setContent(is); AmazonWebServiceResponse<ObjectListing> objectListing = xmlResponseHandler.handle(httpResponse); assertEquals(objectListing.getResult().getIBMSSEKPCrk(), "34567"); assertEquals(objectListing.getResult().getIBMSSEKPEnabled(), false); }
RegionMetadata { public Region getRegion(final String name) { return provider.getRegion(name); } RegionMetadata(final List<Region> regions); RegionMetadata(RegionMetadataProvider provider); List<Region> getRegions(); Region getRegion(final String name); List<Region> getRegionsForService(final String service); @Deprecated Region getRegionByEndpoint(final String endpoint); @Override String toString(); }
@Test public void testGetRegion() { Region region = metadata.getRegion("us-east-1"); Assert.assertNotNull(region); Assert.assertEquals("us-east-1", region.getName()); region = metadata.getRegion("us-west-1"); Assert.assertNotNull(region); Assert.assertEquals("us-west-1", region.getName()); region = metadata.getRegion("cn-north-1"); Assert.assertNotNull(region); Assert.assertEquals("cn-north-1", region.getName()); region = metadata.getRegion("bogus-monkeys"); Assert.assertNull(region); } @Test public void testGetRegion() { Region region = metadata.getRegion("cn-beijing-6"); Assert.assertNotNull(region); Assert.assertEquals("cn-beijing-6", region.getName()); region = metadata.getRegion("cn-shanghai-2"); Assert.assertNotNull(region); Assert.assertEquals("cn-shanghai-2", region.getName()); region = metadata.getRegion("cn-beijing-1"); Assert.assertNotNull(region); Assert.assertEquals("cn-beijing-1", region.getName()); region = metadata.getRegion("bogus-monkeys"); Assert.assertNull(region); }
RegionMetadata { public List<Region> getRegionsForService(final String service) { return provider.getRegionsForService(service); } RegionMetadata(final List<Region> regions); RegionMetadata(RegionMetadataProvider provider); List<Region> getRegions(); Region getRegion(final String name); List<Region> getRegionsForService(final String service); @Deprecated Region getRegionByEndpoint(final String endpoint); @Override String toString(); }
@Test public void testGetRegionsForService() { List<Region> regions = metadata.getRegionsForService("s3"); Assert.assertNotNull(regions); Assert.assertEquals(2, regions.size()); Assert.assertEquals("us-east-1", regions.get(0).getName()); Assert.assertEquals("us-west-1", regions.get(1).getName()); regions = metadata.getRegionsForService("bogus-monkeys"); Assert.assertNotNull(regions); Assert.assertTrue(regions.isEmpty()); } @Test public void testGetRegionsForService() { List<Region> regions = metadata.getRegionsForService("kec"); Assert.assertNotNull(regions); Assert.assertEquals(2, regions.size()); Assert.assertEquals("cn-beijing-6", regions.get(0).getName()); Assert.assertEquals("cn-shanghai-2", regions.get(1).getName()); regions = metadata.getRegionsForService("bogus-monkeys"); Assert.assertNotNull(regions); Assert.assertTrue(regions.isEmpty()); }
RegionMetadata { @Deprecated public Region getRegionByEndpoint(final String endpoint) { return provider.getRegionByEndpoint(endpoint); } RegionMetadata(final List<Region> regions); RegionMetadata(RegionMetadataProvider provider); List<Region> getRegions(); Region getRegion(final String name); List<Region> getRegionsForService(final String service); @Deprecated Region getRegionByEndpoint(final String endpoint); @Override String toString(); }
@Test public void testGetRegionByEndpoint() { Region region = metadata.getRegionByEndpoint("s3-us-west-1.amazonaws.com"); Assert.assertNotNull(region); Assert.assertEquals("us-west-1", region.getName()); try { metadata.getRegionByEndpoint("bogus-monkeys"); Assert.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { } } @SuppressWarnings("deprecation") @Test public void testGetRegionByEndpoint() { Region region = metadata.getRegionByEndpoint("kec.cn-beijing-6.api.ksyun.com"); Assert.assertNotNull(region); Assert.assertEquals("cn-beijing-6", region.getName()); try { metadata.getRegionByEndpoint("bogus-monkeys"); Assert.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { } }
AsperaTransactionImpl implements AsperaTransaction { @Override public boolean pause() { return asperaFaspManagerWrapper.pause(xferid); } AsperaTransactionImpl(String xferid, String bucketName, String key, String fileName, TransferProgress transferProgress, ProgressListenerChain listenerChain); @Override boolean pause(); @Override boolean resume(); @Override boolean cancel(); @Override boolean isDone(); @Override boolean progress(); @Override boolean onQueue(); @Override String getBucketName(); @Override String getKey(); @Override AsperaResult waitForCompletion(); @Override void addProgressListener(ProgressListener listener); @Override void removeProgressListener(ProgressListener listener); @Override ProgressListenerChain getProgressListenerChain(); @Override TransferProgress getProgress(); @Override ITransferListener getTransferListener(); }
@Test public void testAsperaTransactionPause(){ transferListener = TransferListener.getInstance(xferId, null); AsperaTransfer asperaTransaction = new AsperaTransactionImpl(xferId, null, null, null, null, null); transferListener.transferReporter(xferId, msgQueued); transferListener.transferReporter(xferId, msgStats); assertTrue(asperaTransaction.pause()); }
DefaultTokenManager implements TokenManager { @Override public String getToken() { log.debug("DefaultTokenManager getToken()"); if (!checkCache()) { retrieveToken(); } if (token == null) { token = retrieveTokenFromCache(); } if (hasTokenExpired(token)) { token = retrieveTokenFromCache(); } if (isTokenExpiring(token) && !isAsyncInProgress()) { if (null != token.getRefresh_token()) { this.asyncInProgress = true; submitRefreshTask(); } else { retrieveToken(); token = retrieveTokenFromCache(); } } if (token.getAccess_token() != null && !token.getAccess_token().isEmpty()) { return token.getAccess_token(); } else if (token.getDelegated_refresh_token()!= null && !token.getDelegated_refresh_token().isEmpty()) { return token.getDelegated_refresh_token(); } else if (token.getIms_token() != null && !token.getIms_token().isEmpty()) { return token.getIms_token(); } else { return token.getUaa_token(); } } DefaultTokenManager(String apiKey); DefaultTokenManager(TokenProvider provider); void setIamEndpoint(String iamEndpoint); void setIamRefreshOffset(double offset); void setIamMaxRetry(int count); TokenProvider getProvider(); @Override String getToken(); ClientConfiguration getClientConfiguration(); void setClientConfiguration(ClientConfiguration clientConfiguration); static void addProxyConfig(HttpClientBuilder builder, HttpClientSettings settings); }
@Test public void shouldAcceptTokenProvider() { TokenProvider tokenProvider = new TokenProviderUtil(); defaultTokenManager = new DefaultTokenManager(tokenProvider); assertEquals(defaultTokenManager.getToken(), ("ProviderAccessToken")); } @Test(expected = Exception.class) public void shouldBubbleExceptionUpThroughSDK() { TokenProvider tokenProvider = null; defaultTokenManager = new DefaultTokenManager(tokenProvider); defaultTokenManager.getToken().equals("ProviderAccessToken"); } @Test(expected = OAuthServiceException.class) public void shouldHandleNullTokenWithCorrectExcpetion() { DefaultTokenManager defaultTokenManager = new DefaultTokenManager(new TokenProviderNull()); defaultTokenManager.getToken(); }
DefaultTokenManager implements TokenManager { protected synchronized void retrieveToken() { log.debug("OAuthTokenManager.retrieveToken"); if (token == null || (Long.valueOf(token.getExpiration()) < System.currentTimeMillis() / 1000L)) { log.debug("Token is null, retrieving initial token from provider"); boolean tokenRequest = true; int retryCount = 0; while (tokenRequest && retryCount < this.iamMaxRetry) { try { ++retryCount; token = provider.retrieveToken(); tokenRequest = false; } catch (OAuthServiceException exception) { log.debug("Exception retrieving IAM token. Returned status code " + exception.getStatusCode() + "Retry attempt " + retryCount); tokenRequest = shouldRetry(exception.getStatusCode()) ? true : false; if (!tokenRequest || retryCount == this.iamMaxRetry) { throw exception; } } } if(null == token) { throw new OAuthServiceException("Null token returned by the Token Provider"); } cacheToken(token); } } DefaultTokenManager(String apiKey); DefaultTokenManager(TokenProvider provider); void setIamEndpoint(String iamEndpoint); void setIamRefreshOffset(double offset); void setIamMaxRetry(int count); TokenProvider getProvider(); @Override String getToken(); ClientConfiguration getClientConfiguration(); void setClientConfiguration(ClientConfiguration clientConfiguration); static void addProxyConfig(HttpClientBuilder builder, HttpClientSettings settings); }
@Test @Ignore public void shouldOnlyCallIAMOnceInMutliThreadForInitialToken() { TokenProvider tokenProviderMock = mock(TokenProvider.class); when(tokenProviderMock.retrieveToken()).thenReturn(token); defaultTokenManager = new DefaultTokenManager(tokenProviderMock); Thread t1 = new Thread(new ManagerThreadUtil(defaultTokenManager)); Thread t2 = new Thread(new ManagerThreadUtil(defaultTokenManager)); Thread t3 = new Thread(new ManagerThreadUtil(defaultTokenManager)); Thread t4 = new Thread(new ManagerThreadUtil(defaultTokenManager)); t1.start(); t2.start(); t3.start(); t4.start(); assertEquals(1, Mockito.mockingDetails(tokenProviderMock).getInvocations().size()); }
DefaultTokenManager implements TokenManager { public static void addProxyConfig(HttpClientBuilder builder, HttpClientSettings settings) { if (settings.isProxyEnabled()) { log.info("Configuring Proxy. Proxy Host: " + settings.getProxyHost() + " " + "Proxy Port: " + settings.getProxyPort()); builder.setRoutePlanner(new SdkProxyRoutePlanner( settings.getProxyHost(), settings.getProxyPort(), settings.getNonProxyHosts())); if (settings.isAuthenticatedProxy()) { builder.setDefaultCredentialsProvider(ApacheUtils.newProxyCredentialsProvider(settings)); } } } DefaultTokenManager(String apiKey); DefaultTokenManager(TokenProvider provider); void setIamEndpoint(String iamEndpoint); void setIamRefreshOffset(double offset); void setIamMaxRetry(int count); TokenProvider getProvider(); @Override String getToken(); ClientConfiguration getClientConfiguration(); void setClientConfiguration(ClientConfiguration clientConfiguration); static void addProxyConfig(HttpClientBuilder builder, HttpClientSettings settings); }
@Test public void shouldAddProxyToClient() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{ HttpClientBuilder builder = HttpClientBuilder.create(); ClientConfiguration config = new ClientConfiguration().withProxyHost("127.0.0.1").withProxyPort(8080); HttpClientSettings settings = HttpClientSettings.adapt(config); DefaultTokenManager.addProxyConfig(builder, settings); builder.build(); Field field = builder.getClass().getDeclaredField("routePlanner"); field.setAccessible(true); HttpRoutePlanner httpRoutePlanner = (HttpRoutePlanner) field.get(builder); assertNotNull(httpRoutePlanner); } @Test public void shouldNotAddProxyToClient() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{ HttpClientBuilder builder = HttpClientBuilder.create(); ClientConfiguration config = new ClientConfiguration(); HttpClientSettings settings = HttpClientSettings.adapt(config); DefaultTokenManager.addProxyConfig(builder, settings); builder.build(); Field field = builder.getClass().getDeclaredField("routePlanner"); field.setAccessible(true); HttpRoutePlanner httpRoutePlanner = (HttpRoutePlanner) field.get(builder); assertNull(httpRoutePlanner); }
AsperaTransactionImpl implements AsperaTransaction { @Override public boolean resume() { return asperaFaspManagerWrapper.resume(xferid); } AsperaTransactionImpl(String xferid, String bucketName, String key, String fileName, TransferProgress transferProgress, ProgressListenerChain listenerChain); @Override boolean pause(); @Override boolean resume(); @Override boolean cancel(); @Override boolean isDone(); @Override boolean progress(); @Override boolean onQueue(); @Override String getBucketName(); @Override String getKey(); @Override AsperaResult waitForCompletion(); @Override void addProgressListener(ProgressListener listener); @Override void removeProgressListener(ProgressListener listener); @Override ProgressListenerChain getProgressListenerChain(); @Override TransferProgress getProgress(); @Override ITransferListener getTransferListener(); }
@Test public void testAsperaTransactionResume(){ transferListener = TransferListener.getInstance(xferId, null); AsperaTransfer asperaTransaction = new AsperaTransactionImpl(xferId, null, null, null, null, null); transferListener.transferReporter(xferId, msgQueued); transferListener.transferReporter(xferId, msgStats); assertTrue(asperaTransaction.resume()); }
IBMOAuthSigner extends AbstractAWSSigner { @Override public void sign(SignableRequest<?> request, AWSCredentials credentials) { log.debug("++ OAuth signer"); IBMOAuthCredentials oAuthCreds = (IBMOAuthCredentials)credentials; if (oAuthCreds.getTokenManager() instanceof DefaultTokenManager) { DefaultTokenManager tokenManager = (DefaultTokenManager)oAuthCreds.getTokenManager(); tokenManager.setClientConfiguration(clientConfiguration); request.addHeader( AUTHORIZATION,"Bearer " + tokenManager.getToken()); } else { request.addHeader( AUTHORIZATION,"Bearer " + oAuthCreds.getTokenManager().getToken()); } } IBMOAuthSigner(ClientConfiguration clientConfiguration); IBMOAuthSigner(); @Override void sign(SignableRequest<?> request, AWSCredentials credentials); }
@Test public void shouldAddBearerToken() { request = MockRequestBuilder.create() .withContent(new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .withHeader("Host", "demo.us-east-1.amazonaws.com") .withHeader("x-amz-archive-description", "test test") .withPath("/") .withEndpoint("http: TokenProvider tokenProvider = new TokenProviderUtil(); AWSCredentialsProvider testCredProvider = new CredentialProviderUtil(tokenProvider); IBMOAuthSigner signer = new IBMOAuthSigner(); signer.sign(request, testCredProvider.getCredentials()); assertEquals("Bearer ProviderAccessToken", request.getHeaders().get("Authorization")); }
BasicIBMOAuthCredentials implements IBMOAuthCredentials { @Override public TokenManager getTokenManager() { return tokenManager; } BasicIBMOAuthCredentials(String apiKey, String serviceInstanceId); BasicIBMOAuthCredentials(TokenManager tokenManager); BasicIBMOAuthCredentials(TokenManager tokenManager, String serviceInstanceId); BasicIBMOAuthCredentials(TokenProvider tokenProvider); @Override String getAWSAccessKeyId(); @Override String getAWSSecretKey(); @Override TokenManager getTokenManager(); @Override String getApiKey(); @Override String getServiceInstanceId(); }
@Test public void constructorShouldAcceptTokenManager() { TokenManager tokenManger = new TokenManagerUtil(); IBMOAuthCredentials oAuthCreds = new BasicIBMOAuthCredentials(tokenManger); assertTrue(oAuthCreds.getTokenManager().getToken().equals("TokenManagerAccessToken")); } @Test public void constructorShouldAcceptTokenProvider() { TokenProvider tokenProvider = new TokenProviderUtil(); IBMOAuthCredentials oAuthCreds = new BasicIBMOAuthCredentials(tokenProvider); assertTrue(oAuthCreds.getTokenManager().getToken().equals("ProviderAccessToken")); }
AWSCredentialsProviderChain implements AWSCredentialsProvider { public AWSCredentials getCredentials() { if (reuseLastProvider && lastUsedProvider != null) { return lastUsedProvider.getCredentials(); } for (AWSCredentialsProvider provider : credentialsProviders) { try { AWSCredentials credentials = provider.getCredentials(); if (credentials instanceof IBMOAuthCredentials) { log.debug("Loading OAuth credentials from " + provider.toString()); lastUsedProvider = provider; return credentials; } if (credentials.getAWSAccessKeyId() != null && credentials.getAWSSecretKey() != null) { log.debug("Loading credentials from " + provider.toString()); lastUsedProvider = provider; return credentials; } } catch (Exception e) { log.debug("Unable to load credentials from " + provider.toString() + ": " + e.getMessage()); } } throw new SdkClientException("Unable to load AWS credentials from any provider in the chain"); } AWSCredentialsProviderChain(List<? extends AWSCredentialsProvider> credentialsProviders); AWSCredentialsProviderChain(AWSCredentialsProvider... credentialsProviders); boolean getReuseLastProvider(); void setReuseLastProvider(boolean b); AWSCredentials getCredentials(); void refresh(); }
@Test public void testReusingLastProvider() throws Exception { MockCredentialsProvider provider1 = new MockCredentialsProvider(); provider1.throwException = true; MockCredentialsProvider provider2 = new MockCredentialsProvider(); AWSCredentialsProviderChain chain = new AWSCredentialsProviderChain(provider1, provider2); assertEquals(0, provider1.getCredentialsCallCount); assertEquals(0, provider2.getCredentialsCallCount); chain.getCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(1, provider2.getCredentialsCallCount); chain.getCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(2, provider2.getCredentialsCallCount); chain.getCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(3, provider2.getCredentialsCallCount); }
JsonCredentialsProvider implements AWSCredentialsProvider { @Override public AWSCredentials getCredentials() { if (jsonConfigFile == null) { synchronized (this) { if (jsonConfigFile == null) { jsonConfigFile = new JsonConfigFile(); lastRefreshed = System.nanoTime(); } } } long now = System.nanoTime(); long age = now - lastRefreshed; if (age > refreshForceIntervalNanos) { refresh(); } else if (age > refreshIntervalNanos) { if (refreshSemaphore.tryAcquire()) { try { refresh(); } finally { refreshSemaphore.release(); } } } return jsonConfigFile.getCredentials(); } JsonCredentialsProvider(); JsonCredentialsProvider(String jsonConfigFilePath); JsonCredentialsProvider(JsonConfigFile jsonConfigFile); @Override AWSCredentials getCredentials(); @Override void refresh(); long getRefreshIntervalNanos(); void setRefreshIntervalNanos(long refreshIntervalNanos); long getRefreshForceIntervalNanos(); void setRefreshForceIntervalNanos(long refreshForceIntervalNanos); @Override String toString(); }
@Test public void testHmac() { JsonCredentialsProvider provider = newProvider(); JsonCredentials credentials = (JsonCredentials) provider.getCredentials(); Assert.assertEquals("vaws_access_key_id", credentials.getAWSAccessKeyId()); Assert.assertEquals("vaws_secret_access_key", credentials.getAWSSecretKey()); Assert.assertEquals(null, credentials.getApiKey()); Assert.assertEquals(null, credentials.getServiceInstanceId()); }
JsonCredentialsProvider implements AWSCredentialsProvider { @Override public void refresh() { if (jsonConfigFile != null) { jsonConfigFile.refresh(); lastRefreshed = System.nanoTime(); } } JsonCredentialsProvider(); JsonCredentialsProvider(String jsonConfigFilePath); JsonCredentialsProvider(JsonConfigFile jsonConfigFile); @Override AWSCredentials getCredentials(); @Override void refresh(); long getRefreshIntervalNanos(); void setRefreshIntervalNanos(long refreshIntervalNanos); long getRefreshForceIntervalNanos(); void setRefreshForceIntervalNanos(long refreshForceIntervalNanos); @Override String toString(); }
@Test public void testRefresh() throws Exception { File modifiable = File.createTempFile("UpdatableCredentials", ".json"); copyFile(JsonResourceLoader.basicCredentials().asFile(), modifiable); JsonCredentialsProvider testProvider = new JsonCredentialsProvider(modifiable.getPath()); JsonCredentials credentials = (JsonCredentials) testProvider.getCredentials(); Assert.assertEquals("vaws_access_key_id", credentials.getAWSAccessKeyId()); Assert.assertEquals("vaws_secret_access_key", credentials.getAWSSecretKey()); Thread.sleep(1000); copyFile(JsonResourceLoader.basicCredentials2().asFile(), modifiable); testProvider.setRefreshIntervalNanos(1l); JsonCredentials updated = (JsonCredentials) testProvider.getCredentials(); Assert.assertEquals("vaws_access_key_id_2", updated.getAWSAccessKeyId()); Assert.assertEquals("vaws_secret_access_key_2", updated.getAWSSecretKey()); }
ContainerCredentialsProvider implements AWSCredentialsProvider { @Override public AWSCredentials getCredentials() { return credentialsFetcher.getCredentials(); } ContainerCredentialsProvider(); @SdkInternalApi ContainerCredentialsProvider(CredentialsEndpointProvider credentailsEndpointProvider); @Override AWSCredentials getCredentials(); @Override void refresh(); Date getCredentialsExpiration(); }
@Test (expected = AmazonClientException.class) public void testEnvVariableNotSet() { ContainerCredentialsProvider credentialsProvider = new ContainerCredentialsProvider(); credentialsProvider.getCredentials(); } @Test public void getCredentialsWithCorruptResponseDoesNotIncludeCredentialsInExceptionMessage() { stubForCorruptedSuccessResponse(); try { containerCredentialsProvider.getCredentials(); Assert.fail(); } catch (Exception e) { String stackTrace = ExceptionUtils.getStackTrace(e); Assert.assertFalse(stackTrace.contains("ACCESS_KEY_ID")); Assert.assertFalse(stackTrace.contains("SECRET_ACCESS_KEY")); Assert.assertFalse(stackTrace.contains("TOKEN_TOKEN_TOKEN")); } } @Test public void testGetCredentialsThrowsAceFor404ErrorResponse() { stubForErrorResponse(404); try { containerCredentialsProvider.getCredentials(); fail("The test should throw an exception"); } catch (AmazonClientException exception) { assertNotNull(exception.getMessage()); } } @Test public void testGetCredentialsThrowsAseForNon200AndNon404ErrorResponse() { stubForErrorResponse(401); try { containerCredentialsProvider.getCredentials(); fail("The test should have thrown an exception"); } catch (AmazonServiceException exception) { assertEquals(401, exception.getStatusCode()); assertNotNull(exception.getMessage()); } }
AsperaTransactionImpl implements AsperaTransaction { @Override public boolean cancel() { if (asperaFaspManagerWrapper.cancel(xferid)) { transferListener.removeAllTransactionSessions(xferid); return true; } else { return false; } } AsperaTransactionImpl(String xferid, String bucketName, String key, String fileName, TransferProgress transferProgress, ProgressListenerChain listenerChain); @Override boolean pause(); @Override boolean resume(); @Override boolean cancel(); @Override boolean isDone(); @Override boolean progress(); @Override boolean onQueue(); @Override String getBucketName(); @Override String getKey(); @Override AsperaResult waitForCompletion(); @Override void addProgressListener(ProgressListener listener); @Override void removeProgressListener(ProgressListener listener); @Override ProgressListenerChain getProgressListenerChain(); @Override TransferProgress getProgress(); @Override ITransferListener getTransferListener(); }
@Test public void testAsperaTransactionCancel(){ transferListener = TransferListener.getInstance(xferId, null); AsperaTransfer asperaTransaction = new AsperaTransactionImpl(xferId, null, null, null, null, null); transferListener.transferReporter(xferId, msgQueued); transferListener.transferReporter(xferId, msgStats); assertTrue(asperaTransaction.cancel()); }
ContainerCredentialsFetcher extends BaseCredentialsFetcher { @Override public String toString() { return "ContainerCredentialsFetcher"; } ContainerCredentialsFetcher(CredentialsEndpointProvider credentialsEndpointProvider); @Override String toString(); }
@Test public void testNoMetadataService() throws Exception { stubForErrorResponse(); TestCredentialsProvider credentialsProvider = new TestCredentialsProvider(); try { credentialsProvider.getCredentials(); fail("Expected an AmazonClientException, but wasn't thrown"); } catch (AmazonClientException ace) { assertNotNull(ace.getMessage()); } stubForSuccessResonseWithCustomExpirationDate(200, new Date(System.currentTimeMillis() + ONE_MINUTE * 4).toString()); credentialsProvider.getCredentials(); credentialsProvider.setLastInstanceProfileCheck(new Date(System.currentTimeMillis() - (ONE_MINUTE * 61))); stubForErrorResponse(); try { credentialsProvider.getCredentials(); fail("Expected an AmazonClientException, but wasn't thrown"); } catch (AmazonClientException ace) { assertNotNull(ace.getMessage()); } } @Test public void testNeedsToLoadCredentialsMethod() throws Exception { TestCredentialsProvider credentialsProvider = new TestCredentialsProvider(); stubForSuccessResonseWithCustomExpirationDate(200, DateUtils.formatISO8601Date(new Date(System.currentTimeMillis() + ONE_MINUTE * 60 * 24)).toString()); credentialsProvider.getCredentials(); assertFalse(credentialsProvider.needsToLoadCredentials()); stubForSuccessResonseWithCustomExpirationDate(200, DateUtils.formatISO8601Date(new Date(System.currentTimeMillis() + ONE_MINUTE * 16)).toString()); credentialsProvider.getCredentials(); credentialsProvider.setLastInstanceProfileCheck(new Date(System.currentTimeMillis() - ONE_MINUTE * 61)); assertTrue(credentialsProvider.needsToLoadCredentials()); stubForSuccessResonseWithCustomExpirationDate(200, DateUtils.formatISO8601Date(new Date(System.currentTimeMillis() + ONE_MINUTE * 14)).toString()); credentialsProvider.getCredentials(); assertTrue(credentialsProvider.needsToLoadCredentials()); } @Test public void testNoMetadataService() throws Exception { stubForErrorResponse(); TestCredentialsProvider credentialsProvider = new TestCredentialsProvider(); try { credentialsProvider.getCredentials(); fail("Expected an AmazonClientException, but wasn't thrown"); } catch (AmazonClientException ace) { assertNotNull(ace.getMessage()); } stubForSuccessResonseWithCustomExpirationDate(200, new Date(System.currentTimeMillis() + ONE_MINUTE * 4).toString()); AWSCredentials firstCredentials = credentialsProvider.getCredentials(); credentialsProvider.setLastInstanceProfileCheck(new Date(System.currentTimeMillis() - (ONE_MINUTE * 61))); stubForErrorResponse(); AWSCredentials secondCredentials = credentialsProvider.getCredentials(); assertSame(firstCredentials, secondCredentials); }
AmazonWebServiceClient { public String getServiceName() { return getServiceNameIntern(); } AmazonWebServiceClient(ClientConfiguration clientConfiguration); AmazonWebServiceClient(ClientConfiguration clientConfiguration, RequestMetricCollector requestMetricCollector); @SdkProtectedApi protected AmazonWebServiceClient(ClientConfiguration clientConfiguration, RequestMetricCollector requestMetricCollector, boolean disableStrictHostNameVerification); protected AmazonWebServiceClient(AwsSyncClientParams clientParams); @Deprecated void setEndpoint(String endpoint); Signer getSignerByURI(URI uri); @Deprecated void setRegion(Region region); @Deprecated final void configureRegion(Regions region); void shutdown(); @Deprecated void addRequestHandler(RequestHandler requestHandler); @Deprecated void addRequestHandler(RequestHandler2 requestHandler2); @Deprecated void removeRequestHandler(RequestHandler requestHandler); @Deprecated void removeRequestHandler(RequestHandler2 requestHandler2); void setTimeOffset(int timeOffset); AmazonWebServiceClient withTimeOffset(int timeOffset); int getTimeOffset(); RequestMetricCollector getRequestMetricsCollector(); String getServiceName(); String getEndpointPrefix(); final void setServiceNameIntern(String serviceName); final String getSignerRegionOverride(); final void setSignerRegionOverride(String signerRegionOverride); @Deprecated T withRegion(Region region); @Deprecated T withRegion(Regions region); @Deprecated T withEndpoint(String endpoint); @Deprecated @SdkInternalApi final void makeImmutable(); String getSignerOverride(); ClientConfiguration getClientConfiguration(); @Deprecated static final boolean LOGGING_AWS_REQUEST_METRIC; }
@Test public void emptyClient() { AmazonWebServiceClient client = new AmazonWebServiceClient(new ClientConfiguration()) { }; try { client.getServiceName(); } catch (IllegalStateException exception) { } }