Java Code Examples for org.apache.commons.lang3.RandomStringUtils#randomAscii()

The following examples show how to use org.apache.commons.lang3.RandomStringUtils#randomAscii() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProtoBufRecordReaderTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private static Object generateRandomSingleValue(FieldSpec fieldSpec) {
  switch (fieldSpec.getDataType()) {
    case INT:
      return RANDOM.nextInt();
    case LONG:
      return RANDOM.nextLong();
    case FLOAT:
      return RANDOM.nextFloat();
    case DOUBLE:
      return RANDOM.nextDouble();
    case STRING:
      return RandomStringUtils.randomAscii(RANDOM.nextInt(50) + 1);
    default:
      throw new RuntimeException("Not supported fieldSpec - " + fieldSpec);
  }
}
 
Example 2
Source File: FileVersionSelectorTest.java    From PeerWasp with MIT License 6 votes vote down vote up
private static void uploadVersions() throws  Exception {
	content = new ArrayList<String>();

	// add an intial file to the network
	file = new File(root, fileName);
	String fileContent = RandomStringUtils.randomAscii(FILE_SIZE);
	content.add(fileContent);
	logger.info("Initial content: {}...", fileContent.substring(0, 10));
	FileUtils.write(file, fileContent);
	client.getFileManager().createAddProcess(file).execute();

	// update and upload
	for(int i = 0; i < NUM_VERSIONS; ++i) {
		Thread.sleep(2000); // sleep such that each file has different timestamp
		fileContent = RandomStringUtils.randomAscii(FILE_SIZE);
		content.add(fileContent);
		logger.info("File version {} content: {}...", i, fileContent.substring(0, 10));
		FileUtils.write(file, fileContent);
		client.getFileManager().createUpdateProcess(file).execute();
	}
}
 
Example 3
Source File: MessageFailureTest.java    From knox with Apache License 2.0 6 votes vote down vote up
/**
 * Test for a message that bigger than Jetty default but smaller than limit
 * @throws Exception exception on failure
 */
@Test(timeout = 8000)
public void testMessageBiggerThanDefault() throws Exception {
  final String bigMessage = RandomStringUtils.randomAscii(66000);

  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  javax.websocket.Session session = container.connectToServer(client,
          proxyUri);
  session.getBasicRemote().sendText(bigMessage);

  client.awaitClose(CloseReason.CloseCodes.TOO_BIG.getCode(), 1000,
          TimeUnit.MILLISECONDS);

  Assert.assertThat(client.close.getCloseCode().getCode(), CoreMatchers.is(CloseReason.CloseCodes.TOO_BIG.getCode()));

}
 
Example 4
Source File: AbstractRecordReaderTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private static Object generateRandomSingleValue(FieldSpec fieldSpec) {
  switch (fieldSpec.getDataType()) {
    case INT:
      return RANDOM.nextInt();
    case LONG:
      return RANDOM.nextLong();
    case FLOAT:
      return RANDOM.nextFloat();
    case DOUBLE:
      return RANDOM.nextDouble();
    case STRING:
      return RandomStringUtils.randomAscii(RANDOM.nextInt(50) + 1);
    default:
      throw new RuntimeException("Not supported fieldSpec - " + fieldSpec);
  }
}
 
Example 5
Source File: TestMessageContextManager.java    From data-highway with Apache License 2.0 6 votes vote down vote up
public TestMessageContext nextContext() {
  long seqNumber = seqCounter.getAndIncrement();
  String payload = RandomStringUtils.randomAscii(payloadSize);
  int partitionNumber = Math.abs((int) (seqNumber % TOTAL_GROUPS));
  TestMessage message = new TestMessage(origin, partitionNumber, seqNumber, System.currentTimeMillis(), payload);

  TestMessageContext context = new TestMessageContext(message, messageTimeout, metrics, globalActionQueue);

  context.setPrevious(partitionPreviousContext[partitionNumber]);
  partitionPreviousContext[partitionNumber] = context;
  activeMessages.put(seqNumber, context);

  service.schedule(() -> {
    globalActionQueue.offer(() -> {
      try {
        context.generateReport();
      } finally {
        activeMessages.remove(seqNumber);
        context.setPrevious(null); // Prevent memory leak
      }
    });
  }, messageTimeout.toMillis(), MILLISECONDS);

  return context;
}
 
