RandomStringStanzaIdSource.java

  1. /**
  2.  *
  3.  * Copyright 2019 Florian Schmaus
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack.packet.id;

  18. import org.jivesoftware.smack.util.StringUtils;

  19. public final class RandomStringStanzaIdSource  {

  20.     public static class Factory implements StanzaIdSourceFactory {

  21.         private static final int REQUIRED_MIN_LENGTH = 10;

  22.         private final int length;
  23.         private final boolean verySecure;

  24.         public static final Factory VERY_SECURE = new Factory(10, true);
  25.         public static final Factory MEDIUM_SECURE = new Factory(10, false);

  26.         public Factory(int length, boolean verySecure) {
  27.             if (length < REQUIRED_MIN_LENGTH) {
  28.                 throw new IllegalArgumentException(
  29.                                 "Insufficient length " + length + ", must be at least " + REQUIRED_MIN_LENGTH);
  30.             }
  31.             this.length = length;
  32.             this.verySecure = verySecure;
  33.         }

  34.         @Override
  35.         public StanzaIdSource constructStanzaIdSource() {
  36.             StanzaIdSource stanzaIdSource;
  37.             if (verySecure) {
  38.                 stanzaIdSource = () -> StringUtils.randomString(length);
  39.             } else {
  40.                 stanzaIdSource = () -> StringUtils.insecureRandomString(length);
  41.             }
  42.             return stanzaIdSource;
  43.         }

  44.     }
  45. }