下面列出了org.apache.commons.lang3.math.NumberUtils#toLong ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static List<ConfigGroupEnum> compareMD5(final HttpServletRequest request) {
List<ConfigGroupEnum> changedGroup = new ArrayList<>(4);
for (ConfigGroupEnum group : ConfigGroupEnum.values()) {
// md5,lastModifyTime
String[] params = StringUtils.split(request.getParameter(group.name()), ',');
if (params == null || params.length != 2) {
throw new SoulException("group param invalid:" + request.getParameter(group.name()));
}
String clientMd5 = params[0];
long clientModifyTime = NumberUtils.toLong(params[1]);
ConfigDataCache serverCache = CACHE.get(group.name());
if (!StringUtils.equals(clientMd5, serverCache.getMd5()) && clientModifyTime < serverCache.getLastModifyTime()) {
changedGroup.add(group);
}
}
return changedGroup;
}
@Override
public org.sakaiproject.service.gradebook.shared.Assignment getAssignmentByNameOrId(final String gradebookUid,
final String assignmentName) throws AssessmentNotFoundException {
org.sakaiproject.service.gradebook.shared.Assignment assignment = null;
try {
assignment = getAssignment(gradebookUid, assignmentName);
} catch (final AssessmentNotFoundException e) {
// Don't fail on this exception
log.debug("Assessment not found by name", e);
}
if (assignment == null) {
// Try to get the assignment by id
if (NumberUtils.isCreatable(assignmentName)) {
final Long assignmentId = NumberUtils.toLong(assignmentName, -1L);
return getAssignment(gradebookUid, assignmentId);
}
}
return assignment;
}
@Override
public boolean tryLock(String source) {
String value = System.currentTimeMillis() + TIME_MAX_LOCK + "";
Long result = getJedis().setnx(source, value);
if (result == SUCCESS_RESULT) {
return true;
}
String oldValue = getJedis().get(source);
if (StringUtils.equals(oldValue, NOT_EXIST_VALUE)) {
result = getJedis().setnx(source, value);
return result == SUCCESS_RESULT;
}
long time = NumberUtils.toLong(oldValue);
if (time < System.currentTimeMillis()) {
String oldValueMirror = getJedis().getSet(source, System.currentTimeMillis() + TIME_MAX_LOCK + "");
return StringUtils.equals(oldValueMirror, NOT_EXIST_VALUE) || StringUtils.equals(oldValue, oldValueMirror);
}
return false;
}
/**
* Verifies that an element with the supplied attribute and attribute value is present in the DOM
* within a certain amount of time.
*
* @param waitDuration The maximum amount of time to wait for
* @param attribute The attribute to use to select the element with
* @param alias If this word is found in the step, it means the selectorValue is found from the
* data set.
* @param selectorValue The value used in conjunction with the selector to match the element. If alias
* was set, this value is found from the data set. Otherwise it is a literal value.
* @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be present
*/
@Then("^(?:I verify(?: that)? )?(?:a|an|the) element with (?:a|an|the) attribute of \"([^\"]*)\" "
+ "equal to( alias)? \"([^\"]*)\" is present(?: within \"(\\d+)\" seconds?)?(,? ignoring timeouts?)?")
public void presentAttrWait(
final String attribute,
final String alias,
final String selectorValue,
final String waitDuration,
final String ignoringTimeout) {
final String attributeValue = autoAliasUtils.getValue(
selectorValue, StringUtils.isNotBlank(alias), State.getFeatureStateForThread());
try {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final WebDriverWait wait = new WebDriverWait(
webDriver,
NumberUtils.toLong(waitDuration, State.getFeatureStateForThread().getDefaultWait()),
Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
wait.until(ExpectedConditions.presenceOfElementLocated(
By.cssSelector("[" + attribute + "='" + attributeValue + "']")));
} catch (final TimeoutException ex) {
/*
Rethrow if we have not ignored errors
*/
if (StringUtils.isBlank(ignoringTimeout)) {
throw ex;
}
}
}
/**
* Verifies that an element with the supplied attribute and attribute value is not present in the DOM
* within a certain amount of time.
*
* @param waitDuration The maximum amount of time to wait for
* @param attribute The attribute to use to select the element with
* @param alias If this word is found in the step, it means the selectorValue is found from the
* data set.
* @param selectorValue The value used in conjunction with the selector to match the element. If alias was
* set, this value is found from the data set. Otherwise it is a literal value.
* @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be present
*/
@Then("^(?:I verify(?: that)? )?(?:a|an|the) element with (?:a|an|the) attribute of \"([^\"]*)\" "
+ "equal to( alias)? \"([^\"]*)\" is not present(?: within \"(\\d+)\" seconds?)?(,? ignoring timeouts?)?")
public void notPresentAttrWait(
final String attribute,
final String alias,
final String selectorValue,
final String waitDuration,
final String ignoringTimeout) {
final String attributeValue = autoAliasUtils.getValue(
selectorValue, StringUtils.isNotBlank(alias), State.getFeatureStateForThread());
try {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final WebDriverWait wait = new WebDriverWait(
webDriver,
NumberUtils.toLong(waitDuration, State.getFeatureStateForThread().getDefaultWait()),
Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
wait.until(
ExpectedConditions.presenceOfAllElementsLocatedBy(
By.cssSelector("[" + attribute + "='" + attributeValue + "']")));
/*
If we get here the wait succeeded, which means the step has failed
*/
throw new ValidationException("Element was present within " + waitDuration + " seconds");
} catch (final TimeoutException ignored) {
/*
This indicates success
*/
}
}
private static void modified(File war, File dir) throws Exception {
File lastModified = new File(dir, "WEB-INF/lastModified");
if ((!lastModified.exists()) || lastModified.isDirectory() || (war.lastModified() != NumberUtils
.toLong(FileUtils.readFileToString(lastModified, DefaultCharset.charset_utf_8), 0))) {
if (dir.exists()) {
FileUtils.forceDelete(dir);
}
JarTools.unjar(war, "", dir, true);
FileUtils.writeStringToFile(lastModified, war.lastModified() + "", DefaultCharset.charset_utf_8, false);
}
}
public static Map<String,Integer> getChildCounts(SolrResponse response) {
//check if there are subdocs
if (Objects.nonNull(response.getResponse())) {
final Object subDocumentFacetResult = response.getResponse().get("facets");
if (Objects.nonNull(subDocumentFacetResult)) {
Map<String,Integer> childCounts = new HashMap<>();
log.debug("Parsing subdocument facet result from JSON ");
final Object count = ((SimpleOrderedMap) subDocumentFacetResult).get("count");
final Number facetCount = Objects.nonNull(count)? NumberUtils.toLong(count.toString(), 0L) : new Integer(0);
if (Objects.nonNull(((SimpleOrderedMap) subDocumentFacetResult).get("parent_facet")) && facetCount.longValue() > 0) {
final List<SimpleOrderedMap> parentDocs = (ArrayList) ((SimpleOrderedMap) ((SimpleOrderedMap) subDocumentFacetResult).get("parent_facet")).get("buckets");
childCounts = parentDocs.stream()
.collect(Collectors.toMap(
p -> (String) p.get("val"),
p -> {
final Object childrenCount = ((SimpleOrderedMap) p.get("children_facet")).get("count");
return Objects.nonNull(childrenCount)? NumberUtils.toInt(childrenCount.toString(), 0) : new Integer(0);
})
);
}
return childCounts;
}
}
return null;
}
public static Long getBeforeValue(String paramValue) throws Exception {
String value = EncryptorUtils.decrypt(Constants.getEncryptorKey1(), Constants.getEncryptorKey2(), SimpleUtils.deHex(paramValue));
byte datas[] = UploadSupportUtils.getDataBytes(value);
String jsonData = new String(datas, Constants.BASE_ENCODING);
ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, Object> dataMap = (Map<String, Object>) mapper.readValue(jsonData, HashMap.class);
return NumberUtils.toLong((String)dataMap.get("before"), 0);
}
/**
* Verifies that the element is not displayed (i.e. to be visible) on the page within a given amount of time.
* You can use this step to verify that the page is in the correct state before proceeding with the script.
*
* @param waitDuration The maximum amount of time to wait for
* @param selector Either ID, class, xpath, name or css selector
* @param alias If this word is found in the step, it means the selectorValue is found from the
* data set.
* @param selectorValue The value used in conjunction with the selector to match the element. If alias
* was set, this value is found from the data set. Otherwise it is a literal
* value.
* @param ignoringTimeout include this text to continue the script in the event that the element can't be
* found
*/
@Then("^(?:I verify(?: that)? )?(?:a|an|the) element with "
+ "(?:a|an|the) (ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" is not displayed"
+ "(?: within \"(\\d+)\" seconds?)(,? ignoring timeouts?)?")
public void notDisplayWaitStep(
final String selector,
final String alias,
final String selectorValue,
final String waitDuration,
final String ignoringTimeout) {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final By by = getBy.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, State.getFeatureStateForThread());
final WebDriverWait wait = new WebDriverWait(
webDriver,
NumberUtils.toLong(waitDuration, State.getFeatureStateForThread().getDefaultWait()),
Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
try {
final boolean result = wait.until(
ExpectedConditions.not(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)));
if (!result) {
throw new TimeoutException(
"Gave up after waiting " + Integer.parseInt(waitDuration)
+ " seconds for the element to not be displayed");
}
} catch (final TimeoutException ex) {
/*
Rethrow if we have not ignored errors
*/
if (StringUtils.isBlank(ignoringTimeout)) {
throw ex;
}
}
}
@Override
public String getAssignmentScoreStringByNameOrId(final String gradebookUid, final String assignmentName, final String studentUid)
throws GradebookNotFoundException, AssessmentNotFoundException {
String score = null;
try {
score = getAssignmentScoreString(gradebookUid, assignmentName, studentUid);
} catch (final AssessmentNotFoundException e) {
// Don't fail on this exception
log.debug("Assessment not found by name", e);
} catch (final GradebookSecurityException gse) {
log.warn("User {} does not have permission to retrieve score for assignment {}", studentUid, assignmentName, gse);
return null;
}
if (score == null) {
// Try to get the assignment by id
if (NumberUtils.isCreatable(assignmentName)) {
final Long assignmentId = NumberUtils.toLong(assignmentName, -1L);
try {
score = getAssignmentScoreString(gradebookUid, assignmentId, studentUid);
} catch (AssessmentNotFoundException anfe) {
log.debug("Assessment could not be found for gradebook id {} and assignment id {} and student id {}", gradebookUid, assignmentName, studentUid);
}
}
}
return score;
}
private static void initIdGenerator() {
String workerID = Config.WORKER_ID;
workerId = NumberUtils.toLong(workerID, 1);
if (workerId > MAX_WORKER_ID || workerId < 0) {
workerId = new Random().nextInt((int) MAX_WORKER_ID + 1);
}
if (dataCenterId > MAX_DATACENTER_ID || dataCenterId < 0) {
dataCenterId = new Random().nextInt((int) MAX_DATACENTER_ID + 1);
}
}
/**
* Verifies that a link with the supplied text is not placed in the DOM within a certain amount of time.
*
* @param waitDuration The maximum amount of time to wait for
* @param alias If this word is found in the step, it means the linkContent is found from the
* data set.
* @param linkContent The text content of the link we are wait for
* @param ignoringTimeout The presence of this text indicates that timeouts are ignored
*/
@Then("^(?:I verify(?: that)? )?a link with the text content of"
+ "( alias)? \"([^\"]*)\" is not present(?: within \"(\\d+)\" seconds?)?(,? ignoring timeouts?)?")
public void notPresentLinkStep(
final String alias,
final String linkContent,
final String waitDuration,
final String ignoringTimeout) {
try {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final String content = autoAliasUtils.getValue(
linkContent, StringUtils.isNotBlank(alias), State.getFeatureStateForThread());
final WebDriverWait wait = new WebDriverWait(
webDriver,
NumberUtils.toLong(waitDuration, State.getFeatureStateForThread().getDefaultWait()),
Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.linkText(content)));
/*
If we get here the wait succeeded, which means the step has failed
*/
throw new ValidationException("Element was present within " + waitDuration + " seconds");
} catch (final TimeoutException ex) {
/*
This indicates success
*/
}
}
/**
* Load all certificates from configured location.
* */
private void loadAllCertificates() {
// See if certs directory exists in file system.
Path certPath = securityConfig.getCertificateLocation(component);
if (Files.exists(certPath) && Files.isDirectory(certPath)) {
getLogger().info("Loading certificate from location:{}.",
certPath);
File[] certFiles = certPath.toFile().listFiles();
if (certFiles != null) {
CertificateCodec certificateCodec =
new CertificateCodec(securityConfig, component);
long latestCaCertSerailId = -1L;
for (File file : certFiles) {
if (file.isFile()) {
try {
X509CertificateHolder x509CertificateHolder = certificateCodec
.readCertificate(certPath, file.getName());
X509Certificate cert =
CertificateCodec.getX509Certificate(x509CertificateHolder);
if (cert != null && cert.getSerialNumber() != null) {
if (cert.getSerialNumber().toString().equals(certSerialId)) {
x509Certificate = cert;
}
certificateMap.putIfAbsent(cert.getSerialNumber().toString(),
cert);
if (file.getName().startsWith(CA_CERT_PREFIX)) {
String certFileName = FilenameUtils.getBaseName(
file.getName());
long tmpCaCertSerailId = NumberUtils.toLong(
certFileName.substring(CA_CERT_PREFIX_LEN));
if (tmpCaCertSerailId > latestCaCertSerailId) {
latestCaCertSerailId = tmpCaCertSerailId;
}
}
getLogger().info("Added certificate from file:{}.",
file.getAbsolutePath());
} else {
getLogger().error("Error reading certificate from file:{}",
file);
}
} catch (java.security.cert.CertificateException | IOException e) {
getLogger().error("Error reading certificate from file:{}.",
file.getAbsolutePath(), e);
}
}
}
if (latestCaCertSerailId != -1) {
caCertId = Long.toString(latestCaCertSerailId);
}
}
}
}
public Long getLong(Object obj, String key) throws NumberFormatException{
return NumberUtils.toLong(getString(obj, key));
}
@Override
public Long apply(String input) {
return NumberUtils.toLong(input);
}
public long getLong(int row, int col) {
String value = getString(row, col);
return NumberUtils.toLong(value, 0L);
}
private boolean isSubmittedByHuman(HttpServletRequest req) {
long time = NumberUtils.toLong(req.getParameter("timestamp"), 0L);
return StringUtils.isBlank(req.getParameter("leaveblank")) && (System.currentTimeMillis() - time >= 7000);
}
public Long getLong() {
String value = super.get();
return value == null ? null : NumberUtils.toLong(value);
}
/**
* 将10进制的String安全的转化为long,当str为空或非数字字符串时,返回default值
*/
public static long toLong(String str, long defaultValue) {
return NumberUtils.toLong(str, defaultValue);
}
/**
* 将10进制的String安全的转化为long.
*
* 当str为空或非数字字符串时,返回default值
*/
public static long toLong(@Nullable String str, long defaultValue) {
return NumberUtils.toLong(str, defaultValue);
}