Example 6
Source File: ErrataHandlerTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
public void testAdvisoryLength() throws Exception {
    Channel channel = ChannelFactoryTest.createBaseChannel(admin);

    Map errataInfo = new HashMap();


    String advisoryName = RandomStringUtils.randomAscii(101);
    populateErrataInfo(errataInfo);
    errataInfo.put("advisory_name", advisoryName);

    ArrayList packages = new ArrayList();
    ArrayList bugs = new ArrayList();
    ArrayList keywords = new ArrayList();
    ArrayList channels = new ArrayList();
    channels.add(channel.getLabel());

    try {
        Errata errata = handler.create(admin, errataInfo,
            bugs, keywords, packages, channels);
        fail("large advisory name was accepted");
    }
    catch (Exception e) {
        // we expect this to fail
        assertTrue(true);
    }
}
 
Example 7
Source File: Consumer.java    From YuRPC with Apache License 2.0 6 votes vote down vote up
/**
 * 入口方法
 *
 * @param args 参数
 * @throws Throwable 异常
 */
public static void main(String... args) throws Throwable {
    YuRPCClient yuRPCClient = YuRPCClient.defaultYuRPCClient();
    yuRPCClient.start();
    SayService sayService = yuRPCClient.proxy(SayService.class);
    for (int no = 0; no < 100; no++) {
        String value = RandomStringUtils.randomAscii(128);
        Say say = new Say(no, value);
        System.out.println(sayService.perform(say));
    }
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            yuRPCClient.shutdown();
        } catch (Throwable ex) {
            LOGGER.error(ex.getMessage());
        }
    }));
}
 
Example 8
Source File: StringsTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test
public void test_create_prefixed_max_length() throws Exception {
    final String randomString = RandomStringUtils.randomAscii(Short.MAX_VALUE);
    final ByteBuf buf = Strings.createPrefixedBytesFromString(randomString, Unpooled.buffer());

    assertEquals(Short.MAX_VALUE, buf.readShort());
    buf.readBytes(Short.MAX_VALUE);
    assertEquals(false, buf.isReadable());
}
 
Example 9
Source File: ApplicationConsumer.java    From YuRPC with Apache License 2.0 5 votes vote down vote up
/**
 * 启动时钩子
 *
 * @return
 */
@Bean
public CommandLineRunner commandLineRunner() {
    return (String... args) -> {
        for (int no = 0; no < 100; no++) {
            String value = RandomStringUtils.randomAscii(128);
            Say say = new Say(no, value);
            System.out.println(sayService.perform(say));
        }
    };
}
 
Example 10
Source File: SayMethod.java    From YuRPC with Apache License 2.0 5 votes vote down vote up
@Override
public void exec(Object params) throws Exception {
    Integer id = (Integer) params;
    String value = RandomStringUtils.randomAscii(128);
    Say say = new Say(id, value);
    sayService.perform(say);
}
 
Example 11
Source File: KickstartScriptTest.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
public void testLargeScript() throws Exception {
    String largeString = RandomStringUtils.randomAscii(4000);
    KickstartData ksdata = KickstartDataTest.createKickstartWithOptions(user.getOrg());
    ksdata.getScripts().clear();
    KickstartFactory.saveKickstartData(ksdata);
    ksdata = (KickstartData) reload(ksdata);

    // Create 2 scripts, one with data, one without.
    KickstartScript script = createPost(ksdata);
    script.setPosition(1L);
    KickstartScript scriptEmpty = createPost(ksdata);
    script.setData(largeString.getBytes("UTF-8"));

    // Make sure we are setting the blob to be an empty byte
    // array.  The bug happens when one script is empty.
    scriptEmpty.setData(new byte[0]);
    scriptEmpty.setPosition(2L);
    ksdata.addScript(script);
    ksdata.addScript(scriptEmpty);
    TestUtils.saveAndFlush(script);
    TestUtils.saveAndFlush(scriptEmpty);

    KickstartFactory.saveKickstartData(ksdata);
    ksdata = (KickstartData) reload(ksdata);
    Iterator i = ksdata.getScripts().iterator();
    boolean found = false;
    assertTrue(ksdata.getScripts().size() == 2);
    while (i.hasNext()) {
        KickstartScript loaded = (KickstartScript) i.next();
        if (loaded.getDataContents().equals(largeString)) {
            found = true;
        }
    }
    assertTrue(found);
}
 
Example 12
Source File: KafkaFailoverIntegrationTest.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
@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
}
 
