Java Code Examples for java.util.Collections

The following are top voted examples for showing how to use java.util.Collections. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ultrasonic   File: SearchActivity.java   Source Code and License 6 votes vote down vote up
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));
	}
}
 
Example 2
Project: Tarski   File: VizGraphPanel.java   Source Code and License 6 votes vote down vote up
/** 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;
}
 
Example 3
Project: kafka-0.11.0.0-src-with-comment   File: ProduceRequestTest.java   Source Code and License 6 votes vote down vote up
@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());

}
 
Example 4
Project: Mods   File: ItemWrangler.java   Source Code and License 6 votes vote down vote up
@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);
		}
	}
}
 
Example 5
Project: openjdk-jdk10   File: OpenMBeanAttributeInfoSupport.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 6
Project: incubator-netbeans   File: RemoveTest.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 7
Project: MyAnimeViewer   File: OfflineHistoryRecyclerAdapter.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 8
Project: athena   File: RouterTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 9
Project: CommentView   File: Extractor.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 10
Project: jdk8u-jdk   File: SctpChannelImpl.java   Source Code and License 6 votes vote down vote up
@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;
        }
    }
}
 
Example 11
Project: r8   File: BinopLiteralTest.java   Source Code and License 6 votes vote down vote up
@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);
    }
  }
}
 
Example 12
Project: Servlet-4.0-Sampler   File: PushCacheFilter.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 13
Project: hashsdn-controller   File: SimpleIdentityRefAttributeReadingStrategyTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 14
Project: hashsdn-controller   File: DistributedShardedDOMDataTree.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 15
Project: BiglyBT   File: ConsoleInput.java   Source Code and License 6 votes vote down vote up
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 );
		}
	});
}
 
Example 16
Project: NBANDROID-V2   File: ApkUtils.java   Source Code and License 6 votes vote down vote up
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());
    }
 
Example 17
Project: elasticsearch-aem   File: ElasticSearchTransportHandler.java   Source Code and License 6 votes vote down vote up
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");
}
 
Example 18
Project: incubator-netbeans   File: GlobalPathRegistryTest.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 19
Project: springboot-shiro-cas-mybatis   File: ChainingPrincipalResolverTest.java   Source Code and License 6 votes vote down vote up
@Test
public void examineResolve() throws Exception {
    final Credential credential = mock(Credential.class);
    when(credential.getId()).thenReturn("input");

    final PrincipalResolver resolver1 = mock(PrincipalResolver.class);
    when(resolver1.supports(eq(credential))).thenReturn(true);
    when(resolver1.resolve((eq(credential)))).thenReturn(principalFactory.createPrincipal("output"));

    final PrincipalResolver resolver2 = mock(PrincipalResolver.class);
    when(resolver2.supports(any(Credential.class))).thenReturn(false);
    when(resolver2.resolve(argThat(new ArgumentMatcher<Credential>() {
        @Override
        public boolean matches(final Object o) {
            return "output".equals(((Credential) o).getId());
        }
    }))).thenReturn(principalFactory.createPrincipal("final", Collections.<String, Object>singletonMap("mail", "[email protected]")));

    final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver();
    resolver.setChain(Arrays.asList(resolver1, resolver2));
    final Principal principal = resolver.resolve(credential);
    assertEquals("final", principal.getId());
    assertEquals("[email protected]", principal.getAttributes().get("mail"));
}
 
Example 20
Project: buenojo   File: PhotoLocationAnnotatedResourceFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @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;
	
}
 
Example 21
Project: elasticsearch_my   File: TribeServiceTests.java   Source Code and License 5 votes vote down vote up
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");
}
 
Example 22
Project: monarch   File: InvalidateOperation.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 23
Project: elasticsearch_my   File: IndexSearcherWrapperTests.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 24
Project: oscm   File: EventServiceWSTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
}
 
Example 25
Project: kafka-0.11.0.0-src-with-comment   File: MetadataTest.java   Source Code and License 5 votes vote down vote up
@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"));
}
 
Example 26
Project: javaide   File: MixedItemSection.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 27
Project: guava-mock   File: OrderingTest.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 28
Project: oscm   File: ManageAccessCtrl.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 29
Project: cyberduck   File: SpectraReadFeatureTest.java   Source Code and License 5 votes vote down vote up
@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();
}
 
Example 30
Project: ProjectAres   File: Destroyable.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<Location> getProximityLocations(ParticipantState player) {
    if(proximityLocations == null) {
        proximityLocations = Collections.singleton(getBlockRegion().getBounds().center().toLocation(getOwner().getMatch().getWorld()));
    }
    return proximityLocations;
}
 
Example 31
Project: kafka-0.11.0.0-src-with-comment   File: TimestampConverterTest.java   Source Code and License 5 votes vote down vote up
@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());
}
 
Example 32
Project: ditb   File: TestStore.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
}
 
Example 33
Project: java-tutorial   File: Shuffle.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 34
Project: dubbo2   File: ProtocolListenerWrapper.java   Source Code and License 5 votes vote down vote up
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)));
}
 
Example 35
Project: JavaRushTasks   File: Provider.java   Source Code and License 5 votes vote down vote up
public List<Vacancy> getJavaVacancies(String searchString)
{
    if (this.strategy == null)
        return Collections.emptyList();


        return strategy.getVacancies(searchString);
}
 
Example 36
Project: incubator-netbeans   File: NbUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 37
Project: foldem   File: Range.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 38
Project: FastTextView   File: TextMeasureUtil.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 39
Project: Library-System-Android   File: LoginHold.java   Source Code and License 5 votes vote down vote up
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;
        }
    }
 
Example 40
Project: GitHub   File: Picasso.java   Source Code and License 5 votes vote down vote up
Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
    RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
    Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled) {
  this.context = context;
  this.dispatcher = dispatcher;
  this.cache = cache;
  this.listener = listener;
  this.requestTransformer = requestTransformer;
  this.defaultBitmapConfig = defaultBitmapConfig;

  int builtInHandlers = 7; // Adjust this as internal handlers are added or removed.
  int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);
  List<RequestHandler> allRequestHandlers = new ArrayList<>(builtInHandlers + extraCount);

  // ResourceRequestHandler needs to be the first in the list to avoid
  // forcing other RequestHandlers to perform null checks on request.uri
  // to cover the (request.resourceId != 0) case.
  allRequestHandlers.add(new ResourceRequestHandler(context));
  if (extraRequestHandlers != null) {
    allRequestHandlers.addAll(extraRequestHandlers);
  }
  allRequestHandlers.add(new ContactsPhotoRequestHandler(context));
  allRequestHandlers.add(new MediaStoreRequestHandler(context));
  allRequestHandlers.add(new ContentStreamRequestHandler(context));
  allRequestHandlers.add(new AssetRequestHandler(context));
  allRequestHandlers.add(new FileRequestHandler(context));
  allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));
  requestHandlers = Collections.unmodifiableList(allRequestHandlers);

  this.stats = stats;
  this.targetToAction = new WeakHashMap<>();
  this.targetToDeferredRequestCreator = new WeakHashMap<>();
  this.indicatorsEnabled = indicatorsEnabled;
  this.loggingEnabled = loggingEnabled;
  this.referenceQueue = new ReferenceQueue<>();
  this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
  this.cleanupThread.start();
}
 
Example 41
Project: cas4.0.x-server-wechat   File: RememberMeDelegatingExpirationPolicyTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testTicketExpirationWithRememberMe() {
    final Authentication authentication = TestUtils.getAuthentication(
            new SimplePrincipal("test"),
            Collections.<String, Object>singletonMap(
                    RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME, true));
    final TicketGrantingTicketImpl t = new TicketGrantingTicketImpl("111", authentication, this.p);
    assertFalse(t.isExpired());
    t.grantServiceTicket("55", TestUtils.getService(), this.p, false);
    assertTrue(t.isExpired());

}
 
Example 42
Project: unitimes   File: InstructorListUpdateAction.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param frm
 * @param request
 * @return
 * @throws Exception
 */
