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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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: dremio-oss   File: TestArrowFileReader.java   Source Code and License 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 22
Project: ditb   File: RegionReplicaReplicationEndpoint.java   Source Code and License 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 23
Project: guava-mock   File: CacheBuilderFactory.java   Source Code and License 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 24
Project: empiria.player   File: BonusProviderTest.java   Source Code and License 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 25
Project: oscm   File: TriggerServiceWSTest.java   Source Code and License 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 26
Project: monarch   File: AReaderImpl.java   Source Code and License 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 27
Project: BaseClient   File: PlayerSelector.java   Source Code and License 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 28
Project: oneops   File: Assembly.java   Source Code and License 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 29
Project: NioSmtpClient   File: SmtpSession.java   Source Code and License 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 30
Project: ditb   File: TestKeyValueCompression.java   Source Code and License 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 31
Project: OneClient   File: InstanceManager.java   Source Code and License 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 32
Project: Backmemed   File: AnvilSaveConverter.java   Source Code and License 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 33
Project: CustomWorldGen   File: FluidHandlerConcatenate.java   Source Code and License 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 34
Project: CustomWorldGen   File: StructureStrongholdPieces.java   Source Code and License 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 35
Project: crawling-framework   File: EsHttpSourceTestOperations.java   Source Code and License 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 36
Project: Reer   File: DefaultClasspathSnapshotter.java   Source Code and License 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 37
Project: OperatieBRP   File: MeldingBepalerServiceImpl.java   Source Code and License 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 38
Project: angit   File: BeanValidators.java   Source Code and License 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 39
Project: Pogamut3   File: BspListDataStrategy.java   Source Code and License 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 );
  }
 
Example 40
Project: rocket-console   File: MessageServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<MessageView> queryMessageByTopicAndKey(String topic, String key) {
    try {
        return Lists.transform(mqAdminExt.queryMessage(topic, key, QUERY_MESSAGE_MAX_NUM, 0, System.currentTimeMillis()).getMessageList(), new Function<MessageExt, MessageView>() {
            @Override
            public MessageView apply(MessageExt messageExt) {
                return MessageView.fromMessageExt(messageExt);
            }
        });
    } catch (Exception err) {
        throw Throwables.propagate(err);
    }
}
 
Example 41
Project: GitHub   File: ObjectChecker.java   Source Code and License 5 votes vote down vote up
static StackTraceElement[] trimStackTrace(StackTraceElement[] stackTrace) {
  LinkedList<StackTraceElement> list = Lists.newLinkedList();
  for (int i = stackTrace.length - 1; i >= 0; i--) {
    StackTraceElement s = stackTrace[i];
    if (s.getClassName().startsWith(Checkers.class.getPackage().getName())) {
      break;
    }
    list.addLast(s);
  }
  return list.toArray(new StackTraceElement[list.size()]);
}
 
Example 42
Project: n4js   File: N4JSRuntimeCore.java   Source Code and License 5 votes vote down vote up
private void installIndex(ResourceSet resourceSet) {
	// Fill index
	ResourceDescriptionsData index = new OrderedResourceDescriptionsData(
			Collections.<IResourceDescription> emptyList());
	List<Resource> resources = Lists.newArrayList(resourceSet.getResources());
	for (Resource resource : resources) {
		index(resource, resource.getURI(), index);
	}
	Adapter existing = EcoreUtil.getAdapter(resourceSet.eAdapters(), ResourceDescriptionsData.class);
	if (existing != null) {
		resourceSet.eAdapters().remove(existing);
	}
	ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(resourceSet, index);
}
 
Example 43
Project: QDrill   File: HiveScanBatchCreator.java   Source Code and License 5 votes vote down vote up
@Override
public ScanBatch getBatch(FragmentContext context, HiveSubScan config, List<RecordBatch> children)
    throws ExecutionSetupException {
  List<RecordReader> readers = Lists.newArrayList();
  Table table = config.getTable();
  List<InputSplit> splits = config.getInputSplits();
  List<Partition> partitions = config.getPartitions();
  boolean hasPartitions = (partitions != null && partitions.size() > 0);
  int i = 0;

  // Native hive text record reader doesn't handle all types currently. For now use HiveRecordReader which uses
  // Hive InputFormat and SerDe classes to read the data.
  //if (table.getSd().getInputFormat().equals(TextInputFormat.class.getCanonicalName()) &&
  //        table.getSd().getSerdeInfo().getSerializationLib().equals(LazySimpleSerDe.class.getCanonicalName()) &&
  //        config.getColumns() != null) {
  //  for (InputSplit split : splits) {
  //    readers.add(new HiveTextRecordReader(table,
  //        (hasPartitions ? partitions.get(i++) : null),
  //        split, config.getColumns(), context));
  //  }
  //} else {
    for (InputSplit split : splits) {
      readers.add(new HiveRecordReader(table,
          (hasPartitions ? partitions.get(i++) : null),
          split, config.getColumns(), context, config.getHiveReadEntry().hiveConfigOverride));
    }
  //}

  // If there are no readers created (which is possible when the table is empty), create an empty RecordReader to
  // output the schema
  if (readers.size() == 0) {
    readers.add(new HiveRecordReader(table, null, null, config.getColumns(), context,
        config.getHiveReadEntry().hiveConfigOverride));
  }

  return new ScanBatch(config, context, readers.iterator());
}
 