Example 13
Source File: SqsAsyncStabilityTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void sendMessage() {
    log.info(() -> String.format("Starting testing sending messages to queue %s with queueUrl %s", queueName, queueUrl));
    String messageBody = RandomStringUtils.randomAscii(1000);
    IntFunction<CompletableFuture<?>> futureIntFunction =
        i -> sqsAsyncClient.sendMessage(b -> b.queueUrl(queueUrl).messageBody(messageBody));

    runSqsTests("sendMessage", futureIntFunction);
}
 
Example 14
Source File: ShareFolderStarter.java    From PeerWasp with MIT License 5 votes vote down vote up
private void initFiles() throws Exception {
	Path toShare = rootA.resolve(sharedFolderName);
	Files.createDirectory(toShare);

	Path f = toShare.resolve("testfile.txt");
	String content = RandomStringUtils.randomAscii(512*1024);
	Files.write(f, content.getBytes());

	clientsA[0].getFileManager().createAddProcess(toShare.toFile()).execute();
	clientsA[0].getFileManager().createAddProcess(f.toFile()).execute();
}
 
Example 15
Source File: S3KeyGenerator.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Override
public Void call() throws Exception {

  if (multiPart && fileSize < OM_MULTIPART_MIN_SIZE) {
    throw new IllegalArgumentException(
        "Size of multipart upload parts should be at least 5MB (5242880)");
  }
  init();

  AmazonS3ClientBuilder amazonS3ClientBuilder =
      AmazonS3ClientBuilder.standard()
          .withCredentials(new EnvironmentVariableCredentialsProvider());

  if (endpoint.length() > 0) {
    amazonS3ClientBuilder
        .withPathStyleAccessEnabled(true)
        .withEndpointConfiguration(
            new EndpointConfiguration(endpoint, "us-east-1"));

  } else {
    amazonS3ClientBuilder.withRegion(Regions.DEFAULT_REGION);
  }

  s3 = amazonS3ClientBuilder.build();

  content = RandomStringUtils.randomAscii(fileSize);

  timer = getMetrics().timer("key-create");

  System.setProperty(DISABLE_PUT_OBJECT_MD5_VALIDATION_PROPERTY, "true");
  runTests(this::createKey);

  return null;
}
 
Example 16
Source File: YuRPCServerTest.java    From YuRPC with Apache License 2.0 4 votes vote down vote up
@Benchmark
public void perform() {
    String value = RandomStringUtils.randomAscii(128);
    Say say = new Say(no.incrementAndGet(), value);
    System.out.println(sayService.perform(say));
}
 
