name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
hibernate-validator_ConstraintViolationAssert_assertPathEquals_rdh
/** * Asserts that the path matches the expected path. * * @param path * The path under test * @param expectedPath * The expected path */ public static void assertPathEquals(Path path, PathExpectation expectedPath) { assertEquals(new PathExpectation(path), expectedPath, "Path does not match"); }
3.26
hibernate-validator_ClassHierarchyHelper_getHierarchy_rdh
/** * Retrieves all superclasses and interfaces recursively. * * @param clazz * the class to start the search with * @param classes * list of classes to which to add all found super types matching * the given filters * @param filters * filters applying for the search */ private static <T> void getHierarchy(Class<? super T> clazz, List<Class<? super T>> classes, Iterable<Filter> filters) { for (Class<? super T> current = clazz; current != null; current = current.getSuperclass()) { if (classes.contains(current)) { return; } if (acceptedByAllFilters(current, filters)) { classes.add(current); } for (Class<?> currentInterface : current.getInterfaces()) { // safe since interfaces are super-types @SuppressWarnings("unchecked") Class<? super T> currentInterfaceCasted = ((Class<? super T>) (currentInterface)); getHierarchy(currentInterfaceCasted, classes, filters); }} }
3.26
hibernate-validator_ConstraintMappingContextImplBase_addConstraint_rdh
/** * Adds a constraint to the set of constraints managed by this creational context. * * @param constraint * the constraint to add */ protected void addConstraint(ConfiguredConstraint<?> constraint) { constraints.add(constraint); }
3.26
hibernate-validator_ClassVisitor_visitTypeAsClass_rdh
/** * Doesn't perform any checks at the moment but calls a visit methods on its own elements. * * @param element * a class element to check * @param aVoid */ @Override public Void visitTypeAsClass(TypeElement element, Void aVoid) { visitAllMyElements(element); return null; }
3.26
hibernate-validator_ClassVisitor_visitExecutableAsMethod_rdh
/** * Checks whether the constraints of the given method are valid. * * @param element * a method under investigation * @param aVoid */ @Override public Void visitExecutableAsMethod(ExecutableElement element, Void aVoid) { processClassChecks(element); return null; }
3.26
hibernate-validator_ClassVisitor_visitAllMyElements_rdh
/** * Visits all inner elements of provided {@link TypeElement}. * * @param typeElement * inner elements of which you want to visit */ private void visitAllMyElements(TypeElement typeElement) { Name qualifiedName = typeElement.getQualifiedName(); if (!processedTypes.contains(qualifiedName)) { processedTypes.add(qualifiedName); for (Element element : elementUtils.getAllMembers(typeElement)) { visit(element); } } }
3.26
hibernate-validator_ClassVisitor_visitTypeAsInterface_rdh
/** * Doesn't perform any checks at the moment but calls a visit methods on its own elements. * * @param element * a class element to check * @param aVoid */ @Override public Void visitTypeAsInterface(TypeElement element, Void aVoid) { visitAllMyElements(element); return null; }
3.26
hibernate-validator_NotEmptyValidatorForCollection_isValid_rdh
/** * Checks the collection is not {@code null} and not empty. * * @param collection * the collection to validate * @param constraintValidatorContext * context in which the constraint is evaluated * @return returns {@code true} if the collection is not {@code null} and the collection is not empty */ @Override public boolean isValid(Collection collection, ConstraintValidatorContext constraintValidatorContext) { if (collection == null) { return false; } return collection.size() > 0; }
3.26
hibernate-validator_AbstractCachingScriptEvaluatorFactory_getScriptEvaluatorByLanguageName_rdh
/** * Retrieves a script executor for the given language. * * @param languageName * the name of a scripting language * @return a script executor for the given language. Never null. * @throws ScriptEvaluatorNotFoundException * in case no compatible evaluator for the given language has been found */ @Override public ScriptEvaluator getScriptEvaluatorByLanguageName(String languageName) { return scriptEvaluatorCache.computeIfAbsent(languageName, this::createNewScriptEvaluator); }
3.26
hibernate-validator_ModCheckBase_extractDigit_rdh
/** * Returns the numeric {@code int} value of a {@code char} * * @param value * the input {@code char} to be parsed * @return the numeric {@code int} value represented by the character. * @throws NumberFormatException * in case character is not a digit */ protected int extractDigit(char value) throws NumberFormatException { if (Character.isDigit(value)) { return Character.digit(value, DEC_RADIX); } else { throw LOG.getCharacterIsNotADigitException(value); } }
3.26
hibernate-validator_ModCheckBase_extractDigits_rdh
/** * Parses the {@link String} value as a {@link List} of {@link Integer} objects * * @param value * the input string to be parsed * @return List of {@code Integer} objects. * @throws NumberFormatException * in case any of the characters is not a digit */ private List<Integer> extractDigits(final String value) throws NumberFormatException { List<Integer> digits = new ArrayList<Integer>(value.length()); char[] chars = value.toCharArray(); for (char c : chars) { digits.add(extractDigit(c)); } return digits; }
3.26
hibernate-validator_ClassLoadingHelper_run_rdh
/** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17") private static <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run(); }
3.26
hibernate-validator_UUIDValidator_hasCorrectLetterCase_rdh
/** * Validates the letter case of the given character depending on the letter case parameter * * @param ch * The letter to be tested * @return {@code true} if the character is in the specified letter case or letter case is not specified */ private boolean hasCorrectLetterCase(char ch) { if (letterCase == null) { return true; } if ((letterCase == LetterCase.LOWER_CASE) && (!Character.isLowerCase(ch))) {return false; } return (letterCase != LetterCase.UPPER_CASE) || Character.isUpperCase(ch); }
3.26
hibernate-validator_UUIDValidator_extractVersion_rdh
/** * Get the 4 bit UUID version from the current value * * @param version * The old version (in case the version has already been extracted) * @param index * The index of the current value to find the version to extract * @param value * The numeric value at the character position */ private static int extractVersion(int version, int index, int value) {if (index == 14) { return value; } return version; }
3.26
hibernate-validator_NotEmptyValidatorForArraysOfFloat_isValid_rdh
/** * Checks the array is not {@code null} and not empty. * * @param array * the array to validate * @param constraintValidatorContext * context in which the constraint is evaluated * @return returns {@code true} if the array is not {@code null} and the array is not empty */ @Override public boolean isValid(float[] array, ConstraintValidatorContext constraintValidatorContext) { if (array == null) { return false; } return array.length > 0; }
3.26
hibernate-validator_NotEmptyValidatorForArraysOfChar_isValid_rdh
/** * Checks the array is not {@code null} and not empty. * * @param array * the array to validate * @param constraintValidatorContext * context in which the constraint is evaluated * @return returns {@code true} if the array is not {@code null} and the array is not empty */ @Override public boolean isValid(char[] array, ConstraintValidatorContext constraintValidatorContext) { if (array == null) { return false; } return array.length > 0; }
3.26
hibernate-validator_Filters_excludeProxies_rdh
/** * Returns a filter which excludes proxy objects. * * @return a filter which excludes proxy objects */ public static Filter excludeProxies() { return PROXY_FILTER; }
3.26
hibernate-validator_Filters_excludeInterfaces_rdh
/** * Returns a filter which excludes interfaces. * * @return a filter which excludes interfaces */ public static Filter excludeInterfaces() { return INTERFACES_FILTER; }
3.26
hibernate-validator_ComposingConstraintTree_prepareFinalConstraintViolations_rdh
/** * Before the final constraint violations can be reported back we need to check whether we have a composing * constraint whose result should be reported as single violation. * * @param validationContext * meta data about top level validation * @param valueContext * meta data for currently validated value * @param violatedConstraintValidatorContexts * used to accumulate constraint validator contexts that cause constraint violations * @param localConstraintValidatorContext * an optional of constraint violations of top level constraint */ private void prepareFinalConstraintViolations(ValidationContext<?> validationContext, ValueContext<?, ?> valueContext, Collection<ConstraintValidatorContextImpl> violatedConstraintValidatorContexts, Optional<ConstraintValidatorContextImpl> localConstraintValidatorContext) { if (reportAsSingleViolation()) { // We clear the current violations list anyway violatedConstraintValidatorContexts.clear(); // But then we need to distinguish whether the local ConstraintValidator has reported // violations or not (or if there is no local ConstraintValidator at all). // If not we create a violation // using the error message in the annotation declaration at top level. if (!localConstraintValidatorContext.isPresent()) { violatedConstraintValidatorContexts.add(validationContext.createConstraintValidatorContextFor(descriptor, valueContext.getPropertyPath())); } } // Now, if there were some violations reported by // the local ConstraintValidator, they need to be added to constraintViolations. // Whether we need to report them as a single constraint or just add them to the other violations // from the composing constraints, has been taken care of in the previous conditional block. // This takes also care of possible custom error messages created by the constraintValidator, // as checked in test CustomErrorMessage.java // If no violations have been reported from the local ConstraintValidator, or no such validator exists, // then we just add an empty list. if (localConstraintValidatorContext.isPresent()) {violatedConstraintValidatorContexts.add(localConstraintValidatorContext.get()); } }
3.26
hibernate-validator_ComposingConstraintTree_validateComposingConstraints_rdh
/** * Validates all composing constraints recursively. * * @param validationContext * Meta data about top level validation * @param valueContext * Meta data for currently validated value * @param violatedConstraintValidatorContexts * Used to accumulate constraint validator contexts that cause constraint violations * @return Returns an instance of {@code CompositionResult} relevant for boolean composition of constraints */ private CompositionResult validateComposingConstraints(ValidationContext<?> validationContext, ValueContext<?, ?> valueContext, Collection<ConstraintValidatorContextImpl> violatedConstraintValidatorContexts) { CompositionResult compositionResult = new CompositionResult(true, false); for (ConstraintTree<?> tree : children) { List<ConstraintValidatorContextImpl> tmpConstraintValidatorContexts = new ArrayList<>(5); tree.validateConstraints(validationContext, valueContext, tmpConstraintValidatorContexts); violatedConstraintValidatorContexts.addAll(tmpConstraintValidatorContexts); if (tmpConstraintValidatorContexts.isEmpty()) { compositionResult.setAtLeastOneTrue(true); // no need to further validate constraints, because at least one validation passed if (descriptor.getCompositionType() == OR) { break; } } else { compositionResult.setAllTrue(false); if ((descriptor.getCompositionType() == AND) && (validationContext.isFailFastModeEnabled() || descriptor.isReportAsSingleViolation())) { break; } } } return compositionResult; }
3.26
hibernate-validator_PlatformResourceBundleLocator_determineAvailabilityOfResourceBundleControl_rdh
/** * Check whether ResourceBundle.Control is available, which is needed for bundle aggregation. If not, we'll skip * resource aggregation. * <p> * It is *not* available * <ul> * <li>in the Google App Engine environment</li> * <li>when running HV as Java 9 named module (which would be the case when adding a module-info descriptor to the * HV JAR)</li> * </ul> * * @see <a href="http://code.google.com/appengine/docs/java/jrewhitelist.html">GAE JRE whitelist</a> * @see <a href="https://hibernate.atlassian.net/browse/HV-1023">HV-1023</a> * @see <a href="http://download.java.net/java/jdk9/docs/api/java/util/ResourceBundle.Control.html">ResourceBundle.Control</a> */ private static boolean determineAvailabilityOfResourceBundleControl() { try { ResourceBundle.Control dummyControl = AggregateResourceBundleControl.CONTROL; if (dummyControl == null) { return false; } Method getModule = run(GetMethod.action(Class.class, "getModule")); // not on Java 9 if (getModule == null) { return true; } // on Java 9, check whether HV is a named module Object module = getModule.invoke(PlatformResourceBundleLocator.class); Method isNamedMethod = run(GetMethod.action(module.getClass(), "isNamed")); boolean isNamed = ((Boolean) (isNamedMethod.invoke(module))); return !isNamed; } catch (Throwable e) { LOG.info(MESSAGES.unableToUseResourceBundleAggregation()); return false; } }
3.26
hibernate-validator_PlatformResourceBundleLocator_run_rdh
/** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17") private static <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run(); }
3.26
hibernate-validator_ScriptEngineScriptEvaluator_engineAllowsParallelAccessFromMultipleThreads_rdh
/** * Checks whether the given engine is thread-safe or not. * * @return true if the given engine is thread-safe, false otherwise. */private boolean engineAllowsParallelAccessFromMultipleThreads() { String threadingType = ((String) (engine.getFactory().getParameter("THREADING"))); return "THREAD-ISOLATED".equals(threadingType) || "STATELESS".equals(threadingType); }
3.26
hibernate-validator_ScriptEngineScriptEvaluator_evaluate_rdh
/** * Executes the given script, using the given variable bindings. The execution of the script happens either synchronized or * unsynchronized, depending on the engine's threading abilities. * * @param script * the script to be executed * @param bindings * the bindings to be used * @return the script's result * @throws ScriptEvaluationException * in case an error occurred during the script evaluation */ @Override public Object evaluate(String script, Map<String, Object> bindings) throws ScriptEvaluationException { if (engineAllowsParallelAccessFromMultipleThreads()) { return doEvaluate(script, bindings); } else { synchronized(engine) { return doEvaluate(script, bindings); } } }
3.26
hibernate-validator_ValidationProviderHelper_getValidatorBeanClass_rdh
/** * Determines the class of the {@link Validator} corresponding to the given configuration object. */ Class<? extends Validator> getValidatorBeanClass() { return validatorClass; }
3.26
hibernate-validator_ValidationProviderHelper_isHibernateValidator_rdh
/** * Whether the given provider is Hibernate Validator or not. */ public boolean isHibernateValidator() { return isHibernateValidator; }
3.26
hibernate-validator_ValidationProviderHelper_getValidatorFactoryBeanClass_rdh
/** * Determines the class of the {@link ValidatorFactory} corresponding to the given configuration object. */ Class<? extends ValidatorFactory> getValidatorFactoryBeanClass() { return validatorFactoryClass; }
3.26
hibernate-validator_ValidationProviderHelper_isDefaultProvider_rdh
/** * Whether the given provider is the default provider or not. * * @return {@code true} if the given provider is the default provider, {@code false} otherwise */ public boolean isDefaultProvider() { return isDefaultProvider; }
3.26
hibernate-validator_ValidationProviderHelper_determineRequiredQualifiers_rdh
/** * Returns the qualifiers to be used for registering a validator or validator factory. */ @SuppressWarnings("serial") private static Set<Annotation> determineRequiredQualifiers(boolean isDefaultProvider, boolean isHibernateValidator) { HashSet<Annotation> qualifiers = newHashSet(3); if (isDefaultProvider) { qualifiers.add(new AnnotationLiteral<Default>() {}); } if (isHibernateValidator) { qualifiers.add(new AnnotationLiteral<HibernateValidator>() {}); } qualifiers.add(new AnnotationLiteral<Any>() {}); return qualifiers; }
3.26
hibernate-validator_LuhnCheckValidator_isCheckDigitValid_rdh
/** * Validate check digit using Luhn algorithm * * @param digits * The digits over which to calculate the checksum * @param checkDigit * the check digit * @return {@code true} if the luhn check result matches the check digit, {@code false} otherwise */ @Override public boolean isCheckDigitValid(List<Integer> digits, char checkDigit) { int modResult = ModUtil.calculateLuhnMod10Check(digits); if (!Character.isDigit(checkDigit)) { return false; } int checkValue = extractDigit(checkDigit); return checkValue == modResult; }
3.26
hibernate-validator_MetaDataBuilder_adaptOriginsAndImplicitGroups_rdh
/** * Adapts the given constraints to the given bean type. In case a constraint * is defined locally at the bean class the original constraint will be * returned without any modifications. If a constraint is defined in the * hierarchy (interface or super class) a new constraint will be returned * with an origin of {@link org.hibernate.validator.internal.metadata.core.ConstraintOrigin#DEFINED_IN_HIERARCHY}. If a * constraint is defined on an interface, the interface type will * additionally be part of the constraint's groups (implicit grouping). * * @param constraints * The constraints that shall be adapted. The constraints themselves * will not be altered. * @return A constraint adapted to the given bean type. */ protected Set<MetaConstraint<?>> adaptOriginsAndImplicitGroups(Set<MetaConstraint<?>> constraints) { Set<MetaConstraint<?>> adaptedConstraints = newHashSet(); for (MetaConstraint<?> oneConstraint : constraints) { adaptedConstraints.add(adaptOriginAndImplicitGroup(oneConstraint)); } return adaptedConstraints; }
3.26
hibernate-validator_MetaDataBuilder_add_rdh
/** * Adds the given element to this builder. It must be checked with * {@link #accepts(ConstrainedElement)} before, whether this is allowed or * not. * * @param constrainedElement * The element to add. */ public void add(ConstrainedElement constrainedElement) { directConstraints.addAll(adaptConstraints(constrainedElement, constrainedElement.getConstraints())); containerElementsConstraints.addAll(adaptConstraints(constrainedElement, constrainedElement.getTypeArgumentConstraints())); isCascading = isCascading || constrainedElement.getCascadingMetaDataBuilder().isMarkedForCascadingOnAnnotatedObjectOrContainerElements(); }
3.26
hibernate-validator_MetaDataBuilder_adaptConstraints_rdh
/** * Allows specific sub-classes to customize the retrieved constraints. */ protected Set<MetaConstraint<?>> adaptConstraints(ConstrainedElement constrainedElement, Set<MetaConstraint<?>> constraints) { return constraints; } /** * * @param rootClass * The root class. That is the class for which we currently * create a {@code BeanMetaData} * @param hierarchyClass * The class on which the current constraint is defined on * @return Returns {@code ConstraintOrigin.DEFINED_LOCALLY} if the constraint was defined on the root bean, {@code ConstraintOrigin.DEFINED_IN_HIERARCHY}
3.26
hibernate-validator_NotEmptyValidatorForMap_isValid_rdh
/** * Checks the map is not {@code null} and not empty. * * @param map * the map to validate * @param constraintValidatorContext * context in which the constraint is evaluated * @return returns {@code true} if the map is not {@code null} and the map is not empty */ @Override public boolean isValid(Map map, ConstraintValidatorContext constraintValidatorContext) { if (map == null) { return false; } return map.size() > 0; }
3.26
hibernate-validator_ConstraintDescriptorImpl_getMatchingConstraintValidatorDescriptors_rdh
/** * Return all constraint validator descriptors (either generic or cross-parameter) which are registered for the * constraint of this descriptor. * * @return The constraint validator descriptors applying to type of this constraint. */ public List<ConstraintValidatorDescriptor<T>> getMatchingConstraintValidatorDescriptors() { return matchingConstraintValidatorDescriptors; }
3.26
hibernate-validator_ConstraintDescriptorImpl_determineConstraintType_rdh
/** * Determines the type of this constraint. The following rules apply in * descending order: * <ul> * <li>If {@code validationAppliesTo()} is set to either * {@link ConstraintTarget#RETURN_VALUE} or * {@link ConstraintTarget#PARAMETERS}, this value will be considered.</li> * <li>Otherwise, if the constraint is either purely generic or purely * cross-parameter as per its validators, that value will be considered.</li> * <li>Otherwise, if the constraint is not on an executable, it is * considered generic.</li> * <li>Otherwise, the type will be determined based on exclusive existence * of parameters and return value.</li> * <li>If that also is not possible, determination fails (i.e. the user must * specify the target explicitly).</li> * </ul> * * @param constrainable * The annotated member * @param hasGenericValidators * Whether the constraint has at least one generic validator or * not * @param hasCrossParameterValidator * Whether the constraint has a cross-parameter validator * @param externalConstraintType * constraint type as derived from external context, e.g. for * constraints declared in XML via {@code &lt;return-value/gt;} * @return The type of this constraint */ private ConstraintType determineConstraintType(Class<? extends Annotation> constraintAnnotationType, Constrainable constrainable, boolean hasGenericValidators, boolean hasCrossParameterValidator, ConstraintType externalConstraintType) { ConstraintTarget constraintTarget = validationAppliesTo; ConstraintType v5 = null; boolean isExecutable = constraintLocationKind.isExecutable(); // target explicitly set to RETURN_VALUE if (constraintTarget == ConstraintTarget.RETURN_VALUE) { if (!isExecutable) { throw LOG.getParametersOrReturnValueConstraintTargetGivenAtNonExecutableException(annotationDescriptor.getType(), ConstraintTarget.RETURN_VALUE); } v5 = ConstraintType.GENERIC; } else if (constraintTarget == ConstraintTarget.PARAMETERS) { if (!isExecutable) { throw LOG.getParametersOrReturnValueConstraintTargetGivenAtNonExecutableException(annotationDescriptor.getType(), ConstraintTarget.PARAMETERS);} v5 = ConstraintType.CROSS_PARAMETER; } else if (externalConstraintType != null) { v5 = externalConstraintType; } else // try to derive the type from the existing validators if (hasGenericValidators && (!hasCrossParameterValidator)) { v5 = ConstraintType.GENERIC; } else if ((!hasGenericValidators) && hasCrossParameterValidator) { v5 = ConstraintType.CROSS_PARAMETER; } else if (!isExecutable) { v5 = ConstraintType.GENERIC; } else if (constraintAnnotationType.isAnnotationPresent(SupportedValidationTarget.class)) { SupportedValidationTarget supportedValidationTarget = constraintAnnotationType.getAnnotation(SupportedValidationTarget.class); if (supportedValidationTarget.value().length == 1) { v5 = (supportedValidationTarget.value()[0] == ValidationTarget.ANNOTATED_ELEMENT) ? ConstraintType.GENERIC : ConstraintType.CROSS_PARAMETER; } } else if (constrainable instanceof Callable) { boolean hasParameters = constrainable.as(Callable.class).hasParameters(); boolean hasReturnValue = constrainable.as(Callable.class).hasReturnValue(); if ((!hasParameters) && hasReturnValue) { v5 = ConstraintType.GENERIC; } else if (hasParameters && (!hasReturnValue)) { v5 = ConstraintType.CROSS_PARAMETER; } } // Now we are out of luck if (v5 == null) { throw LOG.getImplicitConstraintTargetInAmbiguousConfigurationException(annotationDescriptor.getType()); } if (v5 == ConstraintType.CROSS_PARAMETER) { validateCrossParameterConstraintType(constrainable, hasCrossParameterValidator); } return v5; }
3.26
hibernate-validator_ConstraintDescriptorImpl_run_rdh
/** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17") private static <P> P run(PrivilegedAction<P> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run(); }
3.26
hibernate-validator_ConstraintDescriptorImpl_validateComposingConstraintTypes_rdh
/** * Asserts that this constraint and all its composing constraints share the * same constraint type (generic or cross-parameter). */ private void validateComposingConstraintTypes() { for (ConstraintDescriptorImpl<?> composingConstraint : getComposingConstraintImpls()) { if (composingConstraint.constraintType != constraintType) { throw LOG.getComposedAndComposingConstraintsHaveDifferentTypesException(annotationDescriptor.getType(), composingConstraint.annotationDescriptor.getType(), constraintType, composingConstraint.constraintType); } } }
3.26
hibernate-validator_ConstraintDescriptorImpl_getCompositionType_rdh
/** * * @return the compositionType */ public CompositionType getCompositionType() { return compositionType; }
3.26
hibernate-validator_ValueContexts_getLocalExecutionContextForExecutable_rdh
/** * Creates a value context for validating an executable. Can be applied to both parameter and * return value validation. Does not require a bean metadata information. */ public static <T, V> ValueContext<T, V> getLocalExecutionContextForExecutable(ExecutableParameterNameProvider parameterNameProvider, T value, Validatable validatable, PathImpl propertyPath) { return new ValueContext<>(parameterNameProvider, value, validatable, propertyPath); }
3.26
hibernate-validator_TypeVariableBindings_getTypeVariableBindings_rdh
/** * Returns the bindings for all the type variables from the given type's hierarchy. The returned map will contain an * entry for each type in the given type's class hierarchy (including interfaces). Each entry is a map from the * given type's type variables to the corresponding type variables of the type represented by that entry. */ public static Map<Class<?>, Map<TypeVariable<?>, TypeVariable<?>>> getTypeVariableBindings(Class<?> type) { Map<Class<?>, Map<TypeVariable<?>, TypeVariable<?>>> allBindings = new HashMap<>(); Map<TypeVariable<?>, TypeVariable<?>> v1 = new HashMap<>(); TypeVariable<?>[] subTypeParameters = type.getTypeParameters(); for (TypeVariable<?> typeVariable : subTypeParameters) { v1.put(typeVariable, typeVariable); } allBindings.put(type, v1); collectTypeBindings(type, allBindings, v1); allBindings.put(Object.class, Collections.emptyMap()); return CollectionHelper.toImmutableMap(allBindings); }
3.26
hibernate-validator_ValidatorFactoryConfigurationHelper_determinePropertyConfiguredConstraintMappingContributors_rdh
/** * Returns a list with {@link ConstraintMappingContributor}s configured via the * {@link HibernateValidatorConfiguration#CONSTRAINT_MAPPING_CONTRIBUTORS} property. * * Also takes into account the deprecated {@link HibernateValidatorConfiguration#CONSTRAINT_MAPPING_CONTRIBUTOR} * property. * * @param properties * the properties used to bootstrap the factory * @return a list with property-configured {@link ConstraintMappingContributor}s; May be empty but never {@code null} */ static List<ConstraintMappingContributor> determinePropertyConfiguredConstraintMappingContributors(Map<String, String> properties, ClassLoader externalClassLoader) { @SuppressWarnings("deprecation") String deprecatedPropertyValue = properties.get(HibernateValidatorConfiguration.CONSTRAINT_MAPPING_CONTRIBUTOR); String propertyValue = properties.get(HibernateValidatorConfiguration.CONSTRAINT_MAPPING_CONTRIBUTORS); if (StringHelper.isNullOrEmptyString(deprecatedPropertyValue) && StringHelper.isNullOrEmptyString(propertyValue)) { return Collections.emptyList(); } StringBuilder assembledPropertyValue = new StringBuilder(); if (!StringHelper.isNullOrEmptyString(deprecatedPropertyValue)) { assembledPropertyValue.append(deprecatedPropertyValue); } if (!StringHelper.isNullOrEmptyString(propertyValue)) { if (assembledPropertyValue.length() > 0) { assembledPropertyValue.append(","); } assembledPropertyValue.append(propertyValue); } String[] contributorNames = assembledPropertyValue.toString().split(","); List<ConstraintMappingContributor> contributors = newArrayList(contributorNames.length); for (String contributorName : contributorNames) {@SuppressWarnings("unchecked")Class<? extends ConstraintMappingContributor> contributorType = ((Class<? extends ConstraintMappingContributor>) (run(LoadClass.action(contributorName, externalClassLoader)))); contributors.add(run(NewInstance.action(contributorType, "constraint mapping contributor class"))); } return contributors; }
3.26
hibernate-validator_ValidatorFactoryConfigurationHelper_run_rdh
/** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17") private static <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run();}
3.26
hibernate-validator_UniqueElementsValidator_isValid_rdh
/** * * @param collection * the collection to validate * @param constraintValidatorContext * context in which the constraint is evaluated * @return true if the input collection is null or does not contain duplicate elements */ @Override public boolean isValid(Collection collection, ConstraintValidatorContext constraintValidatorContext) {if ((collection == null) || (collection.size() < 2)) { return true; } List<Object> duplicates = findDuplicates(collection); if (duplicates.isEmpty()) { return true; } if (constraintValidatorContext instanceof HibernateConstraintValidatorContext) { constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class).addMessageParameter("duplicates", duplicates.stream().map(String::valueOf).collect(Collectors.joining(", "))).withDynamicPayload(CollectionHelper.toImmutableList(duplicates)); } return false; }
3.26
hibernate-validator_DefaultValidationOrder_assertDefaultGroupSequenceIsExpandable_rdh
/** * Asserts that the default group sequence of the validated bean can be expanded into the sequences which needs to * be validated. * * @param defaultGroupSequence * the default group sequence of the bean currently validated * @throws jakarta.validation.GroupDefinitionException * in case {@code defaultGroupSequence} cannot be expanded into one of the group sequences * which need to be validated */ @Overridepublic void assertDefaultGroupSequenceIsExpandable(List<Class<?>> defaultGroupSequence) throws GroupDefinitionException { if (sequenceMap == null) { return; } for (Map.Entry<Class<?>, Sequence> entry : sequenceMap.entrySet()) { List<Group> sequenceGroups = entry.getValue().getComposingGroups(); int defaultGroupIndex = sequenceGroups.indexOf(Group.DEFAULT_GROUP); if (defaultGroupIndex != (-1)) { List<Group> defaultGroupList = buildTempGroupList(defaultGroupSequence); ensureDefaultGroupSequenceIsExpandable(sequenceGroups, defaultGroupList, defaultGroupIndex); } } }
3.26
hibernate-validator_AbstractStaxBuilder_readAttribute_rdh
/** * Reads a value of an attribute of a given element. * * @param startElement * an element to get an attribute from * @param qName * a {@link QName} of an attribute to read * @return a value of an attribute if it is present, {@link Optional#empty()} otherwise */ protected Optional<String> readAttribute(StartElement startElement, QName qName) { Attribute attribute = startElement.getAttributeByName(qName); return Optional.ofNullable(attribute).map(Attribute::getValue); }
3.26
hibernate-validator_AbstractStaxBuilder_readSingleElement_rdh
/** * Reads a value between a simple tag element. In case of a {@code <someTag>some-value</someTag>} will * return {@code some-value} as a string. * * @param xmlEventReader * a current {@link XMLEventReader} * @return a value of a current xml tag as a string */ protected String readSingleElement(XMLEventReader xmlEventReader) throws XMLStreamException { // trimming the string value as it might contain leading/trailing spaces or \n XMLEvent xmlEvent = xmlEventReader.nextEvent(); StringBuilder stringBuilder = new StringBuilder(xmlEvent.asCharacters().getData()); while (xmlEventReader.peek().isCharacters()) { xmlEvent = xmlEventReader.nextEvent(); stringBuilder.append(xmlEvent.asCharacters().getData()); } return stringBuilder.toString().trim();}
3.26
hibernate-validator_NotEmptyValidatorForCharSequence_isValid_rdh
/** * Check that the character sequence is not null and its length is strictly superior to 0. * * @author Guillaume Smet */public class NotEmptyValidatorForCharSequence implements ConstraintValidator<NotEmpty, CharSequence> { /** * Checks the character sequence is not {@code null} and not empty. * * @param charSequence * the character sequence to validate * @param constraintValidatorContext * context in which the constraint is evaluated * @return returns {@code true} if the character sequence is not {@code null} and not empty. */ @Override public boolean isValid(CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) { if (charSequence == null) { return false; } return charSequence.length() > 0; }
3.26
hibernate-validator_ConstraintCheckIssue_error_rdh
/** * Creates a new ConstraintCheckIssue of error kind ({@link IssueKind#ERROR}). * * @param element * The element at which the error occurred. * @param annotationMirror * The annotation that causes the error. * @param messageKey * A key for retrieving an error message template from the bundle * <p> * {@code org.hibernate.validator.ap.ValidationProcessorMessages.} * </p> * @param messageParameters * An array with values to put into the error message template * using {@link java.text.MessageFormat}. The number of elements must match * the number of place holders in the message template. */ public static ConstraintCheckIssue error(Element element, AnnotationMirror annotationMirror, String messageKey, Object... messageParameters) { return new ConstraintCheckIssue(element, annotationMirror, IssueKind.ERROR, messageKey, messageParameters); }
3.26
hibernate-validator_ConstraintCheckIssue_isError_rdh
/** * Determine if issue is an error * * @return true if {@link ConstraintCheckIssue#getKind()} equals to {@link IssueKind#ERROR} */ public boolean isError() { return IssueKind.ERROR.equals(kind); }
3.26
hibernate-validator_ConstraintCheckIssue_warning_rdh
/** * Creates a new ConstraintCheckIssue of warning kind ({@link IssueKind#WARNING}). * * @param element * The element at which the error occurred. * @param annotationMirror * The annotation that causes the error. * @param messageKey * A key for retrieving an error message template from the bundle * <p> * {@code org.hibernate.validator.ap.ValidationProcessorMessages.} * </p> * @param messageParameters * An array with values to put into the error message template * using {@link java.text.MessageFormat}. The number of elements must match * the number of place holders in the message template. */ public static ConstraintCheckIssue warning(Element element, AnnotationMirror annotationMirror, String messageKey, Object... messageParameters) { return new ConstraintCheckIssue(element, annotationMirror, IssueKind.WARNING, messageKey, messageParameters); }
3.26
hibernate-validator_ConstraintCheckIssue_isWarning_rdh
/** * Determine if issue is a warning * * @return true if {@link ConstraintCheckIssue#getKind()} equals to {@link IssueKind#WARNING} */ public boolean isWarning() { return IssueKind.WARNING.equals(kind); }
3.26
hibernate-validator_ValidationConfigStaxBuilder_build_rdh
/** * Returns an enum set with the executable types corresponding to the given * XML configuration, considering the special elements * {@link ExecutableType#ALL} and {@link ExecutableType#NONE}. * * @return An enum set representing the given executable types. */ public EnumSet<ExecutableType> build() { return executableTypes.isEmpty() ? null : executableTypes; }
3.26
hibernate-validator_ConstraintValidatorContextImpl_dropLeafNodeIfRequired_rdh
/** * In case nodes are added from within a class-level constraint, the node representing * the constraint element will be dropped. inIterable(), getKey() etc. */ private void dropLeafNodeIfRequired() { if (propertyPath.getLeafNode().getKind() == ElementKind.BEAN) { propertyPath = PathImpl.createCopyWithoutLeafNode(propertyPath); } }
3.26
hibernate-validator_ConstraintValidatorContextImpl_addLeafNode_rdh
/** * Adds the leaf node stored for deferred addition. Either a bean or * property node. */ private void addLeafNode() { switch (leafNodeKind) { case BEAN : propertyPath.addBeanNode(); break; case PROPERTY : propertyPath.addPropertyNode(leafNodeName); break; case CONTAINER_ELEMENT : propertyPath.setLeafNodeTypeParameter(leafNodeContainerType, f1); propertyPath.addContainerElementNode(leafNodeName); break; default : throw new IllegalStateException("Unsupported node kind: " + leafNodeKind); } }
3.26
hibernate-validator_CascadableConstraintMappingContextImplBase_addGroupConversion_rdh
/** * Adds a group conversion for this element. * * @param from * the source group of the conversion * @param to * the target group of the conversion */ public void addGroupConversion(Class<?> from, Class<?> to) { groupConversions.put(from, to); }
3.26
hibernate-validator_FutureOrPresentValidatorForCalendar_getInstant_rdh
/** * Check that the {@code java.util.Calendar} passed to be validated is in * the future. * * @author Alaa Nassef * @author Guillaume Smet */ public class FutureOrPresentValidatorForCalendar extends AbstractFutureOrPresentInstantBasedValidator<Calendar> {@Overrideprotected Instant getInstant(Calendar value) { return value.toInstant(); } }
3.26
hibernate-validator_Sequence_addInheritedGroups_rdh
/** * Recursively add inherited (groups defined on superclasses). * * @param group * the group for which the inherited groups need to be added to {@code expandedGroups} * @param expandedGroups * The list into which to add all groups */ private void addInheritedGroups(Group group, Set<Group> expandedGroups) { for (Class<?> inheritedGroup : group.getDefiningClass().getInterfaces()) { if (isGroupSequence(inheritedGroup)) { throw LOG.getSequenceDefinitionsNotAllowedException(); } Group g = new Group(inheritedGroup); expandedGroups.add(g); addInheritedGroups(g, expandedGroups);} }
3.26
hibernate-validator_NotEmptyValidatorForArraysOfLong_isValid_rdh
/** * Checks the array is not {@code null} and not empty. * * @param array * the array to validate * @param constraintValidatorContext * context in which the constraint is evaluated * @return returns {@code true} if the array is not {@code null} and the array is not empty */ @Override public boolean isValid(long[] array, ConstraintValidatorContext constraintValidatorContext) { if (array == null) { return false; } return array.length > 0; }
3.26
hibernate-validator_ValueExtractorManager_run_rdh
/** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17") private static <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run(); }
3.26
hibernate-validator_AbstractMethodOverrideCheck_findAllOverriddenElements_rdh
/** * Find overridden methods from all super classes and all implemented interfaces. Results are returned as a {@link MethodInheritanceTree}. * * @param overridingMethod * the method for which we want to find the overridden methods * @return a {@link MethodInheritanceTree} containing overridden methods */private MethodInheritanceTree findAllOverriddenElements(ExecutableElement overridingMethod) { TypeElement currentTypeElement = getEnclosingTypeElement(overridingMethod); MethodInheritanceTree.Builder methodInheritanceTreeBuilder = new MethodInheritanceTree.Builder(overridingMethod); collectOverriddenMethods(overridingMethod, currentTypeElement, methodInheritanceTreeBuilder); return methodInheritanceTreeBuilder.build(); }
3.26
hibernate-validator_AbstractMethodOverrideCheck_collectOverriddenMethodsInInterfaces_rdh
/** * Collect overridden methods in the interfaces of a given type. * * @param overridingMethod * the method for which we want to find the overridden methods * @param currentTypeElement * the class we are currently analyzing * @param methodInheritanceTreeBuilder * the method inheritance tree builder */ private void collectOverriddenMethodsInInterfaces(ExecutableElement overridingMethod, TypeElement currentTypeElement, MethodInheritanceTree.Builder methodInheritanceTreeBuilder) { for (TypeMirror implementedInterface : currentTypeElement.getInterfaces()) { TypeElement interfaceTypeElement = ((TypeElement) (typeUtils.asElement(implementedInterface))); ExecutableElement overriddenMethod = getOverriddenMethod(overridingMethod, interfaceTypeElement); ExecutableElement newOverridingMethod; if (overriddenMethod != null) { methodInheritanceTreeBuilder.addOverriddenMethod(overridingMethod, overriddenMethod); newOverridingMethod = overriddenMethod; } else { newOverridingMethod = overridingMethod; } collectOverriddenMethodsInInterfaces(newOverridingMethod, interfaceTypeElement, methodInheritanceTreeBuilder); } }
3.26
hibernate-validator_AbstractMethodOverrideCheck_isJavaLangObjectOrNull_rdh
/** * Determine if the provided {@link TypeElement} represents a {@link java.lang.Object} or is {@code null}. * * @param typeElement * the element to check * @return {@code true} if the provided element is {@link java.lang.Object} or is {@code null}, {@code false} otherwise */ private boolean isJavaLangObjectOrNull(TypeElement typeElement) { return (typeElement == null) || JAVA_LANG_OBJECT.contentEquals(typeElement.getQualifiedName()); }
3.26
hibernate-validator_AbstractMethodOverrideCheck_getEnclosingTypeElementQualifiedName_rdh
/** * Find a {@link String} representation of qualified name ({@link Name}) of corresponding {@link TypeElement} that * contains a given {@link ExecutableElement}. * * @param currentMethod * a method * @return a class/interface qualified name represented by {@link String} to which a method belongs to */ protected String getEnclosingTypeElementQualifiedName(ExecutableElement currentMethod) { return getEnclosingTypeElement(currentMethod).getQualifiedName().toString(); }
3.26
hibernate-validator_AbstractMethodOverrideCheck_getEnclosingTypeElement_rdh
/** * Find the {@link TypeElement} that contains a given {@link ExecutableElement}. * * @param currentMethod * a method * @return the class/interface containing the method represented by a {@link TypeElement} */ private TypeElement getEnclosingTypeElement(ExecutableElement currentMethod) { return ((TypeElement) (typeUtils.asElement(currentMethod.getEnclosingElement().asType()))); }
3.26
hibernate-validator_AbstractMethodOverrideCheck_getOverriddenMethod_rdh
/** * Find a method that is overridden by the one passed to this function. * * @param currentMethod * the method for which we want to find the overridden methods * @param typeElement * the class or interface analyzed * @return the overridden method if there is one, and {@code null} otherwise */ private ExecutableElement getOverriddenMethod(ExecutableElement currentMethod, TypeElement typeElement) { if (typeElement == null) { return null; } TypeElement enclosingTypeElement = getEnclosingTypeElement(currentMethod); for (Element element : elementUtils.getAllMembers(typeElement)) { if (!element.getKind().equals(ElementKind.METHOD)) { continue; } if (elementUtils.overrides(currentMethod, ((ExecutableElement) (element)), enclosingTypeElement)) { return ((ExecutableElement) (element)); } } return null; }
3.26
hibernate-validator_AbstractMethodOverrideCheck_collectOverriddenMethods_rdh
/** * Collect all the overridden elements of the inheritance tree. * * @param overridingMethod * the method for which we want to find the overridden methods * @param currentTypeElement * the class we are analyzing * @param methodInheritanceTreeBuilder * the method inheritance tree builder */ private void collectOverriddenMethods(ExecutableElement overridingMethod, TypeElement currentTypeElement, MethodInheritanceTree.Builder methodInheritanceTreeBuilder) { if (isJavaLangObjectOrNull(currentTypeElement)) { return; } collectOverriddenMethodsInInterfaces(overridingMethod, currentTypeElement, methodInheritanceTreeBuilder); TypeElement superclassTypeElement = ((TypeElement) (typeUtils.asElement(currentTypeElement.getSuperclass()))); if (superclassTypeElement == null) { return; } ExecutableElement overriddenMethod = getOverriddenMethod(overridingMethod, superclassTypeElement); if (overriddenMethod != null) { methodInheritanceTreeBuilder.addOverriddenMethod(overridingMethod, overriddenMethod); overridingMethod = overriddenMethod;} collectOverriddenMethods(overridingMethod, superclassTypeElement, methodInheritanceTreeBuilder); }
3.26
hibernate-validator_ValueContext_getCurrentValidatedValue_rdh
/** * Returns the current value to be validated. */ public final Object getCurrentValidatedValue() { return currentValue; }
3.26
hibernate-validator_ValueContext_setTypeParameter_rdh
/** * Sets the container element information. * * @param containerClass * the class of the container * @param typeParameterIndex * the index of the actual type parameter * @see TypeVariables#getContainerClass(TypeVariable) * @see TypeVariables#getActualTypeParameter(TypeVariable) * @see AnnotatedObject * @see ArrayElement */ public final void setTypeParameter(Class<?> containerClass, Integer typeParameterIndex) { if (containerClass == null) { return; } propertyPath.setLeafNodeTypeParameter(containerClass, typeParameterIndex); }
3.26
hibernate-validator_BeanMetaDataImpl_bySignature_rdh
/** * Builds up the method meta data for this type; each meta-data entry will be stored under the signature of the * represented method and all the methods it overrides. */ private Map<Signature, ExecutableMetaData> bySignature(Set<ExecutableMetaData> executables) { Map<Signature, ExecutableMetaData> v33 = newHashMap(); for (ExecutableMetaData executableMetaData : executables) { for (Signature signature : executableMetaData.getSignatures()) { v33.put(signature, executableMetaData); } } return v33; }
3.26
hibernate-validator_TraversableResolvers_getDefault_rdh
/** * Initializes and returns the default {@link TraversableResolver} depending on the environment. * <p> * If JPA 2 is present in the classpath, a {@link JPATraversableResolver} instance is returned. * <p> * Otherwise, it returns an instance of the default {@link TraverseAllTraversableResolver}. */ public static TraversableResolver getDefault() { // check whether we have Persistence on the classpath Class<?> persistenceClass; try { persistenceClass = run(LoadClass.action(PERSISTENCE_CLASS_NAME, TraversableResolvers.class.getClassLoader()));} catch (ValidationException e) { LOG.debugf("Cannot find %s on classpath. Assuming non JPA 2 environment. All properties will per default be traversable.", PERSISTENCE_CLASS_NAME); return getTraverseAllTraversableResolver(); } // check whether Persistence contains getPersistenceUtil Method persistenceUtilGetter = run(GetMethod.action(persistenceClass, PERSISTENCE_UTIL_METHOD)); if (persistenceUtilGetter == null) { LOG.debugf("Found %s on classpath, but no method '%s'. Assuming JPA 1 environment. All properties will per default be traversable.", PERSISTENCE_CLASS_NAME, PERSISTENCE_UTIL_METHOD); return getTraverseAllTraversableResolver(); } // try to invoke the method to make sure that we are dealing with a complete JPA2 implementation // unfortunately there are several incomplete implementations out there (see HV-374) try { Object persistence = run(NewInstance.action(persistenceClass, "persistence provider")); ReflectionHelper.getValue(persistenceUtilGetter, persistence); } catch (Exception e) { LOG.debugf("Unable to invoke %s.%s. Inconsistent JPA environment. All properties will per default be traversable.", PERSISTENCE_CLASS_NAME, PERSISTENCE_UTIL_METHOD); return getTraverseAllTraversableResolver(); }LOG.debugf("Found %s on classpath containing '%s'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver", PERSISTENCE_CLASS_NAME, PERSISTENCE_UTIL_METHOD); try { @SuppressWarnings("unchecked") Class<? extends TraversableResolver> jpaAwareResolverClass = ((Class<? extends TraversableResolver>) (run(LoadClass.action(JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME, TraversableResolvers.class.getClassLoader())))); LOG.debugf("Instantiated JPA aware TraversableResolver of type %s.", JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME); return run(NewInstance.action(jpaAwareResolverClass, "")); } catch (ValidationException e) { LOG.logUnableToLoadOrInstantiateJPAAwareResolver(JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME); return getTraverseAllTraversableResolver(); } }
3.26
hibernate-validator_TraversableResolvers_run_rdh
/** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17") private static <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run(); }
3.26
hibernate-validator_HibernateConstraintValidator_initialize_rdh
/** * Initializes the validator in preparation for {@link #isValid(Object, ConstraintValidatorContext)} calls. * It is an alternative to {@link #initialize(Annotation)} method. Should be used if any additional information * except annotation is needed to initialize a validator. * Note, when using {@link HibernateConstraintValidator} user should only override one of the methods, either * {@link #initialize(ConstraintDescriptor, HibernateConstraintValidatorInitializationContext)} or {@link #initialize(Annotation)}. * Both methods will be called during initialization, starting with * {@link #initialize(ConstraintDescriptor, HibernateConstraintValidatorInitializationContext)}. * * @param constraintDescriptor * a constraint descriptor for a given constraint declaration * @param initializationContext * an initialization context for a current {@link ConstraintValidatorFactory} */ default void initialize(ConstraintDescriptor<A> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) { }
3.26
hibernate-validator_GetDeclaredMethodHandle_m0_rdh
/** * Before using this method on arbitrary classes, you need to check the {@code HibernateValidatorPermission.ACCESS_PRIVATE_MEMBERS} * permission against the security manager, if the calling class exposes the handle to clients. */public static GetDeclaredMethodHandle m0(Lookup lookup, Class<?> clazz, String methodName, Class<?>... parameterTypes) { return new GetDeclaredMethodHandle(lookup, clazz, methodName, true, parameterTypes);}
3.26
hibernate-validator_FutureOrPresentValidatorForHijrahDate_getReferenceValue_rdh
/** * Check that the {@code java.time.chrono.HijrahDate} passed is in the future. * * @author Guillaume Smet */ public class FutureOrPresentValidatorForHijrahDate extends AbstractFutureOrPresentJavaTimeValidator<HijrahDate> { @Override protected HijrahDate getReferenceValue(Clock reference) { return HijrahDate.now(reference); }
3.26
hibernate-validator_ReflectionHelper_isIterable_rdh
/** * * @param type * the type to check. * @return Returns {@code true} if {@code type} is a iterable type, {@code false} otherwise. */ public static boolean isIterable(Type type) { if ((type instanceof Class) && Iterable.class.isAssignableFrom(((Class<?>) (type)))) { return true; } if (type instanceof ParameterizedType) { return isIterable(((ParameterizedType) (type)).getRawType()); } if (type instanceof WildcardType) { Type[] upperBounds = ((WildcardType) (type)).getUpperBounds(); return (upperBounds.length != 0) && isIterable(upperBounds[0]); } return false; }
3.26
hibernate-validator_ReflectionHelper_isList_rdh
/** * * @param type * the type to check. * @return Returns {@code true} if {@code type} is implementing {@code List}, {@code false} otherwise. */ public static boolean isList(Type type) { if ((type instanceof Class) && List.class.isAssignableFrom(((Class<?>) (type)))) { return true; } if (type instanceof ParameterizedType) { return isList(((ParameterizedType) (type)).getRawType()); } if (type instanceof WildcardType) { Type[] upperBounds = ((WildcardType) (type)).getUpperBounds(); return (upperBounds.length != 0) && isList(upperBounds[0]); } return false; } /** * Tries to retrieve the indexed value from the specified object. * * @param value * The object from which to retrieve the indexed value. The object has to be non {@code null} and * either a collection or array. * @param index * The index. * @return The indexed value or {@code null} if {@code value} is {@code null} or not a collection or array. {@code null}
3.26
hibernate-validator_ReflectionHelper_typeOf_rdh
/** * * @param member * The {@code Member} instance for which to retrieve the type. * @return Returns the {@code Type} of the given {@code Field} or {@code Method}. * @throws IllegalArgumentException * in case {@code member} is not a {@code Field} or {@code Method}. */ public static Type typeOf(Member member) { Type type; if (member instanceof Field) { type = ((Field) (member)).getGenericType(); } else if (member instanceof Method) { type = ((Method) (member)).getGenericReturnType(); } else if (member instanceof Constructor<?>) { type = member.getDeclaringClass(); } else // TODO HV-571 change log method name { throw LOG.getMemberIsNeitherAFieldNorAMethodException(member); } if (type instanceof TypeVariable) { type = TypeHelper.getErasedType(type); } return type; }
3.26
hibernate-validator_ReflectionHelper_isIndexable_rdh
/** * Indicates if the type is considered indexable (ie is a {@code List}, an array or a {@code Map}). * <p> * Note that it does not include {@code Set}s as they are not indexable. * * @param type * the type to inspect. * @return Returns true if the type is indexable. */public static boolean isIndexable(Type type) { return (isList(type) || isMap(type)) || TypeHelper.isArray(type); }
3.26
hibernate-validator_ReflectionHelper_isMap_rdh
/** * * @param type * the type to check. * @return Returns {@code true} if {@code type} is implementing {@code Map}, {@code false} otherwise. */ public static boolean isMap(Type type) { if ((type instanceof Class) && Map.class.isAssignableFrom(((Class<?>) (type)))) { return true; } if (type instanceof ParameterizedType) { return isMap(((ParameterizedType) (type)).getRawType()); } if (type instanceof WildcardType) { Type[] upperBounds = ((WildcardType) (type)).getUpperBounds(); return (upperBounds.length != 0) && isMap(upperBounds[0]); } return false; }
3.26
hibernate-validator_ReflectionHelper_isCollection_rdh
/** * Indicates whether the given type represents a collection of elements or not (i.e. whether it is an * {@code Iterable}, {@code Map} or array type). */ public static boolean isCollection(Type type) { return (isIterable(type) || isMap(type)) || TypeHelper.isArray(type); }
3.26
hibernate-validator_ReflectionHelper_boxedType_rdh
/** * Returns the corresponding auto-boxed type if given a primitive type. Returns the given type itself otherwise. */ public static Class<?> boxedType(Class<?> type) { if (type.isPrimitive()) { return internalBoxedType(((Class<?>) (type))); } else { return type; } } /** * Returns the primitive type for a boxed type. * * @param type * the boxed type * @return the primitive type for a auto-boxed type. In case {@link Void} is passed (which is considered as primitive type by {@link Class#isPrimitive()}), {@link Void}
3.26
hibernate-validator_ReflectionHelper_getMappedValue_rdh
/** * Tries to retrieve the mapped value from the specified object. * * @param value * The object from which to retrieve the mapped value. The object has to be non {@code null} and * must implement the @{code Map} interface. * @param key * The map key. index. * @return The mapped value or {@code null} if {@code value} is {@code null} or not implementing @{code Map}. */ public static Object getMappedValue(Object value, Object key) { if (!(value instanceof Map)) { return null; } Map<?, ?> map = ((Map<?, ?>) (value)); // noinspection SuspiciousMethodCalls return map.get(key); } /** * Returns the auto-boxed type of a primitive type. * * @param primitiveType * the primitive type * @return the auto-boxed type of a primitive type. In case {@link Void} is passed (which is considered as primitive type by {@link Class#isPrimitive()}), {@link Void}
3.26
hibernate-validator_ReflectionHelper_getCollectionElementType_rdh
/** * Determines the type of the elements of an {@code Iterable}, array or the value of a {@code Map}. */ public static Type getCollectionElementType(Type type) { Type indexedType = null; if (isIterable(type) && (type instanceof ParameterizedType)) { ParameterizedType paramType = ((ParameterizedType) (type)); indexedType = paramType.getActualTypeArguments()[0]; } else if (isMap(type) && (type instanceof ParameterizedType)) { ParameterizedType paramType = ((ParameterizedType) (type)); indexedType = paramType.getActualTypeArguments()[1]; } else if (TypeHelper.isArray(type)) { indexedType = TypeHelper.getComponentType(type); } return indexedType; }
3.26
hibernate-validator_ReflectionHelper_getClassFromType_rdh
/** * Converts the given {@code Type} to a {@code Class}. * * @param type * the type to convert * @return the class corresponding to the type */ public static Class<?> getClassFromType(Type type) { if (type instanceof Class) { return ((Class<?>) (type)); } if (type instanceof ParameterizedType) { return getClassFromType(((ParameterizedType) (type)).getRawType()); } if (type instanceof GenericArrayType) { return Object[].class; } throw LOG.getUnableToConvertTypeToClassException(type); }
3.26
hibernate-validator_DefaultConstraintMapping_getBeanConfigurations_rdh
/** * Returns all bean configurations configured through this constraint mapping. * * @param constraintCreationContext * the constraint creation context * @return a set of {@link BeanConfiguration}s with an element for each type configured through this mapping */ public Set<BeanConfiguration<?>> getBeanConfigurations(ConstraintCreationContext constraintCreationContext) { Set<BeanConfiguration<?>> configurations = newHashSet(); for (TypeConstraintMappingContextImpl<?> typeContext : typeContexts) { configurations.add(typeContext.build(constraintCreationContext)); }return configurations; }
3.26
hibernate-validator_ValidationXmlParser_run_rdh
/** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17") private static <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run(); }
3.26
hibernate-validator_ValidationXmlParser_parseValidationXml_rdh
/** * Tries to check whether a <i>validation.xml</i> file exists and parses it. * * @return The parameters parsed out of <i>validation.xml</i> wrapped in an instance of {@code ConfigurationImpl.ValidationBootstrapParameters}. */ public final BootstrapConfiguration parseValidationXml() { InputStream in = getValidationXmlInputStream(); if (in == null) { return BootstrapConfigurationImpl.getDefaultBootstrapConfiguration(); } ClassLoader previousTccl = run(GetClassLoader.fromContext()); try { run(SetContextClassLoader.action(ValidationXmlParser.class.getClassLoader())); // HV-970 The parser helper is only loaded if there actually is a validation.xml file; // this avoids accessing javax.xml.stream.* (which does not exist on Android) when not actually // working with the XML configuration XmlParserHelper xmlParserHelper = new XmlParserHelper(); // the InputStream supports mark and reset in.mark(Integer.MAX_VALUE); XMLEventReader xmlEventReader = xmlParserHelper.createXmlEventReader(VALIDATION_XML_FILE, new CloseIgnoringInputStream(in)); String schemaVersion = xmlParserHelper.getSchemaVersion(VALIDATION_XML_FILE, xmlEventReader); xmlEventReader.close(); in.reset(); // The validation is done first as StAX builders used below are assuming that the XML file is correct and don't // do any validation of the input. Schema schema = getSchema(xmlParserHelper, schemaVersion); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new CloseIgnoringInputStream(in))); in.reset(); xmlEventReader = xmlParserHelper.createXmlEventReader(VALIDATION_XML_FILE, new CloseIgnoringInputStream(in)); ValidationConfigStaxBuilder validationConfigStaxBuilder = new ValidationConfigStaxBuilder(xmlEventReader); xmlEventReader.close(); in.reset(); return validationConfigStaxBuilder.build(); } catch (XMLStreamException | IOException | SAXException e) { throw LOG.getUnableToParseValidationXmlFileException(VALIDATION_XML_FILE, e); } finally { run(SetContextClassLoader.action(previousTccl));m0(in); } }
3.26
hibernate-validator_ConfiguredConstraint_run_rdh
/** * Runs the given privileged action, using a privileged block if required. * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17") private static <V> V run(PrivilegedAction<V> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run(); }
3.26
hibernate-validator_GroupSequenceProviderCheck_retrieveGenericProviderType_rdh
/** * Retrieves the default group sequence provider generic type defined by the given {@code TypeMirror}. * * @param typeMirror * The {@code TypeMirror} instance. * @return The generic type or {@code null} if the given type doesn't implement the {@link org.hibernate.validator.spi.group.DefaultGroupSequenceProvider} interface. */ private TypeMirror retrieveGenericProviderType(TypeMirror typeMirror) { return typeMirror.accept(new SimpleTypeVisitor8<TypeMirror, Void>() { @Override public TypeMirror visitDeclared(DeclaredType declaredType, Void aVoid) { TypeMirror eraseType = typeUtils.erasure(declaredType); if (typeUtils.isSameType(eraseType, defaultGroupSequenceProviderType)) { List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments(); if (!typeArguments.isEmpty()) { return typeArguments.get(0); } return null; } List<? extends TypeMirror> superTypes = typeUtils.directSupertypes(declaredType); for (TypeMirror v11 : superTypes) { TypeMirror genericProviderType = v11.accept(this, aVoid); if (genericProviderType != null) { return genericProviderType; } } return null; } }, null); }
3.26
hibernate-validator_GroupSequenceProviderCheck_hasPublicDefaultConstructor_rdh
/** * Checks that the given {@code TypeElement} has a public * default constructor. * * @param element * The {@code TypeElement} to check. * @return True if the given {@code TypeElement} has a public default constructor, false otherwise */ private boolean hasPublicDefaultConstructor(TypeElement element) { return element.accept(new ElementKindVisitor8<Boolean, Void>(Boolean.FALSE) { @Override public Boolean m0(TypeElement typeElement, Void aVoid) { List<? extends Element> enclosedElements = typeElement.getEnclosedElements(); for (Element enclosedElement : enclosedElements) { if (enclosedElement.accept(this, aVoid)) { return Boolean.TRUE; } } return Boolean.FALSE; } @Override public Boolean visitExecutableAsConstructor(ExecutableElement constructorElement, Void aVoid) { if (constructorElement.getModifiers().contains(Modifier.PUBLIC) && constructorElement.getParameters().isEmpty()) { return Boolean.TRUE; } return Boolean.FALSE; } }, null); }
3.26
hibernate-validator_ValidationInterceptor_validateMethodInvocation_rdh
/** * Validates the Bean Validation constraints specified at the parameters and/or return value of the intercepted method. * * @param ctx * The context of the intercepted method invocation. * @return The result of the method invocation. * @throws Exception * Any exception caused by the intercepted method invocation. A {@link ConstraintViolationException} * in case at least one constraint violation occurred either during parameter or return value validation. */ @AroundInvoke public Object validateMethodInvocation(InvocationContext ctx) throws Exception { ExecutableValidator executableValidator = validator.forExecutables(); Set<ConstraintViolation<Object>> violations = executableValidator.validateParameters(ctx.getTarget(), ctx.getMethod(), ctx.getParameters()); if (!violations.isEmpty()) { throw new ConstraintViolationException(getMessage(ctx.getMethod(), ctx.getParameters(), violations), violations); } Object result = ctx.proceed(); violations = executableValidator.validateReturnValue(ctx.getTarget(), ctx.getMethod(), result); if (!violations.isEmpty()) { throw new ConstraintViolationException(getMessage(ctx.getMethod(), ctx.getParameters(), violations), violations); } return result; } /** * Validates the Bean Validation constraints specified at the parameters and/or return value of the intercepted constructor. * * @param ctx * The context of the intercepted constructor invocation. * @throws Exception * Any exception caused by the intercepted constructor invocation. A {@link ConstraintViolationException}
3.26
hibernate-validator_AbstractConstraintValidatorManagerImpl_resolveAssignableTypes_rdh
/** * Tries to reduce all assignable classes down to a single class. * * @param assignableTypes * The set of all classes which are assignable to the class of the value to be validated and * which are handled by at least one of the validators for the specified constraint. */ private void resolveAssignableTypes(List<Type> assignableTypes) { if ((assignableTypes.size() == 0) || (assignableTypes.size() == 1)) { return; } List<Type> typesToRemove = new ArrayList<>(); do { typesToRemove.clear(); Type type = assignableTypes.get(0); for (int v9 = 1; v9 < assignableTypes.size(); v9++) {if (TypeHelper.isAssignable(type, assignableTypes.get(v9))) { typesToRemove.add(type); } else if (TypeHelper.isAssignable(assignableTypes.get(v9), type)) { typesToRemove.add(assignableTypes.get(v9)); } } assignableTypes.removeAll(typesToRemove); } while (typesToRemove.size() > 0 ); }
3.26
hibernate-validator_AbstractConstraintValidatorManagerImpl_findMatchingValidatorDescriptor_rdh
/** * Runs the validator resolution algorithm. * * @param validatedValueType * The type of the value to be validated (the type of the member/class the constraint was placed on). * @return The class of a matching validator. */ private <A extends Annotation> ConstraintValidatorDescriptor<A> findMatchingValidatorDescriptor(ConstraintDescriptorImpl<A> descriptor, Type validatedValueType) { Map<Type, ConstraintValidatorDescriptor<A>> availableValidatorDescriptors = TypeHelper.getValidatorTypes(descriptor.getAnnotationType(), descriptor.getMatchingConstraintValidatorDescriptors()); List<Type> discoveredSuitableTypes = findSuitableValidatorTypes(validatedValueType, availableValidatorDescriptors.keySet()); resolveAssignableTypes(discoveredSuitableTypes); if (discoveredSuitableTypes.size() == 0) { return null; } if (discoveredSuitableTypes.size() > 1) { throw LOG.getMoreThanOneValidatorFoundForTypeException(validatedValueType, discoveredSuitableTypes); } Type suitableType = discoveredSuitableTypes.get(0); return availableValidatorDescriptors.get(suitableType); }
3.26
hibernate-validator_ConstrainedExecutable_getParameterMetaData_rdh
/** * Constraint meta data for the specified parameter. * * @param parameterIndex * The index in this executable's parameter array of the parameter of * interest. * @return Meta data for the specified parameter. Will never be {@code null}. * @throws IllegalArgumentException * In case this executable doesn't have a parameter with the * specified index. */ public ConstrainedParameter getParameterMetaData(int parameterIndex) { if ((parameterIndex < 0) || (parameterIndex > (parameterMetaData.size() - 1))) { throw LOG.getInvalidExecutableParameterIndexException(callable, parameterIndex); } return parameterMetaData.get(parameterIndex); } /** * Returns meta data for all parameters of the represented executable. * * @return A list with parameter meta data. The length corresponds to the number of parameters of the executable represented by this meta data object, so an empty list may be returned (in case of a parameterless executable), but never {@code null}
3.26
hibernate-validator_ConstrainedExecutable_merge_rdh
/** * Creates a new constrained executable object by merging this and the given * other executable. Both executables must have the same location, i.e. * represent the same executable on the same type. * * @param other * The executable to merge. * @return A merged executable. */ public ConstrainedExecutable merge(ConstrainedExecutable other) { ConfigurationSource mergedSource = ConfigurationSource.max(source, other.source); List<ConstrainedParameter> mergedParameterMetaData = newArrayList(parameterMetaData.size()); int i = 0; for (ConstrainedParameter parameter : parameterMetaData) { mergedParameterMetaData.add(parameter.merge(other.getParameterMetaData(i))); i++; } Set<MetaConstraint<?>> v8 = newHashSet(crossParameterConstraints); v8.addAll(other.crossParameterConstraints); Set<MetaConstraint<?>> mergedReturnValueConstraints = newHashSet(constraints); mergedReturnValueConstraints.addAll(other.constraints); Set<MetaConstraint<?>> mergedTypeArgumentConstraints = new HashSet<>(typeArgumentConstraints); mergedTypeArgumentConstraints.addAll(other.typeArgumentConstraints); CascadingMetaDataBuilder mergedCascadingMetaDataBuilder = cascadingMetaDataBuilder.merge(other.cascadingMetaDataBuilder); return new ConstrainedExecutable(mergedSource, callable, mergedParameterMetaData, v8, mergedReturnValueConstraints, mergedTypeArgumentConstraints, mergedCascadingMetaDataBuilder); }
3.26
hibernate-validator_InheritedMethodsHelper_run_rdh
/** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17") private static <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run(); }
3.26
hibernate-validator_InheritedMethodsHelper_getAllMethods_rdh
/** * Get a list of all methods which the given class declares, implements, * overrides or inherits. Methods are added by adding first all methods of * the class itself and its implemented interfaces, then the super class and * its interfaces, etc. * * @param clazz * the class for which to retrieve the methods * @return set of all methods of the given class */ public static List<Method> getAllMethods(Class<?> clazz) { Contracts.assertNotNull(clazz); List<Method> methods = newArrayList(); for (Class<?> hierarchyClass : ClassHierarchyHelper.getHierarchy(clazz)) { Collections.addAll(methods, run(GetMethods.action(hierarchyClass))); }return methods; }
3.26
hibernate-validator_TypeConstraintMappingContextImpl_m1_rdh
/** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ @IgnoreForbiddenApisErrors(reason = "SecurityManager is deprecated in JDK17")private <T> T m1(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run(); }
3.26
zxing_GenericGFPoly_getCoefficient_rdh
/** * * @return coefficient of x^degree term in this polynomial */ int getCoefficient(int degree) { return coefficients[(coefficients.length - 1) - degree]; }
3.26