Java Code Examples for com.google.common.collect.Lists

The following are top voted examples for showing how to use com.google.common.collect.Lists. 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: athena   File: MastersListCommand.java   View source code 7 votes vote down vote up
@Override
protected void execute() {
    ClusterService service = get(ClusterService.class);
    MastershipService mastershipService = get(MastershipService.class);
    List<ControllerNode> nodes = newArrayList(service.getNodes());
    Collections.sort(nodes, Comparators.NODE_COMPARATOR);

    if (outputJson()) {
        print("%s", json(service, mastershipService, nodes));
    } else {
        for (ControllerNode node : nodes) {
            List<DeviceId> ids = Lists.newArrayList(mastershipService.getDevicesOf(node.id()));
            Collections.sort(ids, Comparators.ELEMENT_ID_COMPARATOR);
            print("%s: %d devices", node.id(), ids.size());
            for (DeviceId deviceId : ids) {
                print("  %s", deviceId);
            }
        }
    }
}
 
Example 2
Project: creacoinj   File: BasicKeyChain.java   View source code 6 votes vote down vote up
/** Returns a list of all ECKeys created after the given UNIX time. */
public List<ECKey> findKeysBefore(long timeSecs) {
    lock.lock();
    try {
        List<ECKey> results = Lists.newLinkedList();
        for (ECKey key : hashToKeys.values()) {
            final long keyTime = key.getCreationTimeSeconds();
            if (keyTime < timeSecs) {
                results.add(key);
            }
        }
        return results;
    } finally {
        lock.unlock();
    }
}
 
Example 3
Project: morf   File: TestSqlStatements.java   View source code 6 votes vote down vote up
/**
 * Tests the select order by statement (with nulls last) against all {@linkplain SqlDialect}s
 *
 * @throws SQLException in case of error.
 */
@Test
public void testSelectOrderByNullsFirstAscNullsFirstDesc() throws SQLException {
  SelectStatement selectOrderByNullsLastStat = select( field("field1"), field("field2")).from(tableRef("OrderByNullsLastTable")).orderBy(field("field1").nullsFirst(),field("field2").desc().nullsFirst());

  String sql = convertStatementToSQL(selectOrderByNullsLastStat);

  sqlScriptExecutorProvider.get().executeQuery(sql, new ResultSetProcessor<Void>() {

    @Override
    public Void process(ResultSet resultSet) throws SQLException {
      List<String> expectedResultField1 = Lists.newArrayList(null,null,"1", "1","3","3");
      List<String> expectedResultField2 = Lists.newArrayList(null,"3", null,"2","4","3");

      int count = 0;
      while (resultSet.next()) {
        assertEquals("count:"+count,expectedResultField1.get(count), resultSet.getString(1));
        assertEquals("count:"+count,expectedResultField2.get(count), resultSet.getString(2));
        count++;
      }
      return null;
    };
  });
}
 
Example 4
Project: Equella   File: RoleSelectorWebControl.java   View source code 6 votes vote down vote up
@Override
public void doEdits(SectionInfo info)
{
	final RoleSelectorWebControlModel model = getModel(info);

	if( model.getSelectedRoles() != null )
	{
		final List<String> controlValues = storageControl.getValues();
		controlValues.clear();
		controlValues.addAll(Lists.transform(model.getSelectedRoles(), new Function<SelectedRole, String>()
		{
			@Override
			public String apply(SelectedRole role)
			{
				return role.getUuid();
			}
		}));
	}
}
 
Example 5
Project: empiria.player   File: CommutationEvaluatorJUnitTest.java   View source code 6 votes vote down vote up
@Test
public void evaluateCorrect() {
    // given
    ExpressionBean bean = new ExpressionBean();

    List<Response> responses = Lists.newArrayList(correctResponse(), correctResponse(), correctResponse(), correctResponse(), correctResponse());
    bean.setTemplate("'0'+'2'+'3'='1'+'4'");
    bean.getResponses().addAll(responses);

    Multiset<Multiset<String>> correctAnswerMultiSet = HashMultiset.create(Lists.<Multiset<String>>newArrayList(
            HashMultiset.create(Lists.newArrayList("answer_1", "answer_4")),
            HashMultiset.create(Lists.newArrayList("answer_0", "answer_2", "answer_3")),
            HashMultiset.create(Lists.newArrayList("answer_0", "answer_2", "answer_3", "answer_1", "answer_4"))));
    bean.setCorectResponses(correctAnswerMultiSet);

    // when
    boolean result = testObj.evaluate(bean);

    // then
    assertThat(result, equalTo(true));
}
 
