Java Code Examples for org.apache.commons.lang.RandomStringUtils#random()

The following examples show how to use org.apache.commons.lang.RandomStringUtils#random() . 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: TAzureStorageOuputTableTestIT.java    From components with Apache License 2.0 6 votes vote down vote up
public TAzureStorageOuputTableTestIT() {
    super("tAzureStorageOutputTableTest");

    properties = new TAzureStorageOutputTableProperties("tests");
    properties = (TAzureStorageOutputTableProperties) setupConnectionProperties(
            (AzureStorageProvideConnectionProperties) properties);
    properties.setupProperties();
    properties.tableName.setValue(tbl_test);
    properties.actionOnTable.setValue(ActionOnTable.Create_table_if_does_not_exist);
    testTimestamp = new Date();
    testString = RandomStringUtils.random(50);

    schemaMappings.add("daty");
    propertyMappings.add("datyMapped");
    schemaMappings.add("inty");
    propertyMappings.add("intyMapped");
    schemaMappings.add("stringy");
    propertyMappings.add("stringyMapped");
    schemaMappings.add("longy");
    propertyMappings.add("longyMapped");
    schemaMappings.add("doubly");
    propertyMappings.add("doublyMapped");
    schemaMappings.add("bytys");
    propertyMappings.add("bytysMapped");

}
 
Example 2
Source File: TestStandardHttpServletResponseEx.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void sendPart_succ() throws Throwable {
  String src = RandomStringUtils.random(100);
  InputStream inputStream = new ByteArrayInputStream(src.getBytes());
  Part part = new InputStreamPart("name", inputStream);
  Buffer buffer = Buffer.buffer();
  ServletOutputStream outputStream = new MockUp<ServletOutputStream>() {
    @Mock
    void write(int b) {
      buffer.appendByte((byte) b);
    }
  }.getMockInstance();

  new Expectations() {
    {
      response.getOutputStream();
      result = outputStream;
    }
  };

  responseEx.sendPart(part).get();

  Assert.assertEquals(src, buffer.toString());
}
 
Example 3
Source File: TestDFSUtil.java    From RDFS with Apache License 2.0 6 votes vote down vote up
private void validatePathConversion(boolean full, boolean isDirectory)
    throws UnsupportedEncodingException {
  Random r = new Random(System.currentTimeMillis());
  // random depth
  int depth = r.nextInt(20) + 1;
  // random length
  int len = r.nextInt(20) + 1;
  String path = "";
  // "xxx" are used to ensure that "/" are not neighbors at the front
  // or the path does not unintentionally end with "/"
  for (int i = 0; i < depth; i++) {
    path += "/xxx"
        + (full ? RandomStringUtils.random(len) : RandomStringUtils
            .randomAscii(len)) + "xxx";
  }
  if (isDirectory)
    path += "xxx/";

  byte[][] pathComponentsFast = DFSUtil.splitAndGetPathComponents(path);
  byte[][] pathComponentsJava = getPathComponentsJavaBased(path);
  comparePathComponents(pathComponentsFast, pathComponentsJava);

  assertNull(DFSUtil.splitAndGetPathComponents("non-separator" + path));
  assertNull(DFSUtil.splitAndGetPathComponents(null));
  assertNull(DFSUtil.splitAndGetPathComponents(""));
}
 
Example 4
Source File: CreateSecretCmdExecIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateSecret() throws Exception {
    DockerClient dockerClient = startSwarm();
    int length = 10;
    boolean useLetters = true;
    boolean useNumbers = false;
    String secretName = RandomStringUtils.random(length, useLetters, useNumbers);
    CreateSecretResponse exec = dockerClient.createSecretCmd(new SecretSpec().withName(secretName).withData("mon secret en clair")).exec();
    assertThat(exec, notNullValue());
    assertThat(exec.getId(), notNullValue());
    LOG.info("Secret created with ID {}", exec.getId());


    List<Secret> secrets = dockerClient.listSecretsCmd()
            .withNameFilter(Lists.newArrayList(secretName))
            .exec();

    assertThat(secrets, IsCollectionWithSize.hasSize(1));

    dockerClient.removeSecretCmd(secrets.get(0).getId())
            .exec();
    LOG.info("Secret removed with ID {}", exec.getId());
    List<Secret> secretsAfterRemoved = dockerClient.listSecretsCmd()
            .withNameFilter(Lists.newArrayList(secretName))
            .exec();

    assertThat(secretsAfterRemoved, IsCollectionWithSize.hasSize(0));
}
 
