Java Code Examples for com.google.common.collect.Lists#newArrayList()

The following examples show how to use com.google.common.collect.Lists#newArrayList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QueryConverterIT.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
@Test
public void countGroupByQueryHavingByCount() throws ParseException, IOException, JSONException {
    QueryConverter queryConverter = new QueryConverter.Builder().sqlString("select cuisine, count(cuisine) from "+COLLECTION+" WHERE borough = 'Manhattan' GROUP BY cuisine HAVING count(cuisine) > 500").build();
    QueryResultIterator<Document> distinctIterable = queryConverter.run(mongoDatabase);
    queryConverter.write(System.out);
    List<Document> results = Lists.newArrayList(distinctIterable);
    assertEquals(4, results.size());
    JSONAssert.assertEquals("[{\n" + 
    		"	\"cuisine\": \"Chinese\",\n" + 
    		"	\"count\": 510\n" +  
    		"}," +
    		"{\n" + 
    		"	\"cuisine\": \"Italian\",\n" + 
    		"	\"count\": 621\n" +  
    		"}," +
    		"{\n" + 
    		"	\"cuisine\": \"Café/Coffee/Tea\",\n" + 
    		"	\"count\": 680\n" +
    		"}," +
    		"{\n" + 
    		"	\"cuisine\": \"American \",\n" + 
    		"	\"count\": 3205\n" +
    		"}]",toJson(results),false);
}
 
Example 2
Source File: ActivityRuleService.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
public List<ActivityRuleEntity> getActivityRule(ActivityRuleEntity activityRuleEntity) throws DTSAdminException {
    ActivityRuleDO activityRuleDO = ActivityRuleHelper.toActivityRuleDO(activityRuleEntity);
    ActivityRuleDOExample example = new ActivityRuleDOExample();
    Criteria criteria = example.createCriteria();
    criteria.andIsDeletedIsNotNull();
    if (StringUtils.isNotEmpty(activityRuleDO.getBizType())) {
        criteria.andBizTypeLike(activityRuleDO.getBizType());
    }
    if (StringUtils.isNotEmpty(activityRuleDO.getApp())) {
        criteria.andAppLike(activityRuleDO.getApp());
    }
    if (StringUtils.isNotEmpty(activityRuleDO.getAppCname())) {
        criteria.andAppCnameLike(activityRuleDO.getAppCname());
    }
    example.setOrderByClause("app,biz_type");
    List<ActivityRuleDO> lists = activityRuleDOMapper.selectByExample(example);
    if (CollectionUtils.isEmpty(lists)) {
        return Lists.newArrayList();
    }
    List<ActivityRuleEntity> entities = Lists.newArrayList();
    for (ActivityRuleDO an : lists) {
        entities.add(ActivityRuleHelper.toActivityRuleEntity(an));
    }
    return entities;
}
 
Example 3
Source File: TreeCuboidScheduler.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private TreeNode doFindBestParent(long cuboidId, TreeNode parentCuboid) {
    if (!canDerive(cuboidId, parentCuboid.cuboidId)) {
        return null;
    }

    List<TreeNode> candidates = Lists.newArrayList();
    for (TreeNode childCuboid : parentCuboid.children) {
        TreeNode candidate = doFindBestParent(cuboidId, childCuboid);
        if (candidate != null) {
            candidates.add(candidate);
        }
    }
    if (candidates.isEmpty()) {
        candidates.add(parentCuboid);
    }

    return Collections.min(candidates, new Comparator<TreeNode>() {
        @Override
        public int compare(TreeNode o1, TreeNode o2) {
            return cuboidComparator.compare(o1.cuboidId, o2.cuboidId);
        }
    });
}
 
Example 4
Source File: MaybeReachingVariableUseTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Computes reaching use on given source.
 */
private void computeUseDef(String src) {
  Compiler compiler = new Compiler();
  src = "function _FUNCTION(param1, param2){" + src + "}";
  Node n = compiler.parseTestCode(src).getFirstChild();
  assertEquals(0, compiler.getErrorCount());
  Scope scope = new SyntacticScopeCreator(compiler).createScope(n, null);
  ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, true);
  cfa.process(null, n);
  ControlFlowGraph<Node> cfg = cfa.getCfg();
  useDef = new MaybeReachingVariableUse(cfg, scope, compiler);
  useDef.analyze();
  def = null;
  uses = Lists.newArrayList();
  new NodeTraversal(compiler,new LabelFinder()).traverse(n);
  assertNotNull("Code should have an instruction labeled D", def);
  assertFalse("Code should have an instruction labeled starting withing U",
      uses.isEmpty());
}
 