Example 6
Project: aliyun-maxcompute-data-collectors   File: DatahubSink.java   View source code 6 votes vote down vote up
private List<String> getPropCols(String propertyString, boolean lowercase) {
    if (StringUtils.isEmpty(propertyString)) {
        logger.warn("Property is empty. property name:" + propertyString);
        return null;
    }
    List<String> propList = Lists.newArrayList();
    String[] propCols = propertyString.split(",");
    for (int i = 0; i < propCols.length; i++) {
        String prop = propCols[i].split("/")[0].trim();
        if (lowercase) {
            prop = prop.toLowerCase();
        }
        propList.add(prop);
    }
    return propList;
}
 
Example 7
Project: empiria.player   File: BonusProviderTest.java   View source code 6 votes vote down vote up
@Test
public void next_imageBonus_random() {
    // given
    final String asset1 = "bonus1";
    final String asset2 = "bonus2.png";
    final Size size = new Size(1, 2);
    BonusResource bonusResource = createBonus(asset2, size, IMAGE);
    ArrayList<BonusResource> bonuses = Lists.newArrayList(createBonus(asset1, size, SWIFFY), bonusResource);
    BonusAction action = createMockAction(bonuses);
    when(bonusConfig.getActions()).thenReturn(Lists.newArrayList(action));
    when(randomWrapper.nextInt(2)).thenReturn(1);

    BonusWithAsset expected = mock(BonusWithAsset.class);
    when(bonusFactory.createBonus(eq(bonusResource))).thenReturn(expected);

    // when
    Bonus result = bonusProvider.next();

    // then
    verify(bonusFactory).createBonus(bonusResource);
    assertThat(result).isEqualTo(expected);
}
 
Example 8
Project: mynlp   File: WordnetTokenizer.java   View source code 6 votes vote down vote up
@Override
public LinkedList<MynlpTerm> token(char[] text) {

    // 处理为空的特殊情况
    if (text.length == 0) {
        return Lists.newLinkedList();
    }

    //构建一个空的Wordnet对象
    final Wordnet wordnet = initEmptyWordNet(text);

    wordnetInitializer.initialize(wordnet);

    //选择一个路径出来(第一次不严谨的分词结果)
    Wordpath wordPath = bestPathComputer.select(wordnet);

    for (WordpathProcessor xProcessor : wordPathProcessors) {
        wordPath = xProcessor.process(wordPath);
    }

    return path2TermList(wordPath);
}
 
Example 9
Project: flume-release-1.7.0   File: ThriftSource.java   View source code 6 votes vote down vote up
@Override
public Status appendBatch(List<ThriftFlumeEvent> events) throws TException {
  sourceCounter.incrementAppendBatchReceivedCount();
  sourceCounter.addToEventReceivedCount(events.size());

  List<Event> flumeEvents = Lists.newArrayList();
  for (ThriftFlumeEvent event : events) {
    flumeEvents.add(EventBuilder.withBody(event.getBody(), event.getHeaders()));
  }

  try {
    getChannelProcessor().processEventBatch(flumeEvents);
  } catch (ChannelException ex) {
    logger.warn("Thrift source %s could not append events to the channel.", getName());
    return Status.FAILED;
  }

  sourceCounter.incrementAppendBatchAcceptedCount();
  sourceCounter.addToEventAcceptedCount(events.size());
  return Status.OK;
}
 
Example 10
Project: pnc-repressurized   File: CustomTrigger.java   View source code 6 votes vote down vote up
/**
 * Trigger.
 *
 * @param player the player
 */
public void trigger(EntityPlayerMP player) {
    List<ICriterionTrigger.Listener<CustomTrigger.Instance>> list = null;

    for (ICriterionTrigger.Listener<CustomTrigger.Instance> listener : this.listeners) {
        if (listener.getCriterionInstance().test()) {
            if (list == null) {
                list = Lists.newArrayList();
            }

            list.add(listener);
        }
    }

    if (list != null) {
        for (ICriterionTrigger.Listener listener1 : list) {
            listener1.grantCriterion(this.playerAdvancements);
        }
    }
}
 
Example 11
Project: creacoinj   File: DatabaseFullPrunedBlockStore.java   View source code 6 votes vote down vote up
/**
 * Create a new store for the given {@link org.creativecoinj.core.NetworkParameters}.
 * @param params The network.
 * @throws BlockStoreException If the store couldn't be created.
 */
