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... | @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); Predicat... |
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 (p... | @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 r... |
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 perso... | @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(perso... |
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(... | @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 at... |
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.get... | @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); ... |
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(... | @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... |
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 su... | @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(personServiceMoc... |
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(); ... | @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, modificationTim... |
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 = personS... | @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 = controlle... |
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 submitte... | @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, F... |
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 ... | @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(creationT... |
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.addAttribu... | @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); assertEqua... |
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: " + searchCriter... | @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); assertEqual... |
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 ... | @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(m... |
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 localizedFeedbac... | @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, pa... |
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(S... | @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).get... |
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> fi... | @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, act... |
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), construc... | @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); Ar... |
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... errorMessa... | @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, "Dynami... |
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... | @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 express... | @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) .ha... |
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 expressi... | @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) .h... |
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 @Overr... | @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); } @Tr... | @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); Argume... |
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) { ... | @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)... |
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 getLastNam... | @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 ... | @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, personC... |
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... | @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(... |
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), constructPageSpecificat... | @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<Pageab... |
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)... | @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, r... |
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 search... | @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(pe... |
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.setStatusC... | @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 findUser... | @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)... | @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... | @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 res... | @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(... |
AmazonS3Client extends AmazonWebServiceClient implements AmazonS3 { protected Request<CreateBucketRequest> addIAMHeaders(Request<CreateBucketRequest> request, CreateBucketRequest createBucketRequest){ if ((null != this.awsCredentialsProvider ) && (this.awsCredentialsProvider.getCredentials() instanceof IBMOAuthCredenti... | @Test public void testServiceInstanceRuntimeParamTakesPrecedence() { String serviceInstanceId = "12345"; CreateBucketRequest request = new CreateBucketRequest("testbucket").withServiceInstanceId(serviceInstanceId); Request<CreateBucketRequest> defaultRequest = new DefaultRequest(Constants.S3_SERVICE_DISPLAY_NAME); Amaz... |
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); stat... | @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 fromStr... | @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, indexO... | @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", ""... |
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)... | @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() { Asse... |
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)... | @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 { 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); stati... | @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.cl... |
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 fromIntege... | @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... | @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 == Intege... | @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(... |
AsperaTransferManager { public void checkMultiSessionAllGlobalConfig(TransferSpecs transferSpecs) { if(asperaTransferManagerConfig.isMultiSession()){ for(TransferSpec transferSpec : transferSpecs.transfer_specs) { transferSpec.setRemote_host(updateRemoteHost(transferSpec.getRemote_host())); } } } protected AsperaTrans... | @Test public void testRemoteHostUpdatedWhenAsperaTransferManagerConfigMultiSessionTrue() { AsperaTransferManagerConfig asperaTransferManagerConfig = new AsperaTransferManagerConfig(); asperaTransferManagerConfig.setMultiSession(true); TransferSpec transferSpec = new TransferSpec(); transferSpec.setRemote_host("mysubDom... |
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, h... | @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(... |
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... | @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", nul... |
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 regionNameIn... | @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.amazona... |
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.getTarg... | @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... |
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}... | @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.setErrorHand... | @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("... |
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, sessi... | @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; spyTransferListene... |
AsperaTransferManagerBuilder { public AsperaTransferManager build() { AsperaTransferManager transferManager = new AsperaTransferManager(this.s3Client, this.tokenManager, this.asperaConfig, this.asperaTransferManagerConfig); return transferManager; } AsperaTransferManagerBuilder(String apiKey, AmazonS3 s3Client); Aspera... | @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).b... |
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 = re... | @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)); }
@T... |
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.getRedactedJsonStrin... | @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(... |
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 ... | @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); Asp... |
JsonErrorUnmarshaller extends AbstractErrorUnmarshaller<JsonNode> { @Override public AmazonServiceException unmarshall(JsonNode jsonContent) throws Exception { return MAPPER.treeToValue(jsonContent, exceptionClass); } JsonErrorUnmarshaller(Class<? extends AmazonServiceException> exceptionClass, String handledErrorCode)... | @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.get... |
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] returne... | @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); As... |
ClientConfiguration { public ApacheHttpClientConfig getApacheHttpClientConfig() { return apacheHttpClientConfig; } ClientConfiguration(); ClientConfiguration(ClientConfiguration other); Protocol getProtocol(); void setProtocol(Protocol protocol); ClientConfiguration withProtocol(Protocol protocol); int getMaxConnectio... | @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.getTy... |
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 maxC... | @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());... | @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 RequestMetricCollect... |
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)... | @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.except... | @Test public void computeDelayBeforeNextRetry_DelegatesToLegacyPolicy() { final RetryPolicyContext context = RetryPolicyContexts.LEGACY; adapter.computeDelayBeforeNextRetry(context); verify(backoffStrategy).delayBeforeNextRetry( eq((AmazonWebServiceRequest) context.originalRequest()), eq((AmazonClientException) context... |
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 co... | @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... |
S3ErrorResponseHandler implements
HttpResponseHandler<AmazonServiceException> { @Override public AmazonServiceException handle(HttpResponse httpResponse) throws XMLStreamException { final AmazonServiceException exception = createException(httpResponse); exception.setHttpHeaders(httpResponse.getHeaders()); retur... | @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 B... |
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 [... | @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 ... |
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; } Aspera... | @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 ... |
RetryUtils { @Deprecated public static boolean isThrottlingException(AmazonServiceException exception) { return isThrottlingException((SdkBaseException) exception); } @Deprecated static boolean isRetryableServiceException(AmazonServiceException exception); static boolean isRetryableServiceException(SdkBaseException ex... | @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... |
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 [\"" + ... | @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); Asp... |
EC2ResourceFetcher { public abstract String readResource(URI endpoint, CredentialsEndpointRetryPolicy retryPolicy, Map<String, String> headers); EC2ResourceFetcher(); @SdkTestInternalApi EC2ResourceFetcher(ConnectionUtils connectionUtils); static EC2ResourceFetcher defaultResourceFetcher(); abstract String readResourc... | @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 IOex... |
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 ja... | @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(); @Overrid... | @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> heade... | @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 proxiesAreNotUsedEvenIf... |
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") > ... | @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) ... |
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, Prog... | @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, msgStat... |
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(); @Overrid... | @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... |
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(); st... | @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_CHECKI... |
AwsClientBuilder { public abstract TypeToBuild build(); protected AwsClientBuilder(ClientConfigurationFactory clientConfigFactory); @SdkTestInternalApi protected AwsClientBuilder(ClientConfigurationFactory clientConfigFactory,
AwsRegionProvider regionProvider); final AWSCredentialsProvi... | @Test public void credentialsNotExplicitlySet_UsesDefaultCredentialChain() throws Exception { AwsAsyncClientParams params = builderWithRegion().build().getAsyncParams(); assertThat(params.getCredentialsProvider(), instanceOf(DefaultAWSCredentialsProviderChain.class)); }
@Test public void metricCollectorNotExplicitlySet... |
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 b... | @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 ... | @Test public void testHeadersAddedToObjectListing() throws Exception { Unmarshaller<ObjectListing, InputStream> unmarshaller = new Unmarshallers.ListObjectsUnmarshaller(false); S3XmlResponseHandler xmlResponseHandler = new S3XmlResponseHandler<ObjectListing>(unmarshaller); HttpResponse httpResponse = new HttpResponse(n... |
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); @Depreca... | @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("... |
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> getRegionsForServi... | @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.get... |
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> getRegionsFo... | @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 (I... |
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()... | @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); as... |
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) &&... | @Test public void shouldAcceptTokenProvider() { TokenProvider tokenProvider = new TokenProviderUtil(); defaultTokenManager = new DefaultTokenManager(tokenProvider); assertEquals(defaultTokenManager.getToken(), ("ProviderAccessToken")); }
@Test(expected = Exception.class) public void shouldBubbleExceptionUpThroughSDK() ... |
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 tokenRe... | @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(defaultTo... |
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 S... | @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 s... |
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... | @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); a... |
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 tokenMan... | @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 token... |
BasicIBMOAuthCredentials implements IBMOAuthCredentials { @Override public TokenManager getTokenManager() { return tokenManager; } BasicIBMOAuthCredentials(String apiKey, String serviceInstanceId); BasicIBMOAuthCredentials(TokenManager tokenManager); BasicIBMOAuthCredentials(TokenManager tokenManager, String serviceI... | @Test public void constructorShouldAcceptTokenManager() { TokenManager tokenManger = new TokenManagerUtil(); IBMOAuthCredentials oAuthCreds = new BasicIBMOAuthCredentials(tokenManger); assertTrue(oAuthCreds.getTokenManager().getToken().equals("TokenManagerAccessToken")); }
@Test public void constructorShouldAcceptToken... |
AWSCredentialsProviderChain implements AWSCredentialsProvider { public AWSCredentials getCredentials() { if (reuseLastProvider && lastUsedProvider != null) { return lastUsedProvider.getCredentials(); } for (AWSCredentialsProvider provider : credentialsProviders) { try { AWSCredentials credentials = provider.getCredenti... | @Test public void testReusingLastProvider() throws Exception { MockCredentialsProvider provider1 = new MockCredentialsProvider(); provider1.throwException = true; MockCredentialsProvider provider2 = new MockCredentialsProvider(); AWSCredentialsProviderChain chain = new AWSCredentialsProviderChain(provider1, provider2);... |
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 - ... | @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.ass... |
JsonCredentialsProvider implements AWSCredentialsProvider { @Override public void refresh() { if (jsonConfigFile != null) { jsonConfigFile.refresh(); lastRefreshed = System.nanoTime(); } } JsonCredentialsProvider(); JsonCredentialsProvider(String jsonConfigFilePath); JsonCredentialsProvider(JsonConfigFile jsonConfigF... | @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 = (JsonCr... |
ContainerCredentialsProvider implements AWSCredentialsProvider { @Override public AWSCredentials getCredentials() { return credentialsFetcher.getCredentials(); } ContainerCredentialsProvider(); @SdkInternalApi ContainerCredentialsProvider(CredentialsEndpointProvider credentailsEndpointProvider); @Override AWSCredentia... | @Test (expected = AmazonClientException.class) public void testEnvVariableNotSet() { ContainerCredentialsProvider credentialsProvider = new ContainerCredentialsProvider(); credentialsProvider.getCredentials(); }
@Test public void getCredentialsWithCorruptResponseDoesNotIncludeCredentialsInExceptionMessage() { stubForCo... |
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, Tran... | @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); a... |
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(... |
AmazonWebServiceClient { public String getServiceName() { return getServiceNameIntern(); } AmazonWebServiceClient(ClientConfiguration clientConfiguration); AmazonWebServiceClient(ClientConfiguration clientConfiguration,
RequestMetricCollector requestMetricCollector); @SdkProtectedApi protected AmazonWebSe... | @Test public void emptyClient() { AmazonWebServiceClient client = new AmazonWebServiceClient(new ClientConfiguration()) { }; try { client.getServiceName(); } catch (IllegalStateException exception) { } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.