com.mifmif.common.regex.Generex Java Examples

The following examples show how to use com.mifmif.common.regex.Generex. 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: RegexPayloadGenerator.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Tells whether or not the given {@code regex} is valid for the payload generator.
 *
 * <p>A regular expression might have a valid syntax but still be invalid for the payload
 * generator if it takes too much time to be processed.
 *
 * @param regex the regular expression that will be validated
 * @return {@code true} if the {@code regex} is valid, {@code false} otherwise
 * @throws IllegalArgumentException if the given {@code regex} is {@code null}
 * @see #hasValidSyntax(String)
 */
public static boolean isValid(final String regex) {
    if (!hasValidSyntax(regex)) {
        return false;
    }
    return TimeOutRunner.run(
            new Runnable() {

                @Override
                public void run() {
                    @SuppressWarnings("unused")
                    Generex generator = new Generex(regex);
                }
            },
            VALID_REGEX_MAX_SECONDS,
            TimeUnit.SECONDS);
}
 
Example #2
Source File: RegexPatternPeerIdAlgorithm.java    From joal with Apache License 2.0 5 votes vote down vote up
public RegexPatternPeerIdAlgorithm(
        @JsonProperty(value = "pattern", required = true) final String pattern
) {
    if (pattern == null) {
        throw new TorrentClientConfigIntegrityException("peerId algorithm pattern must not be null.");
    }
    this.pattern = pattern;
    this.generex = new Generex(pattern);
}
 
Example #3
Source File: RegexPatternKeyAlgorithm.java    From joal with Apache License 2.0 5 votes vote down vote up
public RegexPatternKeyAlgorithm(
        @JsonProperty(value = "pattern", required = true) final String pattern
) {
    if (StringUtils.isBlank(pattern)) {
        throw new TorrentClientConfigIntegrityException("peerId algorithm pattern must not be null.");
    }
    this.pattern = pattern;
    this.generex = new Generex(pattern);
}
 
Example #4
Source File: ValidMockery.java    From Mockery with Apache License 2.0 5 votes vote down vote up
/**
 * Return as legal value the generated value from the regex pattern supplied.
 */
@Override public Object legal(Metadata<Valid> metadata) {
  Valid valid = metadata.getAnnotation();

  String defaultLegal = valid.legal();
  if (!defaultLegal.isEmpty()) {
    return safetyCast.with(defaultLegal,
        metadata.getType());
  }

  String regex = valid.value();
  String result = new Generex(regex).random();

  result = result.replace("^", "")
      .replace("$", "")
      .replace("?", "");

  if (regex.equals(Valid.Template.ID)) {
    if (result.length() > 1 && result.charAt(0) == '0') {
      result = result.replaceFirst("0", "");
    }
  }

  if (regex.equals(Valid.Template.INT)
      || regex.equals(Valid.Template.ID) || regex.equals(Valid.Template.NUMBER)) {
    if (result.length() > 8) {
      result = result.substring(0, 7);
    }
  }

  return safetyCast.with(result, metadata.getType());
}
 
Example #5
Source File: Generator.java    From avro-random-generator with Do What The F*ck You Want To Public License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private String generateRegexString(Schema schema, Object regexProp, LengthBounds lengthBounds) {
  if (!generexCache.containsKey(schema)) {
    if (!(regexProp instanceof String)) {
      throw new RuntimeException(String.format("%s property must be a string", REGEX_PROP));
    }
    generexCache.put(schema, new Generex((String) regexProp));
  }
  // Generex.random(low, high) generates in range [low, high]; we want [low, high), so subtract
  // 1 from maxLength
  return generexCache.get(schema).random(lengthBounds.min(), lengthBounds.max() - 1);
}
 
Example #6
Source File: RegexPayloadGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
public RegexPayloadGenerator(
        String regex, int maxPayloads, int limitCalculationPayloads, boolean randomOrder) {
    validateValid(regex);
    this.generator = new Generex(regex);
    this.maxPayloads = maxPayloads;
    this.numberOfPayloads =
            calculateNumberOfPayloadsImpl(generator, limitCalculationPayloads, randomOrder);
    this.randomOrder = randomOrder;
}
 
