下面列出了怎么用org.apache.commons.lang.Validate的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Checks the availability and the demanded value of the right for the context user. The right will be checked itself on required
* constraints, e. g. if assigned groups required.
* @param user Check the access for the given user instead of the logged-in user.
* @param rightId
* @param values At least one of the values should match.
* @param throwException
* @return
*/
public boolean hasRight(final PFUserDO user, final UserRightId rightId, final boolean throwException, final UserRightValue... values)
{
Validate.notNull(user);
Validate.notNull(values);
final UserRightDO rightDO = user.getRight(rightId);
final UserRight right = userRights.getRight(rightId);
for (final UserRightValue value : values) {
if ((rightDO == null || rightDO.getValue() == null) && right.matches(userGroupCache, user, value) == true) {
return true;
}
if (rightDO != null && rightDO.getValue() == value) {
if (right != null && right.isAvailable(userGroupCache, user, value) == true) {
return true;
}
}
}
if (throwException == true) {
throw new AccessException("access.exception.userHasNotRight", rightId, StringHelper.listToString(", ", (Object[]) values));
}
return false;
}
public static JdbcDataSource getJdbcDataSource(String initScriptLocation) {
Validate.notEmpty(initScriptLocation, "initScriptLocation is empty");
String mavenRelativePath = "src/main/resources/" + initScriptLocation;
String mavenRootRelativePath = "camel-cookbook-transactions/" + mavenRelativePath;
// check that we can load the init script
FileLocator locator = new FileLocator().with(initScriptLocation).with(mavenRelativePath).with(mavenRootRelativePath);
File file = locator.find();
Validate.notNull(file, locator.getErrorMessage());
FileSystemResource script = new FileSystemResource(file);
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1");
dataSource.setUser("sa");
dataSource.setPassword("");
DataSourceInitializer.initializeDataSource(dataSource, script);
return dataSource;
}
@Override
public void execute(ActionMessagePrinter printer)
throws CmdLineActionException {
try (FileManagerClient client = getClient()) {
Validate.notNull(origRef, "Must specify origRef");
Reference ref = new Reference();
ref.setOrigReference(getUri(origRef).toString());
printer.println("Reference: [origRef=" + origRef + ",transferPct=" + client.getRefPctTransferred(ref) + "]");
} catch (Exception e) {
throw new CmdLineActionException(
"Failed to get percent transfered for" + " file '" + origRef
+ "' : " + e.getMessage(), e);
}
}
@Override
public void marshal(Element element) {
Element worldElement = element.addElement("world");
Element xElement = element.addElement("x");
Element yElement = element.addElement("y");
Element zElement = element.addElement("z");
Location value = getValue();
Validate.notNull(value, "getValue() cannot be null when marshalling flag value");
worldElement.addText(value.getWorld().getName());
xElement.addText(String.valueOf(value.getX()));
yElement.addText(String.valueOf(value.getY()));
zElement.addText(String.valueOf(value.getZ()));
if (value.getYaw() != 0f) {
element.addElement("yaw").addText(String.valueOf(value.getYaw()));
}
if (value.getPitch() != 0f) {
element.addElement("pitch").addText(String.valueOf(value.getPitch()));
}
}
/**
* {@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));
}
}
public void attachProxy(Proxy proxy) {
Validate.isTrue(!isProxyAttached(proxy), "Proxy already attached");
Class<? extends Proxy> clazz = proxy.getClass();
Priority priority = Priority.NORMAL;
if (clazz.isAnnotationPresent(ProxyPriority.class)) {
ProxyPriority priorityAnnotation = clazz.getAnnotation(ProxyPriority.class);
priority = priorityAnnotation.value();
}
String[] filter = null;
if (clazz.isAnnotationPresent(Filter.class)) {
Filter filterAnnotation = clazz.getAnnotation(Filter.class);
filter = filterAnnotation.value();
}
ProxyHolder holder = new ProxyHolder();
holder.proxy = proxy;
holder.priority = priority;
holder.filter = filter;
proxies.add(holder);
//Finally sort the list to get an appropriate order
Collections.sort(proxies);
}
private static String generateChunkedQuery(String nestedQuery, List<String> keys, long chunkSize, int partitionCount,
List<Integer> partitions, boolean isFirstRun) {
Validate.isTrue(!keys.isEmpty(), "Need keys to generate chunked query. No keys supplied");
String hashPredicate = generateFullPartitionHashPredicate(generatePerPartitionHashPredicate(keys, partitionCount), partitions);
StringBuilder query = new StringBuilder();
query.append(SELECT_FROM);
query.append(nestedQuery);
// 'nestedTab' alias needed as mysql requires every derived table to have its own alias
query.append(" ) nestedTab1 ");
query.append(hashPredicate);
if (!isFirstRun) {
query.append(" AND ( " + generateKeyChunkingPredicate(keys)).append(" )");
}
query.append(" ORDER BY ").append(keys.get(0));
for (int i = 1; i < keys.size(); i++) {
query.append(" , ").append(keys.get(i));
}
query.insert(0, SELECT_FROM).append(" ) as nestedTab2 LIMIT " + chunkSize);
return query.toString();
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args)
{
Validate.notNull(sender, "Sender cannot be null");
Validate.notNull(args, "Arguments cannot be null");
Validate.notNull(alias, "Alias cannot be null");
if (args.length == 1)
{
return StringUtil.copyPartialMatches(args[0], COMMANDS, new ArrayList<String>(COMMANDS.size()));
}
if (((args.length == 2) && "get".equalsIgnoreCase(args[0])) || "set".equalsIgnoreCase(args[0]))
{
return StringUtil.copyPartialMatches(args[1], MinecraftServer.getServer().tileEntityConfig.getSettings().keySet(), new ArrayList<String>(MinecraftServer.getServer().tileEntityConfig.getSettings().size()));
}
return ImmutableList.of();
}
@Override
public void execute(ActionMessagePrinter printer)
throws CmdLineActionException {
Validate.notNull(taskIds, "Must specify taskIds");
try (WorkflowManagerClient client = getClient()) {
LOGGER.fine(String.format("Starting workflow %d tasks", taskIds.size()));
String instId = client.executeDynamicWorkflow(taskIds, metadata);
LOGGER.fine(String.format("Started workflow with instanceId: %s", instId));
printer.println("Started dynamic workflow with id '" + instId + "'");
} catch (Exception e) {
throw new CmdLineActionException(
"Failed to submit dynamic workflow for taskIds " + taskIds
+ " with metadata " + metadata.getMap() + " : "
+ e.getMessage(), e);
}
}
public static void addMoney(final Player player, final double amount){
Validate.notNull(player);
if(!GameManager.getGameManager().getConfiguration().getVaultLoaded()){
return;
}
if(economy == null){
Bukkit.getLogger().warning("[UhcCore] Vault is not loaded! Couldn't pay "+amount+" to "+player.getName()+"!");
return;
}
final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(player.getUniqueId());
Bukkit.getScheduler().runTaskAsynchronously(UhcCore.getPlugin(), () -> economy.depositPlayer(offlinePlayer, amount));
}
public void append(char[] chars) throws GeneralSecurityException {
Validate.notNull(chars);
if (chars.length != 0) {
char[] value = this.getValue();
char[] result = new char[value.length + chars.length];
int i;
for(i = 0; i < value.length; ++i) {
result[i] = value[i];
value[i] = 0;
}
for(i = 0; i < chars.length; ++i) {
result[value.length + i] = chars[i];
}
this.encrypt(charToByte(result));
for(i = 0; i < result.length; ++i) {
result[i] = 0;
}
}
}
private void signinWithSAML2Artifact(String targetLocation) throws TechnicalConnectorException {
try {
String template = ConnectorIOUtils.getResourceAsString("/sso/SSORequestSTSSAML2Artifact.xml");
template = StringUtils.replaceEach(template, new String[]{"${reqId}", "${endpoint.idp.saml2.artifact}"}, new String[]{this.idGenerator.generateId(), this.getSAML2Artifact()});
NodeList references = this.invokeSecureTokenService(ConnectorXmlUtils.flatten(template)).getElementsByTagNameNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Reference");
Validate.notNull(references);
Validate.isTrue(references.getLength() == 1);
Element reference = (Element)references.item(0);
String uri = reference.getAttribute("URI");
if (StringUtils.isNotBlank(targetLocation)) {
uri = uri + "&RelayState=" + targetLocation;
}
LOG.debug("Launching browser with url [" + uri + "]");
this.launchBrowser(new URI(uri));
} catch (IOException var6) {
throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.CORE_TECHNICAL, var6, new Object[]{var6.getMessage()});
} catch (URISyntaxException var7) {
throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.CORE_TECHNICAL, var7, new Object[]{var7.getMessage()});
}
}
@Override
public org.bukkit.BanEntry addBan(String target, String reason, Date expires, String source) {
Validate.notNull(target, "Ban target cannot be null");
IPBanEntry entry = new IPBanEntry(target, new Date(),
StringUtils.isBlank(source) ? null : source, expires,
StringUtils.isBlank(reason) ? null : reason);
list.func_152687_a(entry);
try {
list.func_152678_f();
} catch (IOException ex) {
MinecraftServer.getLogger().error("Failed to save banned-ips.json, " + ex.getMessage());
}
return new CraftIpBanEntry(target, entry, list);
}
/**
* https://api.mojang.com/users/profiles/minecraft/Username gives the ID
* https://api.mojang.com/user/profiles/ID without dashes/names gives the names used for the unique ID.
* https://sessionserver.mojang.com/session/minecraft/profile/ID example data:
* <p>
* <pre>
* {
* "id": "Without dashes -",
* "name": "",
* "properties": [
* {
* "name": "textures",
* "value": ""
* }
* ]
* }
* </pre>
*/
@Nonnull
public static String getSkinValue(@Nonnull String name, boolean isId) {
Validate.notEmpty(name, "Player name/UUID cannot be null or empty");
try {
String uuid;
JsonParser parser = new JsonParser();
if (!isId) {
URL convertName = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
InputStreamReader readId = new InputStreamReader(convertName.openStream());
JsonObject jObject = parser.parse(readId).getAsJsonObject();
if (mojangError(jObject)) return null;
uuid = jObject.get("id").getAsString();
} else uuid = StringUtils.remove(name, '-');
URL properties = new URL(session + uuid); // + "?unsigned=false"
InputStreamReader readProperties = new InputStreamReader(properties.openStream());
JsonObject jObjectP = parser.parse(readProperties).getAsJsonObject();
if (mojangError(jObjectP)) return null;
JsonObject textureProperty = jObjectP.get("properties").getAsJsonArray().get(0).getAsJsonObject();
//String signature = textureProperty.get("signature").getAsString();
return textureProperty.get("value").getAsString();
} catch (IOException | IllegalStateException e) {
System.err.println("Could not get skin data from session servers! " + e.getMessage());
e.printStackTrace();
return null;
}
}
public void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException {
Validate.notNull(suffix, "Suffix cannot be null");
Validate.isTrue(suffix.length() <= 32, "Suffix '" + suffix + "' is longer than the limit of 32 characters");
CraftScoreboard scoreboard = checkState();
team.setNameSuffix(suffix);
}
@Override
public Result validate(CmdLineOptionInstance optionInst) {
Validate.notNull(optionInst);
for (String value : optionInst.getValues()) {
try {
Class.forName(value);
} catch (Exception e) {
return new Result(Grade.FAIL, "Value '" + value
+ "' for option " + optionInst.getOption().getLongOption()
+ " is not a valid class");
}
}
return new Result(Grade.PASS, "Success");
}
public static synchronized SchematronValidator getInstance(String schematronLocation) throws TransformerException {
Validate.notEmpty(schematronLocation, "Location for the Schematron schema needs to be specified.");
LOG.info(String.format("Retrieving validator for schematron file [%s]", schematronLocation));
if (!cachedTemplates.containsKey(schematronLocation)) {
LOG.debug(String.format("Template for schematron file [%s] not in cache, creating it", schematronLocation));
Source dataSource = new StreamSource(SchematronValidator.class.getResource(schematronLocation).toString());
Templates templates = transformerFactory.newTemplates(dataSource);
cachedTemplates.put(schematronLocation, templates);
LOG.debug(String.format("Template for schematron file [%s] created and cached", schematronLocation));
}
Templates template = (Templates)cachedTemplates.get(schematronLocation);
return new SchematronValidator(template);
}
public RevocationRequest(byte[] publicKeyIdentifier, GeneratedRevocationContract contract) throws TechnicalConnectorException {
Validate.notNull(publicKeyIdentifier);
Validate.notNull(contract);
Validate.isTrue(contract.isContractViewed());
this.publicKeyIdentifier = ArrayUtils.clone(publicKeyIdentifier);
this.contract = contract;
}
private static void validateProxyAddressPort(String proxyAddress, int proxyPort) {
Validate.notEmpty(proxyAddress, "Parameter proxyAddress must not be null nor empty.");
if (proxyPort < MIN_PORT || proxyPort > MAX_PORT) {
throw new IllegalArgumentException(
"Parameter proxyPort must be under: " + MIN_PORT + " <= port <= " + MAX_PORT);
}
}
protected BrooklinMetricInfo(String nameOrRegex, Optional<List<String>> attributes) {
Validate.notNull(nameOrRegex, "Metric name/regex must be non-null");
Validate.notNull(attributes, "attributes must be non-null");
_nameOrRegex = nameOrRegex;
_attributes = attributes;
_hashCode = Objects.hash(_nameOrRegex, _attributes.map(HashSet::new).orElse(null));
}
@Override
public boolean performAction(File product, Metadata productMetadata)
throws CrawlerActionException {
try {
Validate.notNull(productMetadata.getMetadata(PRODUCT_NAME),
PRODUCT_NAME + " was not found in metadata");
FileManagerClient fmClient = RpcCommunicationFactory.createClient(new URL(this.filemgrUrl));
return !fmClient.hasProduct(productMetadata.getMetadata(PRODUCT_NAME));
} catch (Exception e) {
throw new CrawlerActionException("Product failed uniqueness check : ["
+ product + "] : " + e.getMessage(), e);
}
}
@Override
public ResourceServer newEntity(Client client) {
Validate.notNull(client);
Validate.notNull(client.getRepresentation());
Validate.notNull(client.getRepresentation().getBaseUrl());
return new ResourceServer(client);
}
public CommandAliasHelpTopic(final String alias, final String aliasFor, final HelpMap helpMap) {
this.aliasFor = aliasFor.startsWith("/") ? aliasFor : "/" + aliasFor;
this.helpMap = helpMap;
name = alias.startsWith("/") ? alias : "/" + alias;
Validate.isTrue(!name.equals(this.aliasFor), "Command " + name + " cannot be alias for itself");
shortText = ChatColor.YELLOW + "Alias for " + ChatColor.WHITE + this.aliasFor;
}
@Override
protected void doCommit(DefaultTransactionStatus status) throws TransactionException {
@SuppressWarnings("unchecked")
List<DefaultTransactionStatus> list =
(List<DefaultTransactionStatus>) status.getTransaction();
logger.info("prepare to commit transactions on multiple data sources.");
Validate.isTrue(list.size() <= this.getTransactionManagers().size());
TransactionException lastException = null;
for(int i=list.size()-1; i>=0;i--){
PlatformTransactionManager transactionManager=this.getTransactionManagers().get(i);
TransactionStatus localTransactionStatus=list.get(i);
try{
transactionManager.commit(localTransactionStatus);
}
catch (TransactionException e) {
lastException=e;
logger.error("Error in commit", e);
}
}
if (lastException != null) {
throw lastException;
// Rollback will ensue as long as rollbackOnCommitFailure=true
}
}
/**
* @param node
* @return true, if the given skill has the same id as the Skill tree's root node, otherwise false;
*/
public boolean isRootNode(final SkillDO skill)
{
Validate.notNull(skill);
checkRefresh();
if (root == null && skill.getParentId() == null) {
// First skill, so it should be the root node.
return true;
}
if (skill.getId() == null) {
// Node has no id, so it can't be the root node.
return false;
}
return root.getId().equals(skill.getId());
}
/**
* @param obj
* @throws AccessException
* @return true, if modifications were done, false if no modification detected.
* @see #internalUpdate(ExtendedBaseDO, boolean)
*/
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)
public ModificationStatus update(final O obj) throws AccessException
{
Validate.notNull(obj);
if (obj.getId() == null) {
final String msg = "Could not update object unless id is not given:" + obj.toString();
log.error(msg);
throw new RuntimeException(msg);
}
return internalUpdate(obj, true);
}
private static void testGeoFreetextWithPCJSearch(
final SailRepositoryConnection conn)
throws MalformedQueryException, RepositoryException,
TupleQueryResultHandlerException, QueryEvaluationException {
// ring outside point
final String queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "//
+ "PREFIX fts: <http://rdf.useekm.com/fts#> "//
+ "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "//
+ "SELECT ?feature ?point ?wkt ?e ?c ?l ?o ?person ?match " //
+ "{" //
+ " ?person a <http://example.org/ontology/Person> . "//
+ " ?person <http://www.w3.org/2000/01/rdf-schema#label> ?match . "//
+ " FILTER(fts:text(?match, \"!alice & hose\")) " //
+ " ?e a ?c . "//
+ " ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "//
+ " ?e <uri:talksTo> ?o . "//
+ " ?feature a geo:Feature . "//
+ " ?feature geo:hasGeometry ?point . "//
+ " ?point a geo:Point . "//
+ " ?point geo:asWKT ?wkt . "//
+ " FILTER(geof:sfWithin(?wkt, \"POLYGON((-78 39, -77 39, -77 38, -78 38, -78 39))\"^^geo:wktLiteral)) " //
+ "}";//
final TupleQuery tupleQuery = conn.prepareTupleQuery(
QueryLanguage.SPARQL, queryString);
final CountingResultHandler tupleHandler = new CountingResultHandler();
tupleQuery.evaluate(tupleHandler);
log.info("Result count : " + tupleHandler.getCount());
Validate.isTrue(tupleHandler.getCount() == 0);// TODO ==1 some data is missing for this query!
}
public KeyStoreInfo(String pathKeystore, String keystoreType, char[] pwdKeystore, String alias, char[] privateKeyPwd) throws TechnicalConnectorException {
Validate.notEmpty(alias);
Validate.notNull(privateKeyPwd);
if (StringUtils.isNotEmpty(pathKeystore)) {
Validate.notEmpty(keystoreType);
Validate.notNull(pwdKeystore);
}
this.keystorePath = this.getKeystoreLoc(pathKeystore);
this.keystoreType = keystoreType;
this.keystorePassword = ArrayUtils.clone(pwdKeystore);
this.alias = alias;
this.privateKeyPassword = ArrayUtils.clone(privateKeyPwd);
}
public void updateLocationMapping(UUID uuid, Location location) {
Validate.notNull(uuid);
if (location == null) { // unset
if (locationMap.containsKey(uuid)) {
locationMap.remove(uuid);
save();
}
} else {
if (!location.equals(locationMap.get(uuid))) {
locationMap.put(uuid, location);
save();
}
}
}
/**
* Deserialize a JSON string into an object based on a type reference.
* This method allows the caller to specify precisely the desired output
* type for the target object.
* @param json JSON string
* @param typeRef type reference of the target object
* @param <T> type of the target object
* @return deserialized Java object
*/
public static <T> T fromJson(String json, TypeReference<T> typeRef) {
Validate.notNull(json, "null JSON string");
Validate.notNull(typeRef, "null type reference");
T object = null;
try {
object = MAPPER.readValue(json, typeRef);
} catch (IOException e) {
String errorMessage = "Failed to parse json: " + json;
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
}
return object;
}