Example 5
Source File: CascadedConfiguration.java    From caravan with Apache License 2.0 6 votes vote down vote up
public CascadedConfiguration(Configuration configuration, String keySeparator, List<String> cascadedFactors) {
    NullArgumentChecker.DEFAULT.check(configuration, "configuration");
    StringArgumentChecker.DEFAULT.check(keySeparator, "keySeperator");
    NullArgumentChecker.DEFAULT.check(cascadedFactors, "cascadedFactors");

    _configuration = configuration;
    _keySeparator = keySeparator.trim();
    _cascadedKeyParts = Lists.newArrayList();

    StringBuffer keyPart = new StringBuffer(StringValues.EMPTY);
    _cascadedKeyParts.add(keyPart.toString());
    for (String factor : cascadedFactors) {
        if (StringValues.isNullOrWhitespace(factor))
            continue;
        keyPart.append(_keySeparator).append(factor);
        _cascadedKeyParts.add(keyPart.toString());
    }

    Collections.reverse(_cascadedKeyParts);
    _cascadedKeyParts = Collections.unmodifiableList(_cascadedKeyParts);
}
 
Example 6
Source File: FindFirstNonNull.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
	public void find_first_non_null_list_java8_lambda () {

		List<String> strings = Lists.newArrayList(
				null, 
				"Hello",
				null,
				"World");

		Optional<String> firstNonNull = strings
				.stream()
				.filter(p -> p != null)
//				.filter(Objects::nonNull)
				.findFirst();
		
		assertEquals("Hello", firstNonNull.get());
	}
 
Example 7
Source File: SchemaCommand.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getExamples() {
  return Lists.newArrayList(
      "# Print the Avro schema for a Parquet file",
      "sample.parquet",
      "# Print the Avro schema for an Avro file",
      "sample.avro",
      "# Print the Avro schema for a JSON file",
      "sample.json"
  );
}
 
Example 8
Source File: MultiExceptionTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMessageReturnsCombinedMessages() throws Exception {
    MultiException multiException = new MultiException(Lists.newArrayList(
        new Exception("first one"), new Exception("second one")));
    assertThat(multiException.getMessage(), is("first one\n" +
                                               "second one"));
}
 
Example 9
Source File: BooEnvironment.java    From oneops with Apache License 2.0 5 votes vote down vote up
public List<BooPlatform> getPlatformList() {
  List<BooPlatform> platformList = Lists.newArrayList();
  for (Entry<String, BooPlatform> entry : platforms.entrySet()) {
    BooPlatform platform = entry.getValue();
    platform.setName(entry.getKey());
    platformList.add(platform);
  }
  return platformList;
}
 
Example 10
Source File: MNVValidator.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
@VisibleForTesting
static List<VariantContext> outputVariants(@NotNull final MNVRegionValidator regionValidator, @NotNull final MNVMerger merger) {
    final List<VariantContext> result = Lists.newArrayList();
    for (final PotentialMNV validMnv : regionValidator.validMnvs()) {
        final VariantContext mergedVariant = merger.mergeVariants(validMnv, regionValidator.mostFrequentReads());
        result.add(mergedVariant);
    }
    result.addAll(regionValidator.nonMnvVariants());
    result.sort(Comparator.comparing(VariantContext::getStart).thenComparing(variantContext -> variantContext.getReference().length()));
    return result;
}
 
