下面列出了怎么用java.util.Arrays的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void recoverWithRecursiveList(){
AtomicInteger count = new AtomicInteger(0);
List<Integer> result = of(1, 2, 3).<Integer>map(i -> {
throw new RuntimeException();
})
.recoverWith(e->of(100,200,300).peek(i-> {
if (count.incrementAndGet() < 200)
throw new RuntimeException();
}))
.stream()
.toList();
assertThat(count.get(),greaterThan(200));
assertThat(result,equalTo(Arrays.asList(100,200,300)));
}
@Test
public void testGetBusinessObjectDataNotificationRegistrationsByNotificationFilterTrimParameters()
{
// Create a business object data notification registration key.
NotificationRegistrationKey notificationRegistrationKey = new NotificationRegistrationKey(NAMESPACE, NOTIFICATION_NAME);
// Create and persist a business object data notification registration entity.
notificationRegistrationDaoTestHelper.createBusinessObjectDataNotificationRegistrationEntity(notificationRegistrationKey,
NotificationEventTypeEntity.EventTypesBdata.BUS_OBJCT_DATA_STTS_CHG.name(), BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE,
FORMAT_VERSION, STORAGE_NAME, BDATA_STATUS, BDATA_STATUS_2, notificationRegistrationDaoTestHelper.getTestJobActions(),
NotificationRegistrationStatusEntity.ENABLED);
// Retrieve a list of business object data notification registration keys using input parameters with leading and trailing empty spaces.
assertEquals(new BusinessObjectDataNotificationRegistrationKeys(Arrays.asList(notificationRegistrationKey)),
businessObjectDataNotificationRegistrationService.getBusinessObjectDataNotificationRegistrationsByNotificationFilter(
new BusinessObjectDataNotificationFilter(addWhitespace(BDEF_NAMESPACE), addWhitespace(BDEF_NAME), addWhitespace(FORMAT_USAGE_CODE),
addWhitespace(FORMAT_FILE_TYPE_CODE), NO_FORMAT_VERSION, NO_STORAGE_NAME, NO_BDATA_STATUS, NO_BDATA_STATUS)));
}
@Test
public void removeOperationAfterDelete_addRemove_subsequentOperationsAreNotAffected() {
List<String> items = resetToRemoveAfterAddCase();
nodeList.add("foo");
int index = items.size();
nodeList.remove(index);
nodeList.remove(index - 1);
// As a result: "remove" and "add" before it are discarded and the last
// "remove" operation is not affected
List<NodeChange> changes = collectChanges(nodeList);
Assert.assertEquals(1, changes.size());
Assert.assertTrue(changes.get(0) instanceof ListRemoveChange<?>);
verifyRemoved(changes, Arrays.asList(items.get(index - 1)), index - 1);
}
public void testGetJsonMapConfig() throws Exception {
config.clear();
Map<String, Object> configMap = config.getJsonMapConfig("test");
// case1: regular config
Assert.assertEquals("default config", configMap.get("value"));
// case2: config with environment variable
if (!OS.startsWith("windows")) {
Assert.assertEquals(System.getenv("HOME"), configMap.get("value1"));
}
// case3: escape from injecting environment variable
Assert.assertEquals("${ESCAPE}", configMap.get("value2"));
// case4: override to map with centralized file
Assert.assertEquals("test", configMap.get("value3"));
// case5: override to map with centralized file
Assert.assertEquals(Arrays.asList("element1", "element2"), configMap.get("value4"));
// case6: override to map with centralized file
Assert.assertEquals(testMap, configMap.get("value5"));
// case7: default value start with $ but not escape
Assert.assertEquals("$abc", configMap.get("value6"));
}
@Test
public void testFindByDomain() throws TechnicalException {
// create resource_set, resource_scopes being the most important field.
Resource resource1 = new Resource().setResourceScopes(Arrays.asList("a","b","c")).setDomain(DOMAIN_ID).setClientId(CLIENT_ID).setUserId(USER_ID);
Resource resource2 = new Resource().setResourceScopes(Arrays.asList("d","e","f")).setDomain(DOMAIN_ID).setClientId(CLIENT_ID).setUserId(USER_ID);
repository.create(resource1).blockingGet();
repository.create(resource2).blockingGet();
// fetch applications
TestObserver<Page<Resource>> testObserver = repository.findByDomain(DOMAIN_ID, 0, Integer.MAX_VALUE).test();
testObserver.awaitTerminalEvent();
testObserver.assertComplete();
testObserver.assertNoErrors();
testObserver.assertValue(resources -> resources.getData().size() == 2);
}
@Test
public void insert_Success() {
String id = "nm0000001";
Person newPerson = new Person();
newPerson.nconst = id;
newPerson.birthYear = 2020;
newPerson.primaryName = "Tim Tam";
newPerson.primaryProfession = Arrays.asList("Test", "Dancer");
assertThat(this.repo.insert(newPerson), is(newPerson));
assertThat(this.repo.count(), is(2L));
Person actual = this.repo.findById(id).get();
assertThat(actual.nconst, is(id));
assertThat(actual.primaryName, is("Tim Tam"));
assertThat(actual.birthYear, is(2020));
assertThat(actual.deathYear, is(nullValue()));
assertThat(actual.primaryProfession, is(Arrays.asList("Test", "Dancer")));
assertThat(actual.knownForTitles, is(nullValue()));
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FormatTest formatTest = (FormatTest) o;
return Objects.equals(this.integer, formatTest.integer) &&
Objects.equals(this.int32, formatTest.int32) &&
Objects.equals(this.int64, formatTest.int64) &&
Objects.equals(this.number, formatTest.number) &&
Objects.equals(this._float, formatTest._float) &&
Objects.equals(this._double, formatTest._double) &&
Objects.equals(this.string, formatTest.string) &&
Arrays.equals(this._byte, formatTest._byte) &&
Objects.equals(this.binary, formatTest.binary) &&
Objects.equals(this.date, formatTest.date) &&
Objects.equals(this.dateTime, formatTest.dateTime) &&
Objects.equals(this.uuid, formatTest.uuid) &&
Objects.equals(this.password, formatTest.password) &&
Objects.equals(this.bigDecimal, formatTest.bigDecimal);
}
@Test
public void testCreatedSigAndPubkeyAreCanonical() throws Exception {
// Tests that we will not generate non-canonical pubkeys or signatures
// We dump failed data to error log because this test is not expected to be deterministic
ECKey key = new ECKey();
if (!ECKey.isPubKeyCanonical(key.getPubKey())) {
log.error(Utils.HEX.encode(key.getPubKey()));
fail();
}
byte[] hash = new byte[32];
new Random().nextBytes(hash);
byte[] sigBytes = key.sign(Sha256Hash.wrap(hash)).encodeToDER();
byte[] encodedSig = Arrays.copyOf(sigBytes, sigBytes.length + 1);
encodedSig[sigBytes.length] = Transaction.SigHash.ALL.byteValue();
if (!TransactionSignature.isEncodingCanonical(encodedSig)) {
log.error(Utils.HEX.encode(sigBytes));
fail();
}
}
@Override
public CompletableFuture<SchemaVersion> getSchemaVersionBySchemaData(
List<SchemaAndMetadata> schemaAndMetadataList,
SchemaData schemaData) {
final CompletableFuture<SchemaVersion> completableFuture = new CompletableFuture<>();
SchemaVersion schemaVersion;
for (SchemaAndMetadata schemaAndMetadata : schemaAndMetadataList) {
if (Arrays.equals(hashFunction.hashBytes(schemaAndMetadata.schema.getData()).asBytes(),
hashFunction.hashBytes(schemaData.getData()).asBytes())) {
schemaVersion = schemaAndMetadata.version;
completableFuture.complete(schemaVersion);
return completableFuture;
}
}
completableFuture.complete(null);
return completableFuture;
}
@Test
public void testComplexField() throws SyntaxError {
HashMap<String, String> dateIntervals = new HashMap<>();
dateIntervals.put("after","[NOW+23DAYS/DAY TO *]");
dateIntervals.put("before","[* TO NOW+23DAYS/DAY]");
HashMap<String, String> numberIntervals = new HashMap<>();
numberIntervals.put("bigger","[23 TO *]");
numberIntervals.put("smaller","[* TO 22]");
SingleValuedComplexField.UtilDateComplexField<Taxonomy,Date,Date> complexDateField = new ComplexFieldDescriptorBuilder<Taxonomy,Date,Date>()
.setFacet(true, tax -> Arrays.asList(tax.getDate()))
.buildUtilDateComplexField("complexDateTax", Taxonomy.class, Date.class, Date.class);
SingleValuedComplexField.NumericComplexField<Taxonomy,Number,Number> complexNumberField = new ComplexFieldDescriptorBuilder<Taxonomy,Number,Number>()
.setFacet(true, tax -> Arrays.asList(tax.getTerm()))
.buildNumericComplexField("complexNumberTax", Taxonomy.class, Number.class, Number.class);
Assert.assertTrue(FacetMapper.stringQuery2FacetMapper(complexDateField, "dateFacet",dateIntervals).getName().equals("dateFacet"));
Assert.assertTrue(FacetMapper.stringQuery2FacetMapper(complexNumberField, "numericFacet", numberIntervals).getName().equals("numericFacet"));
Assert.assertTrue(true);
}
@Test
public void putsJobSuccessWhenBuildSucceeds() {
// given
when(mockBuild.getResult()).thenReturn(Result.SUCCESS);
when(mockJobData.getOutputArtifacts()).thenReturn(generateOutputArtifactsWithNames(Arrays.asList("artifact_1", "artifact_2")));
// when
assertTrue(publisher.perform(mockBuild, null, null));
// then
final InOrder inOrder = inOrder(mockFactory, mockAWS, mockCodePipelineClient);
inOrder.verify(mockFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION);
inOrder.verify(mockAWS).getCodePipelineClient();
inOrder.verify(mockCodePipelineClient).putJobSuccessResult(putJobSuccessResultRequest.capture());
final PutJobSuccessResultRequest request = putJobSuccessResultRequest.getValue();
assertEquals(jobId, request.getJobId());
assertEquals(BUILD_ID, request.getExecutionDetails().getExternalExecutionId());
assertEquals("Finished", request.getExecutionDetails().getSummary());
assertContainsIgnoreCase(PUBLISHING_ARTIFACTS_MESSAGE, outContent.toString());
assertContainsIgnoreCase(PUT_JOB_SUCCESS_MESSAGE, outContent.toString());
}
/** */
private void checkQueryWithRebalance(CacheMode cacheMode) throws Exception {
IgniteEx ign0 = startGrid(0);
IgniteCache<Object, Object> cache = ign0.createCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME)
.setCacheMode(cacheMode)
.setIndexedTypes(Integer.class, Integer.class));
cache.put(1, 2);
blockRebalanceSupplyMessages(ign0, DEFAULT_CACHE_NAME, getTestIgniteInstanceName(1));
startGrid(1);
startClientGrid(10);
for (Ignite ign : G.allGrids()) {
List<List<?>> res = ign.cache(DEFAULT_CACHE_NAME)
.query(new SqlFieldsQuery("select * from Integer")).getAll();
assertEquals(1, res.size());
assertEqualsCollections(Arrays.asList(1, 2), res.get(0));
}
}
@Test
public void emptyProposerReturnsNoVotes() {
final VoteProposer proposer = new VoteProposer();
assertThat(proposer.getVote(localAddress, new VoteTally(Collections.emptyList())))
.isEqualTo(Optional.empty());
assertThat(
proposer.getVote(
localAddress,
new VoteTally(
Arrays.asList(
Address.fromHexString("0"),
Address.fromHexString("1"),
Address.fromHexString("2")))))
.isEqualTo(Optional.empty());
}
public static List<ClassPath> gerClassPath(Project project) {
List<ClassPath> paths = new ArrayList<ClassPath>();
List<SourceGroup> groups = new ArrayList<SourceGroup>();
groups.addAll(Arrays.asList(ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA)));
ClassPathProvider cpp = project.getLookup().lookup(ClassPathProvider.class);
for (SourceGroup group : groups) {
ClassPath cp = cpp.findClassPath(group.getRootFolder(), ClassPath.COMPILE);
if (cp != null) {
paths.add(cp);
}
cp = cpp.findClassPath(group.getRootFolder(), ClassPath.SOURCE);
if (cp != null) {
paths.add(cp);
}
}
return paths;
}
/**
* Returns an unmodifiable Map of general request
* properties for this connection. The Map keys
* are Strings that represent the request-header
* field names. Each Map value is a unmodifiable List
* of Strings that represents the corresponding
* field values.
*
* @return a Map of the general request properties for this connection.
* @throws IllegalStateException if already connected
* @since 1.4
*/
@Override
public synchronized Map<String, List<String>> getRequestProperties() {
if (connected)
throw new IllegalStateException("Already connected");
// exclude headers containing security-sensitive info
if (setUserCookies) {
return requests.getHeaders(EXCLUDE_HEADERS);
}
/*
* The cookies in the requests message headers may have
* been modified. Use the saved user cookies instead.
*/
Map<String, List<String>> userCookiesMap = null;
if (userCookies != null || userCookies2 != null) {
userCookiesMap = new HashMap<>();
if (userCookies != null) {
userCookiesMap.put("Cookie", Arrays.asList(userCookies));
}
if (userCookies2 != null) {
userCookiesMap.put("Cookie2", Arrays.asList(userCookies2));
}
}
return requests.filterAndAddHeaders(EXCLUDE_HEADERS2, userCookiesMap);
}
@Test
public void boundariesShouldBeDefinedByTheLowestAndHighestPoints() {
Coords3d c1 = new Coords3d(0.0, 10.0, 20.0);
Coords3d c2 = new Coords3d(15.5, 7.0, 30.0);
Coords3d c3 = new Coords3d(20.0, 3.14, 40.0);
Coords3d c4 = new Coords3d(25.0, 5, 60.0);
Triangle3d t1 = new Triangle3d(c1, c2, c3);
Triangle3d t2 = new Triangle3d(c2, c3, c4);
Polyhedron polyhedron = new Polyhedron(Arrays.asList(t1, t2));
Boundaries3d boundaries = polyhedron.getBoundaries();
assertDoubleEquals(0.0, boundaries.getX().getMin());
assertDoubleEquals(25.0, boundaries.getX().getMax());
assertDoubleEquals(3.14, boundaries.getY().getMin());
assertDoubleEquals(10.0, boundaries.getY().getMax());
assertDoubleEquals(20.0, boundaries.getZ().getMin());
assertDoubleEquals(60.0, boundaries.getZ().getMax());
}
private static boolean checkOptionArgsNumber(Option[] options) {
for (Option option : options) {
int argNb = option.getArgs();
String[] args = option.getValues();
if (argNb == 0) {
if (args != null && args.length > 0) {
System.err.println(option.getArgName() + " shall have " + argNb + " arguments (was "
+ Arrays.toString(args) + ")");
return false;
}
} else {
if (args == null || args.length != argNb) {
System.err.println(option.getArgName() + " shall have " + argNb + " arguments (was "
+ Arrays.toString(args) + ")");
return false;
}
}
}
return true;
}
@Test
public void testBasic()
{
Migration m1 = () -> Arrays.asList(v1opA, v1opB);
Migration m2 = () -> Collections.singletonList(v2op);
Migration m3 = () -> Collections.singletonList(v3op);
MigrationSet migrationSet = MigrationSet.build("1", Arrays.asList(m1, m2, m3));
complete(manager.migrate(migrationSet));
ModeledFramework<ModelV3> v3Client = ModeledFramework.wrap(client, v3Spec);
complete(v3Client.read(), (m, e) -> {
Assert.assertEquals(m.getAge(), 30);
Assert.assertEquals(m.getFirstName(), "One");
Assert.assertEquals(m.getLastName(), "Two");
});
int count = manager.debugCount.get();
complete(manager.migrate(migrationSet));
Assert.assertEquals(manager.debugCount.get(), count); // second call should do nothing
}
static Vector<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
List<String> formats = inputUri.getQueryParameters(Intents.Scan.SCAN_FORMATS);
if (formats != null && formats.size() == 1 && formats.get(0) != null){
formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
}
return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
}
void add(Method m) {
if (length == methods.length) {
methods = Arrays.copyOf(methods, 2 * methods.length);
}
methods[length++] = m;
if (m != null && m.isDefault())
defaults++;
}
@Test
public void testInsertByteArrayField() {
byte[] salt = new byte[16];
random.nextBytes(salt);
ByteArrayField entity = new ByteArrayField();
entity.setSalt(salt);
entity = em.insert(entity);
entity = em.load(ByteArrayField.class, entity.getId());
assertTrue(entity.getId() > 0 && Arrays.equals(entity.getSalt(), salt));
}
@Override
public void fill(final Element... elements) {
final Queue<Element> queue = new LinkedList<>(
Arrays.asList(Objects.requireNonNull(elements))
);
forEachSlot((y, x) -> {
if (queue.isEmpty()) {
queue.addAll(Arrays.asList(elements));
}
if (paneElements[y][x].is(emptyElement())) {
paneElements[y][x] = queue.poll();
}
});
this.source.notifyTargets(new Object());
}
@Override
public String toString() {
return "ChunkIndex("
+ "length="
+ length
+ ", sizes="
+ Arrays.toString(sizes)
+ ", offsets="
+ Arrays.toString(offsets)
+ ", timeUs="
+ Arrays.toString(timesUs)
+ ", durationsUs="
+ Arrays.toString(durationsUs)
+ ")";
}
void test(String name, String... expected) {
List<Name> result = enclosingCandidates(names.fromString(name));
if (!result.isEmpty() || expected.length != 0) {
Name[] expectedNames = new Name[expected.length];
int i = 0;
for (String s : expected)
expectedNames[i++] = names.fromString(s);
if (!Arrays.equals(result.toArray(), expectedNames))
throw new AssertionError(name + " : " +
Arrays.toString(expectedNames) + " != " + result);
}
System.out.format((Locale)null, "OK: %s -> [%s]%n", name, result);
}
private boolean matchSubjectKeyID(X509Certificate xcert) {
if (ski == null) {
return true;
}
try {
byte[] extVal = xcert.getExtensionValue("2.5.29.14");
if (extVal == null) {
if (debug != null) {
debug.println("AdaptableX509CertSelector.match: "
+ "no subject key ID extension. Subject: "
+ xcert.getSubjectX500Principal());
}
return true;
}
DerInputStream in = new DerInputStream(extVal);
byte[] certSubjectKeyID = in.getOctetString();
if (certSubjectKeyID == null ||
!Arrays.equals(ski, certSubjectKeyID)) {
if (debug != null) {
debug.println("AdaptableX509CertSelector.match: "
+ "subject key IDs don't match. "
+ "Expected: " + Arrays.toString(ski) + " "
+ "Cert's: " + Arrays.toString(certSubjectKeyID));
}
return false;
}
} catch (IOException ex) {
if (debug != null) {
debug.println("AdaptableX509CertSelector.match: "
+ "exception in subject key ID check");
}
return false;
}
return true;
}
/**
* Creates a new instance of Epoch for acceptors
*
* @param controller
* @param parent
* Consensus to which this epoch belongs
* @param timestamp
* Timestamp of the epoch
*/
public Epoch(ServerViewController controller, Consensus parent, int timestamp) {
this.consensus = parent;
this.timestamp = timestamp;
this.controller = controller;
this.proof = new HashSet<>();
// ExecutionManager manager = consensus.getManager();
this.lastView = controller.getCurrentView();
this.me = controller.getStaticConf().getProcessId();
// int[] acceptors = manager.getAcceptors();
int n = controller.getCurrentViewN();
writeSetted = new boolean[n];
acceptSetted = new boolean[n];
Arrays.fill(writeSetted, false);
Arrays.fill(acceptSetted, false);
if (timestamp == 0) {
this.write = new byte[n][];
this.accept = new byte[n][];
Arrays.fill((Object[]) write, null);
Arrays.fill((Object[]) accept, null);
} else {
Epoch previousEpoch = consensus.getEpoch(timestamp - 1, controller);
this.write = previousEpoch.getWrite();
this.accept = previousEpoch.getAccept();
}
}
MessagingWhen(BlockBuilder blockBuilder,
GeneratedClassMetaData generatedClassMetaData) {
this.blockBuilder = blockBuilder;
this.generatedClassMetaData = generatedClassMetaData;
this.whens.addAll(Arrays.asList(new MessagingTriggeredByWhen(this.blockBuilder),
new MessagingBodyWhen(this.blockBuilder),
new MessagingAssertThatWhen(this.blockBuilder)));
}
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers", "192.169.0.23:9092");
System.out.println("this is the group part test 1");
//消费者的组id
props.put("group.id", "GroupA");//这里是GroupA或者GroupB
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
//从poll(拉)的回话处理时长
props.put("session.timeout.ms", "30000");
//poll的数量限制
//props.put("max.poll.records", "100");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
//订阅主题列表topic
consumer.subscribe(Arrays.asList("foo"));
while (true) {
ConsumerRecords<String, String> records =consumer.poll(100);
for (ConsumerRecord<String, String> record : records)
// 正常这里应该使用线程池处理,不应该在这里处理
System.out.printf("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value()+"\n");
}
}
private void initCombinedFrom(List<ConfigModel> configModels) {
for (ConfigModel model : configModels) {
Configuration conf = ConfigUtil.createLocalConfig(Arrays.asList(model));
String name =
conf.getString(CONFIG_QUALIFIED_MICROSERVICE_NAME_KEY, DEFAULT_MICROSERVICE_NAME);
if (!StringUtils.isEmpty(name)) {
checkMicroserviceName(name);
combinedFrom.add(name);
}
}
combinedFrom.remove(microserviceName);
}
@Override
List<List<ClassKind>> permutations() {
return Arrays.asList(
Arrays.asList(ClassKind.A, ClassKind.B, ClassKind.C),
Arrays.asList(ClassKind.A, ClassKind.B, ClassKind.C),
Arrays.asList(ClassKind.B, ClassKind.A, ClassKind.C),
Arrays.asList(ClassKind.B, ClassKind.C, ClassKind.A),
Arrays.asList(ClassKind.C, ClassKind.A, ClassKind.B),
Arrays.asList(ClassKind.C, ClassKind.B, ClassKind.A)
);
}