private Collection getAvailable(InstructorListUpdateForm frm, HttpServletRequest request) throws Exception {
	HttpSession httpSession = request.getSession();
	if (httpSession.getAttribute(Constants.DEPT_ID_ATTR_NAME) != null) {
		String deptId = (String) httpSession.getAttribute(Constants.DEPT_ID_ATTR_NAME);
		Department d = new DepartmentDAO().get(new Long(deptId));
		List available = Staff.getStaffByDept(d.getDeptCode().trim(), sessionContext.getUser().getCurrentAcademicSessionId());			
		Collections.sort(available, new StaffComparator(StaffComparator.COMPARE_BY_POSITION));
		return available;
	} else {
		return null;
	}
}
 
Example 43
Project: rest-modeling-framework   File: AbstractScopedVisitor.java   Source Code and License 5 votes vote down vote up
private void setAttribute(final EObject eObject, final EAttribute eAttribute, final RAMLParser.IdContext valueToken) {
    if (valueToken.getText().length() > 0) {
        final Object value = createFromString(eAttribute, valueToken);
        if (eAttribute.isMany()) {
            eObject.eSet(eAttribute, Collections.singletonList(value));
        } else {
            eObject.eSet(eAttribute, value);
        }
    }
}
 
Example 44
Project: Random-Music-Generator   File: FugenGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Fügt den Parts eine Engführung an. Der erste, dritte und fünfte Part, spielen den Dux, die restlichen den Comes.
 * @param parts - Liste der Stimmen, welche die Fuge spielen sollen
 * @param fugenSubjects - {@link FugenSubjects} der Fuge
 * @param config - das {@link SongConfig} der Fuge
 */
