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

The following examples show how to use org.apache.commons.lang3.RandomStringUtils#randomAlphanumeric() . 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: UserManagementServiceBean.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public String generateRememberMeToken(UUID userId) {
    String token = RandomStringUtils.randomAlphanumeric(RememberMeToken.TOKEN_LENGTH);

    try (Transaction tx = persistence.createTransaction()) {
        EntityManager em = persistence.getEntityManager();

        RememberMeToken rememberMeToken = metadata.create(RememberMeToken.class);
        rememberMeToken.setToken(token);
        rememberMeToken.setUser(em.getReference(User.class, userId));
        rememberMeToken.setCreateTs(new Date(timeSource.currentTimeMillis()));

        em.persist(rememberMeToken);

        tx.commit();
    }

    return token;
}
 
Example 2
Source File: FileLeafTest.java    From PeerWasp with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {

	// create file with content in folderA
	fileName = "file1.txt";
	file = folderA.resolve(fileName);
	content = RandomStringUtils.randomAlphanumeric(1000);
	Files.write(file, content.getBytes());
	leaf = new TestFileLeaf(file, true);
	leaf.updateContentHash();


	rootBase = new TestFolderComposite(basePath, true, true); // root
	parentA = new TestFolderComposite(folderA, true, false); // not root
	parentB = new TestFolderComposite(folderB, true, false); // not root

	rootBase.putComponent(parentA.getPath(), parentA);
	rootBase.putComponent(parentB.getPath(), parentB);
	rootBase.putComponent(leaf.getPath(), leaf);

	assertNull(rootBase.getParent());
	assertEquals(parentA.getParent(), rootBase);
	assertEquals(parentB.getParent(), rootBase);
	assertEquals(leaf.getParent(), parentA);
	assertNotEquals(leaf.getParent(), parentB);
}
 
Example 3
Source File: TestOzoneFileInterfaces.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testOzoneManagerLocatedFileStatus() throws IOException {
  String data = RandomStringUtils.randomAlphanumeric(20);
  String filePath = RandomStringUtils.randomAlphanumeric(5);
  Path path = createPath("/" + filePath);
  try (FSDataOutputStream stream = fs.create(path)) {
    stream.writeBytes(data);
  }
  FileStatus status = fs.getFileStatus(path);
  assertTrue(status instanceof LocatedFileStatus);
  LocatedFileStatus locatedFileStatus = (LocatedFileStatus) status;
  assertTrue(locatedFileStatus.getBlockLocations().length >= 1);

  for (BlockLocation blockLocation : locatedFileStatus.getBlockLocations()) {
    assertTrue(blockLocation.getNames().length >= 1);
    assertTrue(blockLocation.getHosts().length >= 1);
  }
}
 
Example 4
Source File: Bootstrap.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Transactional
public void createSystemUser() {
    logger.info("Creating system user with random password");
    String randomPassword = RandomStringUtils.randomAlphanumeric(15);

    User systemUser = userService.createUserWithRole(UserService.SYSTEM_USERNAME, randomPassword, Role.ADMIN);

    logger.debug("Disabling System user so that it can't be authenticated");
    systemUser.setEnabled(false);
    userRepository.save(systemUser);

    logger.debug("Setting created by user manually because there is no authenticated user context");
    userService.updateCreatedByUserToSystemUser(systemUser);
}
 
Example 5
Source File: TestBucketUtil.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
public static String getId(final int desiredBucket, final int bucketSize) {
    checkArgument(0 <= desiredBucket && desiredBucket < bucketSize);
    String id = RandomStringUtils.randomAlphanumeric(15);
    while (BucketUtils.getBucket(id, bucketSize) != desiredBucket) {
        id = RandomStringUtils.randomAlphanumeric(15);
    }
    return id;
}
 