Example 44
Project: QDrill   File: WindowPrule.java   Source Code and License 5 votes vote down vote up
private List<DrillDistributionTrait.DistributionField> getDistributionFields(Window.Group window) {
  List<DrillDistributionTrait.DistributionField> groupByFields = Lists.newArrayList();
  for (int group : BitSets.toIter(window.keys)) {
    DrillDistributionTrait.DistributionField field = new DrillDistributionTrait.DistributionField(group);
    groupByFields.add(field);
  }

  return groupByFields;
}
 
Example 45
Project: Equella   File: SchemaServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Transactional
public List<BaseEntityLabel> getSchemaUses(long id)
{
	List<BaseEntityLabel> results = Lists.newArrayList();
	for( SchemaReferences refs : referenceTracker.getBeanList() )
	{
		results.addAll(refs.getSchemaUses(id));
	}
	return results;
}
 
Example 46
Project: Backmemed   File: EnchantmentHelper.java   Source Code and License 5 votes vote down vote up
public static List<EnchantmentData> buildEnchantmentList(Random randomIn, ItemStack itemStackIn, int p_77513_2_, boolean allowTreasure)
{
    List<EnchantmentData> list = Lists.<EnchantmentData>newArrayList();
    Item item = itemStackIn.getItem();
    int i = item.getItemEnchantability();

    if (i <= 0)
    {
        return list;
    }
    else
    {
        p_77513_2_ = p_77513_2_ + 1 + randomIn.nextInt(i / 4 + 1) + randomIn.nextInt(i / 4 + 1);
        float f = (randomIn.nextFloat() + randomIn.nextFloat() - 1.0F) * 0.15F;
        p_77513_2_ = MathHelper.clamp(Math.round((float)p_77513_2_ + (float)p_77513_2_ * f), 1, Integer.MAX_VALUE);
        List<EnchantmentData> list1 = getEnchantmentDatas(p_77513_2_, itemStackIn, allowTreasure);

        if (!list1.isEmpty())
        {
            list.add(WeightedRandom.getRandomItem(randomIn, list1));

            while (randomIn.nextInt(50) <= p_77513_2_)
            {
                removeIncompatible(list1, (EnchantmentData)Util.getLastElement(list));

                if (list1.isEmpty())
                {
                    break;
                }

                list.add(WeightedRandom.getRandomItem(randomIn, list1));
                p_77513_2_ /= 2;
            }
        }

        return list;
    }
}
 
Example 47
Project: saluki   File: GrpcRoutePicker.java   Source Code and License 5 votes vote down vote up
private List<GrpcURL> findGrpcURLByAddress(SocketAddress address) {
  Map<List<SocketAddress>, GrpcURL> addressMapping =
      nameResovleCache.get(GrpcNameResolverProvider.GRPC_ADDRESS_GRPCURL_MAPPING);
  List<GrpcURL> providerUrls = Lists.newArrayList();
  if (!addressMapping.isEmpty()) {
    for (Map.Entry<List<SocketAddress>, GrpcURL> entry : addressMapping.entrySet()) {
      List<SocketAddress> allAddress = entry.getKey();
      if (allAddress.contains(address)) {
        providerUrls.add(entry.getValue());
      }
    }
  }
  return providerUrls;
}
 
Example 48
Project: ditb   File: TestEnableTableHandler.java   Source Code and License 5 votes vote down vote up
private ArrayList<HRegionInfo> filterTableRegions(final TableName tableName,
    List<HRegionInfo> onlineRegions) {
  return Lists.newArrayList(Iterables.filter(onlineRegions, new Predicate<HRegionInfo>() {
    @Override
    public boolean apply(HRegionInfo input) {
      return input.getTable().equals(tableName);
    }
  }));
}
 