Example 11
Source File: CustomIloadBalancer.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
public List<Server> getRoutedList(List<Server> list, String tagKey, String expectedTagValue)
        throws Exception {
    if (TAG_PLATFORM.equalsIgnoreCase(tagKey)) {
        List<Server> resultServerList = Lists.newArrayList(list);

        // 对接天路注册中心
        JavaType javaType = getCollectionType(List.class, FormulaDiscoveryServer.class);
        String value = objectMapper.writeValueAsString(resultServerList);
        List<FormulaDiscoveryServer> serverList = objectMapper.readValue(value, javaType);

        Iterator<Server> iterator1 = resultServerList.iterator();
        Iterator<FormulaDiscoveryServer> iterator2 = serverList.iterator();
        while(iterator2.hasNext()) {
            FormulaDiscoveryServer formulaDiscoveryServer = iterator2.next();
            iterator1.next();
            // 平台(部署组信息)
            String platformName = formulaDiscoveryServer.getInstance().getCustoms().get(
                    FORMULA_DISCOVERY_CUSTOM_PLATFORM);
            // 不符合条件的移出掉
            if (StringUtils.isEmpty(platformName) || !platformName.equals(expectedTagValue)) {
                iterator1.remove();
            }
        }
        // TODO 是否对路由后的实例列表为0时做特殊处理
        return resultServerList;
    }
    return list;
}
 
Example 12
Source File: TestFlexibleAutoInstanceManagement.java    From exhibitor with Apache License 2.0 5 votes vote down vote up
@Test
public void     testNoChange() throws Exception
{
    MockExhibitorInstance       mockExhibitorInstance = new MockExhibitorInstance("a");
    mockExhibitorInstance.getMockConfigProvider().setConfig(StringConfigs.SERVERS_SPEC, "1:a,2:b,3:c");
    mockExhibitorInstance.getMockConfigProvider().setConfig(IntConfigs.AUTO_MANAGE_INSTANCES, 1);
    mockExhibitorInstance.getMockConfigProvider().setConfig(IntConfigs.AUTO_MANAGE_INSTANCES_SETTLING_PERIOD_MS, 0);
    mockExhibitorInstance.getMockConfigProvider().setConfig(IntConfigs.AUTO_MANAGE_INSTANCES_FIXED_ENSEMBLE_SIZE, 0);

    List<ServerStatus>          statuses = Lists.newArrayList();
    statuses.add(new ServerStatus("a", InstanceStateTypes.SERVING.getCode(), "", true));
    statuses.add(new ServerStatus("b", InstanceStateTypes.SERVING.getCode(), "", false));
    statuses.add(new ServerStatus("c", InstanceStateTypes.SERVING.getCode(), "", false));
    Mockito.when(mockExhibitorInstance.getMockForkJoinPool().invoke(Mockito.isA(ClusterStatusTask.class))).thenReturn(statuses);

    final AtomicBoolean         configWasChanged = new AtomicBoolean(false);
    AutomaticInstanceManagement management = new AutomaticInstanceManagement(mockExhibitorInstance.getMockExhibitor())
    {
        @Override
        void adjustConfig(String newSpec, String leaderHostname) throws Exception
        {
            super.adjustConfig(newSpec, leaderHostname);
            configWasChanged.set(true);
        }
    };
    management.call();

    Assert.assertFalse(configWasChanged.get());
}
 
Example 13
Source File: ParquetReaderUtility.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Converts {@link ColumnDescriptor} to {@link SchemaPath} and converts any parquet LOGICAL LIST to something
 * the execution engine can understand (removes the extra 'list' and 'element' fields from the name)
 */
public static List<String> convertColumnDescriptor(final MessageType schema, final ColumnDescriptor columnDescriptor) {
  List<String> path = Lists.newArrayList(columnDescriptor.getPath());

  // go through the path and find all logical lists
  int index = 0;
  Type type = schema;
  while (!type.isPrimitive()) { // don't bother checking the last element in the path as it is a primitive type
    type = type.asGroupType().getType(path.get(index));
    if (type.getOriginalType() == OriginalType.LIST && LogicalListL1Converter.isSupportedSchema(type.asGroupType())) {
      // remove 'list'
      type = type.asGroupType().getType(path.get(index+1));
      path.remove(index+1);

      // remove 'element'
      type = type.asGroupType().getType(path.get(index+1));

      //handle nested list case
      while (type.getOriginalType() == OriginalType.LIST && LogicalListL1Converter.isSupportedSchema(type.asGroupType())) {
        // current 'list'.'element' entry
        path.remove(index+1);

        // nested 'list' entry
        type = type.asGroupType().getType(path.get(index+1));
        path.remove(index+1);

        type = type.asGroupType().getType(path.get(index+1));
      }

      // final 'list'.'element' entry
      path.remove(index+1);

    }
    index++;
  }
  return path;
}
 