Example 6
Source File: UserService.java    From mojito with Apache License 2.0 5 votes vote down vote up
public User createBasicUser(String username, String givenName, String surname, String commonName, boolean partiallyCreated) {
    logger.debug("Creating user: {}", username);

    String randomPassword = RandomStringUtils.randomAlphanumeric(15);
    User userWithRole = createUserWithRole(username, randomPassword, Role.USER, givenName, surname, commonName, partiallyCreated);

    logger.debug("Manually setting created by user to system user because at this point, there isn't an authenticated user context");
    updateCreatedByUserToSystemUser(userWithRole);

    return userWithRole;
}
 
Example 7
Source File: UtilHttp.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static String stashParameterMap(HttpServletRequest request) {
    HttpSession session = request.getSession();
    Map<String, Map<String, Object>> paramMapStore = UtilGenerics.checkMap(session.getAttribute("_PARAM_MAP_STORE_"));
    if (paramMapStore == null) {
        // SCIPIO: Synchronize the creation of this map to prevent lost entries, and
        // make sure it's thread-safe
        //paramMapStore = new HashMap<>();
        //session.setAttribute("_PARAM_MAP_STORE_", paramMapStore);
        synchronized (getSessionSyncObject(request)) {
            paramMapStore = UtilGenerics.checkMap(session.getAttribute("_PARAM_MAP_STORE_"));
            if (paramMapStore == null) {
                paramMapStore = new ConcurrentHashMap<>();
                session.setAttribute("_PARAM_MAP_STORE_", paramMapStore);
            }
        }
    }
    Map<String, Object> parameters = getParameterMap(request);
    // SCIPIO: Just in case of conflict, loop this
    //String paramMapId = RandomStringUtils.randomAlphanumeric(10);
    //paramMapStore.put(paramMapId, parameters);
    while(true) {
        String paramMapId = RandomStringUtils.randomAlphanumeric(10);
        if (paramMapStore.putIfAbsent(paramMapId, parameters) == null) {
            return paramMapId;
        }
    }
}
 
Example 8
Source File: DelayLoopPush.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length > 1) {
        LOGGER.error("too many args. only need one.");
        return;
    }

    LOGGER.info("benchmark push start");

    init(args[0]);

    RANDOM_STR = RandomStringUtils.randomAlphanumeric(pushConfig.getMsgBodyLen());
    final long start = System.currentTimeMillis();
    sendMsg();
    LOGGER.info("benchmark push over, cost:{}ms", System.currentTimeMillis() - start);
}
 
Example 9
Source File: TestOzoneFileInterfaces.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testListStatus() throws IOException {
  List<Path> paths = new ArrayList<>();
  String dirPath = RandomStringUtils.randomAlphanumeric(5);
  Path path = createPath("/" + dirPath);
  paths.add(path);
  assertTrue("Makedirs returned with false for the path " + path,
      fs.mkdirs(path));

  long listObjects = statistics.getLong(Statistic.OBJECTS_LIST.getSymbol());
  long omListStatus = omMetrics.getNumListStatus();
  FileStatus[] statusList = fs.listStatus(createPath("/"));
  assertEquals(1, statusList.length);
  assertEquals(++listObjects,
      statistics.getLong(Statistic.OBJECTS_LIST.getSymbol()).longValue());
  assertEquals(++omListStatus, omMetrics.getNumListStatus());
  assertEquals(fs.getFileStatus(path), statusList[0]);

  dirPath = RandomStringUtils.randomAlphanumeric(5);
  path = createPath("/" + dirPath);
  paths.add(path);
  assertTrue("Makedirs returned with false for the path " + path,
      fs.mkdirs(path));

  statusList = fs.listStatus(createPath("/"));
  assertEquals(2, statusList.length);
  assertEquals(++listObjects,
      statistics.getLong(Statistic.OBJECTS_LIST.getSymbol()).longValue());
  assertEquals(++omListStatus, omMetrics.getNumListStatus());
  for (Path p : paths) {
    assertTrue(Arrays.asList(statusList).contains(fs.getFileStatus(p)));
  }
}
 
