下面列出了怎么用org.apache.commons.lang3.Validate的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Determines the scope for a given input {@code String}.
*
* <p>
* If the {@code String} does not match 'request', 'session', 'page' or 'application', the method will return
* {@link PageContext#PAGE_SCOPE}.
* </p>
*
* @param scope
* the {@code String} to inspect
* @return the scope found, or {@link PageContext#PAGE_SCOPE} if no scope matched
* 如果 <code>scope</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>scope</code> 是blank,抛出 {@link IllegalArgumentException}<br>
*/
public static int getScope(String scope){
Validate.notBlank(scope, "scope can't be blank!");
if (scope.equalsIgnoreCase(SCOPE_REQUEST)){
return PageContext.REQUEST_SCOPE;
}
if (scope.equalsIgnoreCase(SCOPE_SESSION)){
return PageContext.SESSION_SCOPE;
}
if (scope.equalsIgnoreCase(SCOPE_APPLICATION)){
return PageContext.APPLICATION_SCOPE;
}
return PageContext.PAGE_SCOPE;
}
/**
* Load up a ZIP resource from the classpath and generate a {@link ClassNode} for each file with a class extension in that ZIP.
* Behaviour is ZIP or classes within are not a parseable.
* @param path path of ZIP resource
* @return {@link ClassNode} representation of class files in ZIP
* @throws NullPointerException if any argument is {@code null}
* @throws IOException if any IO error occurs
* @throws IllegalArgumentException if {@code path} cannot be found
*/
public static Map<String, ClassNode> readZipResourcesAsClassNodes(String path) throws IOException {
Validate.notNull(path);
Map<String, byte[]> files = readZipFromResource(path);
Map<String, ClassNode> ret = new LinkedHashMap<>();
for (Entry<String, byte[]> entry : files.entrySet()) {
if (!entry.getKey().toLowerCase().endsWith(".class")) {
continue;
}
ClassReader cr = new ClassReader(new ByteArrayInputStream(entry.getValue()));
ClassNode classNode = new ClassNode();
cr.accept(classNode, 0);
ret.put(entry.getKey(), classNode);
}
return ret;
}
/**
* Find nodes matching selector.
*
* @param query CSS selector
* @param roots root nodes to descend into
* @return matching nodes, empty if none
*/
public static <T> Nodes<T> select(String query, Iterable<Node<T>> roots) {
Validate.notEmpty(query);
Validate.notNull(roots);
Evaluator<T> evaluator = QueryParser.parse(query);
ArrayList<Node<T>> nodes = new ArrayList<>();
IdentityHashMap<Node<T>, Boolean> seenNodes = new IdentityHashMap<>();
// dedupe nodes by identity, not equality
for (Node<T> root : roots) {
final Nodes<T> found = select(evaluator, root);
for (Node<T> el : found) {
if (!seenNodes.containsKey(el)) {
nodes.add(el);
seenNodes.put(el, Boolean.TRUE);
}
}
}
return new Nodes<>(nodes);
}
@Override
public List<IFileSpec> getDepotFiles(@Nonnull final List<IFileSpec> fileSpecs,
final GetDepotFilesOptions opts) throws P4JavaException {
Validate.notNull(fileSpecs);
List<IFileSpec> fileList = new ArrayList<>();
List<Map<String, Object>> resultMaps = execMapCmdList(FILES,
processParameters(opts, fileSpecs, server), null);
if (nonNull(resultMaps)) {
for (Map<String, Object> map : resultMaps) {
fileList.add(ResultListBuilder.handleFileReturn(map, server));
}
}
return fileList;
}
/**
* Find the first compatible port type class name of the root.
* <p>
* Compatible port type should be SOAP protocol version 1.1 and 1.2.
* </p>
*
* @param root Root element of wsdl
* @param sense Communication sense type
* @return First compatible port type class name
*/
private static String findFirstCompatiblePortTypeClassName(Element root,
WsType sense) {
Validate.notNull(root, ROOT_ELEMENT_REQUIRED);
Element binding = findFirstCompatibleBinding(root);
// Find all port types elements
List<Element> portTypes = XmlUtils.findElements(PORT_TYPES_XPATH, root);
Validate.notEmpty(portTypes, "No valid port type format");
String portTypeRef = binding.getAttribute(TYPE_ATTRIBUTE);
StringUtils.isNotEmpty(portTypeRef);
Element portType = getReferencedElement(root, portTypes, portTypeRef);
Validate.notNull(portType, "No valid port type reference");
String portTypeName = portType.getAttribute(NAME_ATTRIBUTE);
StringUtils.isNotEmpty(portTypeName);
return convertNameToJavaFormat(portTypeName, sense);
}
/**
* Get the date offset unit enum for a string (using common synonyms like "d", "b", "bd", "w").
*
* @param string The date roll convention name.
* @return The date roll convention enum.
*/
public static DateOffsetUnit getEnum(final String string) {
Validate.notNull(string, "Date offset unit string must not be null.");
if(string.equalsIgnoreCase("d")) {
return DAYS;
}
if(string.equalsIgnoreCase("b")) {
return BUSINESS_DAYS;
}
if(string.equalsIgnoreCase("bd")) {
return BUSINESS_DAYS;
}
if(string.equalsIgnoreCase("w")) {
return WEEKS;
}
if(string.equalsIgnoreCase("m")) {
return MONTHS;
}
if(string.equalsIgnoreCase("y")) {
return YEARS;
}
return DateOffsetUnit.valueOf(string.toUpperCase());
}
/**
* Given a source and destination path, scans the source path for class files and translates them to the destination path. This
* method recursively scans the path.
* <p>
* For example, imagine source path of {@code /src} and a destination path of {@code /dst}...
* <pre>
* /src/A.class -> /dst/A.class
* /src/a/B.class -> /dst/B.class
* /src/a/b/c/d/e/C.class -> /dst/a/b/c/d/e/C.class
* /src/a/b/c/d/e/D.class -> /dst/a/b/c/d/e/D.class
* </pre>
* @param srcDir source directory
* @param dstDir destination directory
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if either of the paths passed in are not directories
* @return source class to destination class mapping
*/
public static Map<File, File> mapPaths(File srcDir, File dstDir) {
Validate.notNull(srcDir);
Validate.notNull(dstDir);
Validate.isTrue(srcDir.isDirectory());
Validate.isTrue(dstDir.isDirectory());
Map<File, File> ret = new HashMap<>();
FileUtils.listFiles(srcDir, new String[]{"class"}, true).forEach((inputFile) -> {
Path relativePath = srcDir.toPath().relativize(inputFile.toPath());
Path outputFilePath = dstDir.toPath().resolve(relativePath);
File outputFile = outputFilePath.toFile();
ret.put(inputFile, outputFile);
});
return ret;
}
/**
* @param cargo cargo
* @param completionTime completion time, the reported time that the event
* actually happened (e.g. the receive took place).
* @param registrationTime registration time, the time the message is
* received
* @param type type of event
* @param location where the event took place
*/
public HandlingEvent(Cargo cargo, Date completionTime,
Date registrationTime, Type type, Location location) {
Validate.notNull(cargo, "Cargo is required");
Validate.notNull(completionTime, "Completion time is required");
Validate.notNull(registrationTime, "Registration time is required");
Validate.notNull(type, "Handling event type is required");
Validate.notNull(location, "Location is required");
if (type.requiresVoyage()) {
throw new IllegalArgumentException(
"Voyage is required for event type " + type);
}
this.completionTime = (Date) completionTime.clone();
this.registrationTime = (Date) registrationTime.clone();
this.type = type;
this.location = location;
this.cargo = cargo;
this.voyage = null;
}
@Override
public IIdType setParts(String theBaseUrl, String theResourceType, String theIdPart, String theVersionIdPart) {
if (isNotBlank(theVersionIdPart)) {
Validate.notBlank(theResourceType, "If theVersionIdPart is populated, theResourceType and theIdPart must be populated");
Validate.notBlank(theIdPart, "If theVersionIdPart is populated, theResourceType and theIdPart must be populated");
}
if (isNotBlank(theBaseUrl) && isNotBlank(theIdPart)) {
Validate.notBlank(theResourceType, "If theBaseUrl is populated and theIdPart is populated, theResourceType must be populated");
}
setValue(null);
myBaseUrl = theBaseUrl;
myResourceType = theResourceType;
myUnqualifiedId = theIdPart;
myUnqualifiedVersionId = StringUtils.defaultIfBlank(theVersionIdPart, null);
myHaveComponentParts = true;
return this;
}
/**
* Construct a Brownian motion.
*
* The constructor allows to set the factory to be used for the construction of
* random variables. This allows to generate Brownian increments represented
* by different implementations of the RandomVariable (e.g. the RandomVariableFromFloatArray internally
* using float representations).
*
* @param timeDiscretization The time discretization used for the Brownian increments.
* @param numberOfFactors Number of factors.
* @param numberOfPaths Number of paths to simulate.
* @param randomNumberGenerator A random number generator for n-dimensional uniform random numbers (n = numberOfTimeSteps*numberOfFactors).
* @param abstractRandomVariableFactory Factory to be used to create random variable.
*/
public BrownianMotionFromRandomNumberGenerator(
final TimeDiscretization timeDiscretization,
final int numberOfFactors,
final int numberOfPaths,
final RandomNumberGenerator randomNumberGenerator,
final RandomVariableFactory abstractRandomVariableFactory) {
super();
this.timeDiscretization = timeDiscretization;
this.numberOfFactors = numberOfFactors;
this.numberOfPaths = numberOfPaths;
this.randomNumberGenerator = randomNumberGenerator;
this.abstractRandomVariableFactory = abstractRandomVariableFactory;
brownianIncrements = null; // Lazy initialization
Validate.notNull(timeDiscretization);
Validate.notNull(randomNumberGenerator);
int requiredDimension = numberOfFactors*timeDiscretization.getNumberOfTimeSteps();
Validate.isTrue(randomNumberGenerator.getDimension() >= requiredDimension, "Dimension of RandomNumberGenerator required to be at least %d.", requiredDimension);
}
/**
* {@inheritDoc}
*/
public final void appendTo(StringBuffer buffer, int value) {
if (value < 100) {
for (int i = mSize; --i >= 2; ) {
buffer.append('0');
}
buffer.append((char)(value / 10 + '0'));
buffer.append((char)(value % 10 + '0'));
} else {
int digits;
if (value < 1000) {
digits = 3;
} else {
Validate.isTrue(value > -1, "Negative values should not be possible", value);
digits = Integer.toString(value).length();
}
for (int i = mSize; --i >= digits; ) {
buffer.append('0');
}
buffer.append(Integer.toString(value));
}
}
/**
* Validates intent name against ASK conventions. Throws an exception in case the convention is not met
* @param intentName name of an intent
*/
public static void validateIntentName(final String intentName) {
// look for reserved intent keyword "invocation" which indicates invocation name definition
if (StringUtils.equalsIgnoreCase("invocation", intentName)) {
// validate invocation name requirements
validateInvocationName(intentName);
} else {
// validate intent name requirements
Validate.isTrue(intentNamePattern.matcher(intentName).matches(), "Your intent " + intentName + " does not meet intent name conventions. The name of an intent can only contain case-insensitive alphabetical characters and underscores.");
}
}
@Override
public String login2(IUser user, Login2Options opts) throws P4JavaException {
Validate.notNull(user);
Validate.notBlank(user.getLoginName(), "Login name shouldn't null or empty");
List<Map<String, Object>> resultMaps = login2(opts, user.getLoginName());
String message = ResultMapParser.parseCommandResultMapIfIsInfoMessageAsString(resultMaps);
return message;
}
/**
* 文件复制. {@link Files#copy}
*
* @param from 如果为null,或文件不存在或者是目录,,抛出异常
* @param to 如果to为null,或文件存在但是一个目录,抛出异常
*/
public static void copyFile(@NotNull Path from, @NotNull Path to) throws IOException {
Validate.isTrue(Files.exists(from), "%s is not exist or not a file", from);
Validate.notNull(to);
Validate.isTrue(!FileUtil.isDirExists(to), "%s is exist but it is a dir", to);
Files.copy(from, to);
}
/**
* 文件复制. @see {@link Files#copy}
*
* @param from 如果为null,或文件不存在或者是目录,,抛出异常
* @param to 如果to为null,或文件存在但是一个目录,抛出异常
*/
public static void copyFile(@NotNull Path from, @NotNull Path to) throws IOException {
Validate.isTrue(Files.exists(from), "%s is not exist or not a file", from);
Validate.notNull(to);
Validate.isTrue(!FileUtil.isDirExists(to), "%s is exist but it is a dir", to);
Files.copy(from, to);
}
/**
* Add a package server that can be used to fetch remote packages
*/
public void addPackageServer(@Nonnull String thePackageServer) {
Validate.notBlank(thePackageServer, "thePackageServer must not be null or empty");
if (!myPackageServers.contains(thePackageServer)) {
myPackageServers.add(thePackageServer);
}
}
/**
* 返回min到max的随机Int,可传入SecureRandom或ThreadLocalRandom.
*
* min必须大于0.
*
* JDK本身不具有控制两端范围的nextInt,因此参考Commons Lang RandomUtils的实现, 不直接复用是因为要传入Random实例
*
* @see org.apache.commons.lang3.RandomUtils#nextInt(long, long)
*/
public static int nextInt(Random random, int min, int max) {
Validate.isTrue(max >= min, "Start value must be smaller or equal to end value.");
MoreValidate.nonNegative("min", min);
if (min == max) {
return min;
}
return min + random.nextInt(max - min);
}
@Override
public Optional<CardinalityEstimator> createCardinalityEstimator(
final int outputIndex,
final Configuration configuration) {
Validate.inclusiveBetween(0, this.getNumOutputs() - 1, outputIndex);
return Optional.of(new FixedSizeCardinalityEstimator(1));
}
public boolean addAssignmentListener(AssignmentListener l) {
Validate.isTrue(l != null, "l cannot be null");
boolean added = ASSIGNMENT_LISTENERS.add(l);
if (added) {
l.onAssigned(this, ALIAS);
if (aliases != null) {
for (String alias : aliases) l.onAssigned(this, alias);
}
}
return added;
}
@Override
public IData<MergeRequestDiffFull> getV3ProjectsMerge_requestsVersionsMergeRequestDiffFullByVersionId(String id, Integer mergeRequestId, Integer versionId){
Validate.notNull(id);
Validate.notNull(mergeRequestId);
Validate.notNull(versionId);
return entityClient.getV3ProjectsMerge_requestsVersionsMergeRequestDiffFullByVersionId(id, mergeRequestId, versionId);
}
@Override
public void handleRequest(final InputStream input, final OutputStream output, final Context context) throws IOException {
final String inputS = IOUtils.toString(Optional.ofNullable(input).orElse(new ByteArrayInputStream("{}".getBytes())));
final JsonNode root = om.readTree(inputS);
final String bucket = Optional.ofNullable(root.get(S3_BUCKET_PROPERTY)).map(JsonNode::textValue).filter(StringUtils::isNotBlank).orElse(System.getenv(S3_BUCKET_PROPERTY));
Validate.notBlank(bucket, S3_BUCKET_PROPERTY + " hasn't been set in the request payload nor as an environment variable.");
final String key = Optional.ofNullable(root.get(S3_KEY_PROPERTY)).map(JsonNode::textValue).filter(StringUtils::isNotBlank)
.orElse(System.getenv(S3_KEY_PROPERTY));
final String region = Optional.ofNullable(root.get(S3_REGION_PROPERTY)).map(JsonNode::textValue).filter(StringUtils::isNotBlank)
.orElse(System.getenv(S3_REGION_PROPERTY));
final AmazonS3 s3client = StringUtils.isNotBlank(region) ? AmazonS3ClientBuilder.standard().withRegion(region).build() : AmazonS3ClientBuilder.defaultClient();
final ListObjectsRequest listRequest = new ListObjectsRequest().withBucketName(bucket).withPrefix(Optional.ofNullable(key).map(k -> k + (k.endsWith("/") ? "" : "/")).orElse(""));
log.info("[INFO] Reading out *.yml conversation script files in folder '" + listRequest.getPrefix() + "' in bucket '" + listRequest.getBucketName() + "'");
final List<S3ObjectSummary> conversationScripts = s3client.listObjects(listRequest).getObjectSummaries().stream()
.filter(os -> os.getKey().toLowerCase().endsWith(".yml")).collect(Collectors.toList());
log.info("[INFO] Found " + conversationScripts.size() + " conversation script files in bucket '" + bucket + "'");
for (final S3ObjectSummary conversationScript : conversationScripts) {
log.info("[INFO] Load conversation script file " + conversationScript.getKey() + " from S3 bucket " + bucket);
AlexaClient.create(s3client.getObject(bucket, conversationScript.getKey()).getObjectContent())
.build()
.startScript();
}
output.write("{ \"OK\" }".getBytes());
}
/**
* Get file as an input stream.
* Append last chunk data to cached file
*
* @param fileCacheKeyStr file cache key
* @param endChunkStream last chunk of file
* @return file stream
*/
public InputStream asInputStream(final String fileCacheKeyStr, InputStream endChunkStream) throws ECFileCacheException {
FileCacheKey fileCacheKey = SerializationHelper.toThriftObject(FileCacheKey.class, Base64.decodeBase64(fileCacheKeyStr));
Validate.isTrue(fileCacheKey.getVersion() == ECodec.VERSION);
List<Integer> redisIds = getRedisIds(fileCacheKey);
Map<Long, Integer> chunkPosAndSize = monitor.get().getChunkPosAndSize(redisIds, fileCacheKey.getUuid());
return new ECFileCacheInputStream(fileCacheKey, chunkPosAndSize, monitor.get(), redisIds, endChunkStream);
}
@Override
public List<MppPreview> getInnClusters(String region, String searchString, String lang, List<String> types, int first, int count) {
try {
drugsDAO.openDataStoreSession();
Validate.noNullElements(new Object[]{searchString, lang});
log.debug("Asked language : " + lang);
lang = getAvailableLanguage(lang);
log.debug("Final language : " + lang);
PaginatedList<Code> inns = codeLogic.findCodesByLabel(region, lang, "CD-INNCLUSTER", searchString, new PaginationOffset(first + count));
return (List<MppPreview>) CollectionUtils.collect(inns.getRows().subList(first, inns.getRows().size()), lang != null && lang.equals("nl") ? INN_TO_MPPPREVIEW_NL : INN_TO_MPPPREVIEW_FR);
} finally {
drugsDAO.closeDataStoreSession();
}
}
/**
* Constructs a valid java package path from target namespace of root wsdl.
* <p>
* Package ends with the package separator. Related package is different
* when web service is rpc encoded or not.
* </p>
*
* @param root Root element of the wsdl
* @return Equivalent java package or empty
*/
public static String getTargetNamespaceRelatedPackage(Element root) {
Validate.notNull(root, ROOT_ELEMENT_REQUIRED);
// Get the namespace attribute from root wsdl
String namespace = getTargetNamespace(root);
String pkg = getTargetNamespaceRelatedPackage(namespace, root)
.toLowerCase();
pkg = pkg.replace('_', 'u');
return pkg.concat(".");
}
public static SqlIOResolver createIOResolver(Config config) {
String sourceResolveValue = config.get(CFG_IO_RESOLVER);
Map<String, String> metadataPrefixProperties = new HashMap<>();
metadataPrefixProperties.put(
String.format(CFG_FMT_SOURCE_RESOLVER_DOMAIN, sourceResolveValue) + CFG_METADATA_TOPIC_PREFIX,
config.get(CFG_METADATA_TOPIC_PREFIX, DEFAULT_METADATA_TOPIC_PREFIX));
Config newConfig = new MapConfig(Arrays.asList(config, metadataPrefixProperties));
Validate.notEmpty(sourceResolveValue, "ioResolver config is not set or empty");
return initializePlugin("SqlIOResolver", sourceResolveValue, newConfig, CFG_FMT_SOURCE_RESOLVER_DOMAIN,
(o, c) -> ((SqlIOResolverFactory) o).create(c, newConfig));
}
/**
* Enable use of inter-document cross-references when needed.
*
* @param prefix Prefix to document in all inter-document cross-references.
* @return this builder
*/
public T withInterDocumentCrossReferences(String prefix) {
Validate.notNull(prefix, "%s must not be null", "prefix");
config.interDocumentCrossReferencesEnabled = true;
config.interDocumentCrossReferencesPrefix = prefix;
return self;
}
/**
* @param position the current position
* @param docBuilder the MarkupDocBuilder
* @param securitySchemeName the name of the current securityScheme
* @param securityScheme the current security scheme securityScheme
*/
public Context(Position position, MarkupDocBuilder docBuilder, String securitySchemeName, SecuritySchemeDefinition securityScheme) {
super(docBuilder);
Validate.inclusiveBetween(Position.SECURITY_SCHEME_BEFORE, Position.SECURITY_SCHEME_AFTER, position);
Validate.notNull(securitySchemeName);
Validate.notNull(securityScheme);
this.position = position;
this.securitySchemeName = securitySchemeName;
this.securityScheme = securityScheme;
}
/**
* Create a new instance.
*
* @param key The cookie key
* @param value The cookie value
*/
AuthCookie(String key, String value) {
Validate.notNull(key, "Key must not be null");
Validate.notNull(value, "Value must not be null");
this.key = key;
this.value = value;
}
public ServerListPingEvent(final InetAddress address, final String motd, final int numPlayers, final int maxPlayers) {
Validate.isTrue(numPlayers >= 0, "Cannot have negative number of players online", numPlayers);
this.address = address;
this.motd = motd;
this.numPlayers = numPlayers;
this.maxPlayers = maxPlayers;
}
public GraphObject(String sha, String type) {
Validate.notBlank(sha, "SHA should not be null or empty");
Validate.notBlank(type, "Type should not be null or empty");
this.sha = sha;
this.type = type;
}