Example 17
Source File: KafkaFailoverIntegrationTest.java    From ja-micro with Apache License 2.0 4 votes vote down vote up
@Ignore
@Test
public void consumerSubscribesToNonExistingTopic() throws InterruptedException {
    ServiceProperties serviceProperties = fillServiceProperties();

    Topic cruft = new Topic("krufty");

    CountDownLatch latch = new CountDownLatch(1);

    Consumer consumer = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class, new MessageHandler<SayHelloToCmd>() {
                @Override
                public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) {
                    latch.countDown();
                }
            }
    ).consumerForTopic(cruft, new DiscardFailedMessages());


    Producer producer = new ProducerFactory(serviceProperties).createProducer();

    String key = RandomStringUtils.randomAscii(5);
    SayHelloToCmd payload = SayHelloToCmd.newBuilder().setName(key).build();

    Message request = Messages.requestFor(cruft, cruft, key, payload, new OrangeContext());

    producer.send(request);


    assertTrue(latch.await(1, TimeUnit.MINUTES));
    producer.shutdown();
    consumer.shutdown();


    // Results:
    // 1.) WITH topic auto creation i.e. KAFKA_AUTO_CREATE_TOPICS_ENABLE = true
    // All ok, needs to discover coordinator etc.
    // 2.) NO topic auto creation i.e. KAFKA_AUTO_CREATE_TOPICS_ENABLE = false
    //2017-04-12 18:27:16,701 [pool-9-thread-1] INFO  c.s.s.f.kafka.messaging.Consumer - Consumer in group kruftmeister-com.sixt.service.unknown subscribed to topic kruftmeister
    //2017-04-12 18:27:16,852 [pool-9-thread-1] WARN  o.apache.kafka.clients.NetworkClient - Error while fetching metadata with correlation id 1 : {kruftmeister=UNKNOWN_TOPIC_OR_PARTITION}
    //2017-04-12 18:27:18,876 [pool-9-thread-1] WARN  o.apache.kafka.clients.NetworkClient - Error while fetching metadata with correlation id 40 : {kruftmeister=UNKNOWN_TOPIC_OR_PARTITION}
    //2017-04-12 18:27:18,889 [pool-9-thread-1] INFO  o.a.k.c.c.i.AbstractCoordinator - Discovered coordinator 172.19.0.3:9092 (id: 2147482646 rack: null) for group kruftmeister-com.sixt.service.unknown.
    //2017-04-12 18:27:18,892 [pool-9-thread-1] INFO  o.a.k.c.c.i.ConsumerCoordinator - Revoking previously assigned partitions [] for group kruftmeister-com.sixt.service.unknown
    //2017-04-12 18:27:18,894 [pool-9-thread-1] DEBUG c.s.s.f.kafka.messaging.Consumer - ConsumerRebalanceListener.onPartitionsRevoked on []
    //2017-04-12 18:27:18,917 [pool-9-thread-1] INFO  o.a.k.c.c.i.AbstractCoordinator - (Re-)joining group kruftmeister-com.sixt.service.unknown
    //2017-04-12 18:27:18,937 [pool-9-thread-1] INFO  o.a.k.c.c.i.AbstractCoordinator - Marking the coordinator 172.19.0.3:9092 (id: 2147482646 rack: null) dead for group kruftmeister-com.sixt.service.unknown
    //2017-04-12 18:27:19,041 [pool-9-thread-1] INFO  o.a.k.c.c.i.AbstractCoordinator - Discovered coordinator 172.19.0.3:9092 (id: 2147482646 rack: null) for group kruftmeister-com.sixt.service.unknown.
    //2017-04-12 18:27:19,041 [pool-9-thread-1] INFO  o.a.k.c.c.i.AbstractCoordinator - (Re-)joining group kruftmeister-com.sixt.service.unknown
    //2017-04-12 18:27:19,135 [pool-9-thread-1] INFO  o.a.k.c.c.i.AbstractCoordinator - Successfully joined group kruftmeister-com.sixt.service.unknown with generation 1
    //2017-04-12 18:27:19,135 [pool-9-thread-1] INFO  o.a.k.c.c.i.ConsumerCoordinator - Setting newly assigned partitions [] for group kruftmeister-com.sixt.service.unknown
    //2017-04-12 18:27:19,135 [pool-9-thread-1] DEBUG c.s.s.f.kafka.messaging.Consumer - ConsumerRebalanceListener.onPartitionsAssigned on []
    // -> assigned to a topic with no partitions?
}
 
Example 18
Source File: RaftTest.java    From atomix with Apache License 2.0 4 votes vote down vote up
private void fillSegment(TestPrimitive primitive) throws InterruptedException, ExecutionException, TimeoutException {
  final String entry = RandomStringUtils.randomAscii(1024);
  primitive.write(entry).get(5, TimeUnit.SECONDS);
  IntStream.range(0, 10 - 1).forEach(i -> primitive.write(entry).join());
}
 
Example 19
Source File: TestSecureOzoneCluster.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetS3Secret() throws Exception {

  // Setup secure OM for start
  setupOm(conf);
  long omVersion =
      RPC.getProtocolVersion(OzoneManagerProtocolPB.class);
  try {
    // Start OM
    om.setCertClient(new CertificateClientTestImpl(conf));
    om.start();
    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    String username = ugi.getUserName();

    // Get first OM client which will authenticate via Kerberos
    omClient = new OzoneManagerProtocolClientSideTranslatorPB(
        OmTransportFactory.create(conf, ugi, null),
        RandomStringUtils.randomAscii(5));

    //Creates a secret since it does not exist
    S3SecretValue attempt1 = omClient.getS3Secret(username);

    //Fetches the secret from db since it was created in previous step
    S3SecretValue attempt2 = omClient.getS3Secret(username);

    //secret fetched on both attempts must be same
    assertEquals(attempt1.getAwsSecret(), attempt2.getAwsSecret());

    //access key fetched on both attempts must be same
    assertEquals(attempt1.getAwsAccessKey(), attempt2.getAwsAccessKey());


    try {
      omClient.getS3Secret("HADOOP/JOHNDOE");
      fail("testGetS3Secret failed");
    } catch (IOException ex) {
      GenericTestUtils.assertExceptionContains("USER_MISMATCH", ex);
    }
  } finally {
    IOUtils.closeQuietly(om);
  }
}
 
Example 20
Source File: FileTestUtils.java    From PeerWasp with MIT License 4 votes vote down vote up
public static String createRandomData(int numChars) {
	return RandomStringUtils.randomAscii(numChars);
}