Example 10
Source File: InvitationManager.java    From mxisd with GNU Affero General Public License v3.0 4 votes vote down vote up
public synchronized IThreePidInviteReply storeInvite(IThreePidInvite invitation) { // TODO better sync
    if (!notifMgr.isMediumSupported(invitation.getMedium())) {
        throw new BadRequestException("Medium type " + invitation.getMedium() + " is not supported");
    }

    String invId = computeId(invitation);
    log.info("Handling invite for {}:{} from {} in room {}", invitation.getMedium(), invitation.getAddress(), invitation.getSender(), invitation.getRoomId());
    IThreePidInviteReply reply = invitations.get(invId);
    if (reply != null) {
        log.info("Invite is already pending for {}:{}, returning data", invitation.getMedium(), invitation.getAddress());
        if (!StringUtils.equals(invitation.getRoomId(), reply.getInvite().getRoomId())) {
            log.info("Sending new notification as new invite room {} is different from the original {}", invitation.getRoomId(), reply.getInvite().getRoomId());
            notifMgr.sendForReply(new ThreePidInviteReply(reply.getId(), invitation, reply.getToken(), reply.getDisplayName(), reply.getPublicKeys()));
        } else {
            // FIXME we should check attempt and send if bigger
        }
        return reply;
    }

    Optional<SingleLookupReply> result = lookup3pid(invitation.getMedium(), invitation.getAddress());
    if (result.isPresent()) {
        log.info("Mapping for {}:{} already exists, refusing to store invite", invitation.getMedium(), invitation.getAddress());
        throw new MappingAlreadyExistsException();
    }

    String token = RandomStringUtils.randomAlphanumeric(64);
    String displayName = invitation.getAddress().substring(0, 3) + "...";
    KeyIdentifier pKeyId = keyMgr.getServerSigningKey().getId();
    KeyIdentifier eKeyId = keyMgr.generateKey(KeyType.Ephemeral);

    String pPubKey = keyMgr.getPublicKeyBase64(pKeyId);
    String ePubKey = keyMgr.getPublicKeyBase64(eKeyId);

    invitation.getProperties().put(CreatedAtPropertyKey, Long.toString(Instant.now().toEpochMilli()));
    invitation.getProperties().put("p_key_algo", pKeyId.getAlgorithm());
    invitation.getProperties().put("p_key_serial", pKeyId.getSerial());
    invitation.getProperties().put("p_key_public", pPubKey);
    invitation.getProperties().put("e_key_algo", eKeyId.getAlgorithm());
    invitation.getProperties().put("e_key_serial", eKeyId.getSerial());
    invitation.getProperties().put("e_key_public", ePubKey);

    reply = new ThreePidInviteReply(invId, invitation, token, displayName, Arrays.asList(pPubKey, ePubKey));

    log.info("Performing invite to {}:{}", invitation.getMedium(), invitation.getAddress());
    notifMgr.sendForReply(reply);

    log.info("Storing invite under ID {}", invId);
    storage.insertInvite(reply);
    invitations.put(invId, reply);
    log.info("A new invite has been created for {}:{} on HS {}", invitation.getMedium(), invitation.getAddress(), invitation.getSender().getDomain());

    return reply;
}
 
Example 11
Source File: RandomEntityGenerator.java    From gossip with MIT License 4 votes vote down vote up
public static String randomString(int length) {
    return RandomStringUtils.randomAlphanumeric(length);
}
 
Example 12
Source File: AbstractTest.java    From elucidate-server with MIT License 4 votes vote down vote up
protected String generateRandomId() {
    return RandomStringUtils.randomAlphanumeric(64);
}
 