Example 5
Source File: AtlasHiveHookContext.java    From atlas with Apache License 2.0 5 votes vote down vote up
public String getQualifiedName(Table table) {
    String tableName = table.getTableName();

    if (table.isTemporary()) {
        if (SessionState.get() != null && SessionState.get().getSessionId() != null) {
            tableName = tableName + TEMP_TABLE_PREFIX + SessionState.get().getSessionId();
        } else {
            tableName = tableName + TEMP_TABLE_PREFIX + RandomStringUtils.random(10);
        }
    }

    return (table.getDbName() + QNAME_SEP_ENTITY_NAME + tableName + QNAME_SEP_METADATA_NAMESPACE).toLowerCase() + getMetadataNamespace();
}
 
Example 6
Source File: RandomTextDataGenerator.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for {@link RandomTextDataGenerator}.
 * @param size the total number of words to consider.
 * @param seed Random number generator seed for repeatability
 * @param wordSize Size of each word
 */
RandomTextDataGenerator(int size, Long seed, int wordSize) {
  random = new Random(seed);
  words = new String[size];
  
  //TODO change the default with the actual stats
  //TODO do u need varied sized words?
  for (int i = 0; i < size; ++i) {
    words[i] = 
      RandomStringUtils.random(wordSize, 0, 0, true, false, null, random);
  }
}
 
Example 7
Source File: RandomTextDataGenerator.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for {@link RandomTextDataGenerator}.
 * @param size the total number of words to consider.
 * @param seed Random number generator seed for repeatability
 * @param wordSize Size of each word
 */
RandomTextDataGenerator(int size, Long seed, int wordSize) {
  random = new Random(seed);
  words = new String[size];
  
  //TODO change the default with the actual stats
  //TODO do u need varied sized words?
  for (int i = 0; i < size; ++i) {
    words[i] = 
      RandomStringUtils.random(wordSize, 0, 0, true, false, null, random);
  }
}
 
Example 8
Source File: ListSecretCmdExecIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void tesListSecret() throws DockerException {
    DockerClient dockerClient = startSwarm();
    int length = 10;
    boolean useLetters = true;
    boolean useNumbers = false;
    String secretName = RandomStringUtils.random(length, useLetters, useNumbers);
    CreateSecretResponse exec = dockerClient.createSecretCmd(new SecretSpec().withName(secretName).withData("mon secret en clair")).exec();
    assertThat(exec, notNullValue());
    assertThat(exec.getId(), notNullValue());
    LOG.info("Secret created with ID {}", exec.getId());


    List<Secret> secrets = dockerClient.listSecretsCmd()
            .withNameFilter(Lists.newArrayList(secretName))
            .exec();

    assertThat(secrets, hasSize(1));

    dockerClient.removeSecretCmd(secrets.get(0).getId())
            .exec();
    LOG.info("Secret removed with ID {}", exec.getId());
    List<Secret> secretsAfterRemoved = dockerClient.listSecretsCmd()
            .withNameFilter(Lists.newArrayList(secretName))
            .exec();

    assertThat(secretsAfterRemoved, hasSize(0));

}
 