Example 14
Source File: PortManager.java    From android-test with Apache License 2.0 5 votes vote down vote up
/** Serves ports in the user specified range. */
public PortManager(Range<Integer> portRange) {
  this(
      portRange,
      Lists.newArrayList(SocketType.TCP, SocketType.UDP),
      SECURE_RANDOM,
      new ClientConnectChecker());
}
 
Example 15
Source File: CanonicalAnnotationTest.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void favourCDKN2ACosmicAnnotation() {
    final CosmicAnnotation p16 = createCosmicAnnotation("CDKN2A", CDKN2A);
    final CosmicAnnotation p14 = createCosmicAnnotation("CDKN2A", CDKN2A_P14ARF);
    final CosmicAnnotation other = createCosmicAnnotation("CDKN2A", CDKN2A_OTHER);

    final List<CosmicAnnotation> all = Lists.newArrayList(other, p14, p16);

    final CanonicalAnnotation victim = new CanonicalAnnotation();
    assertEquals(p16, victim.canonicalCosmicAnnotation(all).get());
    assertFalse(victim.canonicalCosmicAnnotation(Lists.newArrayList(p14)).isPresent());
}
 
Example 16
Source File: LessThan.java    From indexr with Apache License 2.0 4 votes vote down vote up
@Override
public List<Object> args() {return Lists.newArrayList(left, right);}
 
Example 17
Source File: RmlMapperTest.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void canHandleCircularReferenceToSelf() {
  final String theNamePredicate = "http://example.org/vocab#name";
  final String theIsParentOfPredicate = "http://example.org/vocab#isParentOf";
  final String theIsRelatedToPredicate = "http://example.org/vocab#isRelatedTo";
  DataSource input = new TestDataSource(Lists.newArrayList(
    ImmutableMap.of(
            "rdfUri", "http://example.com/persons/1",
            "naam", "Bill",
            "parentOf", "Joe",
            "relatedTo", ""
    ),
    ImmutableMap.of(
            "rdfUri", "http://example.com/persons/2",
            "naam", "Joe",
            "parentOf", "",
            "relatedTo", "Bill")
  ));
  RmlMappingDocument rmlMappingDocument = rmlMappingDocument()
          .withTripleMap("http://example.org/personsMap",
                  makePersonMap(theNamePredicate, theIsParentOfPredicate, theIsRelatedToPredicate))
          .build(x -> Optional.of(input));

  List<Quad> result = rmlMappingDocument
          .execute(new LoggingErrorHandler())
          .collect(toList());

  assertThat(result, containsInAnyOrder(
    likeTriple(
      uri("http://example.com/persons/1"),
      uri(theNamePredicate),
      literal("Bill")
    ),
    likeTriple(
      uri("http://example.com/persons/2"),
      uri(theNamePredicate),
      literal("Joe")
    ),
    likeTriple(
      uri("http://example.com/persons/1"),
      uri(theIsParentOfPredicate),
      uri("http://example.com/persons/2")
    ),
    likeTriple(
      uri("http://example.com/persons/2"),
      uri(theIsRelatedToPredicate),
      uri("http://example.com/persons/1")
    )
  ));
}
 
Example 18
Source File: Vertex.java    From tez with Apache License 2.0 4 votes vote down vote up
List<RootInputLeafOutput<OutputDescriptor, OutputCommitterDescriptor>> getOutputs() {
  return Lists.newArrayList(additionalOutputs.values());
}
 
Example 19
Source File: TestJDWPAgentDebug.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Collection<String> affects() {
    return Lists.newArrayList(affects);
}
 