Example 13
Source File: FeatureTaskHandler.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
static void preprocessConditionalOp(ConditionalOperation task, Callback<ConditionalOperation> callback) throws Exception {
  try {
    task.getEvent().setEnableUUID(task.space.isEnableUUID());
    // Ensure that the ID is a string or null and check for duplicate IDs
    Map<String, Boolean> ids = new HashMap<>();
    for (Entry<Feature> entry : task.modifyOp.entries) {
      final Object objId = entry.input.get(ID);
      String id = (objId instanceof String || objId instanceof Number) ? String.valueOf(objId) : null;
      if (task.prefixId != null) { // Generate IDs here, if a prefixId is required. Add the prefix otherwise.
        id = task.prefixId + ((id == null) ? RandomStringUtils.randomAlphanumeric(16) : id);
      }
      entry.input.put(ID, id);

      if (id != null) { 
        // Minimum length of id should be 1
        if (id.length() < 1) {
          logger.info(task.getMarker(), "Minimum length of object id should be 1.");
          callback.exception(new HttpException(BAD_REQUEST, "Minimum length of object id should be 1."));
          return;
        }
        // Test for duplicate IDs
        if (ids.containsKey(id)) {
          logger.info(task.getMarker(), "Objects with the same ID {} are included in the request.", id);
          callback.exception(new HttpException(BAD_REQUEST, "Objects with the same ID " + id + " is included in the request."));
          return;
        }
        ids.put(id, true);
      }

      entry.input.putIfAbsent(TYPE, "Feature");

      // bbox is a dynamically calculated property
      entry.input.remove(BBOX);

      // Add the XYZ namespace if it is not set yet.
      entry.input.putIfAbsent(PROPERTIES, new HashMap<String, Object>());
      @SuppressWarnings("unchecked") final Map<String, Object> properties = (Map<String, Object>) entry.input.get("properties");
      properties.putIfAbsent(XyzNamespace.XYZ_NAMESPACE, new HashMap<String, Object>());
    }
  } catch (Exception e) {
    logger.error(task.getMarker(), e.getMessage(), e);
    callback.exception(new HttpException(BAD_REQUEST, "Unable to process the request input."));
    return;
  }
  callback.call(task);
}
 
Example 14
Source File: FtsCondition.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected String generateQueryKeyParamName() {
    return "__queryKey" + RandomStringUtils.randomAlphanumeric(6);
}
 
Example 15
Source File: LocalGameRunner.java    From codenjoy with GNU General Public License v3.0 4 votes vote down vote up
private String getPlayerId() {
    return RandomStringUtils.randomAlphanumeric(10);
}
 
Example 16
Source File: RandomUtil.java    From ehcache3-samples with Apache License 2.0 2 votes vote down vote up
/**
 * Generate a password.
 *
 * @return the generated password
 */
public static String generatePassword() {
    return RandomStringUtils.randomAlphanumeric(DEF_COUNT);
}
 
Example 17
Source File: RandomUtil.java    From e-commerce-microservice with Apache License 2.0 2 votes vote down vote up
/**
 * Generate a password.
 *
 * @return the generated password
 */
public static String generatePassword() {
    return RandomStringUtils.randomAlphanumeric(DEF_COUNT);
}
 
Example 18
Source File: RandomUtil.java    From scava with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Generate a password.
 *
 * @return the generated password
 */
public static String generatePassword() {
    return RandomStringUtils.randomAlphanumeric(DEF_COUNT);
}
 
Example 19
Source File: RandomUtil.java    From Spring-5.0-Projects with MIT License 2 votes vote down vote up
/**
 * Generate a unique series to validate a persistent token, used in the
 * authentication remember-me mechanism.
 *
 * @return the generated series data
 */
public static String generateSeriesData() {
    return RandomStringUtils.randomAlphanumeric(DEF_COUNT);
}
 
Example 20
Source File: MigrationFeature.java    From ameba with MIT License 2 votes vote down vote up
/**
 * <p>generateMigrationId.</p>
 *
 * @return a {@link java.lang.String} object.
 */
public static String generateMigrationId() {
    return MIGRATION_ID = RandomStringUtils.randomAlphanumeric(RandomUtils.nextInt(20, 30));
}