private void createNewStore(NetworkParameters params) throws BlockStoreException {
    try {
        // Set up the genesis block. When we start out fresh, it is by
        // definition the top of the chain.
        StoredBlock storedGenesisHeader = new StoredBlock(params.getGenesisBlock().cloneAsHeader(), params.getGenesisBlock().getWork(), 0);
        // The coinbase in the genesis block is not spendable. This is because of how Bitcoin Core inits
        // its database - the genesis transaction isn't actually in the db so its spent flags can never be updated.
        List<Transaction> genesisTransactions = Lists.newLinkedList();
        StoredUndoableBlock storedGenesis = new StoredUndoableBlock(params.getGenesisBlock().getHash(), genesisTransactions);
        put(storedGenesisHeader, storedGenesis);
        setChainHead(storedGenesisHeader);
        setVerifiedChainHead(storedGenesisHeader);
    } catch (VerificationException e) {
        throw new RuntimeException(e); // Cannot happen.
    }
}
 
Example 12
Project: apollo-custom   File: ConfigServiceWithCacheTest.java   View source code 6 votes vote down vote up
@Test
public void testFindLatestActiveReleaseWithReleaseNotFound() throws Exception {
  when(releaseMessageService.findLatestReleaseMessageForMessages(Lists.newArrayList(someKey))).thenReturn(null);
  when(releaseService.findLatestActiveRelease(someAppId, someClusterName, someNamespaceName)).thenReturn(null);

  Release release = configServiceWithCache.findLatestActiveRelease(someAppId, someClusterName, someNamespaceName,
      someNotificationMessages);
  Release anotherRelease = configServiceWithCache.findLatestActiveRelease(someAppId, someClusterName,
      someNamespaceName, someNotificationMessages);

  int retryTimes = 100;

  for (int i = 0; i < retryTimes; i++) {
    configServiceWithCache.findLatestActiveRelease(someAppId, someClusterName,
        someNamespaceName, someNotificationMessages);
  }

  assertNull(release);
  assertNull(anotherRelease);

  verify(releaseMessageService, times(1)).findLatestReleaseMessageForMessages(Lists.newArrayList(someKey));
  verify(releaseService, times(1)).findLatestActiveRelease(someAppId, someClusterName, someNamespaceName);
}
 
Example 13
Project: travny   File: Codegen.java   View source code 6 votes vote down vote up
private List<Map<String, Object>> getIdFields(RecordSchema schema) {
    List<Map<String, Object>> list = Lists.newArrayList();
    for (Field f : schema.getFields()) {
        if (f.isRemoved()) {
            continue;
        }
        boolean isIdField = SchemaNameUtils.isIdSchema(schema.getName()) || f.isIdField();
        if (!isIdField) {
            continue;
        }
        Map<String, Object> fm = Maps.newHashMap();
        fm.put("name", f.getName());
        fm.put("isIdField", isIdField);
        list.add(fm);
    }
    return list;
}
 