Example 20
Source File: AssetGroupEmailServiceTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Test
public void executeEmailServiceForAssetGroupTest(){
    List<Map<String, Object>> ownerEmailDetails=new ArrayList<Map<String,Object>>();
    Map<String,Object>ownerDetails=new HashMap<>();
    ownerDetails.put("ownerName", "jack");
    ownerDetails.put("assetGroup", "aws-all");
    ownerDetails.put("ownerEmail", "[email protected]");
    ownerDetails.put("ownerName", "jack");
    ownerEmailDetails.add(ownerDetails);
    Map<String,Object>patchingDetails=new HashMap<>();
    patchingDetails.put("unpatched_instances", 0);
    patchingDetails.put("patched_instances", 5816);
    patchingDetails.put("total_instances", 5816);
    patchingDetails.put("patching_percentage", 100);
    Response patchingResponse = new Response();
    patchingResponse.setData(patchingDetails);
    Map<String,Object>certificateDetails=new HashMap<>();
    certificateDetails.put("certificates", 1284);
    certificateDetails.put("certificates_expiring", 0);
    Response CertificateResponse = new Response();
    CertificateResponse.setData(certificateDetails);
    Map<String,Object> taggingDetails=new HashMap<>();
    taggingDetails.put("assets", 122083);
    taggingDetails.put("untagged", 47744);
    taggingDetails.put("tagged", 74339);
    taggingDetails.put("compliance", 60);
    Response taggingResponse = new Response();
    taggingResponse.setData(taggingDetails);
    Map<String,Object> vulnerabilityDetails=new HashMap<>();
    vulnerabilityDetails.put("hosts", 6964);
    vulnerabilityDetails.put("vulnerabilities", 94258);
    vulnerabilityDetails.put("totalVulnerableAssets", 5961);
    Response vulnerabilityResponse = new Response();
    vulnerabilityResponse.setData(taggingDetails);
    Map<String,Object> complianceStats=new HashMap<>();
    complianceStats.put("hosts", 6964);
    complianceStats.put("vulnerabilities", 94258);
    complianceStats.put("totalVulnerableAssets", 5961);
    Response complianceStatsResponse = new Response();
    complianceStatsResponse.setData(complianceStats);


    Map<String,Object> topNonCompliant = new HashMap<>();
    topNonCompliant.put("hosts", 6964);
    topNonCompliant.put("vulnerabilities", 94258);
    topNonCompliant.put("totalVulnerableAssets", 5961);
    Response topNonCompliantAppsResponse = new Response();
    topNonCompliantAppsResponse.setData(topNonCompliant);

    Map<String, Object> responseDetails = Maps.newHashMap();
    responseDetails.put("application", "application123");
    List<Map<String, Object>> response = Lists.newArrayList();
    response.add(responseDetails);
    Map<String,Object> applicationNames = new HashMap<>();
    applicationNames.put("response", response);
    applicationNames.put("vulnerabilities", 94258);
    applicationNames.put("totalVulnerableAssets", 5961);
    Response applicationNamesResponse = new Response();
    applicationNamesResponse.setData(applicationNames);


    Map<String,Object> issueDetails = new HashMap<>();
    issueDetails.put("hosts", 6964);
    issueDetails.put("vulnerabilities", 94258);
    issueDetails.put("totalVulnerableAssets", 5961);
    Response issueDetailsResponse = new Response();
    issueDetailsResponse.setData(issueDetails);
    issueDetailsResponse.setMessage("message");
    assertTrue(issueDetailsResponse.getMessage().equals("message"));

    ReflectionTestUtils.setField(assetGroupEmailService, "mailTemplateUrl", mailTemplateUrl);
    when(complianceServiceClient.getPatching(anyString())).thenReturn(patchingResponse);
    when(complianceServiceClient.getCertificates(anyString())).thenReturn(CertificateResponse);
    when(complianceServiceClient.getTagging(anyString())).thenReturn(taggingResponse);
    when(statisticsServiceClient.getComplianceStats(anyString())).thenReturn(complianceStatsResponse);
    when(complianceServiceClient.getVulnerabilities(anyString())).thenReturn(vulnerabilityResponse);

    when(complianceServiceClient.getTopNonCompliantApps(anyString())).thenReturn(topNonCompliantAppsResponse);
    when(complianceServiceClient.getVulnerabilityByApplications(anyString())).thenReturn(applicationNamesResponse);
    when(complianceServiceClient.getDistribution(anyString())).thenReturn(issueDetailsResponse);

    when(notificationService.getAllAssetGroupOwnerEmailDetails()).thenReturn(ownerEmailDetails);
    assetGroupEmailService.executeEmailServiceForAssetGroup();

}