下面列出了java.awt.event.HierarchyListener#java.util.Collections 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Map<Object, Object> decode(List<Object> parts, State state) {
if (parts.get(0) == null
|| (parts.get(0) instanceof List && ((List) parts.get(0)).isEmpty())) {
parts.clear();
return Collections.emptyMap();
}
if (parts.get(0) instanceof Map) {
Map<Object, Object> result = new LinkedHashMap<Object, Object>(parts.size());
for (int i = 0; i < parts.size(); i++) {
result.putAll((Map<? extends Object, ? extends Object>) parts.get(i));
}
return result;
}
return super.decode(parts, state);
}
@Override
public RawDiff next() {
CommitFile file = files.next();
log.info("get file {}", file.getFilename());
List<String> lines;
if (file.getPatch() != null && file.getPatch().length() > 0) {
lines = Arrays.asList(file.getPatch().split("\r?\n"));
} else {
lines = Collections.emptyList();
}
return RawDiff.builder()
.fileName(file.getFilename())
.rawDiff(lines)
.type(file.getPatch() != null ? FileType.SOURCE : FileType.BINARY)
.build();
}
@Test
public void testWriteReportOnlyOnFailureForFailingQueriesAndTests() throws IOException {
String[] args = {"--report-on-failure-only", "true"};
MockFormatter formatter = new MockFormatter();
FormatManager manager = new FormatManager(args);
manager.setAvailableFormatters(Collections.singletonMap("MockFormat", formatter));
manager.setFormattersToUse(new ArrayList<>());
manager.setupFormatter("MockFormat", args);
TestSuite suite = new TestSuite();
Assert.assertFalse(formatter.wroteReport);
com.yahoo.validatar.common.Test failingTest = new com.yahoo.validatar.common.Test();
failingTest.setFailed();
Query failingQuery = new Query();
failingQuery.setFailed();
suite.queries = Collections.singletonList(failingQuery);
suite.tests = Collections.singletonList(failingTest);
manager.writeReports(Collections.singletonList(suite));
Assert.assertTrue(formatter.wroteReport);
}
@Test
public void testScaleUpMinIdle() {
AgentInstanceGroup instanceGroup = createPartition("instanceGroup1", InstanceGroupLifecycleState.Active, "r4.16xlarge", 0, 0, 10);
when(agentManagementService.getInstanceGroups()).thenReturn(singletonList(instanceGroup));
when(agentManagementService.getAgentInstances("instanceGroup1")).thenReturn(Collections.emptyList());
when(agentManagementService.scaleUp(eq("instanceGroup1"), anyInt())).thenReturn(Completable.complete());
testScheduler.advanceTimeBy(6, TimeUnit.MINUTES);
ClusterAgentAutoScaler clusterAgentAutoScaler = new ClusterAgentAutoScaler(titusRuntime, configuration,
agentManagementService, v3JobOperations, schedulingService, testScheduler);
clusterAgentAutoScaler.doAgentScaling().await();
verify(agentManagementService).scaleUp("instanceGroup1", 5);
}
@Test
public void testReportSpan() {
// prepare
SpanData spanData = defaultMockSpanData();
when(spanData.getTags()).thenReturn(Collections.singletonMap(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT));
MicrometerMetricsReporter reporter = MicrometerMetricsReporter.newMetricsReporter()
.withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT)
.build();
// test
reporter.reportSpan(spanData);
// verify
List<Tag> tags = defaultTags();
assertEquals(100, (long) registry.find("span").timer().totalTime(TimeUnit.MILLISECONDS));
assertEquals(1, Metrics.timer("span", tags).count());
}
@Override
public Set<DataObject> instantiate(TemplateWizard wiz) throws IOException {
DataObject result = null;
String targetName = Templates.getTargetName(wizard);
FileObject targetDir = Templates.getTargetFolder(wizard);
DataFolder df = DataFolder.findFolder(targetDir);
FileObject template = Templates.getTemplate( wizard );
DataObject dTemplate = DataObject.find(template);
HashMap<String, Object> templateProperties = new HashMap<String, Object>();
if (selectedText != null) {
templateProperties.put("implementation", selectedText); //NOI18N
}
Project project = Templates.getProject(wizard);
WebModule webModule = WebModule.getWebModule(project.getProjectDirectory());
if (webModule != null) {
JSFVersion version = JSFVersion.forWebModule(webModule);
if (version != null && version.isAtLeast(JSFVersion.JSF_2_2)) {
templateProperties.put("isJSF22", Boolean.TRUE); //NOI18N
}
}
result = dTemplate.createFromTemplate(df,targetName,templateProperties);
return Collections.singleton(result);
}
@Test
void shouldErrorOutWhenMaterialIsReferringToNoneExistingSecretConfig() {
GitMaterial gitMaterial = new GitMaterial("http://example.com");
gitMaterial.setPassword("{{SECRET:[secret_config_id][password]}}");
PipelineConfig up42 = PipelineConfigMother.pipelineConfig("up42", new MaterialConfigs(gitMaterial.config()));
PipelineConfigs defaultGroup = PipelineConfigMother.createGroup("default", up42);
CruiseConfig cruiseConfig = defaultCruiseConfig();
cruiseConfig.setGroup(new PipelineGroups(defaultGroup));
when(goConfigService.cruiseConfig()).thenReturn(cruiseConfig);
when(goConfigService.pipelinesWithMaterial(gitMaterial.getFingerprint())).thenReturn(Collections.singletonList(new CaseInsensitiveString("up42")));
when(goConfigService.findGroupByPipeline(new CaseInsensitiveString("up42"))).thenReturn(defaultGroup);
when(goConfigService.findPipelineByName(new CaseInsensitiveString("up42"))).thenReturn(up42);
assertThatCode(() -> rulesService.validateSecretConfigReferences(gitMaterial))
.isInstanceOf(RulesViolationException.class)
.hasMessage("Pipeline 'up42' is referring to none-existent secret config 'secret_config_id'.");
}
@Test
public void compositeReturnsStatusUpWhenAllChildrenAreUp() {
final Map<String, StatusInfo> childrenMap = new LinkedHashMap<>();
final String upChild1Label = "up-child-1-label";
childrenMap.put(upChild1Label, KNOWN_UP_STATUS_INFO_WITH_WARN_MSG);
final String upChild2Label = "up-child-2-label";
childrenMap.put(upChild2Label, KNOWN_UP_STATUS_INFO_WITH_WARN_MSG);
final StatusInfo actual = StatusInfo.composite(childrenMap);
final List<StatusDetailMessage> expectedDetails = Collections.singletonList(
(createExpectedCompositeDetailMessage(KNOWN_MESSAGE_WARN.getLevel(),
Arrays.asList(upChild1Label, upChild2Label))));
final List<StatusInfo> expectedLabeledChildren =
Arrays.asList(KNOWN_UP_STATUS_INFO_WITH_WARN_MSG.label(upChild1Label),
KNOWN_UP_STATUS_INFO_WITH_WARN_MSG.label(upChild2Label));
final StatusInfo expected =
StatusInfo.of(StatusInfo.Status.UP, expectedDetails, expectedLabeledChildren, null);
assertThat(actual).isEqualTo(expected);
assertThat(actual.isComposite()).isTrue();
}
/**
* Constructor.
*
* @param valueTextMap the map of values to text to store, assigned and not altered, not null
*/
LocaleStore(Map<TextStyle, Map<Long, String>> valueTextMap) {
this.valueTextMap = valueTextMap;
Map<TextStyle, List<Entry<String, Long>>> map = new HashMap<>();
List<Entry<String, Long>> allList = new ArrayList<>();
for (Map.Entry<TextStyle, Map<Long, String>> vtmEntry : valueTextMap.entrySet()) {
Map<String, Entry<String, Long>> reverse = new HashMap<>();
for (Map.Entry<Long, String> entry : vtmEntry.getValue().entrySet()) {
if (reverse.put(entry.getValue(), createEntry(entry.getValue(), entry.getKey())) != null) {
// TODO: BUG: this has no effect
continue; // not parsable, try next style
}
}
List<Entry<String, Long>> list = new ArrayList<>(reverse.values());
Collections.sort(list, COMPARATOR);
map.put(vtmEntry.getKey(), list);
allList.addAll(list);
map.put(null, allList);
}
Collections.sort(allList, COMPARATOR);
this.parsable = map;
}
private List<String> getRelativeCanonicalPaths( final List<File> fileList, final File cutoff )
{
final String cutoffPath = FileSystemUtilities.getCanonicalPath( cutoff ).replace( File.separator, "/" );
final List<String> toReturn = new ArrayList<String>();
for ( File current : fileList )
{
final String canPath = FileSystemUtilities.getCanonicalPath( current ).replace( File.separator, "/" );
if ( !canPath.startsWith( cutoffPath ) )
{
throw new IllegalArgumentException(
"Illegal cutoff provided. Cutoff: [" + cutoffPath + "] must be a parent to CanonicalPath [" + canPath + "]" );
}
toReturn.add( canPath.substring( cutoffPath.length() ) );
}
Collections.sort( toReturn );
return toReturn;
}
/**
* Elements of classes with erased generic type parameters based
* on Comparable can be inserted and found.
*/
public void testGenericComparable() {
int size = 120; // makes measured test run time -> 60ms
ConcurrentHashMap<Object, Boolean> m =
new ConcurrentHashMap<Object, Boolean>();
for (int i = 0; i < size; i++) {
BI bi = new BI(i);
BS bs = new BS(String.valueOf(i));
LexicographicList<BI> bis = new LexicographicList<BI>(bi);
LexicographicList<BS> bss = new LexicographicList<BS>(bs);
assertTrue(m.putIfAbsent(bis, true) == null);
assertTrue(m.containsKey(bis));
if (m.putIfAbsent(bss, true) == null)
assertTrue(m.containsKey(bss));
assertTrue(m.containsKey(bis));
}
for (int i = 0; i < size; i++) {
assertTrue(m.containsKey(Collections.singletonList(new BI(i))));
}
}
@VisibleForTesting
NavigableMap<BigDecimal, BigDecimal> convert(BigDecimal[][] values, Comparator<BigDecimal> comparator) {
if (values == null) {
return null;
}
NavigableMap<BigDecimal, BigDecimal> map = new TreeMap<>(comparator);
Stream.of(values)
.filter(ArrayUtils::isNotEmpty)
.filter(ps -> ps.length == 2)
.filter(ps -> ps[0] != null)
.filter(ps -> ps[1] != null)
.forEach(ps -> map.put(ps[0], ps[1]))
;
return Collections.unmodifiableNavigableMap(map);
}
public List<MagicEdition> listEditions() {
if (!list.isEmpty())
return list;
try {
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//edition/@id";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++)
{
list.add(MTGControler.getInstance().getEnabled(MTGCardsProvider.class).getSetById(nodeList.item(i).getNodeValue()));
}
Collections.sort(list);
} catch (Exception e) {
logger.error("Error retrieving IDs ", e);
}
return list;
}
/**
* @param stage the annotation that specifies this stage
* @param mode execution order
*/
public DefaultStager(Class<A> stage, Order mode) {
this.stage = stage;
Queue<Stageable> localStageables;
switch (mode) {
case FIRST_IN_FIRST_OUT: {
localStageables = new ArrayDeque<>();
break;
}
case FIRST_IN_LAST_OUT: {
localStageables = Collections.asLifoQueue(new ArrayDeque<>());
break;
}
default: {
throw new IllegalArgumentException("Unknown mode: " + mode);
}
}
stageables = localStageables;
}
@Test
public void updateSub() {
// Eval with sum
List<Subscription> sumSub = new ArrayList<>();
sumSub.add(newSubscription("sum", ":true,:sum"));
Evaluator evaluator = newEvaluator();
evaluator.sync(sumSub);
EvalPayload payload = evaluator.eval(0L, data("foo", 1.0, 2.0, 3.0));
List<EvalPayload.Metric> metrics = new ArrayList<>();
metrics.add(new EvalPayload.Metric("sum", Collections.emptyMap(), 6.0));
EvalPayload expected = new EvalPayload(0L, metrics);
Assertions.assertEquals(expected, payload);
// Update to use max instead
List<Subscription> maxSub = new ArrayList<>();
maxSub.add(newSubscription("sum", ":true,:max"));
evaluator.sync(maxSub);
payload = evaluator.eval(0L, data("foo", 1.0, 2.0, 3.0));
metrics = new ArrayList<>();
metrics.add(new EvalPayload.Metric("sum", Collections.emptyMap(), 3.0));
expected = new EvalPayload(0L, metrics);
Assertions.assertEquals(expected, payload);
}
@Test
public void addAvailablePaymentTypes_FindsExistingEntry() throws Exception {
OrganizationReference createdOrgRef = runTX(new Callable<OrganizationReference>() {
@Override
public OrganizationReference call() throws Exception {
OrganizationReference orgRef = new OrganizationReference(
platformOp, supplier,
OrganizationReferenceType.PLATFORM_OPERATOR_TO_SUPPLIER);
dataService.persist(orgRef);
dataService.flush();
return orgRef;
}
});
operatorService
.addAvailablePaymentTypes(OrganizationAssembler
.toVOOrganization(supplier, false, new LocalizerFacade(
localizer, "en")), Collections
.singleton("CREDIT_CARD"));
validate(createdOrgRef, true);
}
/**
* Maps Collection of strings to collection of {@code InetSocketAddress}es.
*
* @param cfgAddrs Collection fo string representations of addresses.
* @return Collection of {@code InetSocketAddress}es
* @throws GridClientException In case of error.
*/
private static Collection<InetSocketAddress> parseAddresses(Collection<String> cfgAddrs)
throws GridClientException {
Collection<InetSocketAddress> addrs = new ArrayList<>(cfgAddrs.size());
for (String srvStr : cfgAddrs) {
try {
String[] split = srvStr.split(":");
InetSocketAddress addr = new InetSocketAddress(split[0], Integer.parseInt(split[1]));
addrs.add(addr);
}
catch (RuntimeException e) {
throw new GridClientException("Failed to create client (invalid server address specified): " +
srvStr, e);
}
}
return Collections.unmodifiableCollection(addrs);
}
/**
* Determines the files that have to be executed (according to the provided
* version information) and orders them in ascending order.
*
* @param fileList
* The list of files to be investigated. The names must have
* passed the test in method
* {@link #getScriptFilesFromDirectory(String, String)}.
* @return The files to be executed in the execution order.
*/
protected List<File> getFileExecutionOrder(List<File> fileList,
DatabaseVersionInfo currentVersion, DatabaseVersionInfo toVersion) {
List<File> result = new ArrayList<File>();
// if the file contains statements for a newer schema, add the file to
// the list
for (File file : fileList) {
DatabaseVersionInfo info = determineVersionInfoForFile(file);
if (info.compareTo(currentVersion) > 0
&& info.compareTo(toVersion) <= 0) {
result.add(file);
}
}
// now sort the list ascending
Collections.sort(result);
return result;
}
private List<String> getAttributes(Element queryElement, String objectName) {
String attribute = queryElement.getAttribute("attribute");
String attributes = queryElement.getAttribute("attributes");
validateOnlyAttributeOrAttributesSpecified(attribute, attributes, objectName);
if (attribute.isEmpty() && attributes.isEmpty()) {
return Collections.emptyList();
}
if (!attribute.isEmpty()) {
return Collections.singletonList(attribute);
} else {
String[] splitAttributes = ATTRIBUTE_SPLIT_PATTERN.split(attributes);
return Arrays.asList(splitAttributes);
}
}
@Test
public void testGrandParentColumnNames() {
try {
String[] columnNames = getAllColumnNames(grandParentClass);
List<String> actualColumnNames = Arrays.asList(columnNames);
Collections.sort(actualColumnNames);
List<String> expectedColumnNames = getExpectedColumnNamesOfGrandParent();
Collections.sort(expectedColumnNames);
Assert.assertEquals(actualColumnNames, expectedColumnNames);
} catch (Exception e) {
Assert.fail();
}
}
/**
* Construct a new transaction builder.
* @param sourceAccount The source account for this transaction. This account is the account
* who will use a sequence number. When build() is called, the account object's sequence number
* will be incremented.
*/
public Builder(TransactionBuilderAccount sourceAccount, Network network) {
checkNotNull(sourceAccount, "sourceAccount cannot be null");
mSourceAccount = sourceAccount;
mOperations = Collections.synchronizedList(new ArrayList<Operation>());
mNetwork = checkNotNull(network, "Network cannot be null");
}
/**
* @return
*/
public Iterable<IOutputManager> getAllSimulationOutputs() {
final SimulationPopulation pop = getSimulationPopulation();
if (pop != null) {
return Iterables.filter(Iterables.concat(Iterables.transform(pop, each -> each.getOutputManager()),
Collections.singletonList(getOutputManager())), each -> each != null);
}
return Collections.EMPTY_LIST;
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, String> filterSearchCriteria(String propertyName, Map<String, String> searchCriteria,
FilterableLookupCriteriaControlPostData postData) {
Map<String, String> filteredSearchCriteria = new HashMap<String, String>(searchCriteria);
UserControlPostData userControlPostData = (UserControlPostData) postData;
// check valid principalName
// ToDo: move the principalId check and setting to the validation stage. At that point the personName should
// be set as well or an error be displayed to the user that the principalName is invalid.
String principalName = searchCriteria.get(propertyName);
if (StringUtils.isNotBlank(principalName)) {
if (!StringUtils.contains(principalName, "*")) {
Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(
principalName);
if (principal == null) {
return null;
} else {
filteredSearchCriteria.put(userControlPostData.getPrincipalIdPropertyName(),
principal.getPrincipalId());
}
} else {
List<Person> people = KimApiServiceLocator.getPersonService().findPeople(Collections.singletonMap(
KimConstants.AttributeConstants.PRINCIPAL_NAME, principalName));
if (people != null && people.size() == 0) {
return null;
}
}
}
if (!StringUtils.contains(principalName, "*")) {
// filter
filteredSearchCriteria.remove(propertyName);
filteredSearchCriteria.remove(userControlPostData.getPersonNamePropertyName());
}
return filteredSearchCriteria;
}
private List<String> generateLongList(int itemCount) {
List<String> list = new ArrayList<>(itemCount);
for (int i = 0; i < itemCount; i++) {
list.add(Integer.toString(i));
}
return Collections.unmodifiableList(list);
}
static Set<String> getQueryParameterNames(Uri uri) {
if (uri.isOpaque()) {
throw new UnsupportedOperationException(NOT_HIERARCHICAL);
}
String query = uri.getEncodedQuery();
if (query == null) {
return Collections.emptySet();
}
Set<String> names = new LinkedHashSet<String>();
int start = 0;
do {
int next = query.indexOf('&', start);
int end = (next == -1) ? query.length() : next;
int separator = query.indexOf('=', start);
if (separator > end || separator == -1) {
separator = end;
}
String name = query.substring(start, separator);
names.add(Uri.decode(name));
// Move start to end of name
start = end + 1;
} while (start < query.length());
return Collections.unmodifiableSet(names);
}
@Override
public ICompute<I> getINode() {
// todo: fix empty map
if (computeFunc instanceof ComputeFunc) {
return new ComputeOp<>((ComputeFunc<O, I>) computeFunc, this,
Collections.emptyMap());
} else if (computeFunc instanceof ComputeCollectorFunc) {
return new ComputeCollectorOp<>((ComputeCollectorFunc<O, I>) computeFunc, this,
Collections.emptyMap());
}
throw new RuntimeException("Unknown function type for compute: " + computeFunc);
}
public static List<VQSLODTranche> findVQSLODTranches(
final List<VariantDatum> data,
final List<Double> trancheThresholds,
final SelectionMetric metric,
final VariantRecalibratorArgumentCollection.Mode model) {
logger.info(String.format("Finding %d tranches for %d variants", trancheThresholds.size(), data.size()));
Collections.sort( data, VariantDatum.VariantDatumLODComparator );
metric.calculateRunningMetric(data);
final List<VQSLODTranche> tranches = new ArrayList<>();
for ( double trancheThreshold : trancheThresholds ) {
VQSLODTranche t = findVQSLODTranche(data, metric, trancheThreshold, model);
if ( t == null ) {
if ( tranches.size() == 0 ) {
throw new UserException(String.format(
"Couldn't find any tranche containing variants with a %s > %.2f. Are you sure the truth files contain unfiltered variants which overlap the input data?",
metric.getName(),
metric.getThreshold(trancheThreshold)));
}
break;
}
tranches.add(t);
}
return tranches;
}
protected DiskStoreDetails getDiskStoreDescription(final String memberName, final String diskStoreName) {
final DistributedMember member = getMember(getCache(), memberName); // may throw a MemberNotFoundException
final ResultCollector<?, ?> resultCollector = getMembersFunctionExecutor(Collections.singleton(member))
.withArgs(diskStoreName).execute(new DescribeDiskStoreFunction());
final Object result = ((List<?>) resultCollector.getResult()).get(0);
if (result instanceof DiskStoreDetails) { // disk store details in hand...
return (DiskStoreDetails) result;
}
else if (result instanceof DiskStoreNotFoundException) { // bad disk store name...
throw (DiskStoreNotFoundException) result;
}
else { // unknown and unexpected return type...
final Throwable cause = (result instanceof Throwable ? (Throwable) result : null);
if (isLogging()) {
if (cause != null) {
getGfsh().logSevere(String.format(
"Exception (%1$s) occurred while executing '%2$s' on member (%3$s) with disk store (%4$s).",
ClassUtils.getClassName(cause), CliStrings.DESCRIBE_DISK_STORE, memberName, diskStoreName), cause);
}
else {
getGfsh().logSevere(String.format(
"Received an unexpected result of type (%1$s) while executing '%2$s' on member (%3$s) with disk store (%4$s).",
ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE, memberName, diskStoreName), null);
}
}
throw new RuntimeException(CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE), cause);
}
}
public List<Subscription> sortResults(String sortingInstructions, final boolean ascending, List<Subscription> list) {
if (sortingInstructions != null) {
Comparator<Subscription> comparator = null;
if (sortingInstructions.equals("eventSinkAddress")) {
comparator = new Comparator<Subscription>() {
public int compare(Subscription o1, Subscription o2) {
if (o2 == null || o1 == null) {
return 0;
}
return (ascending ? 1 : -1) * o1.getEventSinkURL().compareTo(o2.getEventSinkURL());
}
};
} else if (sortingInstructions.equals("createdTime")) {
comparator = new Comparator<Subscription>() {
public int compare(Subscription o1, Subscription o2) {
if (o2 == null || o1 == null) {
return 0;
}
return (ascending ? 1 : -1) * o1.getCreatedTime().compareTo(o2.getCreatedTime());
}
};
} else if (sortingInstructions.equals("subscriptionEndingTime")) {
comparator = new Comparator<Subscription>() {
public int compare(Subscription o1, Subscription o2) {
if (o2 == null || o1 == null) {
return 0;
}
return (ascending ? 1 : -1) * o1.getExpires().compareTo(o2.getExpires());
}
};
}
if (comparator != null) {
Collections.sort(list, comparator);
}
}
return list;
}
@SuppressWarnings("unchecked")
public Set<AttributeRef> findAttributes(DirectedGraph<AttributeRef, ExtendedEdge> dependencyGraph, Scenario scenario) {
if (dependencyGraph == null) {
return Collections.EMPTY_SET;
}
if (logger.isDebugEnabled()) logger.debug("Finding attributes with null in dependency graph\n" + dependencyGraph);
Set<AttributeRef> initialAttributes = findInitialAttributes(scenario);
if (logger.isDebugEnabled()) logger.debug("Initial attributes with nulls: " + initialAttributes);
Set<AttributeRef> result = findReachableAttribuesOnGraph(initialAttributes, dependencyGraph);
if (logger.isDebugEnabled()) logger.debug("Attributes with nulls: " + result);
return result;
}