/*private*/ void addFinalSection(ArrayList<Part> parts, SongConfig config){//private disabled for testing
	int subjectDuration = config.getChordNr() * config.getBeats() * config.getMeasureDivision();
	//speichert in welcher Reihenfolge die Stimmen zu spielen beginnen
	@SuppressWarnings("unchecked")//clone benötigt, da ursprüngliche Reihenfolge in parts erhalten bleiben muss
	ArrayList<Part> order = (ArrayList<Part>) parts.clone();//Objekte in order und parts sind die selben
	Collections.shuffle(order);
	//Intervalle der Stimmen zur Tonhöhe im FugenInfo
	ArrayList<Integer> intervals = intervals(parts, order);
	
	for(int partnr = 0; partnr < order.size(); partnr++){
		Part part = order.get(partnr);
		ArrayList<INote> notes = new ArrayList<INote>();
		//erste freie Stimmen hinzufügen
		notes = melGen.generateSubVoice(config, fugenSubjects, partnr);//überlagernder Themeneinsatz
		notes = MelodyHelper.subNoteList(notes, partnr * subjectDuration / 2, false);
		//Thema hinzufügen
		notes.addAll(fugenSubjects.getSubjectList());
		//zweite freie Stimme hinzufügen
		ArrayList<INote> subVoice = melGen.generateSubVoice(config, fugenSubjects, (order.size() - 1 - partnr));
		subVoice = MelodyHelper.subNoteList(subVoice, (order.size() - 1 - partnr) * subjectDuration / 2, true);
		notes.addAll(subVoice);
		//transponieren und Part hinzufügen
		notes = MelodyHelper.transpone(notes, intervals.get(partnr), config.getKey());
		part.addAll(MelodyHelper.noteListToPart(config, notes, part.getInstrument()));
	}

}
 
Example 45
Project: openjdk-jdk10   File: Locations.java   Source Code and License 5 votes vote down vote up
@Override
Iterable<Set<Location>> listLocationsForModules() {
    if (moduleTable == null)
        return Collections.emptySet();

    return Collections.singleton(moduleTable.locations());
}
 
Example 46
Project: OpenJSharp   File: RelationNotification.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the list of ObjectNames of MBeans expected to be unregistered
 * due to a relation removal (only for relation removal).
 *
 * @return a {@link List} of {@link ObjectName}.
 */
public List<ObjectName> getMBeansToUnregister() {
    List<ObjectName> result;
    if (unregisterMBeanList != null) {
        result = new ArrayList<ObjectName>(unregisterMBeanList);
    } else {
        result = Collections.emptyList();
    }
    return result;
}
 
Example 47
Project: s-store   File: TestOrderBySuite.java   Source Code and License 5 votes vote down vote up
/** add 20 shuffled rows
 * @throws InterruptedException */
private void load(Client client) throws NoConnectionsException, ProcCallException, IOException, InterruptedException {
    int pkey = 0;
    a_int.clear();
    a_inline_str.clear();
    a_pool_str.clear();

    // if you want to test synchronous latency, this
    //  is a good variable to change
    boolean async = true;

    for (int i=0; i < 20; i++) {
        a_int.add(i);
        a_inline_str.add("a_" + i);
        a_pool_str.add(bigString + i);
    }

    Collections.shuffle(a_int);
    Collections.shuffle(a_inline_str);
    Collections.shuffle(a_pool_str);

    for (int i=0; i < 20; i++) {
        SyncCallback cb = new SyncCallback();
        client.callProcedure(cb,
                "InsertO1",
                pkey++,
                a_int.get(i),
                a_inline_str.get(i),
                a_pool_str.get(i));

        if (!async) {
            cb.waitForResponse();
            VoltTable vt = cb.getResponse().getResults()[0];
            assertTrue(vt.getRowCount() == 1);
        }
    }

    client.drain();
}
 
