@Test public void shouldBeAbleToUpdateARole() { RoleRepresentation role = role().thatIs().persistent(token).build(); pause(1000); role.setName(RandomStringUtils.randomAlphabetic(10)); Result<RoleRepresentation> result = client.update(role, token.getAccessToken()); assertThat(result).accepted().withResponseCode(200); RoleRepresentation updated = result.getInstance(); assertThat(updated.getId()).startsWith("rol_"); assertThat(updated.getCreated()).isNotNull(); assertThat(updated.getUpdated()).isNotNull(); assertThat(updated.getCreated()).isEqualTo(role.getCreated()); assertThat(updated.getCreated()).isBefore(updated.getUpdated()); assertThat(updated.getUpdated()).isAfter(role.getUpdated()); assertThat(updated.getName()).isEqualTo(role.getName()); }
@Before public void prepareData(){ TodoEntity nullNameTodo = new TodoEntity(); TodoEntity emptyNameTodo = new TodoEntity(); emptyNameTodo.setName(""); TodoEntity emptyNameButWithSpacesTodo = new TodoEntity(); emptyNameButWithSpacesTodo.setName(" "); TodoEntity name101charsTodo = new TodoEntity(); name101charsTodo.setName(RandomStringUtils.randomAlphanumeric(101)); TodoEntity name500CharsTodo = new TodoEntity(); name500CharsTodo.setName(RandomStringUtils.randomAlphanumeric(500)); improperNameTodoList = Arrays.asList(nullNameTodo, emptyNameTodo, emptyNameButWithSpacesTodo, name101charsTodo, name500CharsTodo); TodoEntity name100charsTodo = new TodoEntity(); name100charsTodo.setName(RandomStringUtils.randomAlphanumeric(100)); TodoEntity nameOneCharTodo = new TodoEntity(); nameOneCharTodo.setName("a"); properNameTodoList = Arrays.asList(name100charsTodo, nameOneCharTodo); }
public static final String download(RemoteWebDriver driver, String url) { String folder = DOWNLOAD_PATH + RandomStringUtils.randomAlphabetic(10); new File(folder).mkdirs(); Map<String, String> headers = new HashMap<String, String>(); headers.put("Cookie", getCookie(driver)); byte[] data = HttpUtils.get(url, headers); try { String filename; String contentDisposition = headers.get("Content-Disposition"); if (StringUtils.contains(contentDisposition, "=")) { filename = contentDisposition.substring(contentDisposition.indexOf("=") + 1); } else { filename = new URL(url).getPath(); if (filename.contains("/")) { filename = filename.substring(filename.lastIndexOf("/") + 1); } } IOUtils.write(data, new FileOutputStream(folder + "/" + filename)); return folder + "/" + filename; } catch (Exception e) { throw new RuntimeException("Download failed!", e); } }
private User createUserIfNotExist(UserProfile userProfile, String langKey, String imageUrl) { String email = userProfile.getEmail(); if (StringUtils.isBlank(email)) { log.error("Cannot create social user because email is null"); throw new IllegalArgumentException("Email cannot be null"); } else { Optional<UserLogin> user = userLoginRepository.findOneByLoginIgnoreCase(email); if (user.isPresent()) { log.info("User already exist associate the connection to this account"); return user.get().getUser(); } } String encryptedPassword = passwordEncoder.encode(RandomStringUtils.random(10)); Set<Authority> authorities = new HashSet<>(1); authorities.add(authorityRepository.findOne("ROLE_USER")); User newUser = new User(); newUser.setUserKey(UUID.randomUUID().toString()); newUser.setPassword(encryptedPassword); newUser.setFirstName(userProfile.getFirstName()); newUser.setLastName(userProfile.getLastName()); newUser.setActivated(true); newUser.setAuthorities(authorities); newUser.setLangKey(langKey); newUser.setImageUrl(imageUrl); UserLogin userLogin = new UserLogin(); userLogin.setUser(newUser); userLogin.setTypeKey(UserLoginType.EMAIL.getValue()); userLogin.setLogin(email); newUser.getLogins().add(userLogin); return userRepository.save(newUser); }
public static MalIntent getSemivalidSchemeHostPortPathPatternURIMalIntent(IntentDataInfo datafield) { MalIntent mal = new MalIntent(datafield); String scheme = datafield.scheme; String host = datafield.host; host = host.replace("*", RandomStringUtils.randomAlphanumeric(10)); String pathPattern = datafield.pathPattern; String semivalidPathPattern; if (pathPattern.contains(".*") || pathPattern.contains("*")) { semivalidPathPattern = pathPattern.replace(".*", RandomStringUtils.randomAlphabetic(10)); semivalidPathPattern = semivalidPathPattern.replace("*", RandomStringUtils.randomAlphanumeric(10)); if (pathPattern.charAt(0) == '/') { mal.setData(Uri.parse(scheme + "://" + host + semivalidPathPattern)); } mal.setData(Uri.parse(scheme + "://" + host + "/" + semivalidPathPattern)); } else { semivalidPathPattern = RandomStringUtils.randomAlphabetic(10); if (pathPattern.equals("") || pathPattern.charAt(0) == '/') { mal.setData(Uri.parse(scheme + "://" + host + semivalidPathPattern)); } mal.setData(Uri.parse(scheme + "://" + host + "/" + semivalidPathPattern)); } return mal; }
@Test public void testReloadStrategyIsNotNullWhenCallingReloadOnChange() throws Exception { ConsulFileConfigurationSource source; String filePath = RandomStringUtils.randomAlphanumeric(15); source = createConfigurationSource(filePath, true, false); assertThat(source.shouldWatchForChange()).isFalse(); assertThat(source.getReloadStrategy()).isNull(); source = createConfigurationSource(filePath, true, true); assertThat(source.shouldWatchForChange()).isTrue(); assertThat(source.getReloadStrategy()).isNotNull(); }
public static void main(String[] args) { String str = ""; for(int i = 0; i < 5; i++) { //System.out.println(RandomStringUtils.randomNumeric(8)); str += RandomStringUtils.randomNumeric(4)+","; } System.out.println(str); System.out.println(str.substring(0,str.lastIndexOf(","))); // for(int i = 0;i<10;i++){ // method1(); // } // if(Days.daysBetween(DateUtils.parseDate("2016-10-25 00:00:00"),DateTime.now()).getDays() == 0){ // System.out.println("today"); // } String dtStr = DateUtils.getCurrentTimeStr(); dtStr = dtStr.substring(0, dtStr.lastIndexOf(" ")) + " 00:00:00"; System.out.println(dtStr); regexPhoneTest("17700001111"); setTimeout(1000,2000); System.out.println(JsonUtils.obj2json(getTimeout())); }
/** * Create a User. * * This is a static method, as tests for other entities might also need it, * if they test an entity which has a required relationship to the User entity. */ public static User createEntity(EntityManager em) { User user = new User(); user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5)); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL); user.setFirstName(DEFAULT_FIRSTNAME); user.setLastName(DEFAULT_LASTNAME); user.setImageUrl(DEFAULT_IMAGEURL); user.setLangKey(DEFAULT_LANGKEY); return user; }
private Address createAddress() { Address senderAddress = new Address(); senderAddress.setCity(RandomStringUtils.randomAlphanumeric(20)); senderAddress.setPostcode(RandomStringUtils.randomAlphanumeric(7)); senderAddress.setCountry(RandomStringUtils.randomAlphanumeric(20)); senderAddress.setStreet(RandomStringUtils.randomAlphanumeric(15)); senderAddress.setStreetNumber("23b"); return senderAddress; }
@Test public void shouldReturnOkIfRequiredHeadersArePresent() throws Exception { Collection<String> requiredHeaders = Stream.of("header1", "header2") .map(Util::randomizeCase) .collect(toList()); SampleMethodHandler sampleMethodHandlerWithRequiredHeaders = new SampleMethodHandler(requiredHeaders); sampleMethodHandlerWithRequiredHeaders.registerPerContentType(CONTENT_TYPE_1, contentTypeMapper1); sampleMethodHandlerWithRequiredHeaders.registerPerAccept(ACCEPT_TYPE_1, acceptMapper1); int output = 0; Map<String, String> headers = requiredHeaders.stream().collect(toConcurrentMap( identity(), header -> RandomStringUtils.randomAlphabetic(5) )); randomiseKeyValues(headers); ApiGatewayProxyRequest requestWithRequiredHeaders = new ApiGatewayProxyRequestBuilder() .withContext(context) .withHeaders(headers) .build(); when(contentTypeMapper1.toInput(requestWithRequiredHeaders, context)).thenReturn(output); when(acceptMapper1.outputToResponse(output)).thenReturn(new ApiGatewayProxyResponse.ApiGatewayProxyResponseBuilder() .withStatusCode(OK.getStatusCode()) .build()); ApiGatewayProxyResponse response = sampleMethodHandlerWithRequiredHeaders.handle(requestWithRequiredHeaders, singletonList(CONTENT_TYPE_1), singletonList(ACCEPT_TYPE_1), context); assertThat(response.getStatusCode()).isEqualTo(OK.getStatusCode()); }
@Test public void shouldNotBeAbleToCreateAnAuthorityWhenTheAuthorityNameAlredyExists() { String name = RandomStringUtils.randomAlphanumeric(15); authority().withName(name).save(); onCreate(authority().withName(name).build()).rejected().withError("ATH-0003", "This authority name is already in use.", ResourceConflictException.class); }
/** * Get random bytes. * * @param count * Number of bytes. * @param textual * Whether the generated data should be textual. * @return The random bytes. */ private byte[] getRandomBytes(int count, boolean textual) { if (textual) { return RandomStringUtils.random(count, 0, 0, true, true, null, rand).getBytes(StandardCharsets.US_ASCII); } else { byte[] data = new byte[count]; rand.nextBytes(data); return data; } }
public Iterable<Row> call(ParquetGeneratorBean x) throws IOException { List<Row> result = new ArrayList<Row>(x.getNumRecord()); Random random = new Random(x.getSeed()); for (int i = 0; i < x.getNumRecord(); i++) { List<Object> temp = new ArrayList<Object>(x.getStructRecord().size()); for (Map.Entry<String, String> entry : x.getStructRecord().entrySet()) { switch (entry.getValue().toLowerCase()) { case "string": temp.add(RandomStringUtils.randomAlphabetic(5)); break; case "int": temp.add(random.nextInt()); break; case "double": temp.add(random.nextDouble()); break; case "dictionary": temp.add(names.get(random.nextInt(names.size()))); break; } } if (!temp.isEmpty()) { result.add(RowFactory.create(temp.toArray())); } } return result; }
@Test public void shouldNotBeAbleToCreateAClientIfTheClientIdAlreadyExists() { String clientId = RandomStringUtils.randomAlphanumeric(15); client().withClientId(clientId).withGrantType(grantType).save(); onCreate(client().withClientId(clientId).withGrantType(grantType).build()).rejected().withError("CLI-0003", "This client id is already in use.", ResourceConflictException.class); }
@Override public Event doExecute(final RequestContext requestContext) throws Exception { final Integer code = Integer.valueOf(RandomStringUtils.randomNumeric(8)); final AzureAuthenticatorTokenCredential c = new AzureAuthenticatorTokenCredential(); c.setToken(code.toString()); WebUtils.putCredential(requestContext, c); requestContext.getFlowScope().put("azureToken", code); if (mode == MultifactorAuthenticationProperties.Azure.AuthenticationModes.POUND) { return new EventFactorySupport().event(this, "authenticate"); } return success(); }
@Test public void test_payment_app_with_success_result() { //创建请求体 BrcbPaymentAlipayAppRequestBody body = new BrcbPaymentAlipayAppRequestBody(); body.setNotifyUrl("http://will.dev.pufubao.net/n/brcb"); body.setOutTradeNo("OUTTRADENO-" + RandomStringUtils.randomNumeric(4)); body.setSpbillCreateIp("127.0.0.1"); body.setOutTradeNo("TEST-ORDER-" + RandomStringUtils.randomNumeric(10));// body.setTotalFee("1"); body.setBody("测试支付"); body.setNonceStr(RandomStringUtils.randomAlphabetic(30)); //返回被封装成2层 //1. 状态化的返回体, 负责整体api调用是否成功型封装 //2. 具体业务需要的返回体, 在状态化的返回体中 payload中承载, 负责业务返回 BrcbStatefulApiResponseBody<BrcbPaymentAlipayAppResponseBody> statefulApiResponseBody = (BrcbStatefulApiResponseBody) brcbAlipayPaymentApi .sandbox(true) .app(body); //断言状态化返回体不可以为空 assertNotNull(statefulApiResponseBody); // // //由于提交的参数不全, 所以预期出现以下错误 // assertEquals("FAIL", statefulApiResponseBody.getReturnCode()); // assertEquals("结算信息不存在", statefulApiResponseBody.getReturnMsg()); }
@Test public void testHugeBloomFilter() { BloomFilter<String> filter1 = new BloomFilter<>(1000000, 3, bitVectorFactory); for (int i = 0; i < 100000; i++) { String s = RandomStringUtils.randomAlphabetic(i % 25 + 1); //System.out.println(s); filter1.add(s); } // TODO check normal distribution }
@Ignore @Test public void producerSendsToNonExistingTopic() { ServiceProperties serviceProperties = fillServiceProperties(); Topic cruft = new Topic("cruft"); Topic lard = new Topic("lard"); Producer producer = new ProducerFactory(serviceProperties).createProducer(); String key = RandomStringUtils.randomAscii(5); SayHelloToCmd payload = SayHelloToCmd.newBuilder().setName(key).build(); Message request = Messages.requestFor(cruft, lard, key, payload, new OrangeContext()); producer.send(request); // Results: // 1.) NO topic auto creation i.e. KAFKA_AUTO_CREATE_TOPICS_ENABLE = false // 2017-04-12 18:14:41,239 [Time-limited test] DEBUG c.s.s.f.kafka.messaging.Producer - Sending message com.sixt.service.framework.kafka.messaging.SayHelloToCmd with key O+oRQ to topic cruft // loads of: 2017-04-12 18:14:41,340 [kafka-producer-network-thread | producer-2] WARN o.apache.kafka.clients.NetworkClient - Error while fetching metadata with correlation id 0 : {cruft=UNKNOWN_TOPIC_OR_PARTITION} // and finally: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms. // 2.) WITH topic auto creation i.e. KAFKA_AUTO_CREATE_TOPICS_ENABLE = true // 2017-04-12 18:18:24,488 [Time-limited test] DEBUG c.s.s.f.kafka.messaging.Producer - Sending message com.sixt.service.framework.kafka.messaging.SayHelloToCmd with key uXdJ~ to topic cruft // one: 2017-04-12 18:18:24,638 [kafka-producer-network-thread | producer-2] WARN o.apache.kafka.clients.NetworkClient - Error while fetching metadata with correlation id 0 : {cruft=LEADER_NOT_AVAILABLE // and finally: success }
@Test public void testConfigLoadedWithPropertiesFile() throws Exception { String filePath = "test.properties"; String expectedMessage = RandomStringUtils.randomAlphanumeric(12); putFileInEtcd(filePath, String.format("message=%s", expectedMessage)); testConfigLoaded(filePath, expectedMessage); }