0

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.

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

It's look nice, but Is it possible to same that?
See second example. It is pretty the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.