Example 48
Project: bullet-core   File: DistributionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCasting() {
    Distribution distribution = makeDistribution(DistributionType.PMF, Collections.singletonList(50.0));

    IntStream.range(0, 25).mapToObj(String::valueOf).map(s -> RecordBox.get().add("field", s).getRecord())
                          .forEach(distribution::consume);

    distribution.consume(RecordBox.get().add("field", "garbage").getRecord());
    distribution.consume(RecordBox.get().add("field", "1.0 garbage").getRecord());


    IntStream.range(50, 100).mapToDouble(i -> i).mapToObj(d -> RecordBox.get().add("field", d).getRecord())
                            .forEach(distribution::consume);

    Clip result = distribution.getAggregation();

    Map<String, Object> metadata = (Map<String, Object>) result.getMeta().asMap().get("meta");
    Assert.assertEquals(metadata.size(), 7);
    Assert.assertFalse((Boolean) metadata.get("isEst"));

    List<BulletRecord> records = result.getRecords();
    Assert.assertEquals(records.size(), 2);

    BulletRecord expectedA = RecordBox.get().add(RANGE_FIELD, NEGATIVE_INFINITY_START + SEPARATOR + 50.0 + END_EXCLUSIVE)
                                            .add(COUNT_FIELD, 25.0)
                                            .add(PROBABILITY_FIELD, 1.0 / 3).getRecord();
    BulletRecord expectedB = RecordBox.get().add(RANGE_FIELD, START_INCLUSIVE + 50.0 + SEPARATOR + POSITIVE_INFINITY_END)
                                            .add(COUNT_FIELD, 50.0)
                                            .add(PROBABILITY_FIELD, 2.0 / 3).getRecord();
    Assert.assertEquals(records.get(0), expectedA);
    Assert.assertEquals(records.get(1), expectedB);
}
 
Example 49
Project: monarch   File: EndpointManagerImpl.java   Source Code and License 5 votes vote down vote up
public synchronized void close() {
  for (Iterator<ConnectionStats> itr = statMap.values().iterator(); itr.hasNext();) {
    ConnectionStats stats = itr.next();
    stats.close();
  }

  statMap.clear();
  endpointMap = Collections.emptyMap();
  listener.clear();
}
 
Example 50
Project: GitHub   File: BaseQuickAdapter.java   Source Code and License 5 votes vote down vote up
/************************************拖拽滑动****************************************/

    @Override
    public boolean onItemMove(int fromPosition, int toPosition) {
        if (fromPosition >= mDragFixCount && toPosition >= mDragFixCount) {
            Collections.swap(mData, fromPosition, toPosition);
            notifyItemMoved(fromPosition, toPosition);
            if (mItemMoveListener != null) {
                mItemMoveListener.onItemMove(fromPosition, toPosition);
            }
            return true;
        }
        return false;
    }
 
Example 51
Project: uavstack   File: GUISSOLdapClient.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private List<String> formatUserEnName(Attribute attr) {

    if (null == attr) {
        return Collections.emptyList();
    }
    List<String> result = new ArrayList<String>();
    String formatCN = "=";
    try {

        NamingEnumeration members = attr.getAll();

        while (members.hasMore()) {
            String memberValue = members.next().toString();
            int indexStart = memberValue.indexOf(formatCN);
            if (indexStart == -1) {
                result.add(memberValue);
                continue;
            }
            int indexEnd = memberValue.indexOf(",");
            String memberCN = memberValue.substring(indexStart + formatCN.length(), indexEnd);

            result.add(memberCN);
        }

    }
    catch (

    Exception e) {

        loggerError("formatUserEnName 648", "", e);
    }
    return result;
}
 
Example 52
Project: googles-monorepo-demo   File: Shorts.java   Source Code and License 5 votes vote down vote up
@Override
public List<Short> subList(int fromIndex, int toIndex) {
  int size = size();
  checkPositionIndexes(fromIndex, toIndex, size);
  if (fromIndex == toIndex) {
    return Collections.emptyList();
  }
  return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
}
 
Example 53
Project: XXXX   File: UtilTest.java   Source Code and License 5 votes vote down vote up
@Test
public void emptyValueOf() throws Exception {
  assertEquals(false, Util.emptyValueOf(boolean.class));
  assertEquals(false, Util.emptyValueOf(Boolean.class));
  assertThat((byte[]) Util.emptyValueOf(byte[].class)).isEmpty();
  assertEquals(Collections.emptyList(), Util.emptyValueOf(Collection.class));
  assertThat((Iterator<?>) Util.emptyValueOf(Iterator.class)).isEmpty();
  assertEquals(Collections.emptyList(), Util.emptyValueOf(List.class));
  assertEquals(Collections.emptyMap(), Util.emptyValueOf(Map.class));
  assertEquals(Collections.emptySet(), Util.emptyValueOf(Set.class));
}
 
