下面列出了java.util.HashSet#isEmpty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void run() {
long instant = System.currentTimeMillis();
try {
HashSet<String> toRemove = new HashSet<>();
logger.debug("Sessions in cache {} for {}", sessionDataCache, sessionManager);
for (SessionData sd : sessionDataCache.values()) {
if ((instant - sd.getLastAccessedTime()) > TimeUnit.SECONDS.toMillis(sd.getMaxInactiveInterval())) {
toRemove.add(sd.getId());
}
}
for (String id : toRemove) {
sessionManager.delete(id, true);
logger.debug("Expiring session with key {}", id);
remove(id);
}
if (!toRemove.isEmpty()) {
logger.info("At {} for {} expired sessions {}", instant, sessionManager, toRemove);
}
} catch (Exception e) { // NOSONAR - recover from any exception
logger.error("An error occured while trying to exipre sessions.", e);
}
}
/**
* Repeat regular expression from min to max times.
*
* @param r The regular expression.
* @param min The minimum number of repetitions.
* @param max The maximum number of repetitions.
* @return The results for repeat.
*/
private HashSet<SuccinctRegExMatch> regexRepeatMinToMax(RegEx r, int min, int max) {
min = (min > 0) ? min - 1 : 0;
max = (max > 0) ? max - 1 : 0;
HashSet<SuccinctRegExMatch> repeatResults = new HashSet<>();
HashSet<SuccinctRegExMatch> internalResults = computeSuccinctly(r);
if (internalResults.isEmpty()) {
return repeatResults;
}
if (min == 0) {
repeatResults.addAll(internalResults);
}
if (max > 0) {
for (SuccinctRegExMatch internalMatch : internalResults) {
repeatResults.addAll(regexRepeatMinToMax(r, internalMatch, min, max));
}
}
return repeatResults;
}
@Override
public boolean matches(Object o) {
if (!(o instanceof ContainerLocalizationCleanupEvent)) {
return false;
}
ContainerLocalizationCleanupEvent evt =
(ContainerLocalizationCleanupEvent) o;
final HashSet<LocalResourceRequest> expected =
new HashSet<LocalResourceRequest>(resources);
for (Collection<LocalResourceRequest> rc : evt.getResources().values()) {
for (LocalResourceRequest rsrc : rc) {
if (!expected.remove(rsrc)) {
return false;
}
}
}
return expected.isEmpty();
}
public Ref<Boolean> scheduleTask(IsoEvery iso, CopyTracker tracker, Fiber parent) {
HashSet<String> implicitGlobals = extractIndirectGlobals(tracker);
if (parent != null) {
Fiber.currentFiber.set(iso.fiber);
try {
HashSet<String> explicitGlobals = iso.ntask.setupGlobals(iso.fiber, tracker == null ? new CopyTracker() : tracker, parent);
implicitGlobals.removeAll(explicitGlobals);
if (!implicitGlobals.isEmpty()) {// load...
initImplicitGlobals(iso.fiber, parent, iso.ntask.getClass().getClassLoader(), implicitGlobals, tracker);
}
} finally {
Fiber.currentFiber.set(null);
}
}
Ref<Boolean> isComplete = iso.ntask.getIsInitCompleteFlag();
iso.setExceptionHandler(defaultExHan);
iso.setInitExceptionHandler(new SetExceptionToInit(isComplete));
// System.err.println("end of scheduleTask - create task");
iso.worker.createTask(iso);
// System.err.println("end of scheduleTask created so ret");
return isComplete;// flag is set once apply block completes
}
private static InputStream getConfigFileInputStream(String configFilePath)
throws IOException {
if (null == configFilePath) {
throw new IOException(
"Could not find config file, name not specified");
}
HashSet<URL> resources = new HashSet<URL>(findResources(configFilePath));
if (resources.isEmpty()) {
File configFile = new File(configFilePath);
if (configFile.exists()) {
return new FileInputStream(configFile);
}
} else if (resources.size() > 1) {
throw new IOException(
"Found multiple " + configFilePath
+ " resources. You're probably bundling the Storm jars with your topology jar. "
+ resources);
} else {
LOG.debug("Using "+configFilePath+" from resources");
URL resource = resources.iterator().next();
return resource.openStream();
}
return null;
}
@Property
public void diffAndMergeAutogenNotebookCode(AutogenNotebookCodeBlob a, AutogenNotebookCodeBlob b)
throws ModelDBException {
AutogenNotebookCodeBlob newA = enforceOneof(a);
AutogenNotebookCodeBlob newB = enforceOneof(b);
AutogenNotebookCodeDiff d = DiffComputer.computeNotebookCodeDiff(newA, newB);
// Applying the diff on top of the original A should get original B
AutogenNotebookCodeBlob diffedB = DiffMerger.mergeNotebookCode(newA, d, new HashSet<String>());
assertEquals(newB, diffedB);
HashSet<String> conflictSet = new HashSet<String>();
// Reapplying the diff should not change the result
diffedB = DiffMerger.mergeNotebookCode(diffedB, d, conflictSet);
if (conflictSet.isEmpty()) {
assertEquals(newB, diffedB);
}
}
public void scheduleTask(IsoCore iso, CopyTracker tracker, Fiber parent) {
SyncTracker st = parent == null ? null : parent.getCurrentSyncTracker();
HashSet<String> implicitGlobals = extractIndirectGlobals(tracker);
if (null != st) {
st.awaitFor(iso.func.getIsInitCompleteFlag());
}
if (parent != null) {
Fiber.currentFiber.set(iso.fiber);
try {
HashSet<String> explicitGlobals = iso.func.setupGlobals(iso.fiber, tracker == null ? new CopyTracker() : tracker, parent);
implicitGlobals.removeAll(explicitGlobals);
if (!implicitGlobals.isEmpty()) {// load...
initImplicitGlobals(iso.fiber, parent, iso.func.getClass().getClassLoader(), implicitGlobals, tracker);
}
} finally {
Fiber.currentFiber.set(null);
}
}
iso.setExceptionHandler(defaultExHan);
iso.worker.createTask(iso);
}
private void configTypeFilter(ShardQueryConfiguration config, Query settings) {
// Get the datatype set if specified
if (null == settings.findParameter(QueryParameters.DATATYPE_FILTER_SET)) {
config.setDatatypeFilter(new HashSet<>());
return;
}
String typeList = settings.findParameter(QueryParameters.DATATYPE_FILTER_SET).getParameterValue();
HashSet<String> typeFilter;
if (null != typeList && !typeList.isEmpty()) {
typeFilter = new HashSet<>();
typeFilter.addAll(Arrays.asList(StringUtils.split(typeList, Constants.PARAM_VALUE_SEP)));
if (!typeFilter.isEmpty()) {
config.setDatatypeFilter(typeFilter);
if (logger.isDebugEnabled()) {
logger.debug("Type Filter: " + typeFilter);
}
}
}
}
/**
* use string divider list value
*
* @param list list
* @param divider divider string
* @return list is empty, return null.
*/
public static String makeString(HashSet<String> list, String divider) {
if (list == null || list.isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
Iterator<String> iterator = list.iterator();
for (int i = 0; iterator.hasNext(); i++) {
String item = iterator.next();
if (i > 0) {
sb.append(divider);
}
sb.append(item);
}
return sb.toString();
}
@Override
public boolean matches(Object o) {
ContainerLocalizationRequestEvent evt =
(ContainerLocalizationRequestEvent) o;
final HashSet<LocalResourceRequest> expected =
new HashSet<LocalResourceRequest>(resources);
for (Collection<LocalResourceRequest> rc : evt.getRequestedResources()
.values()) {
for (LocalResourceRequest rsrc : rc) {
if (!expected.remove(rsrc)) {
return false;
}
}
}
return expected.isEmpty();
}
private String checkSearchedRecordsConsistency(Record[] records) {
String error = null;
HashSet<String> pidSet = new HashSet<String>(Arrays.asList(pids));
for (Record record : records) {
String recordPid = record.getAttribute(SearchDataSource.FIELD_PID);
if (!pidSet.remove(recordPid)) {
error = ClientUtils.format("PID %s not requested!", recordPid);
break;
} else if (SearchDataSource.isDeleted(record)) {
error = ClientUtils.format("PID %s is deleted!", recordPid);
break;
}
}
if (error == null && !pidSet.isEmpty()) {
error = ClientUtils.format("PID %s not found!", pidSet.toString());
}
return error;
}
/**
* Repeat regular expression one or more times.
*
* @param r The regular expression.
* @return The results for repeat.
*/
private HashSet<SuccinctRegExMatch> regexRepeatOneOrMore(RegEx r) {
HashSet<SuccinctRegExMatch> repeatResults = new HashSet<>();
HashSet<SuccinctRegExMatch> internalResults = computeSeedToRepeat(r);
if (internalResults.isEmpty()) {
return repeatResults;
}
repeatResults.addAll(internalResults);
for (SuccinctRegExMatch internalMatch : internalResults) {
repeatResults.addAll(regexRepeatOneOrMore(r, internalMatch));
}
return repeatResults;
}
@Test
public void testBosEntities() {
HashSet<EntityType> entityTypes = new HashSet<EntityType>();
entityTypes.addAll(Arrays.asList(EntityType.values()));
for (String name : EntityNBT.getValidTypeNames()) {
entityTypes.remove(EntityTypeMap.getByName(name));
}
if (!entityTypes.isEmpty()) {
System.out.print("Missing BoS entities: ");
System.out.print(StringUtils.join(entityTypes, ", "));
System.out.println(".");
}
}
@Override
protected void process(DistributionMessage msg, boolean warn) {
if(msg instanceof FinishBackupResponse) {
final HashSet<PersistentID> persistentIds = ((FinishBackupResponse) msg).getPersistentIds();
if(persistentIds != null && !persistentIds.isEmpty()) {
results.put(msg.getSender(), persistentIds);
}
}
super.process(msg, warn);
}
private ArrayList<Pair<CutSet,Double>> evaluateCutSets(ArrayList<ArrayList<NodeLink>> candCS, ArrayList<ArrayList<NodeLink>> remain) {
ArrayList<Pair<CutSet,Double>> cutSets = new ArrayList<>();
for( ArrayList<NodeLink> cand : candCS ) {
HashSet<NodeLink> probe = new HashSet<>(cand);
//determine subproblems for cutset candidates
HashSet<NodeLink> part1 = new HashSet<>();
rCollectInputs(_root, probe, part1);
HashSet<NodeLink> part2 = new HashSet<>();
for( NodeLink rNode : cand )
rCollectInputs(rNode, probe, part2);
//select, score and create cutsets
if( !CollectionUtils.containsAny(part1, part2)
&& !part1.isEmpty() && !part2.isEmpty()) {
//score cutsets (smaller is better)
double base = UtilFunctions.pow(2, _matPoints.size());
double numComb = UtilFunctions.pow(2, cand.size());
double score = (numComb-1)/numComb * base
+ 1/numComb * UtilFunctions.pow(2, part1.size())
+ 1/numComb * UtilFunctions.pow(2, part2.size());
//construct cutset
cutSets.add(Pair.of(new CutSet(
cand.stream().map(p->p._p).toArray(InterestingPoint[]::new),
part1.stream().map(p->p._p).toArray(InterestingPoint[]::new),
part2.stream().map(p->p._p).toArray(InterestingPoint[]::new)), score));
}
else {
remain.add(cand);
}
}
return cutSets;
}
private String getFilenameWExtesion(Long itemGradingId, String agentId, String filename, int dotIndex) {
String filenameWithoutExtension = filename.substring(0, dotIndex);
StringBuilder bindVar = new StringBuilder(filenameWithoutExtension);
bindVar.append("%");
bindVar.append(filename.substring(dotIndex));
List list = getHibernateTemplate().findByNamedParam(
"select filename from MediaData m where m.itemGradingData.itemGradingId = :id and m.createdBy = :agent and m.filename like :file",
new String[]{"id", "agent", "file"},
new Object[]{itemGradingId, agentId, bindVar.toString()});
if (list.isEmpty()) {
return filename;
}
HashSet hs = new HashSet();
Iterator iter = list.iterator();
String name;
int nameLenght;
String extension = filename.substring(dotIndex);
int extensionLength = extension.length();
while (iter.hasNext()) {
name = ((String) iter.next()).trim();
if ((name.equals(filename) || name.startsWith(filenameWithoutExtension + "("))) {
nameLenght = name.length();
hs.add(name.substring(0, nameLenght - extensionLength));
}
}
if (hs.isEmpty()) {
return filename;
}
StringBuffer testName = new StringBuffer(filenameWithoutExtension);
int i = 1;
while (true) {
if (!hs.contains(testName.toString())) {
testName.append(extension);
return testName.toString();
} else {
i++;
testName = new StringBuffer(filenameWithoutExtension);
testName.append("(");
testName.append(i);
testName.append(")");
}
}
}
/**
* Returns the maximally specific superinterface methods
* of a given method signature.
*
* @param classFile a {@link ClassFile}.
* @param methodSignature the {@link Signature} of a method declared in {@code classFile}.
* Only the name and the descriptor are considered.
* @param nonAbstract a {@code boolean}.
* @return a {@link Set}{@code <}{@link ClassFile}{@code >} of classes containing maximally-specific
* superinterface methods of {@code classFile}
* for {@code methodSignature.}{@link Signature#getDescriptor() getDescriptor()}
* and {@code methodSignature.}{@link Signature#getName() getName()},
* as for JVMS v8, section 5.4.3.3. If {@code nonAbstract == true}, such set
* contains all and only the maximally-specific superinterface methods that are
* not abstract. If {@code nonAbstract == false}, it contains exactly all the
* maximally-specific superinterface methods.
*/
private Set<ClassFile> maximallySpecificSuperinterfaceMethods(ClassFile classFile, Signature methodSignature, boolean nonAbstract) {
final HashSet<ClassFile> maximalSet = new HashSet<>();
final HashSet<ClassFile> nextSet = new HashSet<>();
final HashSet<ClassFile> dominatedSet = new HashSet<>();
//initializes next with all the superinterfaces of methodSignature's class
nextSet.addAll(classFile.getSuperInterfaces());
while (!nextSet.isEmpty()) {
//picks a superinterface from the next set
final ClassFile superinterface = nextSet.iterator().next();
nextSet.remove(superinterface);
//determine all the (strict) superinterfaces of the superinterface
final Set<ClassFile> superinterfaceSuperinterfaces =
stream(superinterface.superinterfaces())
.collect(Collectors.toSet());
superinterfaceSuperinterfaces.remove(superinterface);
//look for a method declaration of methodSignature in the superinterface
try {
if (superinterface.hasMethodDeclaration(methodSignature) && !superinterface.isMethodPrivate(methodSignature) && !superinterface.isMethodStatic(methodSignature)) {
//method declaration found: add the superinterface
//to maximalSet...
maximalSet.add(superinterface);
//...remove the superinterface's strict superinterfaces
//from maximalSet, and add them to dominatedSet
maximalSet.removeAll(superinterfaceSuperinterfaces);
dominatedSet.addAll(superinterfaceSuperinterfaces);
} else if (!dominatedSet.contains(superinterface)) {
//no method declaration: add to nextSet all the direct
//superinterfaces of the superinterface that are not
//dominated; skips this step if the superinterface is
//itself dominated
nextSet.addAll(superinterface.getSuperInterfaces());
nextSet.removeAll(dominatedSet);
}
} catch (MethodNotFoundException e) {
//this should never happen
throw new UnexpectedInternalException(e);
}
}
return maximalSet;
}
public void setFuncDef(TheScopeFrame requestor, String varname, TypeAndLocation var, int modifier)
{
HashSet<TypeAndLocation> got = this.funcs.get(varname);
if(got == null)
{
got = new HashSet<TypeAndLocation>();
this.funcs.put(varname, got);
}
got.add(var);
if(this.paThisIsModule && this.replModLevelForcedNewfuncs != null) {
FuncType ft = ((FuncType)var.getType()).getErasedFuncTypeNoRet();
{
HashSet<FuncType> addTo;
if(!replModLevelForcedNewfuncs.containsKey(varname)) {
addTo = new HashSet<FuncType>();
replModLevelForcedNewfuncs.put(varname, addTo);
}else {
addTo = replModLevelForcedNewfuncs.get(varname);
}
addTo.add(ft);
}
{
if(replPrevSessionFuncs.containsKey(varname)) {
HashSet<FuncType> items = replPrevSessionFuncs.get(varname);
items.remove(ft);
if(items.isEmpty()) {
replPrevSessionFuncs.remove(varname);
}
}
}
}
if(isPersisted)
{
HashSet<TypeAndLocation> got2 = this.funcsSelfRequestor.get(varname);
if(got2 == null)
{
got2 = new HashSet<TypeAndLocation>();
this.funcsSelfRequestor.put(varname, got2);
}
got2.add(var);
}
}
public static Statement isHead(Statement head) {
if (head.getLastBasicType() != LASTBASICTYPE_GENERAL) {
return null;
}
HashSet<Statement> setHandlers = DecHelper.getUniquePredExceptions(head);
if (!setHandlers.isEmpty()) {
int hnextcount = 0; // either no statements with connection to next, or more than 1
Statement next = null;
List<StatEdge> lstHeadSuccs = head.getSuccessorEdges(STATEDGE_DIRECT_ALL);
if (!lstHeadSuccs.isEmpty() && lstHeadSuccs.get(0).getType() == StatEdge.TYPE_REGULAR) {
next = lstHeadSuccs.get(0).getDestination();
hnextcount = 2;
}
for (StatEdge edge : head.getSuccessorEdges(StatEdge.TYPE_EXCEPTION)) {
Statement stat = edge.getDestination();
boolean handlerok = true;
if (edge.getExceptions() != null && setHandlers.contains(stat)) {
if (stat.getLastBasicType() != LASTBASICTYPE_GENERAL) {
handlerok = false;
} else {
List<StatEdge> lstStatSuccs = stat.getSuccessorEdges(STATEDGE_DIRECT_ALL);
if (!lstStatSuccs.isEmpty() && lstStatSuccs.get(0).getType() == StatEdge.TYPE_REGULAR) {
Statement statn = lstStatSuccs.get(0).getDestination();
if (next == null) {
next = statn;
} else if (next != statn) {
handlerok = false;
}
if (handlerok) {
hnextcount++;
}
}
}
} else {
handlerok = false;
}
if (!handlerok) {
setHandlers.remove(stat);
}
}
if (hnextcount != 1 && !setHandlers.isEmpty()) {
List<Statement> lst = new ArrayList<>();
lst.add(head);
lst.addAll(setHandlers);
for (Statement st : lst) {
if (st.isMonitorEnter()) {
return null;
}
}
if (DecHelper.checkStatementExceptions(lst)) {
return new CatchStatement(head, next, setHandlers);
}
}
}
return null;
}
@Override
public void search(SearchInterceptorChain chain, DistinguishedName base, Int scope, Filter filter,
ArrayList<Attribute> attributes, Bool typesOnly, Results results, LDAPSearchConstraints constraints)
throws LDAPException {
if (chain.getRequest().containsKey(this.oldFilterName)) {
chain.nextSearch(base, scope, filter, attributes, typesOnly, results, constraints);
} else {
HashSet<String> memberofs = new HashSet<String>();
FilterNode noMemberOfs = null;
Bool foundAttr = new Bool(false);
try {
noMemberOfs = trimMemberOf(filter.getRoot(),memberofs,foundAttr);
} catch (CloneNotSupportedException e) {
throw new LDAPException("Error converting filter",LDAPException.OPERATIONS_ERROR,"Error converting filter",e);
}
chain.getRequest().put(this.oldFilterName, filter);
if (memberofs.isEmpty() || foundAttr.getValue()) {
chain.nextSearch(base, scope, new Filter(noMemberOfs), attributes, typesOnly, results, constraints);
}
chain.getRequest().put(this.skipPostSearchName, this.skipPostSearchName);
for (String memberof : memberofs) {
Results nres = new Results(this.nameSpace.getRouter().getGlobalChain(),0 );
DistinguishedName searchBase = new DistinguishedName(memberof);
SearchInterceptorChain nchain = new SearchInterceptorChain(searchBase,chain.getBindPassword(),0,nameSpace.getRouter().getGlobalChain(),chain.getSession(),chain.getRequest(),this.nameSpace.getRouter());
ArrayList<Attribute> nattrs = new ArrayList<Attribute>();
nchain.nextSearch(searchBase, new Int(0), new Filter("(objectClass=*)"), nattrs, new Bool(false), nres, constraints);
nres.start();
if (nres.hasMore()) {
Entry group = nres.next();
LDAPAttribute members = group.getEntry().getAttribute(this.searchAttribute);
if (members != null) {
for (String member : members.getStringValueArray()) {
//if base?
DistinguishedName userDN = new DistinguishedName(member);
SearchInterceptorChain userChain = new SearchInterceptorChain(userDN,chain.getBindPassword(),0,nameSpace.getRouter().getGlobalChain(),chain.getSession(),chain.getRequest(),this.nameSpace.getRouter());
userChain.nextSearch(userDN, new Int(0), new Filter(noMemberOfs), attributes, new Bool(false), results, constraints);
}
}
}
nres.finish();
}
chain.getRequest().remove(this.skipPostSearchName);
}
}