Example 14
Project: Reer   File: RegexBackedCSourceParser.java   View source code 6 votes vote down vote up
private List<Include> parseFile(File file) {
    List<Include> includes = Lists.newArrayList();
    try {
        BufferedReader bf = new BufferedReader(new PreprocessingReader(new BufferedReader(new FileReader(file))));

        try {
            String line;
            while ((line = bf.readLine()) != null) {
                Matcher m = includePattern.matcher(line.trim());

                if (m.matches()) {
                    boolean isImport = "import".equals(m.group(1));
                    String value = m.group(2);

                    includes.add(DefaultInclude.parse(value, isImport));
                }
            }
        } finally {
            IOUtils.closeQuietly(bf);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    return includes;
}
 
Example 15
Project: NioSmtpClient   File: SmtpSessionTest.java   View source code 6 votes vote down vote up
private void assertResponsesMapped(int responsesExpected, CompletableFuture<SmtpClientResponse> future) throws Exception {
  List<SmtpResponse> responses = Lists.newArrayList();
  for (int i = 0; i < responsesExpected; i++) {
    responses.add(new DefaultSmtpResponse(250 + i, "OK " + i));
  }

  responseFuture.complete(responses);

  verify(responseHandler).createResponseFuture(eq(responsesExpected), any());

  assertThat(future.isDone()).isTrue();
  assertThat(future.get().getResponses().size()).isEqualTo(responses.size());

  for (int i = 0; i < responsesExpected; i++) {
    assertThat(future.get().getSession()).isEqualTo(session);
    assertThat(future.get().getResponses().get(i).code()).isEqualTo(responses.get(i).code());
    assertThat(future.get().getResponses().get(i).details()).isEqualTo(responses.get(i).details());
  }
}
 
Example 16
Project: Reer   File: ConsumerOperationParameters.java   View source code 6 votes vote down vote up
public Builder setLaunchables(Iterable<? extends Launchable> launchables) {
    Set<String> taskPaths = new LinkedHashSet<String>();
    List<InternalLaunchable> launchablesParams = Lists.newArrayList();
    for (Launchable launchable : launchables) {
        Object original = new ProtocolToModelAdapter().unpack(launchable);
        if (original instanceof InternalLaunchable) {
            // A launchable created by the provider - just hand it back
            launchablesParams.add((InternalLaunchable) original);
        } else if (original instanceof TaskListingLaunchable) {
            // A launchable synthesized by the consumer - unpack it into a set of task names
            taskPaths.addAll(((TaskListingLaunchable) original).getTaskNames());
        } else if (launchable instanceof Task) {
            // A task created by a provider that does not understand launchables
            taskPaths.add(((Task) launchable).getPath());
        } else {
            throw new GradleException("Only Task or TaskSelector instances are supported: "
                + (launchable != null ? launchable.getClass() : "null"));
        }
    }
    // Tasks are ignored by providers if launchables is not null
    this.launchables = launchablesParams.isEmpty() ? null : launchablesParams;
    tasks = Lists.newArrayList(taskPaths);
    return this;
}
 
Example 17
Project: sonar-css-plugin   File: RuleDescriptionsGenerator.java   View source code 6 votes vote down vote up
private String generateHtmlLessFunctionTable(List<StandardFunction> standardFunctions) {
  StringBuilder html = new StringBuilder("<table style=\"border: 0;\">\n");
  List<List<StandardFunction>> subLists = Lists.partition(standardFunctions, 3);
  for (List<StandardFunction> subList : subLists) {
    html.append("<tr>");
    for (StandardFunction standardCssFunction : subList) {
      List<String> links = standardCssFunction.getLinks().stream().filter(f -> f.contains("lesscss.org")).collect(Collectors.toList());
      html.append("<td style=\"border: 0; \">");
      if (!links.isEmpty()) {
        html.append("<a target=\"_blank\" href=\"").append(links.get(0)).append("\">");
      }
      html.append("<code>").append(standardCssFunction.getName()).append("</code>");
      if (!links.isEmpty()) {
        html.append("</a>");
      }
      html.append("</code>");
      for (int i = 1; i < links.size(); i++) {
        html.append("&nbsp;&nbsp;<a target=\"_blank\" href=\"").append(links.get(i)).append("\">#").append(i + 1).append("</a>");
      }
      html.append("</td>\n");
    }
    html.append("</tr>");
  }
  html.append("</table>\n");
  return html.toString();
}
 
Example 18
Project: hadoop   File: FSAclBaseTest.java   View source code 6 votes vote down vote up
@Test
public void testRemoveAclOnlyDefault() throws IOException {
  FileSystem.mkdirs(fs, path, FsPermission.createImmutable((short)0750));
  List<AclEntry> aclSpec = Lists.newArrayList(
    aclEntry(ACCESS, USER, ALL),
    aclEntry(ACCESS, GROUP, READ_EXECUTE),
    aclEntry(ACCESS, OTHER, NONE),
    aclEntry(DEFAULT, USER, "foo", ALL));
  fs.setAcl(path, aclSpec);
  fs.removeAcl(path);
  AclStatus s = fs.getAclStatus(path);
  AclEntry[] returned = s.getEntries().toArray(new AclEntry[0]);
  assertArrayEquals(new AclEntry[] { }, returned);
  assertPermission((short)0750);
  assertAclFeature(false);
}
 
Example 19
Project: Elasticsearch   File: PluginLoader.java   View source code 6 votes vote down vote up
private List<CrateComponentLoader.OnModuleReference> loadModuleReferences(Plugin plugin) {
    List<CrateComponentLoader.OnModuleReference> list = Lists.newArrayList();
    for (Method method : plugin.getClass().getDeclaredMethods()) {
        if (!method.getName().equals("onModule")) {
            continue;
        }
        if (method.getParameterTypes().length == 0 || method.getParameterTypes().length > 1) {
            logger.warn("Plugin: {} implementing onModule with no parameters or more than one parameter", plugin.name());
            continue;
        }
        Class moduleClass = method.getParameterTypes()[0];
        if (!Module.class.isAssignableFrom(moduleClass)) {
            logger.warn("Plugin: {} implementing onModule by the type is not of Module type {}", plugin.name(), moduleClass);
            continue;
        }
        method.setAccessible(true);
        //noinspection unchecked
        list.add(new CrateComponentLoader.OnModuleReference(moduleClass, method));
    }

    return list;
}
 
Example 20
Project: appinventor-extensions   File: ColorChoicePropertyEditor.java   View source code 6 votes vote down vote up
/**
 * Creates a new instance of the property editor.
 *
 * @param hexPrefix  language specific hex number prefix
 * @param colors  colors to be shown in property editor - must not be
 *                {@code null} or empty
 */
public ColorChoicePropertyEditor(final Color[] colors, final String hexPrefix) {
  this.hexPrefix = hexPrefix;
  this.colors = colors;

  // Initialize UI
  List<DropDownItem> choices = Lists.newArrayList();
  for (final Color color : colors) {
    choices.add(new DropDownItem(WIDGET_NAME, color.getHtmlDescription(), new Command() {
      @Override
      public void execute() {
        property.setValue(hexPrefix + color.alphaString + color.rgbString);
      }
    }));
  }
  selectedColorMenu = new DropDownButton(WIDGET_NAME, colors[0].getHtmlDescription(), choices, false,  true, false);

  selectedColorMenu.setStylePrimaryName("ode-ColorChoicePropertyEditor");

  initWidget(selectedColorMenu);
}
 
Example 21
Project: DecompiledMinecraft   File: PlayerProfileCache.java   View source code 6 votes vote down vote up
private List<PlayerProfileCache.ProfileEntry> getEntriesWithLimit(int limitSize)
{
    ArrayList<PlayerProfileCache.ProfileEntry> arraylist = Lists.<PlayerProfileCache.ProfileEntry>newArrayList();

    for (GameProfile gameprofile : Lists.newArrayList(Iterators.limit(this.gameProfiles.iterator(), limitSize)))
    {
        PlayerProfileCache.ProfileEntry playerprofilecache$profileentry = this.getByUUID(gameprofile.getId());

        if (playerprofilecache$profileentry != null)
        {
            arraylist.add(playerprofilecache$profileentry);
        }
    }

    return arraylist;
}
 
Example 22
Project: dremio-oss   File: TestArrowFileReader.java   View source code 6 votes vote down vote up
/** Helper method to get the values in given range in colBit vector used in this test class. */
private static List<Boolean> getBitValues(VectorContainer container, int start, int end) {
  FieldReader reader = container.getValueAccessorById(NullableBitVector.class, 0).getValueVector().getReader();

  List<Boolean> values = Lists.newArrayList();
  for(int i=start; i<end; i++) {
    reader.setPosition(i);
    if (reader.isSet()) {
      values.add(reader.readBoolean());
    } else {
      values.add(null);
    }
  }

  return values;
}
 
Example 23
Project: ditb   File: RegionReplicaReplicationEndpoint.java   View source code 6 votes vote down vote up
@Override
public WALEntryFilter getWALEntryfilter() {
  WALEntryFilter superFilter = super.getWALEntryfilter();
  WALEntryFilter skipReplayedEditsFilter = getSkipReplayedEditsFilter();

  if (superFilter == null) {
    return skipReplayedEditsFilter;
  }

  if (skipReplayedEditsFilter == null) {
    return superFilter;
  }

  ArrayList<WALEntryFilter> filters = Lists.newArrayList();
  filters.add(superFilter);
  filters.add(skipReplayedEditsFilter);
  return new ChainWALEntryFilter(filters);
}
 
Example 24
Project: guava-mock   File: CacheBuilderFactory.java   View source code 6 votes vote down vote up
/**
 * Sets.cartesianProduct doesn't allow sets that contain null, but we want null to mean
 * "don't call the associated CacheBuilder method" - that is, get the default CacheBuilder
 * behavior. This method wraps the elements in the input sets (which may contain null) as
 * Optionals, calls Sets.cartesianProduct with those, then transforms the result to unwrap
 * the Optionals.
 */
private Iterable<List<Object>> buildCartesianProduct(Set<?>... sets) {
  List<Set<Optional<?>>> optionalSets = Lists.newArrayListWithExpectedSize(sets.length);
  for (Set<?> set : sets) {
    Set<Optional<?>> optionalSet =
        Sets.newLinkedHashSet(Iterables.transform(set, NULLABLE_TO_OPTIONAL));
    optionalSets.add(optionalSet);
  }
  Set<List<Optional<?>>> cartesianProduct = Sets.cartesianProduct(optionalSets);
  return Iterables.transform(cartesianProduct,
      new Function<List<Optional<?>>, List<Object>>() {
        @Override public List<Object> apply(List<Optional<?>> objs) {
          return Lists.transform(objs, OPTIONAL_TO_NULLABLE);
        }
      });
}
 
Example 25
Project: empiria.player   File: BonusProviderTest.java   View source code 6 votes vote down vote up
@Test
public void next_swiffyBonus() {
    // given
    final String asset = "swiffy0";
    final Size size = new Size(1, 2);
    BonusResource bonusResource = createBonus(asset, size, SWIFFY);
    BonusAction action = createMockAction(Lists.newArrayList(bonusResource));
    when(bonusConfig.getActions()).thenReturn(Lists.newArrayList(action));

    BonusWithAsset expected = mock(BonusWithAsset.class);
    when(bonusFactory.createBonus(eq(bonusResource))).thenReturn(expected);

    // when
    Bonus result = bonusProvider.next();

    // then
    verify(bonusFactory).createBonus(bonusResource);
    assertThat(result).isEqualTo(expected);
}
 
Example 26
Project: oscm   File: TriggerServiceWSTest.java   View source code 5 votes vote down vote up
public static List<VOParameter> getVOParameters(
        ParameterValueType valueType, String paramValue, String optionId) {
    List<VOParameter> result = getVOParameters(valueType, paramValue);

    VOParameterOption option = new VOParameterOption();
    option.setOptionId(optionId);

    result.get(0).getParameterDefinition()
            .setParameterOptions(Lists.newArrayList(option));

    return result;
}
 
Example 27
Project: monarch   File: AReaderImpl.java   View source code 5 votes vote down vote up
private static OrcProto.Metadata extractMetadata(ByteBuffer bb, int metadataAbsPos,
    int metadataSize, CompressionCodec codec, int bufferSize) throws IOException {
  bb.position(metadataAbsPos);
  bb.limit(metadataAbsPos + metadataSize);
  return OrcProto.Metadata.parseFrom(InStream.createCodedInputStream("metadata",
      Lists.<DiskRange>newArrayList(new BufferChunk(bb, 0)), metadataSize, codec, bufferSize));
}
 
Example 28
Project: BaseClient   File: PlayerSelector.java   View source code 5 votes vote down vote up
private static List<Predicate<Entity>> func_179648_b(Map<String, String> p_179648_0_)
{
    List<Predicate<Entity>> list = Lists.<Predicate<Entity>>newArrayList();
    final int i = parseIntWithDefault(p_179648_0_, "lm", -1);
    final int j = parseIntWithDefault(p_179648_0_, "l", -1);

    if (i > -1 || j > -1)
    {
        list.add(new Predicate<Entity>()
        {
            public boolean apply(Entity p_apply_1_)
            {
                if (!(p_apply_1_ instanceof EntityPlayerMP))
                {
                    return false;
                }
                else
                {
                    EntityPlayerMP entityplayermp = (EntityPlayerMP)p_apply_1_;
                    return (i <= -1 || entityplayermp.experienceLevel >= i) && (j <= -1 || entityplayermp.experienceLevel <= j);
                }
            }
        });
    }

    return list;
}
 
Example 29
Project: oneops   File: Assembly.java   View source code 5 votes vote down vote up
public List<Environment> getEnvironmentList() {
  List<Environment> environmentList = Lists.newArrayList();
  for (Entry<String, Environment> entry : environments.entrySet()) {
    Environment environment = entry.getValue();
    environment.setName(entry.getKey());
    environmentList.add(environment);
  }
  return environmentList;

}
 
Example 30
Project: NioSmtpClient   File: SmtpSession.java   View source code 5 votes vote down vote up
private CompletableFuture<SmtpClientResponse> sendAsChunked(String from, Collection<String> recipients, MessageContent content, Optional<SendInterceptor> sequenceInterceptor) {
  if (ehloResponse.isSupported(Extension.PIPELINING)) {
    List<Object> objects = Lists.newArrayListWithExpectedSize(3 + recipients.size());
    objects.add(mailCommand(from, recipients));
    objects.addAll(rpctCommands(recipients));

    Iterator<ByteBuf> chunkIterator = content.getContentChunkIterator(channel.alloc());

    ByteBuf firstChunk = chunkIterator.next();
    if (firstChunk == null) {
      throw new IllegalArgumentException("The MessageContent was empty; size is " +
          (content.size().isPresent() ? Integer.toString(content.size().getAsInt()) : "not present"));
    }

    objects.add(getBdatRequestWithData(firstChunk, !chunkIterator.hasNext()));

    return beginSequence(sequenceInterceptor, objects.size(), objects.toArray())
        .thenSendInTurn(getBdatIterator(chunkIterator))
        .toResponses();

  } else {
    SendSequence sequence = beginSequence(sequenceInterceptor, 1, mailCommand(from, recipients));

    for (String recipient : recipients) {
      sequence.thenSend(SmtpRequests.rcpt(recipient));
    }

    return sequence
        .thenSendInTurn(getBdatIterator(content.getContentChunkIterator(channel.alloc())))
        .toResponses();
  }
}
 
Example 31
Project: ditb   File: TestKeyValueCompression.java   View source code 5 votes vote down vote up
@Test
public void testRepeatingKVs() throws Exception {
  List<KeyValue> kvs = Lists.newArrayList();
  for (int i = 0; i < 400; i++) {
    byte[] row = Bytes.toBytes("row" + (i % 10));
    byte[] fam = Bytes.toBytes("fam" + (i % 127));
    byte[] qual = Bytes.toBytes("qual" + (i % 128));
    kvs.add(new KeyValue(row, fam, qual, 12345L, VALUE));
  }
  
  runTestCycle(kvs);
}
 
Example 32
Project: OneClient   File: InstanceManager.java   View source code 5 votes vote down vote up
public static ObservableList<Instance> getRecentInstances() {
	loadRecent();
	if (getInstances().isEmpty())
		return FXCollections.emptyObservableList();
	List<Instance> recent = Lists.newArrayList();
	for (String name : RECENT_INSTANCES) {
		if (INSTANCES_MAP.containsKey(name))
			recent.add(INSTANCES_MAP.get(name));
	}
	if (recent.isEmpty()) {
		int size = getInstances().size();
		return FXCollections.observableArrayList(getInstances().subList(0, Math.min(size, MAX_RECENT)));
	}
	return FXCollections.observableArrayList(recent);
}
 
Example 33
Project: Backmemed   File: AnvilSaveConverter.java   View source code 5 votes vote down vote up
public List<WorldSummary> getSaveList() throws AnvilConverterException
{
    if (this.savesDirectory != null && this.savesDirectory.exists() && this.savesDirectory.isDirectory())
    {
        List<WorldSummary> list = Lists.<WorldSummary>newArrayList();
        File[] afile = this.savesDirectory.listFiles();

        for (File file1 : afile)
        {
            if (file1.isDirectory())
            {
                String s = file1.getName();
                WorldInfo worldinfo = this.getWorldInfo(s);

                if (worldinfo != null && (worldinfo.getSaveVersion() == 19132 || worldinfo.getSaveVersion() == 19133))
                {
                    boolean flag = worldinfo.getSaveVersion() != this.getSaveVersion();
                    String s1 = worldinfo.getWorldName();

                    if (StringUtils.isEmpty(s1))
                    {
                        s1 = s;
                    }

                    long i = 0L;
                    list.add(new WorldSummary(worldinfo, s, s1, 0L, flag));
                }
            }
        }

        return list;
    }
    else
    {
        throw new AnvilConverterException(I18n.translateToLocal("selectWorld.load_folder_access"));
    }
}
 
Example 34
Project: CustomWorldGen   File: FluidHandlerConcatenate.java   View source code 5 votes vote down vote up
@Override
public IFluidTankProperties[] getTankProperties()
{
    List<IFluidTankProperties> tanks = Lists.newArrayList();
    for (IFluidHandler handler : subHandlers)
    {
        Collections.addAll(tanks, handler.getTankProperties());
    }
    return tanks.toArray(new IFluidTankProperties[tanks.size()]);
}
 
Example 35
Project: CustomWorldGen   File: StructureStrongholdPieces.java   View source code 5 votes vote down vote up
/**
 * sets up Arrays with the Structure pieces and their weights
 */
public static void prepareStructurePieces()
{
    structurePieceList = Lists.<StructureStrongholdPieces.PieceWeight>newArrayList();

    for (StructureStrongholdPieces.PieceWeight structurestrongholdpieces$pieceweight : PIECE_WEIGHTS)
    {
        structurestrongholdpieces$pieceweight.instancesSpawned = 0;
        structurePieceList.add(structurestrongholdpieces$pieceweight);
    }

    strongComponentType = null;
}
 
Example 36
Project: crawling-framework   File: EsHttpSourceTestOperations.java   View source code 5 votes vote down vote up
public List<HttpSourceTest> all() {
    BoolQueryBuilder filter = QueryBuilders.boolQuery()
            .must(QueryBuilders.existsQuery("source_url"));


    Client client = getConnection().getClient();
    TimeValue keepAlive = TimeValue.timeValueMinutes(10);
    SearchResponse response = client.prepareSearch(getIndex())
            .setTypes(getType())
            .setPostFilter(filter)
            .setSize(100)
            .setScroll(keepAlive)
            .setFetchSource(true)
            .setExplain(false)
            .execute()
            .actionGet();

    List<HttpSourceTest> result = Lists.newArrayList();
    do {
        result.addAll(Arrays.stream(response.getHits().getHits())
                .map(SearchHit::getSource)
                .filter(Objects::nonNull)
                .map(this::mapToHttpSourceTest)
                .collect(Collectors.toList()));
        response = client.prepareSearchScroll(response.getScrollId())
                .setScroll(keepAlive)
                .execute()
                .actionGet();
    } while (response.getHits().getHits().length != 0);
    return result;
}
 
Example 37
Project: Reer   File: DefaultClasspathSnapshotter.java   View source code 5 votes vote down vote up
@Override
protected void visitDirectoryTree(DirectoryFileTree directoryTree, List<DefaultFileDetails> fileTreeElements) {
    // Sort non-root elements as their order is not important
    List<DefaultFileDetails> subElements = Lists.newArrayList();
    super.visitDirectoryTree(directoryTree, subElements);
    Collections.sort(subElements, FILE_DETAILS_COMPARATOR);
    fileTreeElements.addAll(subElements);
}
 
Example 38
Project: OperatieBRP   File: MeldingBepalerServiceImpl.java   View source code 5 votes vote down vote up
@Override
public List<Melding> geefWaarschuwingen(final List<BijgehoudenPersoon> bijgehoudenPersoonList) {
    final List<Melding> meldingList = Lists.newLinkedList();
    bijgehoudenPersoonList.forEach(
            persoon -> controleerVerstrekkingbeperkingOpPersoon(persoon.getPersoonslijst(), persoon.getCommunicatieId(), meldingList));
    return meldingList;
}
 
Example 39
Project: angit   File: BeanValidators.java   View source code 5 votes vote down vote up
/**
 * 辅助方法, 转换Set<ConstraintViolation>为List<message>
 *
 * @param constraintViolations the constraint violations
 * @return the list
 */
@SuppressWarnings("rawtypes")
public static List<String> extractMessage(Set<? extends ConstraintViolation> constraintViolations) {
    List<String> errorMessages = Lists.newArrayList();
    errorMessages.addAll(constraintViolations.stream().map((Function<ConstraintViolation, String>) ConstraintViolation::getMessage).collect(Collectors.toList()));
    return errorMessages;
}
 
Example 40
Project: Pogamut3   File: BspListDataStrategy.java   View source code 5 votes vote down vote up
/** Split data
* 
* See {@link IBspStrategy#splitData(Object, Object)}
*/
  public SplitData<ArrayList<TElement>> splitData(TBoundary boundary, ArrayList<TElement> data) {
      ArrayList<TElement> positiveData = Lists.newArrayList();
      ArrayList<TElement> negativeData = Lists.newArrayList();
      
      for (TElement element : data) {
          BspOccupation occupation = determineElementOccupation(boundary, element);
          
          if (occupation.intersectsPositive()) {
              positiveData.add(element);
          }
          
          if (occupation.intersectsNegative()) {
              negativeData.add(element);
          }
      }
      
      if ( positiveData.isEmpty() ) {
      	positiveData = null;
      }
      
      if ( negativeData.isEmpty() ) {
      	negativeData = null;
      } 
      
      return new SplitData<ArrayList<TElement>>( negativeData, positiveData );
  }