Example #7
Source File: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private static List<HasMetadata> processTemplate(Template template, Boolean failOnMissing)  {
  List<Parameter> parameters = template != null ? template.getParameters() : null;
  KubernetesList list = new KubernetesListBuilder()
    .withItems(template.getObjects())
    .build();

  try {
    String json = OBJECT_MAPPER.writeValueAsString(list);
    if (parameters != null && !parameters.isEmpty()) {
      // lets make a few passes in case there's expressions in values
      for (int i = 0; i < 5; i++) {
        for (Parameter parameter : parameters) {
          String name = parameter.getName();
          String regex = "${" + name + "}";
          String value;
          if (Utils.isNotNullOrEmpty(parameter.getValue())) {
            value = parameter.getValue();
          } else if (EXPRESSION.equals(parameter.getGenerate())) {
            Generex generex = new Generex(parameter.getFrom());
            value = generex.random();
          } else if (failOnMissing) {
            throw new IllegalArgumentException("No value available for parameter name: " + name);
          } else {
            value = "";
          }
          json = json.replace(regex, value);
        }
      }
    }

    list = OBJECT_MAPPER.readValue(json, KubernetesList.class);
  } catch (IOException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
  return list.getItems();
}
 
Example #8
Source File: Generator.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private String generateRegexString(Schema schema, Object regexProp, LengthBounds lengthBounds) {
  if (!generexCache.containsKey(schema)) {
    if (!(regexProp instanceof String)) {
      throw new RuntimeException(String.format("%s property must be a string", REGEX_PROP));
    }
    generexCache.put(schema, new Generex((String) regexProp));
  }
  // Generex.random(low, high) generates in range [low, high]; we want [low, high), so subtract
  // 1 from maxLength
  return generexCache.get(schema).random(lengthBounds.min(), lengthBounds.max() - 1);
}
 
Example #9
Source File: RegexPayloadGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private static boolean isInfiniteImpl(Generex generator, int limit) {
    try {
        return generator.isInfinite() && limit <= 0;
    } catch (StackOverflowError ignore) {
        // Infinite...
    }
    return true;
}
 
Example #10
Source File: DataProviders.java    From binder-swagger-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected DataProvider collectStringProperty(Swagger swagger, StringProperty schema, boolean clean) {
    return gen(() -> {
        StringProperty.Format uriFormat = StringProperty.Format.fromName(schema.getFormat());
        if (uriFormat == StringProperty.Format.URI || uriFormat == StringProperty.Format.URL)
            return faker.internet().url();
        else if (!isEmpty(schema.getPattern())) {
            Generex generex = new Generex(schema.getPattern());
            return generex.random();
        } else
            return faker.lorem().word();
    });
}
 
Example #11
Source File: RandomGenerator.java    From JTAF-XCore with Apache License 2.0 4 votes vote down vote up
/**
    * Use a regular expression to generate a string or use methods to select US
    * state name or abbreviations and generate phone numbers and strings.
    * 
    * @param method
    *            - the method to be used. Either abbrevUSState, USState, phone,
    *            number, or string
    * @param length
    *            - length of number or string to be generated. lengthMin,
    *            lengthMax, min, and max should not be specified when using
    *            this parameter.
    * @param lengthMin
    *            - used to specify minimum length of random string generated
    * @param lengthMax
    *            - used to specify maximum length of random string generated
    * @param min
    *            - used to specify minimum length of random number generated
    * @param max
    *            - used to specify maximum length of random number generated
    * @param regexp
    *            - regular expression to be used for string generation. This
    *            should not be specified if method parameter is.
    * @return the randomly generated string
    */
public static String generate(String method, String length, String lengthMin, String lengthMax, String min, String max, String regexp) {
	String valueGenerated = null;

	if (regexp != null && !regexp.equalsIgnoreCase("")) {
		if (method != null && !method.equalsIgnoreCase("")) {
			logger.fatal("Oops! Specified 'method' ('" + method + "') and 'regexp' ('" + regexp + "') simulteneously. Use only one of it, please. Will use 'regexp' here...");
		}
		valueGenerated = generateRegexp(regexp);
	} else {
		if (method != null && !method.equalsIgnoreCase("")) {
			if (method.equalsIgnoreCase("abbrevUSState")) {
				valueGenerated = generateAbbrevUSState();
			} else if (method.equalsIgnoreCase("USState")) {
				valueGenerated = generateUSState();
			} else if (method.equalsIgnoreCase("phone")) {
				valueGenerated = generatePhone();
			} else if (method.equalsIgnoreCase("number")) {
				// verify input parameters
				if ((length != null && !length.equalsIgnoreCase("")) && (min != null && !min.equalsIgnoreCase("")) && (max != null && !max.equalsIgnoreCase(""))) {
					logger.fatal("Oops! Specified 'length', 'min' and 'max' parameters... You can use 'length' or 'max + min' only. Fix your test script, please! Will use 'length' here only...");
					min = null;
					max = null;
				}
				if (((min != null && !min.equalsIgnoreCase("")) && (max == null)) || ((min == null) && (max != null && !max.equalsIgnoreCase("")))) {
					logger.fatal("Oops! Specified only one of 'min', 'max' parameters... You have specify 'max' and 'min' both. Fix your test script, please! Will use default 'length' here...");
					min = null;
					max = null;
				}
				if ((length == null || length.equalsIgnoreCase("")) && (min == null || min.equalsIgnoreCase("")) && (max == null || max.equalsIgnoreCase(""))) {
					length = "5";
				}

				try {
					int maxInt = Integer.parseInt(max);
					int minInt = Integer.parseInt(min);
					valueGenerated = String.valueOf(minInt + (int) (Math.random() * (maxInt - minInt)));
				} catch (Exception e) {
					Generex generex = new Generex("[0-9]{" + length + "}");
					valueGenerated = generex.random();
				}
			} else if (method.equalsIgnoreCase("string")) {
				// verify input parameters
				if ((length != null && !length.equalsIgnoreCase("")) && (lengthMin != null && !lengthMin.equalsIgnoreCase("")) && (lengthMax != null && !lengthMax.equalsIgnoreCase(""))) {
					logger.fatal("Oops! Specified 'length', 'lengthMin' and 'lengthMax' parameters... You can use 'length' or 'lengthMax + lengthMin' only. Fix your test script, please! Will use 'length' here only...");
					lengthMin = null;
					lengthMax = null;
				}
				if (length == null && (((lengthMin != null && !lengthMin.equalsIgnoreCase("")) && (lengthMax == null)) || ((lengthMin == null) && (lengthMax != null && !lengthMax.equalsIgnoreCase(""))))) {
					logger.fatal("Oops! Specified only one of 'lengthMin', 'lengthMax' parameters... You have specify 'lengthMax' and 'lengthMin' both. Fix your test script, please! Will use default 'length' here...");
					lengthMin = null;
					lengthMax = null;
				}

				int lengthInt;
				try {
					int lengthMinInt = Integer.parseInt(lengthMin);
					int lengthMaxInt = Integer.parseInt(lengthMax);
					lengthInt = lengthMinInt + (int) (Math.random() * (lengthMaxInt - lengthMinInt));
				} catch (NumberFormatException numberFormatException) {
					try {
						lengthInt = Integer.parseInt(length);
					} catch (NumberFormatException numberFormatException2) {
						lengthInt = DEFAULT_LENGTH;
					}
				}

				valueGenerated = generateString(CHARS_FOR_RANDOM_STRING, lengthInt);
			}
		}
	}
	return valueGenerated;
}
 
Example #12
Source File: TemplateOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public KubernetesList processLocally(Map<String, String> valuesMap)  {
  String namespace = getItem() != null ? getItem().getMetadata().getNamespace() : getNamespace();
  if (namespace == null) {
    namespace = getConfig().getNamespace();
  }

  String name = getItem() != null ? getItem().getMetadata().getName() : getName();

  Template t = withParameters(valuesMap)
    .inNamespace(namespace)
    .withName(name)
    .get();

  List<Parameter> parameters = t != null ? t.getParameters() : null;
  KubernetesList list = new KubernetesListBuilder()
    .withItems(t != null && t.getObjects() != null ? t.getObjects() : Collections.<HasMetadata>emptyList())
    .build();

  try {
    String json = JSON_MAPPER.writeValueAsString(list);
    if (parameters != null && !parameters.isEmpty()) {
      // lets make a few passes in case there's expressions in values
      for (int i = 0; i < 5; i++) {
        for (Parameter parameter : parameters) {
          String parameterName = parameter.getName();
          String parameterValue;
          if (valuesMap.containsKey(parameterName)) {
            parameterValue = valuesMap.get(parameterName);
          } else if (Utils.isNotNullOrEmpty(parameter.getValue())) {
            parameterValue = parameter.getValue();
          } else if (EXPRESSION.equals(parameter.getGenerate())) {
            Generex generex = new Generex(parameter.getFrom());
            parameterValue = generex.random();
          } else if (parameter.getRequired() == null || !parameter.getRequired()) {
            parameterValue = "";
          } else {
            throw new IllegalArgumentException("No value available for parameter name: " + parameterName);
          }
          if (parameterValue == null) {
            logger.debug("Parameter {} has a null value", parameterName);
            parameterValue = "";
          }
          json = Utils.interpolateString(json, Collections.singletonMap(parameterName, parameterValue));
        }
      }
    }

    list = JSON_MAPPER.readValue(json, KubernetesList.class);
  } catch (IOException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
  return list;
}
 
Example #13
Source File: Regex.java    From mockneat with Apache License 2.0 4 votes vote down vote up
@Override
public Supplier<String> supplier() {
    notNull(regExp, "regExp");
    validRegex(regExp);
    return () -> new Generex(regExp).random();
}
 
Example #14
Source File: RegexPayloadGenerator.java    From zap-extensions with Apache License 2.0 4 votes vote down vote up
public RegexIterator(Generex generex, int maxPayloads, boolean randomOrder) {
    this.generex = generex;
    this.maxPayloads = maxPayloads;
    this.randomOrder = randomOrder;
    reset();
}
 
Example #15
Source File: RegexPayloadGenerator.java    From zap-extensions with Apache License 2.0 3 votes vote down vote up
/**
 * Tells whether or not the given {@code regex} has a valid syntax for the payload generator.
 *
 * @param regex the regular expression that will be validated
 * @return {@code true} if the {@code regex} has a valid syntax, {@code false} otherwise
 * @see #isValid(String)
 */
public static boolean hasValidSyntax(String regex) {
    if (regex == null) {
        throw new IllegalArgumentException("Parameter regex must not be null.");
    }
    return Generex.isValidPattern(regex);
}
 
Example #16
Source File: CommonSteps.java    From NoraUi with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Update a html input text with a random text.
 *
 * @param pageElement
 *            The concerned page of field AND key of PageElement concerned (sample: $demo.DemoPage-button)
 * @param randRegex
 *            Is the new data (random value generated and match with randRegex)
 * @param conditions
 *            list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
 * @throws TechnicalException
 *             is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
 *             Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_ERROR_ON_INPUT} message (with screenshot, no exception)
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
@Conditioned
@Quand("Je mets à jour le texte {page-element} avec une valeur aléatoire qui vérifie {string}(\\?)")
@When("I update text {page-element} with ramdom match {string}(\\?)")
public void updateTextWithRamdomValueMatchRegexp(PageElement pageElement, String randRegex, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
    updateText(pageElement, new Generex(randRegex).random());
}
 
Example #17
Source File: ContextSteps.java    From NoraUi with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Save in context a text generated with ramdom match a regExp.
 * 
 * @param randRegex
 *            Is the new data (random value generated and match with randRegex)
 * @param targetKey
 *            Target key to save retrieved value.
 * @param conditions
 *            list of 'expected' values condition and 'actual' values
 *            ({@link com.github.noraui.gherkin.GherkinStepCondition}).
 * @throws FailureException
 *             if the scenario encounters a functional error
 * @throws TechnicalException
 *             is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
 */
@Conditioned
@Quand("Je génère du texte aléatoire correspond à {string} et j\'enregistre la valeur dans la clé {string} du contexte(\\?)")
@When("I generate text with ramdom match {string} and save the value in {string} context key(\\?)")
public void generateAndSaveTextWithRamdomValueMatchRegexp(String randRegex, String targetKey, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
    try {
        String rand = new Generex(randRegex).random();
        Context.saveValue(targetKey, rand);
        Context.getCurrentScenario().write(PREFIX_SAVE + targetKey + "=" + rand);
    } catch (final Exception e) {
        new Result.Failure<>("", Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_GENERATE_RANDOM_VALUE), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
    }
}
 
Example #18
Source File: RandomGenerator.java    From JTAF-XCore with Apache License 2.0 2 votes vote down vote up
/**
    * Generates a random phone number.
    * 
    * @return the randomly generated phone number.
    */
public static String generatePhone() {
	Generex generex = new Generex("[0-9]{10}");
	return generex.random();
}
 
Example #19
Source File: RandomGenerator.java    From JTAF-XCore with Apache License 2.0 2 votes vote down vote up
/**
    * This randomly generates a string given a set of characters and a desired
    * length.
    * 
    * @param chars
    *            - The characters to be used
    * @param length
    *            - The length of the resulting string
    * @return The generated string
    */
public static String generateString(String chars, int length) {
	Generex generex = new Generex("[" + chars + "]{" + length + "}");
	return generex.random();
}
 
Example #20
Source File: RandomGenerator.java    From JTAF-XCore with Apache License 2.0 2 votes vote down vote up
/**
    * Generate a string using a specified regular expression.
    * 
    * @param regexp
    *            - regular expression to be used to generate the string
    * @return the randomly generated string
    */
public static String generateRegexp(String regexp) {
	Generex generex = new Generex(regexp);
	return generex.random();
}
 
Example #21
Source File: RegexPayloadGenerator.java    From zap-extensions with Apache License 2.0 2 votes vote down vote up
/**
 * Calculates the number of payloads that the given regular expression would produce, limiting
 * up to the given {@code limit} (if positive) and whether it's random.
 *
 * <p>If the payloads should be generated in random order the limit would be the number of
 * payloads, otherwise, if the regular expression is infinite and no limit is provided it
 * returns {@code DEFAULT_LIMIT_CALCULATION_PAYLOADS}.
 *
 * @param regex the regular expression that will be used to calculate the number of payloads
 *     generated
 * @param limit if positive, the maximum number of payloads that are allowed, otherwise,
 *     negative or zero, for no limit
 * @param randomOrder {@code true} if the payloads are generated randomly, {@code false}
 *     otherwise.
 * @return the number of payloads that would be produced by the given regular expression
 * @throws IllegalArgumentException if the given {@code regex} is {@code null} or not valid
 * @see #DEFAULT_LIMIT_CALCULATION_PAYLOADS
 * @see #calculateNumberOfPayloads(String, int)
 * @see #isInfinite(String, int)
 * @see #isValid(String)
 */
public static int calculateNumberOfPayloads(String regex, int limit, boolean randomOrder) {
    validateValid(regex);
    return calculateNumberOfPayloadsImpl(new Generex(regex), limit, randomOrder);
}
 
Example #22
Source File: RegexPayloadGenerator.java    From zap-extensions with Apache License 2.0 2 votes vote down vote up
/**
 * Tells whether or not the given {@code regex} is infinite, that is, generates an infinite
 * number of payloads, taking into account the given {@code limit}.
 *
 * @param regex the regular expression that will be validated
 * @param limit if positive, the maximum number of payloads that are allowed, otherwise,
 *     negative or zero, for no limit
 * @return {@code true} if the {@code regex} is infinite, {@code false} otherwise
 * @throws IllegalArgumentException if the given {@code regex} is {@code null} or not valid
 * @see #isValid(String)
 */
public static boolean isInfinite(String regex, int limit) {
    validateValid(regex);
    return isInfiniteImpl(new Generex(regex), limit);
}