Example 49
Project: QDrill   File: SelectionVectorPrelVisitor.java   Source Code and License 5 votes vote down vote up
@Override
public Prel visitPrel(Prel prel, Void value) throws RuntimeException {
  SelectionVectorMode[] encodings = prel.getSupportedEncodings();
  List<RelNode> children = Lists.newArrayList();
  for (Prel child : prel) {
    child = child.accept(this, null);
    children.add(convert(encodings, child));
  }

  return (Prel) prel.copy(prel.getTraitSet(), children);
}
 
Example 50
Project: businessworks   File: InterceptorStackCallback.java   Source Code and License 5 votes vote down vote up
/**
 * Removes stacktrace elements related to AOP internal mechanics from the
 * throwable's stack trace and any causes it may have.
 */
private void pruneStacktrace(Throwable throwable) {
  for(Throwable t = throwable; t != null; t = t.getCause()) {
    StackTraceElement[] stackTrace = t.getStackTrace();
    List<StackTraceElement> pruned = Lists.newArrayList();
    for (StackTraceElement element : stackTrace) {
      String className = element.getClassName();
      if (!AOP_INTERNAL_CLASSES.contains(className) && !className.contains("$EnhancerByGuice$")) {
        pruned.add(element);
      }
    }
    t.setStackTrace(pruned.toArray(new StackTraceElement[pruned.size()]));
  }
}
 
Example 51
Project: wmboost-data   File: DocumentTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPutIntegerList() {
	Integer[] expected = {3, 1, 4};
	List<Integer> input = Lists.newArrayList(3, 1, 4);
	
	Document document = docFactory.create();
	document.intsEntry("value1").put(input);

	// confirm value has actually been added
	IDataCursor cursor = document.getIData().getCursor();
	Integer[] returnedValue = (Integer[]) IDataUtil.get(cursor, "value1");
	assertArrayEquals(expected, returnedValue);
}
 
Example 52
Project: cakes   File: TestListWithExpectedSize.java   Source Code and License 5 votes vote down vote up
/**
 * java.lang.OutOfMemoryError: GC overhead limit exceeded
 */
@Test
public void testListWithExpectedSize() {
    List<Order> orders = Lists.newArrayListWithExpectedSize(20000000);
    for (int i = 0; i < 20000000; i++) {
        orders.add(new Order(i, i, "channel" + i, "18612534461"));
    }
    System.out.println("finished!!!");
}
 
Example 53
Project: dremio-oss   File: TestFrameworkTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = AssertionError.class)
public void testSchemaTestBuilderSetInvalidBaselineColumns() throws Exception {
  final String query = "SELECT ltrim('dremio') as col FROM (VALUES(1)) limit 0";

  List<Pair<SchemaPath, MajorType>> expectedSchema = Lists.newArrayList();
MajorType majorType = Types.required(MinorType.VARCHAR);
  expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));

  testBuilder()
      .sqlQuery(query)
      .baselineColumns("col")
      .schemaBaseLine(expectedSchema)
      .build()
      .run();
}
 
Example 54
Project: OperatieBRP   File: GroepElement.java   Source Code and License 5 votes vote down vote up
/**
 * Bepaalt of een groep een verantwoordingsgroep is, volgens definitie R1541.
 * @return true als groep een verantwoordingsgroep is
 */
@Bedrijfsregel(Regel.R1541)
public boolean isVerantwoordingsgroep() {
    return Lists.newArrayList(
            ElementHelper.getObjectElement(Element.ADMINISTRATIEVEHANDELING),
            ElementHelper.getObjectElement(Element.ACTIE),
            ElementHelper.getObjectElement(Element.ACTIEBRON),
            ElementHelper.getObjectElement(Element.DOCUMENT),
            ElementHelper.getObjectElement(Element.GEDEBLOKKEERDEMELDING)).contains(this.getObjectElement());
}
 
Example 55
Project: Reer   File: BaseCrossBuildResultsStore.java   Source Code and License 5 votes vote down vote up
private List<String> toList(Object object) {
    Object[] value = (Object[]) object;
    if (value == null) {
        return null;
    }
    List<String> list = Lists.newLinkedList();
    for (Object aValue : value) {
        list.add(aValue.toString());
    }
    return list;
}
 
Example 56
Project: dremio-oss   File: ConvertFromJsonOperator.java   Source Code and License 5 votes vote down vote up
/**
 * Update field schema
 * @param datasetConfig old dataset config
 * @param fieldName field's name
 * @param fieldSchema new field schema
 * @return updated dataset config
 */