Example 9
Source File: ContainerExecDecoratorTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void configureCloud() throws Exception {
    cloud = setupCloud(this, name);
    client = cloud.connect();
    deletePods(client, getLabels(this, name), false);

    String image = "busybox";
    Container c = new ContainerBuilder().withName(image).withImagePullPolicy("IfNotPresent").withImage(image)
            .withCommand("cat").withTty(true).build();
    Container d = new ContainerBuilder().withName(image + "1").withImagePullPolicy("IfNotPresent").withImage(image)
            .withCommand("cat").withTty(true).withWorkingDir("/home/jenkins/agent1").build();
    String podName = "test-command-execution-" + RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
    pod = client.pods().create(new PodBuilder().withNewMetadata().withName(podName)
            .withLabels(getLabels(this, name)).endMetadata().withNewSpec().withContainers(c, d).withNodeSelector(Collections.singletonMap("kubernetes.io/os", "linux")).withTerminationGracePeriodSeconds(0L).endSpec().build());

    System.out.println("Created pod: " + pod.getMetadata().getName());

    PodTemplate template = new PodTemplate();
    template.setName(pod.getMetadata().getName());
    agent = mock(KubernetesSlave.class);
    when(agent.getNamespace()).thenReturn(client.getNamespace());
    when(agent.getPodName()).thenReturn(pod.getMetadata().getName());
    doReturn(cloud).when(agent).getKubernetesCloud();
    when(agent.getPod()).thenReturn(Optional.of(pod));
    StepContext context = mock(StepContext.class);
    when(context.get(Node.class)).thenReturn(agent);

    decorator = new ContainerExecDecorator();
    decorator.setNodeContext(new KubernetesNodeContext(context));
    decorator.setContainerName(image);
}
 
Example 10
Source File: CodeVerifier.java    From oxAuth with MIT License 5 votes vote down vote up
public static String generateCodeVerifier() {
    String alphabetic = "abcdefghijklmnopqrstuvwxyz";
    String chars = alphabetic + alphabetic.toUpperCase()
            + "1234567890" + "-._~";
    String code = RandomStringUtils.random(MAX_CODE_VERIFIER_LENGTH, chars);
    Preconditions.checkState(isCodeVerifierValid(code));
    return code;
}
 
Example 11
Source File: ECSCloud.java    From amazon-ecs-plugin with MIT License 5 votes vote down vote up
@Override
public synchronized Collection<NodeProvisioner.PlannedNode> provision(Label label, int excessWorkload) {

    LOGGER.log(Level.INFO, "Asked to provision {0} agent(s) for: {1}", new Object[]{excessWorkload, label});

    List<NodeProvisioner.PlannedNode> result = new ArrayList<>();
    final ECSTaskTemplate template = getTemplate(label);
    if (template != null) {
        String parentLabel = template.getInheritFrom();
        final ECSTaskTemplate merged = template.merge(getTemplate(parentLabel));

        for (int i = 1; i <= excessWorkload; i++) {
            String agentName = name + "-" + label.getName() + "-" + RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
            LOGGER.log(Level.INFO, "Will provision {0}, for label: {1}", new Object[]{agentName, label} );
            result.add(
                    new NodeProvisioner.PlannedNode(
                            agentName,
                            Computer.threadPoolForRemoting.submit(
                                    new ProvisioningCallback(merged, agentName)
                            ),
                            1
                    )
            );
        }
    }
    return result.isEmpty() ? Collections.emptyList() : result;

}
 
Example 12
Source File: XMLMappingGeneratorTrans.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
private String getGTName(QName name) {
	if (name == null) {
		return null;
	}
	if (name.getNamespaceURI() == null) {
		return name.getLocalPart();
	}
	if (name.getNamespaceURI().isEmpty()) {
		return name.getLocalPart();
	}
	if (name.getLocalPart() == null) {
		return null;
	}
	if (name.getLocalPart().isEmpty()) {
		return null;
	}
	String prefix = namespaces.get(name.getNamespaceURI());
	if (prefix != null) {
		return prefix + ":" + name.getLocalPart();
	}
	String newprefix = new String(name.getNamespaceURI());
	// newprefix+="#";
	String newrandomstring = RandomStringUtils.random(5, true, false);
	namespaces.put(newprefix, newrandomstring);
	return newrandomstring + ":" + name.getLocalPart();

}
 