Example 54
Project: elasticsearch_my   File: GrokProcessorFactoryTests.java   Source Code and License 5 votes vote down vote up
public void testCreateWithInvalidPattern() throws Exception {
    GrokProcessor.Factory factory = new GrokProcessor.Factory(Collections.emptyMap());
    Map<String, Object> config = new HashMap<>();
    config.put("field", "_field");
    config.put("patterns", Collections.singletonList("["));
    ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> factory.create(null, null, config));
    assertThat(e.getMessage(), equalTo("[patterns] Invalid regex pattern found in: [[]. premature end of char-class"));
}
 
Example 55
Project: avro-compatibility   File: ChronologyCompatibilityCheckResultTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAccessors() {
  ChronologyCompatibilityCheckResult result = new ChronologyCompatibilityCheckResult(CAN_READ, ALL,
      Collections.singletonList(resultIncompatible));

  assertThat(result.getChronology(), is(ALL));
  assertThat(result.getCompatibility(), is(CAN_READ));
  assertThat(result.getResults(), is(Collections.singletonList(resultIncompatible)));
  assertThat(result.getType(), is(SchemaCompatibilityType.INCOMPATIBLE));
}
 
Example 56
Project: datarouter   File: PathNode.java   Source Code and License 5 votes vote down vote up
public String toSlashedString(){
	List<PathNode> ancestry = new ArrayList<>();
	PathNode nextParent = this;
	while(nextParent != null && nextParent.value != null){
		ancestry.add(nextParent);
		nextParent = nextParent.parent;
	}
	Collections.reverse(ancestry);
	return ancestry.stream()
			.map(pathNode -> pathNode.value)
			.collect(Collectors.joining("/", "/", ""));
}
 
Example 57
Project: Equella   File: CALMetadataCollection.java   Source Code and License 5 votes vote down vote up
@Override
public void relationDeleted(Relation relation)
{
	CALHolding holding = calDao.getHoldingInItem(relation.getSecondItem());
	if( holding != null )
	{
		calDao.updateHoldingReference(null, Collections.singletonList(relation.getFirstItem()));
	}
}
 
Example 58
Project: iTAP-controller   File: FloodlightModuleLoader.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the map of modules and their names.
 * @return An UNMODIFIABLE map of the modules and their names.
 */
public synchronized Map<String, IFloodlightModule> getModuleNameMap() {
    if(moduleNameMap == null)
        return ImmutableMap.of();
    else
        return Collections.unmodifiableMap(moduleNameMap);
}
 
Example 59
Project: DroidSentinel   File: Population.java   Source Code and License 5 votes vote down vote up
public void fitnessInitialPopulation() {

        ArrayList<Chromosome> compare_population = new ArrayList<Chromosome>();

        for(int i = 0; i < this.initial_population.size(); i++) {
            compare_population.add(this.initial_population.get(i));
        }


        Collections.sort(compare_population, new Comparator<Chromosome>() {

            @Override
            public int compare(Chromosome t, Chromosome t1) {
                return Double.compare(t.getSmape(), t1.getSmape());
            }

        });

        for(int i = 0; i < NUM_WORK_POPULATION; i++) {
            this.work_population.add(compare_population.get(i));
        }

        for(int i = 0; i < this.work_population.size(); i++) {
            if (this.work_population.get(i).getBueno()) {
                this.stop = true;

            }
        }

        if (this.stop) {
            this.best_population.add(0, this.work_population.get(0));
        }
    }
 
Example 60
Project: dotwebstack-framework   File: SupportedMediaTypesScannerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void constructor_FindsSupportedTupleProviders_WhenProvided() {
  // Arrange & Act
  SupportedMediaTypesScanner scanner = new SupportedMediaTypesScanner(Collections.emptyList(),
      Collections.singletonList(new StubTupleMessageBodyWriter()));

  // Assert
  assertThat(scanner.getMediaTypes(ResultType.TUPLE).length, equalTo(1));
  assertThat(Arrays.asList(scanner.getMediaTypes(ResultType.TUPLE)),
      IsCollectionContaining.hasItems(MediaTypes.SPARQL_RESULTS_JSON_TYPE));
  assertThat(scanner.getTupleEntityWriters().size(), equalTo(1));
}