private DatasetConfig updateDatasetField(DatasetConfig datasetConfig, final String fieldName, CompleteType fieldSchema) {
  // clone the dataset config
  Serializer<DatasetConfig> serializer = ProtostuffSerializer.of(DatasetConfig.getSchema());
  DatasetConfig newDatasetConfig = serializer.deserialize(serializer.serialize(datasetConfig));

  List<DatasetField> datasetFields = newDatasetConfig.getDatasetFieldsList();
  if (datasetFields == null) {
    datasetFields = Lists.newArrayList();
  }

  DatasetField datasetField = Iterables.find(datasetFields, new Predicate<DatasetField>() {
    @Override
    public boolean apply(@Nullable DatasetField input) {
      return fieldName.equals(input.getFieldName());
    }
  }, null);

  if (datasetField == null) {
    datasetField = new DatasetField().setFieldName(fieldName);
    datasetFields.add(datasetField);
  }

  datasetField.setFieldSchema(ByteString.copyFrom(fieldSchema.serialize()));
  newDatasetConfig.setDatasetFieldsList(datasetFields);

  return newDatasetConfig;
}
 
Example 57
Project: Equella   File: SelectionsTableState.java   Source Code and License 5 votes vote down vote up
public List<SelectionsTableSelection> getSelections()
{
	if( selections == null )
	{
		selections = Lists.newArrayList();
	}
	return selections;
}
 
Example 58
Project: NioSmtpClient   File: SmtpSessionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void itDoesNotPipelineRsetUnlessSupportedByTheServer() {
  resetEhloExtensions();
  when(responseHandler.createResponseFuture(anyInt(), any())).thenAnswer(a -> CompletableFuture.completedFuture(Lists.newArrayList(OK_RESPONSE)));

  session.send(ALICE, BOB, MessageContent.of(Unpooled.copiedBuffer(MESSAGE_BYTES))).join();
  session.send(ALICE, BOB, MessageContent.of(Unpooled.copiedBuffer(MESSAGE_BYTES))).join();

  InOrder order = inOrder(channel);
  order.verify(channel).write(req(SmtpCommand.MAIL, "FROM:<" + ALICE + ">"));
  order.verify(channel).flush();
  order.verify(channel).write(req(SmtpCommand.RCPT, "TO:<" + BOB + ">"));
  order.verify(channel).flush();
  order.verify(channel).write(req(SmtpCommand.DATA));
  order.verify(channel).flush();
  order.verify(channel).write(DotCrlfBuffer.get());
  order.verify(channel).flush();

  order.verify(channel).write(req(SmtpCommand.RSET));
  order.verify(channel).flush();
  order.verify(channel).write(req(SmtpCommand.MAIL, "FROM:<" + ALICE + ">"));
  order.verify(channel).flush();
  order.verify(channel).write(req(SmtpCommand.RCPT, "TO:<" + BOB + ">"));
  order.verify(channel).flush();
  order.verify(channel).write(req(SmtpCommand.DATA));
  order.verify(channel).flush();
  order.verify(channel).write(DotCrlfBuffer.get());
  order.verify(channel).flush();

  assertThat(log.getLog()).isEqualTo(
      "MAIL, 250 OK, RCPT, 250 OK, DATA, 250 OK, <contents>, 250 OK, " +
      "RSET, 250 OK, " +
      "MAIL, 250 OK, RCPT, 250 OK, DATA, 250 OK, <contents>, 250 OK");
}
 
Example 59
Project: Reer   File: ModelSchemaAspectExtractor.java   Source Code and License 5 votes vote down vote up
public <T> List<ModelSchemaAspect> extract(ModelSchemaExtractionContext<T> extractionContext, List<ModelPropertyExtractionResult<?>> propertyResults) {
    List<ModelSchemaAspect> aspects = Lists.newArrayList();
    for (ModelSchemaAspectExtractionStrategy strategy : strategies) {
        ModelSchemaAspectExtractionResult result = strategy.extract(extractionContext, propertyResults);
        if (result != null) {
            aspects.add(result.getAspect());
        }
    }
    return aspects;
}
 
Example 60
Project: QDrill   File: DrillParserUtil.java   Source Code and License 5 votes vote down vote up
public static SqlNode createCondition(SqlNode left, SqlOperator op, SqlNode right) {

    // if one of the operands is null, return the other
    if (left == null || right == null) {
      return left != null ? left : right;
    }

    List<Object> listCondition = Lists.newArrayList();
    listCondition.add(left);
    listCondition.add(new SqlParserUtil.ToTreeListItem(op, SqlParserPos.ZERO));
    listCondition.add(right);

    return SqlParserUtil.toTree(listCondition);
  }