下面列出了java.util.AbstractSet#java.util.SortedSet 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String getFileName(String homePath, Pattern pattern) {
File home = new File(homePath);
SortedSet<String> files = Sets.newTreeSet();
if (home.exists() && home.isDirectory()) {
File[] listFiles = home.listFiles();
if (listFiles != null) {
for (File file : listFiles) {
final Matcher matcher = pattern.matcher(file.getName());
if (matcher.matches()) {
files.add(file.getAbsolutePath());
}
}
}
}
if (files.isEmpty()) {
throw new RuntimeException("cannot find " + pattern.toString() + " in " + homePath);
} else {
return files.last();
}
}
/**
*
* @param timeString Given a time, provide the {@link TimeRegions} at or before that time.
* Time can be in milliseconds or relative time.
* @return transactional regions that are present at or before the given time
* @throws IOException if there are any errors while trying to fetch the {@link TimeRegions}
*/
@Override
@SuppressWarnings("WeakerAccess")
public RegionsAtTime getRegionsOnOrBeforeTime(String timeString) throws IOException {
long time = TimeMathParser.parseTime(timeString, TimeUnit.MILLISECONDS);
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
TimeRegions timeRegions = dataJanitorState.getRegionsOnOrBeforeTime(time);
if (timeRegions == null) {
return new RegionsAtTime(time, new TreeSet<String>(), dateFormat);
}
SortedSet<String> regionNames = new TreeSet<>();
Iterable<String> regionStrings = Iterables.transform(timeRegions.getRegions(), TimeRegions.BYTE_ARR_TO_STRING_FN);
for (String regionString : regionStrings) {
regionNames.add(regionString);
}
return new RegionsAtTime(timeRegions.getTime(), regionNames, dateFormat);
}
/**
*
* @param timeString Given a time, provide the {@link TimeRegions} at or before that time.
* Time can be in milliseconds or relative time.
* @return transactional regions that are present at or before the given time
* @throws IOException if there are any errors while trying to fetch the {@link TimeRegions}
*/
@Override
@SuppressWarnings("WeakerAccess")
public RegionsAtTime getRegionsOnOrBeforeTime(String timeString) throws IOException {
long time = TimeMathParser.parseTime(timeString, TimeUnit.MILLISECONDS);
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
TimeRegions timeRegions = dataJanitorState.getRegionsOnOrBeforeTime(time);
if (timeRegions == null) {
return new RegionsAtTime(time, new TreeSet<String>(), dateFormat);
}
SortedSet<String> regionNames = new TreeSet<>();
Iterable<String> regionStrings = Iterables.transform(timeRegions.getRegions(), TimeRegions.BYTE_ARR_TO_STRING_FN);
for (String regionString : regionStrings) {
regionNames.add(regionString);
}
return new RegionsAtTime(timeRegions.getTime(), regionNames, dateFormat);
}
/**
* headSet returns set with keys in requested range
*/
public void testDescendingHeadSetContents() {
NavigableSet set = dset5();
SortedSet sm = set.headSet(m4);
assertTrue(sm.contains(m1));
assertTrue(sm.contains(m2));
assertTrue(sm.contains(m3));
assertFalse(sm.contains(m4));
assertFalse(sm.contains(m5));
Iterator i = sm.iterator();
Object k;
k = (Integer)(i.next());
assertEquals(m1, k);
k = (Integer)(i.next());
assertEquals(m2, k);
k = (Integer)(i.next());
assertEquals(m3, k);
assertFalse(i.hasNext());
sm.clear();
assertTrue(sm.isEmpty());
assertEquals(2, set.size());
assertEquals(m4, set.first());
}
@Test
public void complete_order_of_type_local_expenses_works_when_having_office_administrator_role_test() {
// given
Person personDaniel = (Person) partyRepository.findPartyByReference(
Person_enum.DanielOfficeAdministratorFr.getRef());
SortedSet<PartyRole> rolesforDylan = personDaniel.getRoles();
assertThat(rolesforDylan.size()).isEqualTo(1);
assertThat(rolesforDylan.first().getRoleType()).isEqualTo(partyRoleTypeRepository.findByKey(PartyRoleTypeEnum.OFFICE_ADMINISTRATOR.getKey()));
// when
queryResultsCache.resetForNextTransaction(); // workaround: clear MeService#me cache
setFixtureClockDate(2018,1, 6);
sudoService.sudo(Person_enum.DanielOfficeAdministratorFr.getRef().toLowerCase(), (Runnable) () ->
wrap(mixin(Order_completeWithApproval.class, order)).act( personDaniel, new LocalDate(2018,1, 6), null));
assertThat(order.getApprovalState()).isEqualTo(OrderApprovalState.APPROVED);
assertThat(taskRepository.findIncompleteByRole(partyRoleTypeRepository.findByKey(PartyRoleTypeEnum.OFFICE_ADMINISTRATOR.getKey())).size()).isEqualTo(0);
}
public void testSorting() throws Exception {
SortedSet<VersionString> set = new TreeSet<VersionString>();
set.add(v3);
set.add(v0);
set.add(v1);
set.add(v4);
set.add(v2);
assertEquals(v0, set.first());
assertTrue(set.remove(v0));
assertEquals(v1, set.first());
assertTrue(set.remove(v1));
assertEquals(v2, set.first());
assertTrue(set.remove(v2));
assertEquals(v3, set.first());
assertTrue(set.remove(v3));
assertEquals(v4, set.first());
assertTrue(set.remove(v4));
assertTrue(set.isEmpty());
}
public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
final AcademicServiceRequestBean bean = getOrCreateAcademicServiceRequestBean(request);
request.setAttribute("bean", bean);
final Collection<AcademicServiceRequest> remainingRequests = bean.searchAcademicServiceRequests();
final Collection<AcademicServiceRequest> specificRequests = getAndRemoveSpecificRequests(bean, remainingRequests);
final SortedSet<AcademicServiceRequest> sorted = new TreeSet<AcademicServiceRequest>(getComparator(request));
sorted.addAll(remainingRequests);
request.setAttribute("remainingRequests", remainingRequests);
request.setAttribute("specificRequests", specificRequests);
final CollectionPager<AcademicServiceRequest> pager =
new CollectionPager<AcademicServiceRequest>(sorted, REQUESTS_PER_PAGE);
request.setAttribute("collectionPager", pager);
request.setAttribute("numberOfPages", Integer.valueOf(pager.getNumberOfPages()));
final String pageParameter = request.getParameter("pageNumber");
final Integer page = StringUtils.isEmpty(pageParameter) ? Integer.valueOf(1) : Integer.valueOf(pageParameter);
request.setAttribute("pageNumber", page);
request.setAttribute("resultPage", pager.getPage(page));
return mapping.findForward("searchResults");
}
private List<SearchResult> searchResults(MailboxSession session, Mailbox mailbox, SearchQuery query) throws MailboxException {
MessageMapper mapper = messageMapperFactory.getMessageMapper(session);
final SortedSet<MailboxMessage> hitSet = new TreeSet<>();
UidCriterion uidCrit = findConjugatedUidCriterion(query.getCriteria());
if (uidCrit != null) {
// if there is a conjugated uid range criterion in the query tree we can optimize by
// only fetching this uid range
UidRange[] ranges = uidCrit.getOperator().getRange();
for (UidRange r : ranges) {
Iterator<MailboxMessage> it = mapper.findInMailbox(mailbox, MessageRange.range(r.getLowValue(), r.getHighValue()), FetchType.Metadata, UNLIMITED);
while (it.hasNext()) {
hitSet.add(it.next());
}
}
} else {
// we have to fetch all messages
Iterator<MailboxMessage> messages = mapper.findInMailbox(mailbox, MessageRange.all(), FetchType.Full, UNLIMITED);
while (messages.hasNext()) {
MailboxMessage m = messages.next();
hitSet.add(m);
}
}
return ImmutableList.copyOf(new MessageSearches(hitSet.iterator(), query, textExtractor, attachmentContentLoader, session).iterator());
}
/**
* Get a list of all PDP domains for a given PDB entry
* @param pdbId PDB ID
* @return Set of domain names, e.g. "PDP:4HHBAa"
* @throws IOException if the server cannot be reached
*/
@Override
public SortedSet<String> getPDPDomainNamesForPDB(String pdbId) throws IOException{
SortedSet<String> results = null;
try {
URL u = new URL(server + "getPDPDomainNamesForPDB?pdbId="+pdbId);
logger.info("Fetching {}",u);
InputStream response = URLConnectionTools.getInputStream(u);
String xml = JFatCatClient.convertStreamToString(response);
results = XMLUtil.getDomainRangesFromXML(xml);
} catch (MalformedURLException e){
logger.error("Problem generating PDP request URL for "+pdbId,e);
throw new IllegalArgumentException("Invalid PDB name: "+pdbId, e);
}
return results;
}
private SortedSet<FontFeature>
makeGlyphMappingFeatures(String script, String language, int bidiLevel, Axis axis, boolean kerned, Orientation orientation, Combination combination) {
SortedSet<FontFeature> features = new java.util.TreeSet<FontFeature>();
if ((script != null) && !script.isEmpty())
features.add(FontFeature.SCPT.parameterize(script));
if ((language != null) && !language.isEmpty())
features.add(FontFeature.LANG.parameterize(language));
if (bidiLevel >= 0)
features.add(FontFeature.BIDI.parameterize(bidiLevel));
if (kerned)
features.add(FontFeature.KERN.parameterize(Boolean.TRUE));
else
features.add(FontFeature.KERN.parameterize(Boolean.FALSE));
if ((orientation != null) && orientation.isRotated())
features.add(FontFeature.ORNT.parameterize(orientation));
if ((combination != null) && !combination.isNone())
features.add(FontFeature.COMB.parameterize(combination));
if ((axis != null) && axis.cross(!combination.isNone()).isVertical() && !orientation.isRotated())
features.add(FontFeature.VERT.parameterize(Boolean.TRUE));
return features;
}
void setAttacker(final MagicGame game,final Set<MagicCombatCreature> blockers) {
final SortedSet<MagicCombatCreature> candidateBlockersSet =
new TreeSet<>(new BlockerComparator(this));
for (final MagicCombatCreature blocker : blockers) {
if (blocker.permanent.canBlock(permanent)) {
candidateBlockersSet.add(blocker);
}
}
candidateBlockers=new MagicCombatCreature[candidateBlockersSet.size()];
candidateBlockersSet.toArray(candidateBlockers);
attackerScore=ArtificialScoringSystem.getAttackerScore(this);
}
@Override
public boolean checkAbnormal ()
{
SortedSet<AbstractChordInter> embraced = TupletsBuilder.getEmbracedChords(
this,
getChords());
setAbnormal(embraced == null);
return isAbnormal();
}
public SortedSet<Range> buildRanges(Collection<String> fields) {
TreeSet<Range> ranges = new TreeSet<>();
for (String field : fields) {
ranges.add(new Range(field, field + Constants.NULL_BYTE_STRING));
}
return ranges;
}
@Override
public boolean isEmpty() {
for (SortedSet<E> set : sets) {
if (!set.isEmpty()) {
return false;
}
}
return true;
}
@Override
public void generateMetaInfo(Map<String, SortedSet<String>> metaInfo) throws IOException {
String dirName = CLDRConverter.DESTINATION_DIR + File.separator + "sun" + File.separator + "util" + File.separator
+ "cldr" + File.separator;
File dir = new File(dirName);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, METAINFO_CLASS + ".java");
if (!file.exists()) {
file.createNewFile();
}
CLDRConverter.info("Generating file " + file);
try (PrintWriter out = new PrintWriter(file, "us-ascii")) {
out.println(CopyrightHeaders.getOpenJDKCopyright());
out.println("package sun.util.cldr;\n\n"
+ "import java.util.ListResourceBundle;\n");
out.printf("public class %s extends ListResourceBundle {\n", METAINFO_CLASS);
out.println(" @Override\n" +
" protected final Object[][] getContents() {\n" +
" final Object[][] data = new Object[][] {");
for (String key : metaInfo.keySet()) {
out.printf(" { \"%s\",\n", key);
out.printf(" \"%s\" },\n", toLocaleList(metaInfo.get(key)));
}
out.println(" };\n return data;\n }\n}");
}
}
@Test
public void lists_source_ref_description_for_top_level_targets() {
SortedSet<Target> topLevelTargets = searchChainResolver.allTopLevelTargets();
assertThat(topLevelTargets.size(), is(3));
Iterator<Target> i = topLevelTargets.iterator();
assertSearchRefDescriptionIs(i.next(), providerId.toString());
assertSearchRefDescriptionIs(i.next(), searchChainId.toString());
assertSearchRefDescriptionIs(i.next(), "source[provider = provider, provider2]");
}
public String[] listUserNamesNonExpired()
{
return useManagedResourceClassloader(new Work<String[]>()
{
@Override
String[] doWork()
{
Set<String> userSet = authenticationService.getUsersWithTickets(true);
SortedSet<String> sorted = new TreeSet<String>(userSet);
return sorted.toArray(new String[0]);
}
});
}
@Test
public void testToFlexgrid50() {
OchSignal input = newDwdmSlot(CHL_50GHZ, 0);
SortedSet<OchSignal> expected = newOchSignalTreeSet();
expected.addAll(ImmutableList.of(
newFlexGridSlot(-3), newFlexGridSlot(-1),
newFlexGridSlot(+1), newFlexGridSlot(+3)));
SortedSet<OchSignal> flexGrid = OchSignal.toFlexGrid(input);
assertEquals(expected, flexGrid);
}
@Test
public void testOneLineRepresentation() {
SortedSet<JobRuntimePrediction> predictions = new TreeSet<>();
predictions.add(new JobRuntimePrediction(0.95, 26.2));
predictions.add(new JobRuntimePrediction(0.1, 10.0));
predictions.add(new JobRuntimePrediction(0.2, 15.0));
JobRuntimePredictions jobRuntimePredictions = new JobRuntimePredictions("1", "some-id", predictions);
Optional<String> asString = jobRuntimePredictions.toSimpleString();
assertThat(asString).isPresent();
assertThat(asString.get()).isEqualTo("0.1=10.0;0.2=15.0;0.95=26.2");
}
@SuppressWarnings("unchecked")
@Override
public boolean containsAll(Collection<?> c) {
if (c.isEmpty()) {
return true;
}
if (persisted) {
try {
SortedSet<E> all = new TreeSet<>(set.comparator());
for (Object o : c) {
all.add((E) o);
}
try (SortedSetInputStream<E> stream = getBoundedFileHandler().getInputStream(getStart(), getEnd())) {
E obj = stream.readObject();
while (obj != null) {
if (all.remove(obj)) {
if (all.isEmpty()) {
return true;
}
}
obj = stream.readObject();
}
}
} catch (Exception e) {
throw new IllegalStateException("Unable to read file into a complete set", e);
}
return false;
} else {
return set.containsAll(c);
}
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
SingularSortedSet2(final SortedSet rawTypes, final SortedSet<Integer> integers, final SortedSet<T> generics, final SortedSet<? extends Number> extendsGenerics) {
this.rawTypes = rawTypes;
this.integers = integers;
this.generics = generics;
this.extendsGenerics = extendsGenerics;
}
protected SortedSet<File> findHMDBFilesInDirectory(File dir) throws IOException {
// Sort for consistency + sanity.
SortedSet<File> results = new TreeSet<>((a, b) -> a.getName().compareTo(b.getName()));
for (File file : dir.listFiles()) { // Do our own filtering so we can log rejects, of which we expect very few.
if (HMDB_FILE_REGEX.matcher(file.getName()).matches()) {
results.add(file);
} else {
LOGGER.warn("Found non-conforming HMDB file in directory %s: %s", dir.getAbsolutePath(), file.getName());
}
}
return results;
}
public static boolean containsPrefixedWith(
final SortedSet<Filter> statements, final StartsWithFilter outer,
final BiFunction<StartsWithFilter, StartsWithFilter, Boolean> check
) {
return statements
.stream()
.filter(inner -> inner instanceof StartsWithFilter)
.map(StartsWithFilter.class::cast)
.filter(statements::contains)
.filter(inner -> outer.tag().equals(inner.tag()))
.filter(inner -> check.apply(inner, outer))
.findFirst()
.isPresent();
}
public BufferedFileBackedSortedSet(BufferedFileBackedSortedSet<E> other) {
this(other.comparator, other.bufferPersistThreshold, other.maxOpenFiles, other.numRetries, new ArrayList<>(other.handlerFactories), other.setFactory);
for (SortedSet<E> subSet : other.set.getSets()) {
FileSortedSet<E> clone = ((FileSortedSet<E>) subSet).clone();
this.set.addSet(clone);
if (!clone.isPersisted()) {
this.buffer = clone;
}
}
this.sizeModified = other.sizeModified;
this.size = other.size;
}
@GwtIncompatible // java.io.ObjectInputStream
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
factory = (Supplier<? extends SortedSet<V>>) stream.readObject();
valueComparator = factory.get().comparator();
Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject();
setMap(map);
}
private Class<?> resolveInterface(Class<?> type) {
Class<?> classToCreate;
if (type == List.class || type == Collection.class) {
classToCreate = LinkedList.class;
} else if (type == Map.class) {
classToCreate = LinkedHashMap.class;
} else if (type == SortedSet.class) { // issue #510 Collections Support
classToCreate = TreeSet.class;
} else if (type == Set.class) {
classToCreate = HashSet.class;
} else {
classToCreate = type;
}
return classToCreate;
}
@Override
public E last() {
SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
while (true) {
E element = sortedUnfiltered.last();
if (predicate.apply(element)) {
return element;
}
sortedUnfiltered = sortedUnfiltered.headSet(element);
}
}
/**
* Get all the tool activities in this activity. Called by Activity.getAllToolActivities(). Recursively get tool
* activity from its children.
*/
@Override
protected void getToolActivitiesInActivity(SortedSet<ToolActivity> toolActivities) {
for (Iterator<Activity> i = this.getActivities().iterator(); i.hasNext();) {
Activity child = i.next();
child.getToolActivitiesInActivity(toolActivities);
}
}
@Test
public void shouldNotContainDuplicateNamedApiErrors() {
Map<String, Integer> nameToCountMap = new HashMap<>();
SortedSet<String> duplicateErrorNames = new TreeSet<>();
for (ApiError apiError : getProjectApiErrors().getProjectApiErrors()) {
Integer currentCount = nameToCountMap.get(apiError.getName());
if (currentCount == null)
currentCount = 0;
Integer newCount = currentCount + 1;
nameToCountMap.put(apiError.getName(), newCount);
if (newCount > 1)
duplicateErrorNames.add(apiError.getName());
}
if (!duplicateErrorNames.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("There are ApiError instances in the ProjectApiErrors that share duplicate names. [name, count]: ");
boolean first = true;
for (String dup : duplicateErrorNames) {
if (!first)
sb.append(", ");
sb.append("[").append(dup).append(", ").append(nameToCountMap.get(dup)).append("]");
first = false;
}
throw new AssertionError(sb.toString());
}
}
@Test
public void testOrder() throws Exception {
//make sure the interceptors get ordered correctly
SortedSet<Phase> phases = new TreeSet<Phase>();
phases.add(new Phase(Phase.PRE_PROTOCOL, 1));
List<Interceptor<? extends Message>> lst = new ArrayList<Interceptor<? extends Message>>();
lst.add(new MustUnderstandInterceptor());
lst.add(new WSS4JInInterceptor());
lst.add(new SAAJInInterceptor());
PhaseInterceptorChain chain = new PhaseInterceptorChain(phases);
chain.add(lst);
String output = chain.toString();
assertTrue(output.contains("MustUnderstandInterceptor, SAAJInInterceptor, WSS4JInInterceptor"));
}