Java 类java.util.Collections 实例源码
项目:gigreminder
文件:GoogleMusicSource.java
@Override
public List<String> loadArtists(Context context) {
try (Cursor cursor = context.getContentResolver().query(
URI, PROJECTION, null, null, null)) {
if (cursor == null) {
throw new IllegalStateException("No cursor was obtained");
}
Set<String> artistsSet = new HashSet<>();
while (cursor.moveToNext()) {
int columnIndex = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
String artist = cursor.getString(columnIndex);
if (!artist.isEmpty()) {
artistsSet.add(artist);
}
}
List<String> artists = Arrays.asList(artistsSet.toArray(new String[artistsSet.size()]));
Collections.sort(artists);
return artists;
}
}
项目:ultrasonic
文件:SearchActivity.java
private void onSongSelected(MusicDirectory.Entry song, boolean save, boolean append, boolean autoplay, boolean playNext)
{
DownloadService downloadService = getDownloadService();
if (downloadService != null)
{
if (!append && !playNext)
{
downloadService.clear();
}
downloadService.download(Collections.singletonList(song), save, false, playNext, false, false);
if (autoplay)
{
downloadService.play(downloadService.size() - 1);
}
Util.toast(SearchActivity.this, getResources().getQuantityString(R.plurals.select_album_n_songs_added, 1, 1));
}
}
项目:Tarski
文件:VizGraphPanel.java
/** True if this TypePanel object does not need to be rebuilt. */
private boolean upToDate(final AlloyType type, List<AlloyAtom> atoms) {
if (!this.type.equals(type)) {
return false;
}
atoms = new ArrayList<AlloyAtom>(atoms);
Collections.sort(atoms);
if (!this.atoms.equals(atoms)) {
return false;
}
for (int i = 0; i < this.atoms.size(); i++) {
final String n = this.atoms.get(i).getVizName(VizGraphPanel.this.vizState, true);
if (!this.atomnames[i].equals(n)) {
return false;
}
}
return true;
}
项目:kafka-0.11.0.0-src-with-comment
文件:ProduceRequestTest.java
@Test
public void shouldBeFlaggedAsIdempotentWhenIdempotentRecords() throws Exception {
final MemoryRecords memoryRecords = MemoryRecords.withIdempotentRecords(1,
CompressionType.NONE,
1L,
(short) 1,
1,
1,
simpleRecord);
final ProduceRequest request = new ProduceRequest.Builder(RecordBatch.CURRENT_MAGIC_VALUE,
(short) -1,
10,
Collections.singletonMap(
new TopicPartition("topic", 1), memoryRecords)).build();
assertTrue(request.isIdempotent());
}
项目:Mods
文件:ItemWrangler.java
@Override
public void draw(WeaponsCapability weaponsCapability, ItemStack stack, final EntityLivingBase living, World world) {
super.draw(weaponsCapability, stack, living, world);
if (!world.isRemote) {
weaponsCapability.controlledSentry = null;
List<EntitySentry> list = world.getEntitiesWithinAABB(EntitySentry.class,
living.getEntityBoundingBox().grow(128, 128, 128), new Predicate<EntitySentry>() {
@Override
public boolean apply(EntitySentry input) {
// TODO Auto-generated method stub
return input.getOwner() == living && !input.isDisabled();
}
});
Collections.sort(list, new EntityAINearestAttackableTarget.Sorter(living));
if (!list.isEmpty()) {
list.get(0).setControlled(true);
weaponsCapability.controlledSentry = list.get(0);
}
}
}
项目:openjdk-jdk10
文件:OpenMBeanAttributeInfoSupport.java
static <T> Descriptor makeDescriptor(OpenType<T> openType,
T defaultValue,
T[] legalValues,
Comparable<T> minValue,
Comparable<T> maxValue) {
Map<String, Object> map = new HashMap<String, Object>();
if (defaultValue != null)
map.put("defaultValue", defaultValue);
if (legalValues != null) {
Set<T> set = new HashSet<T>();
for (T v : legalValues)
set.add(v);
set = Collections.unmodifiableSet(set);
map.put("legalValues", set);
}
if (minValue != null)
map.put("minValue", minValue);
if (maxValue != null)
map.put("maxValue", maxValue);
if (map.isEmpty()) {
return openType.getDescriptor();
} else {
map.put("openType", openType);
return new ImmutableDescriptor(map);
}
}
项目:incubator-netbeans
文件:RemoveTest.java
public void testRemoveUntrackedFile () throws Exception {
File file = new File(workDir, "toRemove");
file.createNewFile();
assertTrue(file.exists());
GitClient client = getClient(workDir);
Map<File, GitStatus> statuses = client.getStatus(new File[] { file }, NULL_PROGRESS_MONITOR);
assertEquals(1, statuses.size());
assertStatus(statuses, workDir, file, false, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_ADDED, GitStatus.Status.STATUS_ADDED, false);
Monitor m = new Monitor();
client.addNotificationListener(m);
client.remove(new File[] { file }, false, m);
assertFalse(file.exists());
assertEquals(Collections.singleton(file), m.notifiedFiles);
statuses = client.getStatus(new File[] { file }, NULL_PROGRESS_MONITOR);
assertEquals(0, statuses.size());
}
项目:MyAnimeViewer
文件:OfflineHistoryRecyclerAdapter.java
public void addLibraryRecordList(List<OfflineHistoryRecord> offlineRecords) {
if (offlineRecords == null || offlineRecords == Collections.EMPTY_LIST)
return;
//checkLibraryRecord(offlineRecords);
int startPos = 0;
if (mItems != null) {
startPos = this.mItems.size();
this.mItems.addAll(offlineRecords);
} else {
this.mItems = offlineRecords;
}
mResults = (List<OfflineHistoryRecord>) ((ArrayList<OfflineHistoryRecord>) mItems).clone();
if (offlineRecords.size() > 1)
this.notifyItemRangeInserted(startPos, offlineRecords.size() - 1);
else
this.notifyItemRangeInserted(startPos, 1);
}
项目:athena
文件:RouterTest.java
/**
* Tests deleting a IPv4 route entry.
*/
@Test
public void testIpv4RouteDelete() {
// Firstly add a route
testIpv4RouteAdd();
RouteEntry deleteRouteEntry = new RouteEntry(
Ip4Prefix.valueOf("1.1.1.0/24"),
Ip4Address.valueOf("192.168.10.1"));
FibEntry deleteFibEntry = new FibEntry(
Ip4Prefix.valueOf("1.1.1.0/24"), null, null);
reset(fibListener);
fibListener.update(Collections.emptyList(), Collections.singletonList(
new FibUpdate(FibUpdate.Type.DELETE, deleteFibEntry)));
replay(fibListener);
router.processRouteUpdates(Collections.singletonList(
new RouteUpdate(RouteUpdate.Type.DELETE, deleteRouteEntry)));
verify(fibListener);
}
项目:CommentView
文件:Extractor.java
/**
* Extract $cashtag references from Tweet text.
*
* @param text of the tweet from which to extract cashtags
* @return List of cashtags referenced (without the leading $ sign)
*/
public List<Entity> extractCashtagsWithIndices(String text) {
if (text == null || text.length() == 0) {
return Collections.emptyList();
}
// Performance optimization.
// If text doesn't contain $, text doesn't contain
// cashtag, so we can simply return an empty list.
if (text.indexOf('$') == -1) {
return Collections.emptyList();
}
List<Entity> extracted = new ArrayList<Entity>();
Matcher matcher = Regex.VALID_CASHTAG.matcher(text);
while (matcher.find()) {
extracted.add(new Entity(matcher, Type.CASHTAG, Regex.VALID_CASHTAG_GROUP_CASHTAG));
}
return extracted;
}
项目:jdk8u-jdk
文件:SctpChannelImpl.java
@Override
public Set<SocketAddress> getRemoteAddresses()
throws IOException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (!isConnected() || isShutdown)
return Collections.emptySet();
try {
return SctpNet.getRemoteAddresses(fdVal, 0/*unused*/);
} catch (SocketException unused) {
/* an open connected channel should always have remote addresses */
return remoteAddresses;
}
}
}
项目:r8
文件:BinopLiteralTest.java
@Test
public void lit16NotSupported() {
String[] lit8OnlyBinops = new String[]{
"shl", "shr", "ushr",
};
for (String binop : lit8OnlyBinops) {
for (int lit16Value : lit16Values) {
DexEncodedMethod method = oneMethodApplication(
"int", Collections.singletonList("int"),
1,
" const/16 v0, " + lit16Value,
" " + binop + "-int/2addr p0, v0 ",
" return p0"
);
DexCode code = method.getCode().asDexCode();
assertEquals(3, code.instructions.length);
assertTrue(code.instructions[0] instanceof Const16);
assertEquals(lit16Value, ((Const16) code.instructions[0]).BBBB);
assertTrue(code.instructions[2] instanceof Return);
}
}
}
项目:Servlet-4.0-Sampler
文件:PushCacheFilter.java
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
HttpServletMapping mapping = ((HttpServletRequest) request).getHttpServletMapping();
String resourceURI = mapping.getMatchValue();
if (mapping.getServletName().equals("jsp")) {
// Push resources
resourceCache.keySet().stream()
.filter(resourceURI::contains)
.findFirst()
.ifPresent(s -> resourceCache.get(s)
.forEach(path -> httpServletRequest.newPushBuilder().path(path).push()));
// create empty resource list if absent
resourceCache.putIfAbsent(resourceURI, Collections.newSetFromMap(new ConcurrentHashMap<>()));
} else {
// Add resource
resourceCache.keySet().stream()
.filter(httpServletRequest.getHeader("Referer")::contains)
.forEach(page -> resourceCache.get(page).add(resourceURI));
}
chain.doFilter(request, response);
}
项目:hashsdn-controller
文件:SimpleIdentityRefAttributeReadingStrategyTest.java
@Test
public void testReadIdRef() throws Exception {
final Map<String, Map<Date, IdentityMapping>> identityMapping = Maps.newHashMap();
final IdentityMapping value = new IdentityMapping();
final Date rev = new Date();
identityMapping.put("namespace", Collections.singletonMap(rev, value));
identityMapping.put("inner", Collections.singletonMap(rev, value));
final SimpleIdentityRefAttributeReadingStrategy key = new SimpleIdentityRefAttributeReadingStrategy(null, "key",
identityMapping);
String read = key.readElementContent(XmlElement.fromString("<el xmlns=\"namespace\">local</el>"));
assertEquals(
org.opendaylight.yangtools.yang.common.QName.create(URI.create("namespace"), rev, "local").toString(),
read);
read = key.readElementContent(XmlElement.fromString("<el xmlns:a=\"inner\" xmlns=\"namespace\">a:local</el>"));
assertEquals(org.opendaylight.yangtools.yang.common.QName.create(URI.create("inner"), rev, "local").toString(),
read);
read = key.readElementContent(
XmlElement.fromString("<top xmlns=\"namespace\"><el>local</el></top>").getOnlyChildElement());
assertEquals(
org.opendaylight.yangtools.yang.common.QName.create(URI.create("namespace"), rev, "local").toString(),
read);
}
项目:hashsdn-controller
文件:DistributedShardedDOMDataTree.java
void resolveShardAdditions(final Set<DOMDataTreeIdentifier> additions) {
LOG.debug("{}: Resolving additions : {}", memberName, additions);
final ArrayList<DOMDataTreeIdentifier> list = new ArrayList<>(additions);
// we need to register the shards from top to bottom, so we need to atleast make sure the ordering reflects that
Collections.sort(list, (o1, o2) -> {
if (o1.getRootIdentifier().getPathArguments().size() < o2.getRootIdentifier().getPathArguments().size()) {
return -1;
} else if (o1.getRootIdentifier().getPathArguments().size()
== o2.getRootIdentifier().getPathArguments().size()) {
return 0;
} else {
return 1;
}
});
list.forEach(this::createShardFrontend);
}
项目:BiglyBT
文件:ConsoleInput.java
protected void
registerAlertHandler()
{
com.biglybt.core.logging.Logger.addListener(new ILogAlertListener() {
private java.util.Set history = Collections.synchronizedSet( new HashSet());
@Override
public void alertRaised(LogAlert alert) {
if (!alert.repeatable) {
if ( history.contains( alert.text )){
return;
}
history.add( alert.text );
}
out.println( alert.text );
if (alert.err != null)
alert.err.printStackTrace( out );
}
});
}
项目:NBANDROID-V2
文件:ApkUtils.java
public static void gradleSignApk(NbGradleProject project, String displayName, List<String> tasks, KeystoreSelector keystoreSelector, File out) {
GradleCommandTemplate.Builder builder = new GradleCommandTemplate.Builder(
displayName != null ? displayName : "", tasks);
List<String> arguments = new ArrayList<>();
arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_STORE_FILE, keystoreSelector.getStoreFile().getAbsolutePath()));
arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_STORE_PASSWORD, keystoreSelector.getStorePassword()));
arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_KEY_ALIAS, keystoreSelector.getKeyAlias()));
arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_KEY_PASSWORD, keystoreSelector.getKeyPassword()));
arguments.add(createArgument(AndroidProject.PROPERTY_APK_LOCATION, out.getAbsolutePath()));
// These were introduced in 2.3, but gradle doesn't care if it doesn't know the properties and so they don't affect older versions.
arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_V1_ENABLED, Boolean.toString(keystoreSelector.isV1SigningEnabled())));
arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_V2_ENABLED, Boolean.toString(keystoreSelector.isV2SigningEnabled())));
builder.setArguments(arguments);
builder.setJvmArguments(Collections.EMPTY_LIST);
builder.setBlocking(true);
executeCommandTemplate(project, builder.create());
}
项目:elasticsearch-aem
文件:ElasticSearchTransportHandler.java
private ReplicationResult doDeactivate(TransportContext ctx, ReplicationTransaction tx, RestClient restClient) throws ReplicationException, JSONException, IOException {
ReplicationLog log = tx.getLog();
ObjectMapper mapper = new ObjectMapper();
IndexEntry content = mapper.readValue(tx.getContent().getInputStream(), IndexEntry.class);
Response deleteResponse = restClient.performRequest(
"DELETE",
"/" + content.getIndex() + "/" + content.getType() + "/" + DigestUtils.md5Hex(content.getPath()),
Collections.<String, String>emptyMap());
LOG.debug(deleteResponse.toString());
log.info(getClass().getSimpleName() + ": Delete Call returned " + deleteResponse.getStatusLine().getStatusCode() + ": " + deleteResponse.getStatusLine().getReasonPhrase());
if (deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED || deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ReplicationResult.OK;
}
LOG.error("Could not delete " + content.getType() + " at " + content.getPath());
return new ReplicationResult(false, 0, "Replication failed");
}
项目:incubator-netbeans
文件:GlobalPathRegistryTest.java
public void testMemoryLeak124055 () throws Exception {
final GlobalPathRegistry reg = GlobalPathRegistry.getDefault();
final Set<? extends ClassPath> src = reg.getPaths(ClassPath.SOURCE);
final Set<? extends ClassPath> boot = reg.getPaths(ClassPath.BOOT);
final Set<? extends ClassPath> compile = reg.getPaths(ClassPath.COMPILE);
assertTrue(src.isEmpty());
assertTrue(boot.isEmpty());
assertTrue(compile.isEmpty());
assertEquals(Collections.<FileObject>emptySet(), reg.getSourceRoots());
r.register(ClassPath.COMPILE, new ClassPath[] {cp3});
SFBQImpl query = Lookup.getDefault().lookup(SFBQImpl.class);
query.addPair(cp3.getRoots()[0].toURL(),cp4.getRoots());
//There should be one translated source root
assertEquals(1, reg.getSourceRoots().size());
assertEquals(1, reg.getResults().size());
r.unregister(ClassPath.COMPILE, new ClassPath[] {cp3});
//There shouldn't be registered source root
assertTrue(reg.getSourceRoots().isEmpty());
assertTrue(reg.getResults().isEmpty());
}
项目:buenojo
文件:PhotoLocationAnnotatedResourceFactory.java
/**
*
* @param allResources
* @param filteredResorces
* @param filteredResourcesRatio
* @param count
* @return
*/
private ArrayList<IKeywordAnnotated>shuffleWithRandomAndKeywordFilteredImages(ArrayList<IKeywordAnnotated>allResources,ArrayList<IKeywordAnnotated> filteredResources, Float filteredResourcesRatio, Integer count){
Integer randomCount = Math.round(count *filteredResourcesRatio);
Integer filteredCount = Math.round(count * (1-filteredResourcesRatio));
Random random = new Random ();
IKeywordAnnotated randomResources[] = new IKeywordAnnotated[randomCount];
randomResources = BuenOjoRandomUtils.pickSample(randomResources, randomCount, random);
IKeywordAnnotated filteredResourcesArray[] = filteredResources.toArray(new IKeywordAnnotated[filteredResources.size()]);
filteredResourcesArray = BuenOjoRandomUtils.pickSample(filteredResourcesArray, filteredCount, random);
ArrayList<IKeywordAnnotated> result = new ArrayList<>(count);
Collections.addAll(result, randomResources);
Collections.addAll(result, filteredResourcesArray);
Collections.shuffle(result,random);
return result;
}
项目:elasticsearch_my
文件:TribeServiceTests.java
public void testMergeCustomMetaDataSimple() {
Map<String, MetaData.Custom> mergedCustoms =
TribeService.mergeChangedCustomMetaData(Collections.singleton(MergableCustomMetaData1.TYPE),
s -> Collections.singletonList(new MergableCustomMetaData1("data1")));
TestCustomMetaData mergedCustom = (TestCustomMetaData) mergedCustoms.get(MergableCustomMetaData1.TYPE);
assertThat(mergedCustom, instanceOf(MergableCustomMetaData1.class));
assertNotNull(mergedCustom);
assertEquals(mergedCustom.getData(), "data1");
}
项目:monarch
文件:InvalidateOperation.java
@Override
public List getOperations() {
byte deserializationPolicy = DistributedCacheOperation.DESERIALIZATION_POLICY_NONE;
QueuedOperation qOp = new QueuedOperation(getOperation(), this.key, null, null,
deserializationPolicy, this.callbackArg);
return Collections.singletonList(qOp);
}
项目:elasticsearch_my
文件:IndexSearcherWrapperTests.java
FieldMaskingReader(String field, DirectoryReader in, AtomicInteger closeCalls) throws IOException {
super(in, new SubReaderWrapper() {
@Override
public LeafReader wrap(LeafReader reader) {
return new FieldFilterLeafReader(reader, Collections.singleton(field), true);
}
});
this.closeCalls = closeCalls;
this.field = field;
}
项目:oscm
文件:EventServiceWSTest.java
/**
* Creates a technology provider and imports a technical product. Also a
* supplier is created for which a service is created and published.
*/
private static void initTestData() throws Exception {
// OPERATOR:
WebserviceTestBase.getOperator().addCurrency(
WebserviceTestBase.CURRENCY_EUR);
registerProvider();
registerSupplier();
WebserviceTestBase.savePaymentInfoToSupplier(supplier,
PaymentInfoType.INVOICE);
// TECHNCIAL PROVIDER:
initProviderServices();
importTechnicalService(serviceProvisioningService);
accountService.addSuppliersForTechnicalService(techProduct,
Collections.singletonList(supplier.getOrganizationId()));
// SUPPLIER:
initSupplierServices();
marketplace = WebserviceTestBase.registerMarketplace(
supplier.getOrganizationId(), "mp");
enablePaymentType(accountService);
registerMarketableService(serviceProvisioningService);
WebserviceTestBase.publishToMarketplace(service, true, srvMarketplace,
marketplace);
service = serviceProvisioningService.activateService(service);
VOSubscription subscription = WebserviceTestBase.createSubscription(
accountService, subscriptionService, "subscrname", service);
subscriptionKey = subscription.getKey();
instanceId = subscription.getServiceInstanceId();
}
项目:kafka-0.11.0.0-src-with-comment
文件:MetadataTest.java
@Test
public void testNonExpiringMetadata() throws Exception {
metadata = new Metadata(refreshBackoffMs, metadataExpireMs, true, false, new ClusterResourceListeners());
// Test that topic is not expired if not used within the expiry interval
long time = 0;
metadata.add("topic1");
metadata.update(Cluster.empty(), Collections.<String>emptySet(), time);
time += Metadata.TOPIC_EXPIRY_MS;
metadata.update(Cluster.empty(), Collections.<String>emptySet(), time);
assertTrue("Unused topic expired when expiry disabled", metadata.containsTopic("topic1"));
// Test that topic is not expired if used within the expiry interval
metadata.add("topic2");
metadata.update(Cluster.empty(), Collections.<String>emptySet(), time);
for (int i = 0; i < 3; i++) {
time += Metadata.TOPIC_EXPIRY_MS / 2;
metadata.update(Cluster.empty(), Collections.<String>emptySet(), time);
assertTrue("Topic expired even though in use", metadata.containsTopic("topic2"));
metadata.add("topic2");
}
// Test that topics added using setTopics don't expire
HashSet<String> topics = new HashSet<>();
topics.add("topic4");
metadata.setTopics(topics);
time += metadataExpireMs * 2;
metadata.update(Cluster.empty(), Collections.<String>emptySet(), time);
assertTrue("Unused topic expired when expiry disabled", metadata.containsTopic("topic4"));
}
项目:javaide
文件:MixedItemSection.java
/**
* Places all the items in this instance at particular offsets. This
* will call {@link OffsettedItem#place} on each item. If an item
* does not know its write size before the call to {@code place},
* it is that call which is responsible for setting the write size.
* This method may only be called once per instance; subsequent calls
* will throw an exception.
*/
public void placeItems() {
throwIfNotPrepared();
switch (sort) {
case INSTANCE: {
Collections.sort(items);
break;
}
case TYPE: {
Collections.sort(items, TYPE_SORTER);
break;
}
}
int sz = items.size();
int outAt = 0;
for (int i = 0; i < sz; i++) {
OffsettedItem one = items.get(i);
try {
int placedAt = one.place(this, outAt);
if (placedAt < outAt) {
throw new RuntimeException("bogus place() result for " +
one);
}
outAt = placedAt + one.writeSize();
} catch (RuntimeException ex) {
throw ExceptionWithContext.withContext(ex,
"...while placing " + one);
}
}
writeSize = outAt;
}
项目:guava-mock
文件:OrderingTest.java
public void testExplicit_sortingExample() {
Comparator<Integer> c
= Ordering.explicit(2, 8, 6, 1, 7, 5, 3, 4, 0, 9);
List<Integer> list = Arrays.asList(0, 3, 5, 6, 7, 8, 9);
Collections.sort(list, c);
assertThat(list).containsExactly(8, 6, 7, 5, 3, 0, 9).inOrder();
reserializeAndAssert(c);
}
项目:oscm
文件:ManageAccessCtrl.java
private void populateOrganizations(String marketplaceId)
throws ObjectNotFoundException {
boolean restricted = model.isSelectedMarketplaceRestricted();
// no need to populate organization list when selected marketplace is
// not restricted
if (restricted) {
List<POOrganization> organizations = new ArrayList<>();
for (VOOrganization voOrganization : marketplaceService
.getAllOrganizations(marketplaceId)) {
POOrganization poOrganization = toPOOrganization(voOrganization);
long key = poOrganization.getKey();
organizations.add(poOrganization);
}
Collections.sort(organizations, new Comparator<POOrganization>() {
@Override
public int compare(POOrganization org1, POOrganization org2) {
return Boolean.valueOf(org2.isSelected()).compareTo(
Boolean.valueOf(org1.isSelected()));
}
});
model.setOrganizations(organizations);
}
}
项目:cyberduck
文件:SpectraReadFeatureTest.java
@Test
public void testRead() throws Exception {
final Host host = new Host(new SpectraProtocol() {
@Override
public Scheme getScheme() {
return Scheme.http;
}
}, System.getProperties().getProperty("spectra.hostname"), Integer.valueOf(System.getProperties().getProperty("spectra.port")), new Credentials(
System.getProperties().getProperty("spectra.user"), System.getProperties().getProperty("spectra.key")
));
final SpectraSession session = new SpectraSession(host, new DisabledX509TrustManager(),
new DefaultX509KeyManager());
session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
final byte[] content = new RandomStringGenerator.Builder().build().generate(1000).getBytes();
final TransferStatus status = new TransferStatus().length(content.length);
status.setChecksum(new CRC32ChecksumCompute().compute(new ByteArrayInputStream(content), status));
final OutputStream out = new S3WriteFeature(session).write(test, status, new DisabledConnectionCallback());
assertNotNull(out);
new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out);
out.close();
new SpectraBulkService(session).pre(Transfer.Type.download, Collections.singletonMap(test, status), new DisabledConnectionCallback());
final InputStream in = new SpectraReadFeature(session).read(test, status, new DisabledConnectionCallback());
assertNotNull(in);
final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
new StreamCopier(status, status).transfer(in, buffer);
assertArrayEquals(content, buffer.toByteArray());
in.close();
new SpectraDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
session.close();
}
项目:ProjectAres
文件:Destroyable.java
@Override
public Iterable<Location> getProximityLocations(ParticipantState player) {
if(proximityLocations == null) {
proximityLocations = Collections.singleton(getBlockRegion().getBounds().center().toLocation(getOwner().getMatch().getWorld()));
}
return proximityLocations;
}
项目:kafka-0.11.0.0-src-with-comment
文件:TimestampConverterTest.java
@Test
public void testWithSchemaDateToTimestamp() {
TimestampConverter<SourceRecord> xform = new TimestampConverter.Value<>();
xform.configure(Collections.singletonMap(TimestampConverter.TARGET_TYPE_CONFIG, "Timestamp"));
SourceRecord transformed = xform.apply(new SourceRecord(null, null, "topic", 0, Date.SCHEMA, DATE.getTime()));
assertEquals(Timestamp.SCHEMA, transformed.valueSchema());
// No change expected since the source type is coarser-grained
assertEquals(DATE.getTime(), transformed.value());
}
项目:ditb
文件:TestStore.java
/**
* Getting data from memstore and files
* @throws IOException
*/
@Test
public void testGet_FromMemStoreAndFiles() throws IOException {
init(this.name.getMethodName());
//Put data in memstore
this.store.add(new KeyValue(row, family, qf1, 1, (byte[])null));
this.store.add(new KeyValue(row, family, qf2, 1, (byte[])null));
//flush
flush(1);
//Add more data
this.store.add(new KeyValue(row, family, qf3, 1, (byte[])null));
this.store.add(new KeyValue(row, family, qf4, 1, (byte[])null));
//flush
flush(2);
//Add more data
this.store.add(new KeyValue(row, family, qf5, 1, (byte[])null));
this.store.add(new KeyValue(row, family, qf6, 1, (byte[])null));
//Get
result = HBaseTestingUtility.getFromStoreFile(store,
get.getRow(), qualifiers);
//Need to sort the result since multiple files
Collections.sort(result, KeyValue.COMPARATOR);
//Compare
assertCheck();
}
项目:java-tutorial
文件:Shuffle.java
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// 下面的for循环可以使用Arrays.asList替代,更简洁和高效
// list = Arrays.asList(args);
for (String a : args)
list.add(a);
Collections.shuffle(list);
System.out.println(list);
}
项目:dubbo2
文件:ProtocolListenerWrapper.java
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {
return protocol.refer(type, url);
}
return new ListenerInvokerWrapper<T>(protocol.refer(type, url),
Collections.unmodifiableList(
ExtensionLoader.getExtensionLoader(InvokerListener.class)
.getActivateExtension(url, Constants.INVOKER_LISTENER_KEY)));
}
项目:JavaRushTasks
文件:Provider.java
public List<Vacancy> getJavaVacancies(String searchString)
{
if (this.strategy == null)
return Collections.emptyList();
return strategy.getVacancies(searchString);
}
项目:incubator-netbeans
文件:NbUtils.java
/**
* Creates unmodifiable copy of the original map converting <code>AttributeSet</code>s
* to their immutable versions.
*/
public static Map<String, AttributeSet> immutize(Map<String, ? extends AttributeSet> map, Object... filterOutKeys) {
Map<String, AttributeSet> immutizedMap = new HashMap<String, AttributeSet>();
for(String name : map.keySet()) {
AttributeSet attribs = map.get(name);
if (filterOutKeys.length == 0) {
immutizedMap.put(name, AttributesUtilities.createImmutable(attribs));
} else {
List<Object> pairs = new ArrayList<Object>();
// filter out attributes specified by filterOutKeys
first:
for(Enumeration<? extends Object> keys = attribs.getAttributeNames(); keys.hasMoreElements(); ) {
Object key = keys.nextElement();
for(Object filterOutKey : filterOutKeys) {
if (Utilities.compareObjects(key, filterOutKey)) {
continue first;
}
}
pairs.add(key);
pairs.add(attribs.getAttribute(key));
}
immutizedMap.put(name, AttributesUtilities.createImmutable(pairs.toArray()));
}
}
return Collections.unmodifiableMap(immutizedMap);
}
项目:foldem
文件:Range.java
/**
* Obtains an unmodifiable view containing all hands within this
* {@link Range} including weighted hands.
*
* @return An unmodifiable view containing all hands within this
* {@link Range}.
*/
public Collection<Hand> all() {
List<Hand> hands = new ArrayList<>();
hands.addAll(constant);
for (List<Hand> l : weighted.values()) {
hands.addAll(l);
}
return Collections.unmodifiableCollection(hands);
}
项目:FastTextView
文件:TextMeasureUtil.java
public static List<ReplacementSpan> getSortedReplacementSpans(final Spanned spanned, int start, int end) {
List<ReplacementSpan> sortedSpans = new LinkedList<>();
ReplacementSpan[] spans = spanned.getSpans(start, end, ReplacementSpan.class);
if (spans.length > 0) {
sortedSpans.addAll(Arrays.asList(spans));
}
Collections.sort(sortedSpans, new Comparator<ReplacementSpan>() {
@Override
public int compare(ReplacementSpan span1, ReplacementSpan span2) {
return spanned.getSpanStart(span1) - spanned.getSpanStart(span2);
}
});
return sortedSpans;
}
项目:Library-System-Android
文件:LoginHold.java
public boolean checkFormat(String username){
ArrayList<Character> charList = new ArrayList<Character>();
Collections.addAll(charList, '!', '$', '#', '@');
boolean containsSpecial = false;
for(Character character: charList) {
if (username.contains(Character.toString(character))) {
containsSpecial = true;
}
}
int numberCharacters = 0;
if(containsSpecial){
for(int i=0; i<username.length();i++){
String symbol = String.valueOf(username.charAt(i));
Pattern pattern = Pattern.compile("[A-z]");
Matcher matcher = pattern.matcher(symbol);
if(matcher.matches()){
numberCharacters++;
System.out.println("Match: " + numberCharacters);
}
}
}
if(numberCharacters>2){
return true;
}
else {
return false;
}
}