kibar
kibar

Reputation: 824

Parse.com create objectId with java

I have parse.com project and I want to create objectId. I found this method: randomString in this link: parse-server-cryptoUtils.

export function randomString(size: number): string {
  if (size === 0) {
    throw new Error('Zero-length randomString is useless.');
  }
  const chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
               'abcdefghijklmnopqrstuvwxyz' +
               '0123456789');
  let objectId = '';
  const bytes = randomBytes(size);
  for (let i = 0; i < bytes.length; ++i) {
    objectId += chars[bytes.readUInt8(i) % chars.length];
  }
  return objectId;
}

How I can write this method on java? I can't convert this bytes.readUInt8.

Upvotes: 0

Views: 48

Answers (1)

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

I have found this approach somehwere and successfully use it.

public class RandomString {

    private static final char[] SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();

    private final Random random = new Random();
    private final char[] buf;

    public RandomString(int length) {
        assert length > 0;
        buf = new char[length];
    }

    String nextString() {
        for (int i = 0; i < buf.length; i++) {
            buf[i] = SYMBOLS[random.nextInt(SYMBOLS.length)];
        }
        return new String(buf);
    }
}

P.S. your example in Java could look like this snapshot:

public static String randomString(int size) {
    if (size <= 0)
        throw new RuntimeException("Zero-length randomString is useless.");

    final char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();

    StringBuilder objectId = new StringBuilder();
    Random random = new Random();

    for (int i = 0; i < size; ++i)
        objectId.append(chars[random.nextInt(Integer.MAX_VALUE) % chars.length]);

    return objectId.toString();
}

Upvotes: 1

Related Questions