Example 13
Source File: UpdateClientAction.java    From oxTrust with MIT License 4 votes vote down vote up
public void generatePassword() throws EncryptionException {
	String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	String pwd = RandomStringUtils.random(40, characters);
	this.client.setOxAuthClientSecret(pwd);
	this.client.setEncodedClientSecret(encryptionService.encrypt(pwd));
}
 
Example 14
Source File: PhdParticipant.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void ensureExternalAccess() {
    if (StringUtils.isEmpty(getAccessHashCode())) {
        super.setAccessHashCode(UUID.randomUUID().toString());
        super.setPassword(RandomStringUtils.random(15, 0, 0, true, true, null, new SecureRandom()));
    }
}
 
Example 15
Source File: TestConcurrentClients.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
static String randomString( int len ){
  return RandomStringUtils.random(len, true, false);
}
 
Example 16
Source File: InsecureHTTPMethod.java    From zap-extensions with Apache License 2.0 4 votes vote down vote up
private void testTraceOrTrack(String method) throws Exception {

        HttpMessage msg = getNewMsg();
        msg.getRequestHeader().setMethod(method);
        // TRACE is supported in 1.0. TRACK is presumably the same, since it is
        // a alias for TRACE. Typical Microsoft.
        msg.getRequestHeader().setVersion(HttpRequestHeader.HTTP10);
        String randomcookiename =
                RandomStringUtils.random(
                        15, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
        String randomcookievalue =
                RandomStringUtils.random(
                        40, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
        TreeSet<HtmlParameter> cookies = msg.getCookieParams();
        cookies.add(
                new HtmlParameter(HtmlParameter.Type.cookie, randomcookiename, randomcookievalue));
        msg.setCookieParams(cookies);
        // do not follow redirects. That might ruin our day.
        sendAndReceive(msg, false);

        // if the response *body* from the TRACE request contains the cookie,we're in business :)
        if (msg.getResponseBody().toString().contains(randomcookievalue)) {
            newAlert()
                    .setConfidence(Alert.CONFIDENCE_MEDIUM)
                    .setName(
                            Constant.messages.getString(
                                    "ascanbeta.insecurehttpmethod.detailed.name", method))
                    .setDescription(
                            Constant.messages.getString(
                                    "ascanbeta.insecurehttpmethod.trace.exploitable.desc", method))
                    .setUri(msg.getRequestHeader().getURI().getURI())
                    .setOtherInfo(
                            Constant.messages.getString(
                                    "ascanbeta.insecurehttpmethod.trace.exploitable.extrainfo",
                                    randomcookievalue))
                    .setSolution(Constant.messages.getString("ascanbeta.insecurehttpmethod.soln"))
                    .setEvidence(randomcookievalue)
                    .setMessage(msg)
                    .raise();
        }
    }
 
Example 17
Source File: DistkvListBenchmark.java    From distkv with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Benchmark
public void testAsyncPut() {
  String randomStr = RandomStringUtils.random(5);
  asyncClient.lists().put(randomStr, dummyData);
}
 
Example 18
Source File: EntityJerseyResourceIT.java    From atlas with Apache License 2.0 4 votes vote down vote up
private String random() {
    return RandomStringUtils.random(10);
}
 
Example 19
Source File: StringUtil.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static String getRandomString(int length) {
    return RandomStringUtils.random(length);
}
 
Example 20
Source File: StringUtil.java    From jeewx with Apache License 2.0 3 votes vote down vote up
/**
 * 随即生成指定位数的含验证码字符串
 * 
 * @author Peltason
 * 
 * @date 2007-5-9
 * @param bit
 *            指定生成验证码位数
 * @return String
 */
public static String random(int bit) {
	if (bit == 0)
		bit = 6; // 默认6位
	// 因为o和0,l和1很难区分,所以,去掉大小写的o和l
	String str = "";
	str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz";// 初始化种子
	return RandomStringUtils.random(bit, str);// 返回6位的字符串
}